SDB implementation of RDF API (and merge from trunk)

This commit is contained in:
brianjlowe 2012-06-04 21:09:36 +00:00
parent 8aa257d564
commit cead502f89
194 changed files with 10522 additions and 5324 deletions

View file

@ -3,7 +3,7 @@
<!-- $This file is distributed under the terms of the license in /doc/license.txt$ -->
<!-- ======================================================================
Build script for the Vitro core webapp.
Build script for the Vitro core webapp.
This can be used on its own, or invoked from a Product build script.
====================================================================== -->
@ -12,7 +12,7 @@
<!-- - - - - - - - - - - - - - - - - -
properties
- - - - - - - - - - - - - - - - - -->
- - - - - - - - - - - - - - - - -->
<dirname property="corebase.dir" file="${ant.file.vitroCore}" />
<!-- A product script will override appbase.dir, but not corebase.dir -->
@ -137,15 +137,15 @@ deploy - Deploy the application directly into the Tomcat webapps directory.
<delete dir="${solr.home.dir}" excludes="data/**/*" includeemptydirs="true" />
</target>
<!-- - - - - - - - - - - - - - - - - -
target: compileUtilities
- - - - - - - - - - - - - - - - - -->
<target name="compileUtilities">
<!-- - - - - - - - - - - - - - - - - -
target: compileUtilities
- - - - - - - - - - - - - - - - - -->
<target name="compileUtilities">
<mkdir dir="${utility.classes.dir}" />
<javac srcdir="${utilities.source.dir}" destdir="${utility.classes.dir}" debug="true" deprecation="${javac.deprecation}" encoding="UTF8" includeantruntime="false" optimize="false" source="1.6">
<classpath refid="utility.compile.classpath" />
</javac>
</target>
</target>
<!-- - - - - - - - - - - - - - - - - -
target: prepare

View file

@ -33,10 +33,15 @@ log4j.appender.AllAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS}
log4j.rootLogger=INFO, AllAppender
# These classes are too chatty to display INFO messages.
log4j.logger.edu.cornell.mannlib.vitro.webapp.startup.StartupStatus=WARN
log4j.logger.edu.cornell.mannlib.vitro.webapp.controller.freemarker.BrowseController=WARN
log4j.logger.edu.cornell.mannlib.vitro.webapp.dao.jena.pellet.PelletListener=WARN
log4j.logger.edu.cornell.mannlib.vitro.webapp.dao.jena.RDBGraphGenerator=WARN
# Spring as a whole is too chatty to display INFO messages.
log4j.logger.org.springframework=WARN
# suppress odd warnings from libraries
log4j.logger.com.hp.hpl.jena.sdb.layout2.LoaderTuplesNodes=FATAL
log4j.logger.com.hp.hpl.jena.db.impl.PSet_TripleStore_RDB=FATAL

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -3,15 +3,12 @@
package edu.cornell.mannlib.vitro.webapp.beans;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
/**
* User: bdc34
* Date: Oct 18, 2007
@ -69,9 +66,7 @@ public interface Individual extends ResourceBean, Comparable<Individual> {
void setVClasses(List<VClass> vClassList, boolean direct);
/** Does the individual belong to this class? */
boolean isVClass(String uri);
public boolean isMemberOfClassProhibitedFromSearch(ProhibitedFromSearch pfs);
boolean isVClass(String uri);
void setObjectPropertyStatements(List<ObjectPropertyStatement> list);
List<ObjectPropertyStatement> getObjectPropertyStatements();

View file

@ -192,11 +192,6 @@ public class IndividualImpl extends BaseResourceBean implements Individual, Comp
}
return false;
}
public boolean isMemberOfClassProhibitedFromSearch(ProhibitedFromSearch pfs) {
throw new UnsupportedOperationException(this.getClass().getName() +
".isMemberOfClassProhibitedFromSearch must be overriden by a subclass");
}
public List<VClass> getVClasses(boolean direct) {
if (direct) {

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.servlet.setup;
package edu.cornell.mannlib.vitro.webapp.config;
import java.io.File;
import java.sql.Connection;
@ -12,10 +12,13 @@ import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
public class BasicSmokeTests implements ServletContextListener {
/**
* Test that gets run at servlet context startup to check for the existence and
* validity of properties in the configuration.
*/
public class ConfigurationPropertiesSmokeTests implements ServletContextListener {
private static final String PROPERTY_HOME_DIRECTORY = "vitro.home.directory";
private static final String PROPERTY_DB_URL = "VitroConnection.DataSource.url";

View file

@ -1,587 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.IndividualListController;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.SelectListGenerator;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
import edu.cornell.mannlib.vitro.webapp.utils.pageDataGetter.PageDataGetterUtils;
import static edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary.DISPLAY_ONT_MODEL;
/**
* This servlet is for servicing requests for JSON objects/data.
* It could be generalized to get other types of data ex. XML, HTML etc
* @author bdc34
*
*/
public class JsonServlet extends VitroHttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(JsonServlet.class);
private static final int REPLY_SIZE = 256;
private static final int INDIVIDUALS_PER_PAGE = 30;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
VitroRequest vreq = new VitroRequest(req);
try{
if(vreq.getParameter("getEntitiesByVClass") != null ){
if( vreq.getParameter("resultKey") == null) {
getEntitiesByVClass(req, resp);
return;
} else {
getEntitiesByVClassContinuation( req, resp);
return;
}
}else if( vreq.getParameter("getN3EditOptionList") != null ){
doN3EditOptionList(req,resp);
return;
}else if( vreq.getParameter("getSolrIndividualsByVClass") != null ){
getSolrIndividualsByVClass(req,resp);
return;
}else if( vreq.getParameter("getVClassesForVClassGroup") != null ){
getVClassesForVClassGroup(req,resp);
return;
} else if( vreq.getParameter("getSolrIndividualsByVClasses") != null ){
log.debug("AJAX request to retrieve individuals by vclasses");
getSolrIndividualsByVClasses(req,resp);
return;
} else if( vreq.getParameter("getDataForPage") != null ){
getDataForPage(req,resp);
return;
}
}catch(Exception ex){
log.warn(ex,ex);
}
}
private void getVClassesForVClassGroup(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException {
JSONObject map = new JSONObject();
VitroRequest vreq = new VitroRequest(req);
String vcgUri = vreq.getParameter("classgroupUri");
if( vcgUri == null ){
log.debug("no URI passed for classgroupUri");
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
VClassGroupCache vcgc = VClassGroupCache.getVClassGroupCache(getServletContext());
VClassGroup vcg = vcgc.getGroup(vcgUri);
if( vcg == null ){
log.debug("Could not find vclassgroup: " + vcgUri);
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
ArrayList<JSONObject> classes = new ArrayList<JSONObject>(vcg.size());
for( VClass vc : vcg){
JSONObject vcObj = new JSONObject();
vcObj.put("name", vc.getName());
vcObj.put("URI", vc.getURI());
vcObj.put("entityCount", vc.getEntityCount());
classes.add(vcObj);
}
map.put("classes", classes);
map.put("classGroupName", vcg.getPublicName());
map.put("classGroupUri", vcg.getURI());
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
Writer writer = resp.getWriter();
writer.write(map.toString());
}
private void getSolrIndividualsByVClass( HttpServletRequest req, HttpServletResponse resp ){
String errorMessage = null;
JSONObject rObj = null;
try{
VitroRequest vreq = new VitroRequest(req);
VClass vclass=null;
String vitroClassIdStr = vreq.getParameter("vclassId");
if ( vitroClassIdStr != null && !vitroClassIdStr.isEmpty()){
vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vitroClassIdStr);
if (vclass == null) {
log.debug("Couldn't retrieve vclass ");
throw new Exception (errorMessage = "Class " + vitroClassIdStr + " not found");
}
}else{
log.debug("parameter vclassId URI parameter expected ");
throw new Exception("parameter vclassId URI parameter expected ");
}
vreq.setAttribute("displayType", vitroClassIdStr);
rObj = getSolrIndividualsByVClass(vclass.getURI(),req, getServletContext());
}catch(Exception ex){
errorMessage = ex.toString();
log.error(ex,ex);
}
if( rObj == null )
rObj = new JSONObject();
try{
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
if( errorMessage != null ){
rObj.put("errorMessage", errorMessage);
resp.setStatus(500 /*HttpURLConnection.HTTP_SERVER_ERROR*/);
}else{
rObj.put("errorMessage", "");
}
Writer writer = resp.getWriter();
writer.write(rObj.toString());
}catch(JSONException jse){
log.error(jse,jse);
} catch (IOException e) {
log.error(e,e);
}
}
public static JSONObject getSolrIndividualsByVClass(String vclassURI, HttpServletRequest req, ServletContext context) throws Exception {
List<String> vclassURIs = new ArrayList<String>();
vclassURIs.add(vclassURI);
VitroRequest vreq = new VitroRequest(req);
VClass vclass=null;
JSONObject rObj = new JSONObject();
Map<String, Object> map = getSolrVClassIntersectionResults(vclassURIs, vreq, context);
//last parameter indicates single vclass instead of multiple vclasses
rObj = processVClassResults(map, vreq, context, false);
return rObj;
}
// Accepts multiple vclasses and returns individuals which correspond to the intersection of those classes (i.e. have all those types)
private void getSolrIndividualsByVClasses( HttpServletRequest req, HttpServletResponse resp ){
log.debug("Executing retrieval of individuals by vclasses");
String errorMessage = null;
JSONObject rObj = null;
try{
VitroRequest vreq = new VitroRequest(req);
VClass vclass=null;
log.debug("Retrieving solr individuals by vclasses");
// Could have multiple vclass ids sent in
String[] vitroClassIdStr = vreq.getParameterValues("vclassId");
if ( vitroClassIdStr != null && vitroClassIdStr.length > 0){
for(String vclassId: vitroClassIdStr) {
log.debug("Iterating throug vclasses, using VClass " + vclassId);
vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vclassId);
if (vclass == null) {
log.error("Couldn't retrieve vclass ");
throw new Exception (errorMessage = "Class " + vclassId + " not found");
}
}
}else{
log.error("parameter vclassId URI parameter expected but not found");
throw new Exception("parameter vclassId URI parameter expected ");
}
List<String> vclassIds = Arrays.asList(vitroClassIdStr);
rObj = getSolrIndividualsByVClasses(vclassIds,req, getServletContext());
}catch(Exception ex){
errorMessage = ex.toString();
log.error(ex,ex);
}
if( rObj == null )
rObj = new JSONObject();
try{
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
if( errorMessage != null ){
rObj.put("errorMessage", errorMessage);
resp.setStatus(500 /*HttpURLConnection.HTTP_SERVER_ERROR*/);
}else{
rObj.put("errorMessage", "");
}
Writer writer = resp.getWriter();
writer.write(rObj.toString());
}catch(JSONException jse){
log.error(jse,jse);
} catch (IOException e) {
log.error(e,e);
}
}
public static JSONObject getSolrIndividualsByVClasses(List<String> vclassURIs, HttpServletRequest req, ServletContext context) throws Exception {
VitroRequest vreq = new VitroRequest(req);
log.debug("Retrieve solr results for vclasses" + vclassURIs.toString());
Map<String, Object> map = getSolrVClassIntersectionResults(vclassURIs, vreq, context);
log.debug("Results returned from Solr for " + vclassURIs.toString() + " are of size " + map.size());
JSONObject rObj = processVClassResults(map, vreq, context, true);
return rObj;
}
//Including version for Solr query for Vclass Intersections
private static Map<String,Object> getSolrVClassIntersectionResults(List<String> vclassURIs, VitroRequest vreq, ServletContext context){
log.debug("Retrieving Solr intersection results for " + vclassURIs.toString());
String alpha = IndividualListController.getAlphaParameter(vreq);
int page = IndividualListController.getPageParameter(vreq);
log.debug("Alpha and page parameters are " + alpha + " and " + page);
Map<String,Object> map = null;
try {
map = IndividualListController.getResultsForVClassIntersections(
vclassURIs,
page, INDIVIDUALS_PER_PAGE,
alpha,
vreq.getWebappDaoFactory().getIndividualDao(),
context);
} catch(Exception ex) {
log.error("Error in retrieval of search results for VClass " + vclassURIs.toString(), ex);
}
return map;
}
// Map given to process method includes the actual individuals returned from the search
public static JSONObject processVClassResults(Map<String, Object> map, VitroRequest vreq, ServletContext context, boolean multipleVclasses) throws Exception{
JSONObject rObj = PageDataGetterUtils.processVclassResultsJSON(map, vreq, multipleVclasses);
return rObj;
}
public static Collection<String> getMostSpecificTypes(Individual individual, WebappDaoFactory wdf) {
ObjectPropertyStatementDao opsDao = wdf.getObjectPropertyStatementDao();
Map<String, String> mostSpecificTypes = opsDao.getMostSpecificTypesInClassgroupsForIndividual(individual.getURI());
return mostSpecificTypes.values();
}
public static String getDataPropertyValue(Individual ind, DataProperty dp, WebappDaoFactory wdf){
String value = ind.getDataValue(dp.getURI());
if( value == null || value.isEmpty() )
return "";
else
return value;
}
/**
* Gets an option list for a given EditConfiguration and Field.
* Requires following HTTP query parameters:
* editKey
* field
*/
private void doN3EditOptionList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.debug("in doN3EditOptionList()");
String field = req.getParameter("field");
if( field == null ){
log.debug("could not find query parameter 'field' for doN3EditOptionList");
throw new IllegalArgumentException(" getN3EditOptionList requires parameter 'field'");
}
HttpSession sess = req.getSession(false);
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(sess, req);
if( editConfig == null ) {
log.debug("could not find query parameter 'editKey' for doN3EditOptionList");
throw new IllegalArgumentException(" getN3EditOptionList requires parameter 'editKey'");
}
if( log.isDebugEnabled() )
log.debug(" attempting to get option list for field '" + field + "'");
// set ProhibitedFromSearch object so picklist doesn't show
// individuals from classes that should be hidden from list views
OntModel displayOntModel =
(OntModel) getServletConfig().getServletContext().getAttribute(DISPLAY_ONT_MODEL);
if (displayOntModel != null) {
ProhibitedFromSearch pfs = new ProhibitedFromSearch(
DisplayVocabulary.SEARCH_INDEX_URI, displayOntModel);
editConfig.setProhibitedFromSearch(pfs);
}
Map<String,String> options = SelectListGenerator.getOptions(editConfig, field, (new VitroRequest(req)).getFullWebappDaoFactory());
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
ServletOutputStream out = resp.getOutputStream();
out.println("[");
for(String key : options.keySet()){
JSONArray jsonObj = new JSONArray();
jsonObj.put( options.get(key));
jsonObj.put( key);
out.println(" " + jsonObj.toString() + ",");
}
out.println("]");
}
private void getEntitiesByVClassContinuation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
log.debug("in getEntitiesByVClassContinuation()");
VitroRequest vreq = new VitroRequest(req);
String resKey = vreq.getParameter("resultKey");
if( resKey == null )
throw new ServletException("Could not get resultKey");
HttpSession session = vreq.getSession();
if( session == null )
throw new ServletException("there is no session to get the pervious results from");
@SuppressWarnings("unchecked")
List<Individual> entsInVClass = (List<Individual>) session.getAttribute(resKey);
if( entsInVClass == null )
throw new ServletException("Could not find List<Individual> for resultKey " + resKey);
List<Individual> entsToReturn = new ArrayList<Individual>(REPLY_SIZE);
boolean more = false;
int count = 0;
/* we have a large number of items to send back so we need to stash the list in the session scope */
if( entsInVClass.size() > REPLY_SIZE){
more = true;
ListIterator<Individual> entsFromVclass = entsInVClass.listIterator();
while ( entsFromVclass.hasNext() && count <= REPLY_SIZE ){
entsToReturn.add( entsFromVclass.next());
entsFromVclass.remove();
count++;
}
if( log.isDebugEnabled() ) log.debug("getEntitiesByVClassContinuation(): Creating reply with continue token," +
" sending in this reply: " + count +", remaing to send: " + entsInVClass.size() );
} else {
//send out reply with no continuation
entsToReturn = entsInVClass;
count = entsToReturn.size();
session.removeAttribute(resKey);
if( log.isDebugEnabled()) log.debug("getEntitiesByVClassContinuation(): sending " + count + " Ind without continue token");
}
//put all the entities on the JSON array
JSONArray ja = individualsToJson( entsToReturn );
//put the responseGroup number on the end of the JSON array
if( more ){
try{
JSONObject obj = new JSONObject();
obj.put("resultGroup", "true");
obj.put("size", count);
StringBuffer nextUrlStr = req.getRequestURL();
nextUrlStr.append("?")
.append("getEntitiesByVClass").append( "=1&" )
.append("resultKey=").append( resKey );
obj.put("nextUrl", nextUrlStr.toString());
ja.put(obj);
}catch(JSONException je ){
throw new ServletException(je.getMessage());
}
}
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
ServletOutputStream out = resp.getOutputStream();
out.print( ja.toString() );
log.debug("done with getEntitiesByVClassContinuation()");
}
/**
* Gets a list of entities that are members of the indicated vClass.
*
* If the list is large then we will pass some token indicating that there is more
* to come. The results are sent back in 250 entity blocks. To get all of the
* entities for a VClass just keep requesting lists until there are not more
* continue tokens.
*
* If there are more entities the last item on the returned array will be an object
* with no id property. It will look like this:
*
* {"resultGroup":0,
* "resultKey":"2WEK2306",
* "nextUrl":"http://caruso.mannlib.cornell.edu:8080/vitro/dataservice?getEntitiesByVClass=1&resultKey=2WEK2306&resultGroup=1&vclassId=null",
* "entsInVClass":1752,
* "nextResultGroup":1,
* "standardReplySize":256}
*
*/
private void getEntitiesByVClass(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
log.debug("in getEntitiesByVClass()");
VitroRequest vreq = new VitroRequest(req);
String vclassURI = vreq.getParameter("vclassURI");
WebappDaoFactory daos = (new VitroRequest(req)).getFullWebappDaoFactory();
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
resp.getWriter();
if( vclassURI == null ){
log.debug("getEntitiesByVClass(): no value for 'vclassURI' found in the HTTP request");
out.print( (new JSONArray()).toString() ); return;
}
VClass vclass = daos.getVClassDao().getVClassByURI( vclassURI );
if( vclass == null ){
log.debug("getEntitiesByVClass(): could not find vclass for uri '"+ vclassURI + "'");
out.print( (new JSONArray()).toString() ); return;
}
List<Individual> entsInVClass = daos.getIndividualDao().getIndividualsByVClass( vclass );
if( entsInVClass == null ){
log.debug("getEntitiesByVClass(): null List<Individual> retruned by getIndividualsByVClass() for "+vclassURI);
out.print( (new JSONArray().toString() )); return ;
}
int numberOfEntsInVClass = entsInVClass.size();
List<Individual> entsToReturn = new ArrayList<Individual>( REPLY_SIZE );
String requestHash = null;
int count = 0;
boolean more = false;
/* we have a large number of items to send back so we need to stash the list in the session scope */
if( entsInVClass.size() > REPLY_SIZE){
more = true;
HttpSession session = vreq.getSession(true);
requestHash = Integer.toString((vclassURI + System.currentTimeMillis()).hashCode());
session.setAttribute(requestHash, entsInVClass );
ListIterator<Individual> entsFromVclass = entsInVClass.listIterator();
while ( entsFromVclass.hasNext() && count < REPLY_SIZE ){
entsToReturn.add( entsFromVclass.next());
entsFromVclass.remove();
count++;
}
if( log.isDebugEnabled() ){ log.debug("getEntitiesByVClass(): Creating reply with continue token, found " + numberOfEntsInVClass + " Individuals"); }
}else{
if( log.isDebugEnabled() ) log.debug("getEntitiesByVClass(): sending " + numberOfEntsInVClass +" Individuals without continue token");
entsToReturn = entsInVClass;
count = entsToReturn.size();
}
//put all the entities on the JSON array
JSONArray ja = individualsToJson( entsToReturn );
//put the responseGroup number on the end of the JSON array
if( more ){
try{
JSONObject obj = new JSONObject();
obj.put("resultGroup", "true");
obj.put("size", count);
obj.put("total", numberOfEntsInVClass);
StringBuffer nextUrlStr = req.getRequestURL();
nextUrlStr.append("?")
.append("getEntitiesByVClass").append( "=1&" )
.append("resultKey=").append( requestHash );
obj.put("nextUrl", nextUrlStr.toString());
ja.put(obj);
}catch(JSONException je ){
throw new ServletException("unable to create continuation as JSON: " + je.getMessage());
}
}
resp.setContentType("application/json;charset=UTF-8");
out.print( ja.toString() );
log.debug("done with getEntitiesByVClass()");
}
/**
* Gets data based on data getter for page uri and returns in the form of Json objects
* @param req
* @param resp
*/
private void getDataForPage(HttpServletRequest req, HttpServletResponse resp)
throws Exception{
VitroRequest vreq = new VitroRequest(req);
String errorMessage = null;
JSONObject rObj = null;
String pageUri = vreq.getParameter("pageUri");
if(pageUri != null && !pageUri.isEmpty()) {
ServletContext context = getServletContext();
Map<String,Object> data = PageDataGetterUtils.getDataForPage(pageUri, vreq, context);
//Convert to json version based on type of page
if(data != null) {
//Convert to json version based on type of page
rObj = PageDataGetterUtils.covertDataToJSONForPage(pageUri, data, vreq, context);
}
}
if( rObj == null )
rObj = new JSONObject();
//Send object
try{
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
if( errorMessage != null ){
rObj.put("errorMessage", errorMessage);
resp.setStatus(500 /*HttpURLConnection.HTTP_SERVER_ERROR*/);
}else{
rObj.put("errorMessage", "");
}
Writer writer = resp.getWriter();
writer.write(rObj.toString());
}catch(JSONException jse){
log.error(jse,jse);
} catch (IOException e) {
log.error(e,e);
}
}
private JSONArray individualsToJson(List<Individual> individuals) throws ServletException {
JSONArray ja = new JSONArray();
Iterator<Individual> it = individuals.iterator();
try{
while(it.hasNext()){
Individual ent = (Individual) it.next();
JSONObject entJ = new JSONObject();
entJ.put("name", ent.getName());
entJ.put("URI", ent.getURI());
ja.put( entJ );
}
}catch(JSONException ex){
throw new ServletException("could not convert list of Individuals into JSON: " + ex);
}
return ja;
}
}

View file

@ -6,7 +6,6 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -26,8 +25,8 @@ import freemarker.template.Template;
* A base class for servlets that handle AJAX requests.
*/
public abstract class VitroAjaxController extends HttpServlet {
private static final Log log = LogFactory.getLog(VitroAjaxController.class);
private static final Log log = LogFactory.getLog(VitroAjaxController.class);
/**
* Sub-classes must implement this method to handle both GET and POST
@ -67,38 +66,31 @@ public abstract class VitroAjaxController extends HttpServlet {
*/
@SuppressWarnings("unused")
protected Actions requiredActions(VitroRequest vreq) {
return Actions.AUTHORIZED;
}
/**
* Returns the current Freemarker Configuration so the controller can process
* its data through a template.
*/
protected final Configuration getFreemarkerConfiguration(VitroRequest vreq) {
return FreemarkerConfigurationLoader.getConfig(vreq, getServletContext());
return Actions.AUTHORIZED;
}
/**
* Process data through a Freemarker template and output the result.
*/
protected void writeTemplate(String templateName, Map<String, Object> map,
Configuration config, HttpServletRequest request, HttpServletResponse response) {
Template template = null;
try {
template = config.getTemplate(templateName);
PrintWriter out = response.getWriter();
template.process(map, out);
} catch (Exception e) {
log.error(e, e);
}
protected void writeTemplate(String templateName, Map<String, Object> map,
VitroRequest vreq, HttpServletResponse response) {
Configuration config = FreemarkerConfigurationLoader.getConfig(vreq);
try {
Template template = config.getTemplate(templateName);
PrintWriter out = response.getWriter();
template.process(map, out);
} catch (Exception e) {
log.error(e, e);
}
}
protected void doError(HttpServletResponse response, String errorMsg,
int httpstatus) {
response.setStatus(httpstatus);
try {
response.getWriter().write(errorMsg);
} catch (IOException e) {
log.debug("IO exception during output", e);
}
}
protected void doError(HttpServletResponse response, String errorMsg, int httpstatus){
response.setStatus(httpstatus);
try {
response.getWriter().write(errorMsg);
} catch (IOException e) {
log.debug("IO exception during output",e );
}
}
}

View file

@ -130,10 +130,12 @@ public class BaseSiteAdminController extends FreemarkerHttpServlet {
data.put("siteInfo", UrlBuilder.getUrl("/editForm", "controller", "ApplicationBean"));
}
//TODO: Add specific permissions for page management
if (PolicyHelper.isAuthorizedForActions(vreq, SimplePermission.MANAGE_MENUS.ACTIONS)) {
data.put("menuManagement", UrlBuilder.getUrl("/individual",
"uri", "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#DefaultMenu",
"switchToDisplayModel", "true"));
data.put("pageManagement", UrlBuilder.getUrl("/pageList"));
}
if (PolicyHelper.isAuthorizedForActions(vreq, SimplePermission.SEE_STARTUP_STATUS.ACTIONS)) {

View file

@ -32,7 +32,6 @@ import edu.cornell.mannlib.vitro.webapp.controller.freemarker.TemplateProcessing
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailFactory;
import freemarker.template.Configuration;
public class ContactMailController extends FreemarkerHttpServlet {
private static final Log log = LogFactory
@ -112,15 +111,14 @@ public class ContactMailController extends FreemarkerHttpServlet {
String originalReferer = getOriginalRefererFromSession(vreq);
Configuration config = (Configuration) vreq.getAttribute("freemarkerConfig");
String msgText = composeEmail(webusername, webuseremail, comments,
deliveryfrom, originalReferer, vreq.getRemoteAddr(), config, vreq);
deliveryfrom, originalReferer, vreq.getRemoteAddr(), vreq);
try {
// Write the message to the journal file
FileWriter fw = new FileWriter(locateTheJournalFile(vreq),true);
PrintWriter outFile = new PrintWriter(fw);
writeBackupCopy(outFile, msgText, config, vreq);
writeBackupCopy(outFile, msgText, vreq);
try {
// Send the message
@ -222,7 +220,7 @@ public class ContactMailController extends FreemarkerHttpServlet {
private String composeEmail(String webusername, String webuseremail,
String comments, String deliveryfrom,
String originalReferer, String ipAddr, Configuration config,
String originalReferer, String ipAddr,
HttpServletRequest request) {
Map<String, Object> email = new HashMap<String, Object>();
@ -238,7 +236,7 @@ public class ContactMailController extends FreemarkerHttpServlet {
}
try {
return processTemplateToString(template, email, config, request);
return processTemplateToString(template, email, request);
} catch (TemplateProcessingException e) {
log.error("Error processing email text through template: " + e.getMessage(), e);
return null;
@ -246,7 +244,7 @@ public class ContactMailController extends FreemarkerHttpServlet {
}
private void writeBackupCopy(PrintWriter outFile, String msgText,
Configuration config, HttpServletRequest request) {
HttpServletRequest request) {
Map<String, Object> backup = new HashMap<String, Object>();
String template = TEMPLATE_BACKUP;
@ -256,7 +254,7 @@ public class ContactMailController extends FreemarkerHttpServlet {
backup.put("msgText", msgText);
try {
String backupText = processTemplateToString(template, backup, config, request);
String backupText = processTemplateToString(template, backup, request);
outFile.print(backupText);
outFile.flush();
//outFile.close();

View file

@ -2,7 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
@ -14,7 +13,6 @@ import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.TemplateProcessingHelper.TemplateProcessingException;
import freemarker.template.Configuration;
/**
* TEMPORARY for transition from JSP to FreeMarker. Once transition
@ -34,35 +32,33 @@ public class FreemarkerComponentGenerator extends FreemarkerHttpServlet {
// Mimic what FreemarkerHttpServlet does for a new request
VitroRequest vreq = new VitroRequest(request);
FreemarkerConfiguration config = getConfig(vreq);
vreq.setAttribute("freemarkerConfig", config);
Map<String, Object> map = getPageTemplateValues(vreq);
request.setAttribute("ftl_head", getHead("head", map, config, vreq));
request.setAttribute("ftl_identity", get("identity", map, config, vreq));
request.setAttribute("ftl_menu", get("menu", map, config, vreq));
request.setAttribute("ftl_search", get("search", map, config, vreq));
request.setAttribute("ftl_footer", get("footer", map, config, vreq));
request.setAttribute("ftl_googleAnalytics", get("googleAnalytics", map, config, vreq));
request.setAttribute("ftl_head", getHead("head", map, vreq));
request.setAttribute("ftl_identity", get("identity", map, vreq));
request.setAttribute("ftl_menu", get("menu", map, vreq));
request.setAttribute("ftl_search", get("search", map, vreq));
request.setAttribute("ftl_footer", get("footer", map, vreq));
request.setAttribute("ftl_googleAnalytics", get("googleAnalytics", map, vreq));
}
private String get(String templateName, Map<String, Object> root, Configuration config, HttpServletRequest request) {
private String get(String templateName, Map<String, Object> root, HttpServletRequest request) {
templateName += ".ftl";
try {
return processTemplate(templateName, root, config, request).toString();
return processTemplate(templateName, root, request).toString();
} catch (TemplateProcessingException e) {
log.error("Error processing template " + templateName + ": " + e.getMessage(), e);
return null;
}
}
private String getHead(String templateName, Map<String, Object> root, Configuration config, HttpServletRequest request) {
private String getHead(String templateName, Map<String, Object> root, HttpServletRequest request) {
// The Freemarker head template displays the page title in the <title> tag. Get the value out of the request.
String title = (String) request.getAttribute("title");
if (!StringUtils.isEmpty(title)) {
root.put("title", title);
}
return get(templateName, root, config, request);
return get(templateName, root, request);
}
// RY We need the servlet context in getConfig(). For some reason using the method inherited from

View file

@ -17,9 +17,9 @@ import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.Route;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfigurationConstants;
import edu.cornell.mannlib.vitro.webapp.web.directives.IndividualShortViewDirective;
import edu.cornell.mannlib.vitro.webapp.web.methods.IndividualLocalNameMethod;
import edu.cornell.mannlib.vitro.webapp.web.methods.IndividualPlaceholderImageUrlMethod;
import edu.cornell.mannlib.vitro.webapp.web.methods.IndividualProfileUrlMethod;
@ -40,14 +40,12 @@ public class FreemarkerConfiguration extends Configuration {
private final String themeDir;
private final ServletContext context;
private final ApplicationBean appBean;
private final String appName;
FreemarkerConfiguration(String themeDir, VitroRequest vreq, ServletContext context) {
FreemarkerConfiguration(String themeDir, ApplicationBean appBean, ServletContext context) {
this.themeDir = themeDir;
this.context = context;
this.appBean = vreq.getAppBean();
this.appName = appBean.getApplicationName();
this.appBean = appBean;
String buildEnv = ConfigurationProperties.getBean(context).getProperty("Environment.build");
log.debug("Current build environment: " + buildEnv);
@ -88,7 +86,7 @@ public class FreemarkerConfiguration extends Configuration {
setTemplateLoader(createTemplateLoader());
setSharedVariables(vreq);
setSharedVariables();
}
@ -96,13 +94,12 @@ public class FreemarkerConfiguration extends Configuration {
* These are values that are accessible to all
* templates loaded by the Configuration's TemplateLoader. They
* should be application- rather than request-specific.
* @param VitroRequest vreq
*/
private void setSharedVariables(VitroRequest vreq) {
private void setSharedVariables() {
Map<String, Object> sharedVariables = new HashMap<String, Object>();
sharedVariables.put("siteName", appName);
sharedVariables.put("siteName", appBean.getApplicationName());
sharedVariables.put("version", getRevisionInfo());
sharedVariables.put("urls", getSiteUrls());
sharedVariables.put("themeDir", themeDir);
@ -158,6 +155,7 @@ public class FreemarkerConfiguration extends Configuration {
map.put("dump", new freemarker.ext.dump.DumpDirective());
map.put("dumpAll", new freemarker.ext.dump.DumpAllDirective());
map.put("help", new freemarker.ext.dump.HelpDirective());
map.put("shortView", new IndividualShortViewDirective());
return map;
}

View file

@ -19,10 +19,9 @@ public class FreemarkerConfigurationLoader {
private static final Map<String, FreemarkerConfiguration> themeToConfigMap = new HashMap<String, FreemarkerConfiguration>();
public static FreemarkerConfiguration getConfig(VitroRequest vreq,
ServletContext context) {
public static FreemarkerConfiguration getConfig(VitroRequest vreq) {
String themeDir = getThemeDir(vreq.getAppBean());
return getConfigForTheme(themeDir, vreq, context);
return getConfigForTheme(themeDir, vreq.getAppBean(), vreq.getSession().getServletContext());
}
private static String getThemeDir(ApplicationBean appBean) {
@ -46,16 +45,16 @@ public class FreemarkerConfigurationLoader {
* 1. The template loader is theme-specific, since it specifies a theme
* directory to load templates from.
*
* 2. Shared variables like stylesheets are theme-specific.
* 2. Some shared variables are theme-specific.
*/
private static FreemarkerConfiguration getConfigForTheme(String themeDir,
VitroRequest vreq, ServletContext context) {
ApplicationBean appBean, ServletContext context) {
synchronized (themeToConfigMap) {
if (themeToConfigMap.containsKey(themeDir)) {
return themeToConfigMap.get(themeDir);
} else {
FreemarkerConfiguration config = new FreemarkerConfiguration(
themeDir, vreq, context);
themeDir, appBean, context);
themeToConfigMap.put(themeDir, config);
return config;
}

View file

@ -41,7 +41,6 @@ import edu.cornell.mannlib.vitro.webapp.web.templatemodels.Tags;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.User;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.menu.MainMenu;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
@ -100,9 +99,6 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
return;
}
FreemarkerConfiguration config = getConfig(vreq);
vreq.setAttribute("freemarkerConfig", config);
responseValues = processRequest(vreq);
doResponse(vreq, response, responseValues);
@ -196,10 +192,6 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
doGet(request, response);
}
protected FreemarkerConfiguration getConfig(VitroRequest vreq) {
return FreemarkerConfigurationLoader.getConfig(vreq, getServletContext());
}
/**
* By default, a page requires authorization for no actions.
* Subclasses that require authorization to process their page will override
@ -249,8 +241,6 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
protected void doTemplate(VitroRequest vreq, HttpServletResponse response,
ResponseValues values) throws TemplateProcessingException {
Configuration config = getConfig(vreq);
Map<String, Object> templateDataModel = new HashMap<String, Object>();
templateDataModel.putAll(getPageTemplateValues(vreq));
@ -265,7 +255,7 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
if (bodyTemplate != null) {
// Tell the template and any directives it uses that we're processing a body template.
templateDataModel.put("templateType", BODY_TEMPLATE_TYPE);
bodyString = processTemplateToString(bodyTemplate, templateDataModel, config, vreq);
bodyString = processTemplateToString(bodyTemplate, templateDataModel, vreq);
} else {
// The subcontroller has not defined a body template. All markup for the page
// is specified in the main page template.
@ -276,7 +266,7 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
// Tell the template and any directives it uses that we're processing a page template.
templateDataModel.put("templateType", PAGE_TEMPLATE_TYPE);
writePage(templateDataModel, config, vreq, response, values.getStatusCode(), values);
writePage(templateDataModel, vreq, response, values.getStatusCode(), values);
}
protected void doRedirect(HttpServletRequest request, HttpServletResponse response, ResponseValues values)
@ -346,7 +336,7 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
private Map<String, Object> buildRequestUrls(VitroRequest vreq) {
Map<String, Object> requestUrls = new HashMap<String, Object>();
FreemarkerConfiguration config = (FreemarkerConfiguration)vreq.getAttribute("freemarkerConfig");
FreemarkerConfiguration config = FreemarkerConfigurationLoader.getConfig(vreq);
TemplateModel urlModel = config.getSharedVariable("urls");
try {
@ -485,29 +475,19 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
return siteName;
}
protected StringWriter processTemplate(String templateName, Map<String, Object> map, Configuration config,
protected StringWriter processTemplate(String templateName, Map<String, Object> map,
HttpServletRequest request) throws TemplateProcessingException {
TemplateProcessingHelper helper = new TemplateProcessingHelper(config, request, getServletContext());
TemplateProcessingHelper helper = new TemplateProcessingHelper(request, getServletContext());
return helper.processTemplate(templateName, map);
}
protected StringWriter processTemplate(ResponseValues values, Configuration config,
HttpServletRequest request) throws TemplateProcessingException {
return processTemplate(values.getTemplateName(), values.getMap(), config, request);
}
// In fact, we can put StringWriter objects directly into the data model, so perhaps we should eliminate the processTemplateToString() methods.
protected String processTemplateToString(String templateName, Map<String, Object> map, Configuration config,
protected String processTemplateToString(String templateName, Map<String, Object> map,
HttpServletRequest request) throws TemplateProcessingException {
return processTemplate(templateName, map, config, request).toString();
return processTemplate(templateName, map, request).toString();
}
protected String processTemplateToString(ResponseValues values, Configuration config,
HttpServletRequest request) throws TemplateProcessingException {
return processTemplate(values, config, request).toString();
}
protected void writePage(Map<String, Object> root, Configuration config, HttpServletRequest request,
protected void writePage(Map<String, Object> root, HttpServletRequest request,
HttpServletResponse response, int statusCode, ResponseValues rv) throws TemplateProcessingException {
// For an error page, use the standard page template rather than a special one, in case that is the source
@ -515,17 +495,17 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
// less likely.
String pageTemplateName =
rv instanceof ExceptionResponseValues ? Template.PAGE_DEFAULT.toString() : getPageTemplateName();
writeTemplate(pageTemplateName, root, config, request, response, statusCode);
writeTemplate(pageTemplateName, root, request, response, statusCode);
}
protected void writeTemplate(String templateName, Map<String, Object> map, Configuration config,
protected void writeTemplate(String templateName, Map<String, Object> map,
HttpServletRequest request, HttpServletResponse response) throws TemplateProcessingException {
writeTemplate(templateName, map, config, request, response, 0);
writeTemplate(templateName, map, request, response, 0);
}
protected void writeTemplate(String templateName, Map<String, Object> map, Configuration config,
protected void writeTemplate(String templateName, Map<String, Object> map,
HttpServletRequest request, HttpServletResponse response, int statusCode) throws TemplateProcessingException {
StringWriter sw = processTemplate(templateName, map, config, request);
StringWriter sw = processTemplate(templateName, map, request);
write(sw, response, statusCode);
}

View file

@ -28,10 +28,10 @@ public class HomePageController extends FreemarkerHttpServlet {
Map<String, Object> body = new HashMap<String, Object>();
List<DataGetter> dgList = DataGetterUtils.getDataGettersForPage(vreq.getDisplayModel(), DisplayVocabulary.HOME_PAGE_URI);
List<DataGetter> dgList = DataGetterUtils.getDataGettersForPage(vreq, vreq.getDisplayModel(), DisplayVocabulary.HOME_PAGE_URI);
for( DataGetter dg : dgList){
Map<String,Object> moreData = dg.getData(getServletContext(),vreq,body);
Map<String,Object> moreData = dg.getData(body);
if( moreData != null ){
body.putAll(moreData);
}

View file

@ -2,25 +2,21 @@
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
@ -165,36 +161,14 @@ public class IndividualListController extends FreemarkerHttpServlet {
}
}
// //Pulling out common code that is used for both single (regular) vclass query and multiple (intersection) query
// public static Map<String,Object> getResultsForVClasses(List<String> vclassURIs, int page, String alpha, IndividualDao indDao, ServletContext context)
// throws IOException, ServletException{
// Map<String,Object> rvMap = new HashMap<String,Object>();
// try{
// SolrQuery query = getQuery(vclassURIs, alpha, page, INDIVIDUALS_PER_PAGE);
// rvMap = getResultsForVClassQuery(query, page, alpha, indDao, context);
// List<Individual> individuals = (List<Individual>) rvMap.get("entities");
// if (individuals == null)
// log.debug("entities list is null for vclasses " + vclassURIs.toString() );
// } catch(Throwable th) {
// log.error("An error occurred retrieving results for vclass query", th);
// }
// return rvMap;
// }
@SuppressWarnings("unchecked")
public static Map<String,Object> getResultsForVClass(String vclassURI, int page, String alpha, IndividualDao indDao, ServletContext context)
throws IOException, SearchException{
throws SearchException{
Map<String,Object> rvMap = new HashMap<String,Object>();
try{
//make query for this rdf:type
List<String> classUris = new ArrayList<String>();
classUris.add(vclassURI);
SolrQuery query = getQuery(classUris, alpha, page, INDIVIDUALS_PER_PAGE);
rvMap = getResultsForVClassQuery(query, page, INDIVIDUALS_PER_PAGE, alpha, indDao, context);
List<Individual> individuals = (List<Individual>) rvMap.get("entities");
if (individuals == null)
log.debug("entities list is null for vclass " + vclassURI );
} catch (ServletException e) {
List<String> classUris = Collections.singletonList(vclassURI);
IndividualListQueryResults results = buildAndExecuteVClassQuery(classUris, alpha, page, INDIVIDUALS_PER_PAGE, context, indDao);
rvMap = getResultsForVClassQuery(results, page, INDIVIDUALS_PER_PAGE, alpha);
} catch (SolrServerException e) {
String msg = "An error occurred retrieving results for vclass query";
log.error(msg, e);
// Throw this up to processRequest, so the template gets the error message.
@ -205,72 +179,34 @@ public class IndividualListController extends FreemarkerHttpServlet {
return rvMap;
}
@SuppressWarnings("unchecked")
public static Map<String,Object> getResultsForVClassIntersections(List<String> vclassURIs, int page, int pageSize, String alpha, IndividualDao indDao, ServletContext context)
throws IOException, ServletException{
public static Map<String,Object> getResultsForVClassIntersections(List<String> vclassURIs, int page, int pageSize, String alpha, IndividualDao indDao, ServletContext context) {
Map<String,Object> rvMap = new HashMap<String,Object>();
try{
// make query for multiple rdf types
SolrQuery query = getQuery(vclassURIs, alpha, page, pageSize);
log.debug("Executed solr query for " + vclassURIs.toString());
rvMap = getResultsForVClassQuery(query, page, pageSize, alpha, indDao, context);
List<Individual> individuals = (List<Individual>) rvMap.get("entities");
if (individuals == null)
log.debug("entities list is null for vclass " + vclassURIs.toString() );
IndividualListQueryResults results = buildAndExecuteVClassQuery(vclassURIs, alpha, page, pageSize, context, indDao);
rvMap = getResultsForVClassQuery(results, page, pageSize, alpha);
} catch(Throwable th) {
log.error("Error retrieving individuals corresponding to intersection multiple classes." + vclassURIs.toString(), th);
}
return rvMap;
}
private static IndividualListQueryResults buildAndExecuteVClassQuery(
List<String> vclassURIs, String alpha, int page, int pageSize,
ServletContext context, IndividualDao indDao)
throws SolrServerException {
SolrQuery query = getQuery(vclassURIs, alpha, page, pageSize);
IndividualListQueryResults results = IndividualListQueryResults.runQuery(query, indDao, context);
log.debug("Executed solr query for " + vclassURIs);
if (results.getIndividuals().isEmpty()) {
log.debug("entities list is null for vclass " + vclassURIs);
}
return results;
}
/**
* This method is now called in a couple of places. It should be refactored
* into a DAO or similar object.
*/
protected static Map<String,Object> getResultsForVClassQuery(SolrQuery query, int page, int pageSize, String alpha, IndividualDao indDao, ServletContext context)
throws IOException, ServletException {
Map<String,Object> rvMap = new HashMap<String,Object>();
SolrServer solr = SolrSetup.getSolrServer(context);
QueryResponse response = null;
// Execute query for individuals of the specified type
try {
response = solr.query(query);
} catch (Throwable t) {
log.error(t, t);
}
if ( response == null ) {
throw new ServletException("Could not run search in IndividualListController");
}
SolrDocumentList docs = response.getResults();
if (docs == null) {
throw new ServletException("Could not run search in IndividualListController");
}
// get list of individuals for the search results
long hitCount = docs.getNumFound();
log.debug("Number of search results: " + hitCount);
Iterator<SolrDocument> docIter = docs.iterator();
List<Individual> individuals = new ArrayList<Individual>(docs.size());
while ( docIter.hasNext() ){
SolrDocument doc = docIter.next();
if (doc != null) {
String uri = doc.get(VitroSearchTermNames.URI).toString();
Individual individual = indDao.getIndividualByURI( uri );
if (individual != null) {
individuals.add( individual );
log.debug("Adding individual " + uri + " to individual list display");
} else {
log.debug("No existing individual for search document with uri = " + uri);
}
}
}
private static Map<String,Object> getResultsForVClassQuery(IndividualListQueryResults results, int page, int pageSize, String alpha) {
Map<String,Object> rvMap = new HashMap<String,Object>();
long hitCount = results.getHitCount();
if ( hitCount > pageSize ){
rvMap.put("showPages", Boolean.TRUE);
List<PageRecord> pageRecords = makePagesList(hitCount, pageSize, page);
@ -281,9 +217,8 @@ public class IndividualListController extends FreemarkerHttpServlet {
}
rvMap.put("alpha",alpha);
rvMap.put("totalCount", hitCount);
rvMap.put("entities",individuals);
rvMap.put("entities", results.getIndividuals());
return rvMap;
}
@ -337,17 +272,13 @@ public class IndividualListController extends FreemarkerHttpServlet {
}
private static String makeMultiClassQuery( List<String> vclassUris){
String queryText = "";
List<String> queryTypes = new ArrayList<String>();
try {
// query term for rdf:type - multiple types possible
for(String vclassUri: vclassUris) {
queryTypes.add(VitroSearchTermNames.RDFTYPE + ":\"" + vclassUri + "\" ");
}
if (queryTypes.size() > 0) {
queryText = StringUtils.join(queryTypes, " AND ");
}
return queryText;
return StringUtils.join(queryTypes, " AND ");
} catch (Exception ex){
log.error("Could not make Solr query",ex);
return "";

View file

@ -0,0 +1,98 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames;
import edu.cornell.mannlib.vitro.webapp.search.solr.SolrSetup;
/**
* Holds the Individuals that were found in a Solr search query.
*
* Provides a convenience method to run the query and to find the Individuals.
*/
public class IndividualListQueryResults {
private static final Log log = LogFactory
.getLog(IndividualListQueryResults.class);
private static final IndividualListQueryResults EMPTY_RESULT = new IndividualListQueryResults(
0, new ArrayList<Individual>());
// ----------------------------------------------------------------------
// Convenience method
// ----------------------------------------------------------------------
public static IndividualListQueryResults runQuery(SolrQuery query,
IndividualDao indDao, ServletContext context)
throws SolrServerException {
SolrServer solr = SolrSetup.getSolrServer(context);
QueryResponse response = null;
response = solr.query(query);
if (response == null) {
log.debug("response from search query was null");
return EMPTY_RESULT;
}
SolrDocumentList docs = response.getResults();
if (docs == null) {
log.debug("results from search query response was null");
return EMPTY_RESULT;
}
// get list of individuals for the search results
long hitCount = docs.getNumFound();
log.debug("Number of search results: " + hitCount);
List<Individual> individuals = new ArrayList<Individual>(docs.size());
for (SolrDocument doc : docs) {
String uri = doc.get(VitroSearchTermNames.URI).toString();
Individual individual = indDao.getIndividualByURI(uri);
if (individual == null) {
log.debug("No individual for search document with uri = " + uri);
} else {
individuals.add(individual);
log.debug("Adding individual " + uri + " to individual list");
}
}
return new IndividualListQueryResults((int) hitCount, individuals);
}
// ----------------------------------------------------------------------
// The instance
// ----------------------------------------------------------------------
private final int hitCount;
private final List<Individual> individuals;
public IndividualListQueryResults(int hitCount, List<Individual> individuals) {
this.hitCount = hitCount;
this.individuals = individuals;
}
public int getHitCount() {
return hitCount;
}
public List<Individual> getIndividuals() {
return individuals;
}
}

View file

@ -0,0 +1,117 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
public class ListClassGroupsController extends FreemarkerHttpServlet {
private static final Log log = LogFactory.getLog(ListClassGroupsController.class.getName());
private static final String TEMPLATE_NAME = "siteAdmin-classHierarchy.ftl";
@Override
protected Actions requiredActions(VitroRequest vreq) {
return SimplePermission.EDIT_ONTOLOGY.ACTIONS;
}
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
Map<String, Object> body = new HashMap<String, Object>();
try {
body.put("displayOption", "group");
body.put("pageTitle", "Class Groups");
VClassGroupDao dao = vreq.getFullWebappDaoFactory().getVClassGroupDao();
List<VClassGroup> groups = dao.getPublicGroupsWithVClasses();
String json = new String();
int counter = 0;
if (groups != null) {
for(VClassGroup vcg: groups) {
if ( counter > 0 ) {
json += ", ";
}
String publicName = vcg.getPublicName();
if ( StringUtils.isBlank(publicName) ) {
publicName = "(unnamed group)";
}
try {
json += "{ \"name\": \"<a href='./editForm?uri="+URLEncoder.encode(vcg.getURI(),"UTF-8")+"&amp;controller=Classgroup'>"+publicName+"</a>\", ";
} catch (Exception e) {
json += "{ \"name\": \"" + publicName + "\", ";
}
Integer t;
json += "\"data\": { \"displayRank\": \"" + (((t = Integer.valueOf(vcg.getDisplayRank())) != -1) ? t.toString() : "") + "\"}, ";
List<VClass> classList = vcg.getVitroClassList();
if (classList != null && classList.size()>0) {
json += "\"children\": [";
Iterator<VClass> classIt = classList.iterator();
while (classIt.hasNext()) {
VClass vcw = classIt.next();
if (vcw.getName() != null && vcw.getURI() != null) {
try {
json += "{ \"name\": \"<a href='vclassEdit?uri="+URLEncoder.encode(vcw.getURI(),"UTF-8")+"'>"+vcw.getName()+"</a>\", ";
} catch (Exception e) {
json += "\"" + vcw.getName() + "\", ";
}
} else {
json += "\"\", ";
}
String shortDefStr = (vcw.getShortDef() == null) ? "" : vcw.getShortDef();
json += "\"data\": { \"shortDef\": \"" + shortDefStr + "\"}, \"children\": [] ";
if (classIt.hasNext())
json += "} , ";
else
json += "}] ";
}
}
else {
json += "\"children\": [] ";
}
json += "} ";
counter += 1;
}
}
body.put("jsonTree",json);
} catch (Throwable t) {
t.printStackTrace();
}
return new TemplateResponseValues(TEMPLATE_NAME, body);
}
}

View file

@ -0,0 +1,141 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.vocabulary.OWL;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions;
import edu.cornell.mannlib.vitro.webapp.beans.Ontology;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
public class ListVClassWebappsController extends FreemarkerHttpServlet {
private static final Log log = LogFactory.getLog(ListVClassWebappsController.class.getName());
private static final String TEMPLATE_NAME = "siteAdmin-classHierarchy.ftl";
@Override
protected Actions requiredActions(VitroRequest vreq) {
return SimplePermission.EDIT_ONTOLOGY.ACTIONS;
}
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
Map<String, Object> body = new HashMap<String, Object>();
try {
body.put("displayOption", "all");
body.put("pageTitle", "All Classes");
List<VClass> classes = null;
if (vreq.getParameter("showPropertyRestrictions") != null) {
PropertyDao pdao = vreq.getFullWebappDaoFactory().getObjectPropertyDao();
classes = pdao.getClassesWithRestrictionOnProperty(vreq.getParameter("propertyURI"));
} else {
VClassDao vcdao = vreq.getFullWebappDaoFactory().getVClassDao();
if (vreq.getParameter("iffRoot") != null) {
classes = vcdao.getRootClasses();
} else {
classes = vcdao.getAllVclasses();
}
}
String json = new String();
int counter = 0;
String ontologyURI = vreq.getParameter("ontologyUri");
if (classes != null) {
Collections.sort(classes);
Iterator<VClass> classesIt = classes.iterator();
while (classesIt.hasNext()) {
if ( counter > 0 ) {
json += ", ";
}
VClass cls = (VClass) classesIt.next();
if ( (ontologyURI==null) || ( (ontologyURI != null) && (cls.getNamespace()!=null) && (ontologyURI.equals(cls.getNamespace())) ) ) {
if (cls.getName() != null)
try {
json += "{ \"name\": \"<a href='./vclassEdit?uri="+URLEncoder.encode(cls.getURI(),"UTF-8")+"'>"+cls.getLocalNameWithPrefix()+"</a>\", ";
} catch (Exception e) {
json += "{ \"name\": \"" + cls.getLocalNameWithPrefix() + "\", ";
}
else
json += "{ \"name\": \"\"";
String shortDef = (cls.getShortDef()==null) ? "" : cls.getShortDef();
json += "\"data\": { \"shortDef\": \"" + shortDef + "\", ";
// get group name
WebappDaoFactory wadf = vreq.getFullWebappDaoFactory();
VClassGroupDao groupDao= wadf.getVClassGroupDao();
String groupURI = cls.getGroupURI();
String groupName = "";
VClassGroup classGroup = null;
if(groupURI != null) {
classGroup = groupDao.getGroupByURI(groupURI);
if (classGroup!=null) {
groupName = classGroup.getPublicName();
}
}
json += "\"classGroup\": \"" + groupName + "\", ";
// get ontology name
OntologyDao ontDao = wadf.getOntologyDao();
String ontName = null;
try {
Ontology ont = ontDao.getOntologyByURI(cls.getNamespace());
ontName = ont.getName();
} catch (Exception e) {}
ontName = (ontName == null) ? "" : ontName;
json += "\"ontology\": \"" + ontName + "\"} }";
counter += 1;
}
}
body.put("jsonTree",json);
}
} catch (Throwable t) {
t.printStackTrace();
}
return new TemplateResponseValues(TEMPLATE_NAME, body);
}
}

View file

@ -282,9 +282,9 @@ public class MenuManagementController extends FreemarkerHttpServlet {
try{
String className = DataGetterUtils.getJClassForDataGetterURI(displayModel, dataGetterURI);
//TODO: Change so that instantiation here occurs correctly <-- how should data getter be instantiated
DataGetter pg = DataGetterUtils.dataGetterForURI(vreq.getDisplayModel(), dataGetterURI);
DataGetter pg = DataGetterUtils.dataGetterForURI(vreq, vreq.getDisplayModel(), dataGetterURI);
//TODO: Check template data variable and what that is?
Map<String, Object> pageData = pg.getData(getServletContext(), vreq, templateData);
Map<String, Object> pageData = pg.getData(templateData);
//Map<String, Object> pageInfo = vreq.getWebappDaoFactory().getPageDao().getPage(pageURI);
SelectDataGetterUtils.processAndRetrieveData(vreq, getServletContext(), pageData, className, templateData);
} catch(Exception ex) {

View file

@ -23,7 +23,6 @@ import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.Tem
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.utils.dataGetter.DataGetter;
import edu.cornell.mannlib.vitro.webapp.utils.dataGetter.DataGetterUtils;
import edu.cornell.mannlib.vitro.webapp.utils.pageDataGetter.PageDataGetterUtils;
/**
* Controller for getting data for pages defined in the display model.
*
@ -68,7 +67,7 @@ public class PageController extends FreemarkerHttpServlet{
//executePageDataGetters( pageUri, vreq, getServletContext(), mapForTemplate );
//these should all be data getters now
executeDataGetters( pageUri, vreq, getServletContext(), mapForTemplate);
executeDataGetters( pageUri, vreq, mapForTemplate);
mapForTemplate.putAll( getPageControllerValues( pageUri, vreq, getServletContext(), mapForTemplate));
@ -76,12 +75,12 @@ public class PageController extends FreemarkerHttpServlet{
return rv;
}
private void executeDataGetters(String pageUri, VitroRequest vreq, ServletContext context, Map<String, Object> mapForTemplate)
private void executeDataGetters(String pageUri, VitroRequest vreq, Map<String, Object> mapForTemplate)
throws Exception {
List<DataGetter> dgList = DataGetterUtils.getDataGettersForPage(vreq.getDisplayModel(), pageUri);
List<DataGetter> dgList = DataGetterUtils.getDataGettersForPage(vreq, vreq.getDisplayModel(), pageUri);
for( DataGetter dg : dgList){
Map<String,Object> moreData = dg.getData(context,vreq,mapForTemplate);
Map<String,Object> moreData = dg.getData(mapForTemplate);
if( moreData != null ){
mapForTemplate.putAll(moreData);
}

View file

@ -0,0 +1,247 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.vocabulary.OWL;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions;
import edu.cornell.mannlib.vitro.webapp.beans.Ontology;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailFactory;
import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
public class ShowClassHierarchyController extends FreemarkerHttpServlet {
private static final Log log = LogFactory.getLog(ShowClassHierarchyController.class.getName());
private static final String TEMPLATE_NAME = "siteAdmin-classHierarchy.ftl";
private int MAXDEPTH = 7;
private VClassDao vcDao = null;
private int previous_posn = 0;
private int childCount = 0;
private int uriCounter = 0;
@Override
protected Actions requiredActions(VitroRequest vreq) {
return SimplePermission.EDIT_ONTOLOGY.ACTIONS;
}
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
Map<String, Object> body = new HashMap<String, Object>();
try {
String displayOption = "";
if ( vreq.getParameter("displayOption") != null ) {
displayOption = vreq.getParameter("displayOption");
}
else {
displayOption = "asserted";
}
body.put("displayOption", displayOption);
boolean inferred = ( displayOption.equals("inferred") );
if ( inferred ) {
body.put("pageTitle", "Inferred Class Hierarchy");
}
else {
body.put("pageTitle", "Asserted Class Hierarchy");
}
if (vreq.getAssertionsWebappDaoFactory() != null && !inferred) {
vcDao = vreq.getAssertionsWebappDaoFactory().getVClassDao();
} else {
vcDao = vreq.getFullWebappDaoFactory().getVClassDao();
}
String json = new String();
String ontologyUri = vreq.getParameter("ontologyUri");
String startClassUri = vreq.getParameter("vclassUri");
List<VClass> roots = null;
if (ontologyUri != null) {
roots = vcDao.getOntologyRootClasses(ontologyUri);
} else if (startClassUri != null) {
roots = new LinkedList<VClass>();
roots.add(vcDao.getVClassByURI(startClassUri));
} else {
roots = vcDao.getRootClasses();
}
if (roots.isEmpty()) {
roots = new LinkedList<VClass>();
roots.add(vreq.getFullWebappDaoFactory().getVClassDao()
.getTopConcept());
}
Collections.sort(roots);
int counter = 0;
Iterator rootIt = roots.iterator();
if (!rootIt.hasNext()) {
VClass vcw = new VClass();
vcw.setName("<strong>No classes found.</strong>");
json += addVClassDataToResultsList(vreq.getFullWebappDaoFactory(), vcw,0,ontologyUri,counter);
} else {
while (rootIt.hasNext()) {
VClass root = (VClass) rootIt.next();
if (root != null) {
json += addChildren(vreq.getFullWebappDaoFactory(), root, 0, ontologyUri,counter,"parent");
counter += 1;
}
}
int length = json.length();
if ( length > 0 ) {
json += " }";
}
}
body.put("jsonTree",json);
} catch (Throwable t) {
t.printStackTrace();
}
return new TemplateResponseValues(TEMPLATE_NAME, body);
}
private String addChildren(WebappDaoFactory wadf, VClass parent, int position, String ontologyUri, int counter, String status) {
String rowElts = addVClassDataToResultsList(wadf, parent, position, ontologyUri, counter);
int childShift = (rowElts.length() > 0) ? 1 : 0; // if addVClassDataToResultsList filtered out the result, don't shift the children over
int length = rowElts.length();
String leaves = "";
leaves += rowElts;
List childURIstrs = vcDao.getSubClassURIs(parent.getURI());
if ((childURIstrs.size()>0) && position<MAXDEPTH) {
List childClasses = new ArrayList();
Iterator childURIstrIt = childURIstrs.iterator();
while (childURIstrIt.hasNext()) {
String URIstr = (String) childURIstrIt.next();
try {
VClass child = (VClass) vcDao.getVClassByURI(URIstr);
if (!child.getURI().equals(OWL.Nothing.getURI())) {
childClasses.add(child);
}
} catch (Exception e) {}
}
Collections.sort(childClasses);
Iterator childClassIt = childClasses.iterator();
while (childClassIt.hasNext()) {
VClass child = (VClass) childClassIt.next();
leaves += addChildren(wadf, child, position + childShift, ontologyUri, counter, "child");
if (!childClassIt.hasNext()) {
if ( ontologyUri == null ) {
leaves += " }] ";
}
else if ( ontologyUri != null && length > 0 ) {
// need this for when we show the classes associated with an ontology
String ending = leaves.substring(leaves.length() - 2, leaves.length());
if ( ending.equals("] ") ) {
log.debug("[1] leaves += }]");
leaves += "}]";
}
else if ( ending.equals(" [") ){
log.debug("[2] leaves += ]");
leaves += "] ";
}
else {
log.debug("[3] leaves += }]");
leaves += "}]";
}
}
}
}
}
else {
if ( ontologyUri == null ) {
leaves += "] ";
}
else if ( ontologyUri != null && length > 0 ) {
leaves += "] ";
}
}
return leaves;
}
private String addVClassDataToResultsList(WebappDaoFactory wadf, VClass vcw, int position, String ontologyUri, int counter) {
String tempString = "";
if (ontologyUri == null || ( (vcw.getNamespace()!=null) && (vcw.getNamespace().equals(ontologyUri)) ) ) {
// first if statement ensures that the first class begins with correct format
if ( counter < 1 && position < 1 ) {
tempString += "{ \"name\": ";
}
else if ( position == previous_posn ) {
tempString += "}, { \"name\": ";
}
else if ( position > previous_posn ) {
tempString += " { \"name\": ";
}
else if ( position < previous_posn ) {
tempString += "}, { \"name\": ";
}
try {
tempString += "\"<a href='vclassEdit?uri="+URLEncoder.encode(vcw.getURI(),"UTF-8")+"'>"+vcw.getLocalNameWithPrefix()+"</a>\", ";
} catch (Exception e) {
tempString += "\" " + ((vcw.getLocalNameWithPrefix() == null) ? "" : vcw.getLocalNameWithPrefix()) + "\", ";
}
tempString += "\"data\": { \"shortDef\": \"" + ((vcw.getShortDef() == null) ? "" : vcw.getShortDef()) + "\", ";
// Get group name if it exists
VClassGroupDao groupDao= wadf.getVClassGroupDao();
String groupURI = vcw.getGroupURI();
String groupName = null;
VClassGroup classGroup = null;
if(groupURI != null) {
classGroup = groupDao.getGroupByURI(groupURI);
if (classGroup != null) {
groupName = classGroup.getPublicName();
}
}
tempString += "\"classGroup\": \"" + ((groupName == null) ? "" : groupName) + "\", ";
// Get ontology name
String ontName = null;
try {
OntologyDao ontDao = wadf.getOntologyDao();
Ontology ont = ontDao.getOntologyByURI(vcw.getNamespace());
ontName = ont.getName();
} catch (Exception e) {}
tempString += "\"ontology\": \"" + ((ontName == null) ? "" : ontName) + "\"}, \"children\": [";
previous_posn = position;
}
return tempString;
}
}

View file

@ -13,7 +13,7 @@ import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.Template;
@ -27,8 +27,8 @@ public class TemplateProcessingHelper {
private HttpServletRequest request = null;
private ServletContext context = null;
public TemplateProcessingHelper(Configuration config, HttpServletRequest request, ServletContext context) {
this.config = config;
public TemplateProcessingHelper(HttpServletRequest request, ServletContext context) {
this.config = FreemarkerConfigurationLoader.getConfig(new VitroRequest(request));
this.request = request;
this.context = context;
}
@ -41,13 +41,6 @@ public class TemplateProcessingHelper {
return sw;
}
protected StringWriter processTemplate(ResponseValues values) throws TemplateProcessingException {
if (values == null) {
return null;
}
return processTemplate(values.getTemplateName(), values.getMap());
}
private void processTemplate(Template template, Map<String, Object> map, Writer writer)
throws TemplateProcessingException {
@ -72,18 +65,6 @@ public class TemplateProcessingHelper {
}
}
// For cases where we need a String instead of a StringWriter. StringWriter objects can be put in the template data model,
// but we can use this method from a jsp, for example.
public String processTemplateToString(String templateName, Map<String, Object> map)
throws TemplateProcessingException {
return processTemplate(templateName, map).toString();
}
protected String processTemplateToString(ResponseValues values)
throws TemplateProcessingException {
return processTemplate(values).toString();
}
private Template getTemplate(String templateName) throws TemplateProcessingException {
Template template = null;
try {

View file

@ -125,22 +125,20 @@ public class IndividualRdfAssembler {
}
newModel = getLabelAndTypes(entity, contextModel, newModel );
// get all the statements not covered by the object property / datatype property code above
// note implication that extendedLinkedData individuals will only be evaluated for the
// recognized object properties.
contextModel.enterCriticalSection(Lock.READ);
try {
StmtIterator iter = contextModel.listStatements(subj, (Property) null, (RDFNode) null);
while (iter.hasNext()) {
Statement stmt = iter.next();
if (!newModel.contains(stmt)) {
newModel.add(stmt);
}
}
} finally {
contextModel.leaveCriticalSection();
}
//bdc34: The following code adds all triples where entity is the Subject.
// contextModel.enterCriticalSection(Lock.READ);
// try {
// StmtIterator iter = contextModel.listStatements(subj, (Property) null, (RDFNode) null);
// while (iter.hasNext()) {
// Statement stmt = iter.next();
// if (!newModel.contains(stmt)) {
// newModel.add(stmt);
// }
// }
// } finally {
// contextModel.leaveCriticalSection();
// }
if (recurseDepth == 0 && includes != null && entity.isVClass(PERSON_CLASS_URI)) {

View file

@ -73,7 +73,7 @@ import edu.cornell.mannlib.vitro.webapp.dao.jena.VitroJenaModelMaker;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VitroJenaSDBModelMaker;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VitroJenaSpecialModelMaker;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent;
import edu.cornell.mannlib.vitro.webapp.servlet.setup.JenaDataSourceSetup;
import edu.cornell.mannlib.vitro.webapp.servlet.setup.WebappDaoSDBSetup;
import edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryUtils;
import edu.cornell.mannlib.vitro.webapp.utils.jena.JenaIngestUtils;
import edu.cornell.mannlib.vitro.webapp.utils.jena.JenaIngestUtils.MergeResult;
@ -942,7 +942,7 @@ public class JenaIngestController extends BaseEditController {
log.debug("Connecting to DB at "+jdbcUrl);
StoreDesc storeDesc = new StoreDesc(LayoutType.LayoutTripleNodesHash,dbTypeObj) ;
ServletContext ctx = vreq.getSession().getServletContext();
BasicDataSource bds = JenaDataSourceSetup.makeBasicDataSource(
BasicDataSource bds = WebappDaoSDBSetup.makeBasicDataSource(
driver, jdbcUrl, username, password, ctx);
try {
VitroJenaSDBModelMaker vsmm = new VitroJenaSDBModelMaker(storeDesc, bds);

View file

@ -0,0 +1,39 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.utils.pageDataGetter.PageDataGetterUtils;
/**
* Gets data based on data getter for page uri and returns in the form of Json objects
*/
public class GetDataForPage extends JsonObjectProducer {
private static final Log log = LogFactory.getLog(GetDataForPage.class);
protected GetDataForPage(VitroRequest vreq) {
super(vreq);
}
@Override
protected JSONObject process() throws Exception {
JSONObject rObj = null;
String pageUri = vreq.getParameter("pageUri");
if(pageUri != null && !pageUri.isEmpty()) {
Map<String,Object> data = PageDataGetterUtils.getDataForPage(pageUri, vreq, ctx);
//Convert to json version based on type of page
if(data != null) {
//Convert to json version based on type of page
rObj = PageDataGetterUtils.covertDataToJSONForPage(pageUri, data, vreq, ctx);
}
}
return rObj;
}
}

View file

@ -0,0 +1,125 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import static edu.cornell.mannlib.vitro.webapp.controller.json.JsonServlet.REPLY_SIZE;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
/**
* Gets a list of entities that are members of the indicated vClass.
*
* If the list is large then we will pass some token indicating that there is more
* to come. The results are sent back in 250 entity blocks. To get all of the
* entities for a VClass just keep requesting lists until there are not more
* continue tokens.
*
* If there are more entities the last item on the returned array will be an object
* with no id property. It will look like this:
*
* {"resultGroup":0,
* "resultKey":"2WEK2306",
* "nextUrl":"http://caruso.mannlib.cornell.edu:8080/vitro/dataservice?getEntitiesByVClass=1&resultKey=2WEK2306&resultGroup=1&vclassId=null",
* "entsInVClass":1752,
* "nextResultGroup":1,
* "standardReplySize":256}
*
*/
public class GetEntitiesByVClass extends JsonArrayProducer {
private static final Log log = LogFactory.getLog(GetEntitiesByVClass.class);
protected GetEntitiesByVClass(VitroRequest vreq) {
super(vreq);
}
@Override
protected JSONArray process() throws ServletException {
log.debug("in getEntitiesByVClass()");
String vclassURI = vreq.getParameter("vclassURI");
WebappDaoFactory daos = vreq.getFullWebappDaoFactory();
if( vclassURI == null ){
throw new ServletException("getEntitiesByVClass(): no value for 'vclassURI' found in the HTTP request");
}
VClass vclass = daos.getVClassDao().getVClassByURI( vclassURI );
if( vclass == null ){
throw new ServletException("getEntitiesByVClass(): could not find vclass for uri '"+ vclassURI + "'");
}
List<Individual> entsInVClass = daos.getIndividualDao().getIndividualsByVClass( vclass );
if( entsInVClass == null ){
throw new ServletException("getEntitiesByVClass(): null List<Individual> retruned by getIndividualsByVClass() for "+vclassURI);
}
int numberOfEntsInVClass = entsInVClass.size();
List<Individual> entsToReturn = new ArrayList<Individual>( REPLY_SIZE );
String requestHash = null;
int count = 0;
boolean more = false;
/* we have a large number of items to send back so we need to stash the list in the session scope */
if( entsInVClass.size() > REPLY_SIZE){
more = true;
HttpSession session = vreq.getSession(true);
requestHash = Integer.toString((vclassURI + System.currentTimeMillis()).hashCode());
session.setAttribute(requestHash, entsInVClass );
ListIterator<Individual> entsFromVclass = entsInVClass.listIterator();
while ( entsFromVclass.hasNext() && count < REPLY_SIZE ){
entsToReturn.add( entsFromVclass.next());
entsFromVclass.remove();
count++;
}
if( log.isDebugEnabled() ){ log.debug("getEntitiesByVClass(): Creating reply with continue token, found " + numberOfEntsInVClass + " Individuals"); }
}else{
if( log.isDebugEnabled() ) log.debug("getEntitiesByVClass(): sending " + numberOfEntsInVClass +" Individuals without continue token");
entsToReturn = entsInVClass;
count = entsToReturn.size();
}
//put all the entities on the JSON array
JSONArray ja = individualsToJson( entsToReturn );
//put the responseGroup number on the end of the JSON array
if( more ){
try{
JSONObject obj = new JSONObject();
obj.put("resultGroup", "true");
obj.put("size", count);
obj.put("total", numberOfEntsInVClass);
StringBuffer nextUrlStr = vreq.getRequestURL();
nextUrlStr.append("?")
.append("getEntitiesByVClass").append( "=1&" )
.append("resultKey=").append( requestHash );
obj.put("nextUrl", nextUrlStr.toString());
ja.put(obj);
}catch(JSONException je ){
throw new ServletException("unable to create continuation as JSON: " + je.getMessage());
}
}
log.debug("done with getEntitiesByVClass()");
return ja;
}
}

View file

@ -0,0 +1,96 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import static edu.cornell.mannlib.vitro.webapp.controller.json.JsonServlet.REPLY_SIZE;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
/**
*
*/
public class GetEntitiesByVClassContinuation extends JsonArrayProducer {
private static final Log log = LogFactory
.getLog(GetEntitiesByVClassContinuation.class);
protected GetEntitiesByVClassContinuation(VitroRequest vreq) {
super(vreq);
}
@Override
protected JSONArray process() throws ServletException {
log.debug("in getEntitiesByVClassContinuation()");
String resKey = vreq.getParameter("resultKey");
if( resKey == null )
throw new ServletException("Could not get resultKey");
HttpSession session = vreq.getSession();
if( session == null )
throw new ServletException("there is no session to get the pervious results from");
@SuppressWarnings("unchecked")
List<Individual> entsInVClass = (List<Individual>) session.getAttribute(resKey);
if( entsInVClass == null )
throw new ServletException("Could not find List<Individual> for resultKey " + resKey);
List<Individual> entsToReturn = new ArrayList<Individual>(REPLY_SIZE);
boolean more = false;
int count = 0;
/* we have a large number of items to send back so we need to stash the list in the session scope */
if( entsInVClass.size() > REPLY_SIZE){
more = true;
ListIterator<Individual> entsFromVclass = entsInVClass.listIterator();
while ( entsFromVclass.hasNext() && count <= REPLY_SIZE ){
entsToReturn.add( entsFromVclass.next());
entsFromVclass.remove();
count++;
}
if( log.isDebugEnabled() ) log.debug("getEntitiesByVClassContinuation(): Creating reply with continue token," +
" sending in this reply: " + count +", remaing to send: " + entsInVClass.size() );
} else {
//send out reply with no continuation
entsToReturn = entsInVClass;
count = entsToReturn.size();
session.removeAttribute(resKey);
if( log.isDebugEnabled()) log.debug("getEntitiesByVClassContinuation(): sending " + count + " Ind without continue token");
}
//put all the entities on the JSON array
JSONArray ja = individualsToJson( entsToReturn );
//put the responseGroup number on the end of the JSON array
if( more ){
try{
JSONObject obj = new JSONObject();
obj.put("resultGroup", "true");
obj.put("size", count);
StringBuffer nextUrlStr = vreq.getRequestURL();
nextUrlStr.append("?")
.append("getEntitiesByVClass").append( "=1&" )
.append("resultKey=").append( resKey );
obj.put("nextUrl", nextUrlStr.toString());
ja.put(obj);
}catch(JSONException je ){
throw new ServletException(je.getMessage());
}
}
log.debug("done with getEntitiesByVClassContinuation()");
return ja;
}
}

View file

@ -0,0 +1,79 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewService;
import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewService.ShortViewContext;
import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewServiceSetup;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.IndividualTemplateModel;
/**
* Does a Solr search for individuals, and uses the short view to render each of
* the results.
*/
public class GetRenderedSolrIndividualsByVClass extends JsonObjectProducer {
private static final Log log = LogFactory
.getLog(GetRenderedSolrIndividualsByVClass.class);
protected GetRenderedSolrIndividualsByVClass(VitroRequest vreq) {
super(vreq);
}
/**
* Search for individuals by VClass. The class URI and the paging
* information are in the request parameters.
*/
@Override
protected JSONObject process() throws Exception {
JSONObject rObj = null;
VClass vclass = getVclassParameter(vreq);
String vclassId = vclass.getURI();
vreq.setAttribute("displayType", vclassId);
rObj = JsonServlet.getSolrIndividualsByVClass(vclassId, vreq, ctx);
addShortViewRenderings(rObj);
return rObj;
}
/**
* Look through the return object. For each individual, render the short
* view and insert the resulting HTML into the object.
*/
private void addShortViewRenderings(JSONObject rObj) throws JSONException {
JSONArray individuals = rObj.getJSONArray("individuals");
String vclassName = rObj.getJSONObject("vclass").getString("name");
for (int i = 0; i < individuals.length(); i++) {
JSONObject individual = individuals.getJSONObject(i);
individual.put("shortViewHtml",
renderShortView(individual.getString("URI"), vclassName));
}
}
private String renderShortView(String individualUri, String vclassName) {
IndividualDao iDao = vreq.getWebappDaoFactory().getIndividualDao();
Individual individual = iDao.getIndividualByURI(individualUri);
Map<String, Object> modelMap = new HashMap<String, Object>();
modelMap.put("individual",
new IndividualTemplateModel(individual, vreq));
modelMap.put("vclass", vclassName);
ShortViewService svs = ShortViewServiceSetup.getService(ctx);
return svs.renderShortView(individual, ShortViewContext.BROWSE,
modelMap, vreq);
}
}

View file

@ -0,0 +1,42 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
/**
*
*/
public class GetSolrIndividualsByVClass extends JsonObjectProducer {
private static final Log log = LogFactory
.getLog(GetSolrIndividualsByVClass.class);
protected GetSolrIndividualsByVClass(VitroRequest vreq) {
super(vreq);
}
@Override
protected JSONObject process() throws Exception {
VClass vclass=null;
String vitroClassIdStr = vreq.getParameter("vclassId");
if ( vitroClassIdStr != null && !vitroClassIdStr.isEmpty()){
vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vitroClassIdStr);
if (vclass == null) {
log.debug("Couldn't retrieve vclass ");
throw new Exception ("Class " + vitroClassIdStr + " not found");
}
}else{
log.debug("parameter vclassId URI parameter expected ");
throw new Exception("parameter vclassId URI parameter expected ");
}
vreq.setAttribute("displayType", vitroClassIdStr);
return JsonServlet.getSolrIndividualsByVClass(vclass.getURI(), vreq, ctx);
}
}

View file

@ -0,0 +1,51 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
/**
* Accepts multiple vclasses and returns individuals which correspond to the
* intersection of those classes (i.e. have all those types)
*/
public class GetSolrIndividualsByVClasses extends JsonObjectProducer {
private static final Log log = LogFactory
.getLog(GetSolrIndividualsByVClasses.class);
public GetSolrIndividualsByVClasses(VitroRequest vreq) {
super(vreq);
}
@Override
protected JSONObject process() throws Exception {
log.debug("Executing retrieval of individuals by vclasses");
VClass vclass=null;
log.debug("Retrieving solr individuals by vclasses");
// Could have multiple vclass ids sent in
String[] vitroClassIdStr = vreq.getParameterValues("vclassId");
if ( vitroClassIdStr != null && vitroClassIdStr.length > 0){
for(String vclassId: vitroClassIdStr) {
log.debug("Iterating throug vclasses, using VClass " + vclassId);
vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vclassId);
if (vclass == null) {
log.error("Couldn't retrieve vclass ");
throw new Exception ("Class " + vclassId + " not found");
}
}
}else{
log.error("parameter vclassId URI parameter expected but not found");
throw new Exception("parameter vclassId URI parameter expected ");
}
List<String> vclassIds = Arrays.asList(vitroClassIdStr);
return JsonServlet.getSolrIndividualsByVClasses(vclassIds, vreq, ctx);
}
}

View file

@ -0,0 +1,56 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache;
/**
*
*/
public class GetVClassesForVClassGroup extends JsonObjectProducer {
private static final Log log = LogFactory
.getLog(GetVClassesForVClassGroup.class);
public GetVClassesForVClassGroup(VitroRequest vreq) {
super(vreq);
}
@Override
protected JSONObject process() throws Exception {
JSONObject map = new JSONObject();
String vcgUri = vreq.getParameter("classgroupUri");
if( vcgUri == null ){
throw new Exception("no URI passed for classgroupUri");
}
VClassGroupCache vcgc = VClassGroupCache.getVClassGroupCache(ctx);
VClassGroup vcg = vcgc.getGroup(vcgUri);
if( vcg == null ){
throw new Exception("Could not find vclassgroup: " + vcgUri);
}
ArrayList<JSONObject> classes = new ArrayList<JSONObject>(vcg.size());
for( VClass vc : vcg){
JSONObject vcObj = new JSONObject();
vcObj.put("name", vc.getName());
vcObj.put("URI", vc.getURI());
vcObj.put("entityCount", vc.getEntityCount());
classes.add(vcObj);
}
map.put("classes", classes);
map.put("classGroupName", vcg.getPublicName());
map.put("classGroupUri", vcg.getURI());
return map;
}
}

View file

@ -0,0 +1,60 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
/**
* A base for classes that produce a JSON array based on the parameters in the
* VitroRequest.
*
* Catches any exceptions. Logs the error and returns an empty JSON array.
*/
public abstract class JsonArrayProducer extends JsonProducer {
private static final Log log = LogFactory.getLog(JsonArrayProducer.class);
protected final VitroRequest vreq;
protected final ServletContext ctx;
protected JsonArrayProducer(VitroRequest vreq) {
this.vreq = vreq;
this.ctx = vreq.getSession().getServletContext();
}
/**
* Sub-classes implement this method. Given the request, produce a JSON
* object as the result.
*/
protected abstract JSONArray process() throws Exception;
public final void process(HttpServletResponse resp) throws IOException {
JSONArray jsonArray = null;
try {
jsonArray = process();
} catch (Exception e) {
log.error("Failed to create JSON response" + e);
resp.setStatus(500 /* HttpURLConnection.HTTP_SERVER_ERROR */);
}
if (jsonArray == null) {
jsonArray = new JSONArray();
}
log.debug("Response to JSON request: " + jsonArray.toString());
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
Writer writer = resp.getWriter();
writer.write(jsonArray.toString());
}
}

View file

@ -0,0 +1,76 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
/**
* A base for classes that produce a JSON object, based on the parameters in the
* request.
*
* The result is never empty. At worst, it is an object that contains only an
* "errorMessage" field.
*
* If an exception occurrs during processing, The "errorMessage" field will
* contain the exception message and the response status will be set to 500
* (server error). Normally, "errorMessage" will be empty, and the status will
* default to 200 (OK).
*/
public abstract class JsonObjectProducer extends JsonProducer {
private static final Log log = LogFactory.getLog(JsonObjectProducer.class);
protected final VitroRequest vreq;
protected final ServletContext ctx;
protected JsonObjectProducer(VitroRequest vreq) {
this.vreq = vreq;
this.ctx = vreq.getSession().getServletContext();
}
/**
* Sub-classes implement this method. Given the request, produce a JSON
* object as the result.
*/
protected abstract JSONObject process() throws Exception;
public final void process(HttpServletResponse resp) throws IOException {
JSONObject jsonObject = null;
String errorMessage = "";
try {
jsonObject = process();
} catch (Exception e) {
log.error("Failed to create JSON response" + e);
errorMessage = e.toString();
resp.setStatus(500 /* HttpURLConnection.HTTP_SERVER_ERROR */);
}
if (jsonObject == null) {
jsonObject = new JSONObject();
}
log.debug("Response to JSON request: " + jsonObject.toString());
try {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
Writer writer = resp.getWriter();
jsonObject.put("errorMessage", errorMessage);
writer.write(jsonObject.toString());
} catch (JSONException e) {
log.error(e, e);
}
}
}

View file

@ -0,0 +1,89 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
/**
* A base for the classes that produce JSON results. Contains some useful constants and convenience methods.
*/
public abstract class JsonProducer {
private static final Log log = LogFactory.getLog(JsonProducer.class);
/**
* Process a list of Individuals into a JSON array that holds the Names and URIs.
*/
protected JSONArray individualsToJson(List<Individual> individuals) throws ServletException {
try{
JSONArray ja = new JSONArray();
for (Individual ent: individuals) {
JSONObject entJ = new JSONObject();
entJ.put("name", ent.getName());
entJ.put("URI", ent.getURI());
ja.put( entJ );
}
return ja;
}catch(JSONException ex){
throw new ServletException("could not convert list of Individuals into JSON: " + ex);
}
}
/**
* Get the "vclassId" parameter from the request and instantiate the VClass.
*
* There must be one, and it must be valid.
*/
protected VClass getVclassParameter(VitroRequest vreq) {
String vclassId = vreq.getParameter("vclassId");
if (StringUtils.isEmpty(vclassId)) {
log.error("parameter vclassId expected but not found");
throw new IllegalStateException("parameter vclassId expected ");
}
return instantiateVclass(vclassId, vreq);
}
/**
* Get one or more "vclassId" parameters from the request. Confirm that
* there is at least one, and that all are valid.
*
* Return value is never null and never empty.
*/
protected List<String> getVclassIds(VitroRequest vreq) {
String[] vclassIds = vreq.getParameterValues("vclassId");
if ((vclassIds == null) || (vclassIds.length == 0)) {
log.error("parameter vclassId expected but not found");
throw new IllegalStateException("parameter vclassId expected ");
}
for (String vclassId : vclassIds) {
instantiateVclass(vclassId, vreq);
}
return Arrays.asList(vclassIds);
}
private VClass instantiateVclass(String uri, VitroRequest vreq) {
VClass vclass = vreq.getWebappDaoFactory().getVClassDao()
.getVClassByURI(uri);
if (vclass == null) {
log.error("Couldn't retrieve vclass ");
throw new IllegalStateException("Class " + uri + " not found");
}
return vclass;
}
}

View file

@ -0,0 +1,141 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.IndividualListController;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.utils.log.LogUtils;
import edu.cornell.mannlib.vitro.webapp.utils.pageDataGetter.PageDataGetterUtils;
/**
* This servlet is for servicing requests for JSON objects/data.
* It could be generalized to get other types of data ex. XML, HTML etc
* @author bdc34
*
* Moved most of the logic into a group of JsonProducer classes. jeb228
*/
public class JsonServlet extends VitroHttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(JsonServlet.class);
private static final int INDIVIDUALS_PER_PAGE = 30;
public static final int REPLY_SIZE = 256;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
log.debug(LogUtils.formatRequestProperties(log, "debug", req));
VitroRequest vreq = new VitroRequest(req);
if (vreq.getParameter("getEntitiesByVClass") != null) {
if( vreq.getParameter("resultKey") == null) {
new GetEntitiesByVClass(vreq).process(resp);
} else {
new GetEntitiesByVClassContinuation(vreq).process(resp);
}
}else if( vreq.getParameter("getN3EditOptionList") != null ){
throw new IllegalArgumentException("The call invoked deprecated classes " +
"and the parameter for this call appeared nowhere in the code base, " +
"so it was removed in May, 2012.");
}else if( vreq.getParameter("getSolrIndividualsByVClass") != null ){
new GetSolrIndividualsByVClass(vreq).process(resp);
}else if( vreq.getParameter("getVClassesForVClassGroup") != null ){
new GetVClassesForVClassGroup(vreq).process(resp);
} else if( vreq.getParameter("getSolrIndividualsByVClasses") != null ){
log.debug("AJAX request to retrieve individuals by vclasses");
new GetSolrIndividualsByVClasses(vreq).process(resp);
} else if( vreq.getParameter("getDataForPage") != null ){
new GetDataForPage(vreq).process(resp);
}else if( vreq.getParameter("getRenderedSolrIndividualsByVClass") != null ){
new GetRenderedSolrIndividualsByVClass(vreq).process(resp);
}
}
public static JSONObject getSolrIndividualsByVClass(String vclassURI, HttpServletRequest req, ServletContext context) throws Exception {
List<String> vclassURIs = Collections.singletonList(vclassURI);
VitroRequest vreq = new VitroRequest(req);
Map<String, Object> map = getSolrVClassIntersectionResults(vclassURIs, vreq, context);
//last parameter indicates single vclass instead of multiple vclasses
return processVClassResults(map, vreq, context, false);
}
public static JSONObject getSolrIndividualsByVClasses(List<String> vclassURIs, HttpServletRequest req, ServletContext context) throws Exception {
VitroRequest vreq = new VitroRequest(req);
log.debug("Retrieve solr results for vclasses" + vclassURIs.toString());
Map<String, Object> map = getSolrVClassIntersectionResults(vclassURIs, vreq, context);
log.debug("Results returned from Solr for " + vclassURIs.toString() + " are of size " + map.size());
JSONObject rObj = processVClassResults(map, vreq, context, true);
return rObj;
}
//Including version for Solr query for Vclass Intersections
private static Map<String,Object> getSolrVClassIntersectionResults(List<String> vclassURIs, VitroRequest vreq, ServletContext context){
log.debug("Retrieving Solr intersection results for " + vclassURIs.toString());
String alpha = IndividualListController.getAlphaParameter(vreq);
int page = IndividualListController.getPageParameter(vreq);
log.debug("Alpha and page parameters are " + alpha + " and " + page);
Map<String,Object> map = null;
try {
map = IndividualListController.getResultsForVClassIntersections(
vclassURIs,
page, INDIVIDUALS_PER_PAGE,
alpha,
vreq.getWebappDaoFactory().getIndividualDao(),
context);
} catch(Exception ex) {
log.error("Error in retrieval of search results for VClass " + vclassURIs.toString(), ex);
}
return map;
}
// Map given to process method includes the actual individuals returned from the search
public static JSONObject processVClassResults(Map<String, Object> map, VitroRequest vreq, ServletContext context, boolean multipleVclasses) throws Exception{
JSONObject rObj = PageDataGetterUtils.processVclassResultsJSON(map, vreq, multipleVclasses);
return rObj;
}
public static Collection<String> getMostSpecificTypes(Individual individual, WebappDaoFactory wdf) {
ObjectPropertyStatementDao opsDao = wdf.getObjectPropertyStatementDao();
Map<String, String> mostSpecificTypes = opsDao.getMostSpecificTypesInClassgroupsForIndividual(individual.getURI());
return mostSpecificTypes.values();
}
public static String getDataPropertyValue(Individual ind, DataProperty dp, WebappDaoFactory wdf){
String value = ind.getDataValue(dp.getURI());
if( value == null || value.isEmpty() )
return "";
else
return value;
}
}

View file

@ -18,7 +18,6 @@ import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServ
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.TemplateProcessingHelper.TemplateProcessingException;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State;
import freemarker.template.Configuration;
/**
* A temporary means of displaying the Login templates within the SiteAdmin
@ -164,13 +163,11 @@ public class LoginTemplateHelper extends LoginTemplateHelperBase {
*/
private String doTemplate(VitroRequest vreq, TemplateResponseValues values) throws TemplateProcessingException {
// Set it up like FreeMarkerHttpServlet.doGet() would do.
Configuration config = getConfig(vreq);
Map<String, Object> map = new HashMap<String, Object>();
map.putAll(getPageTemplateValues(vreq));
map.putAll(values.getMap());
return processTemplateToString(values.getTemplateName(), map, config, vreq);
return processTemplateToString(values.getTemplateName(), map, vreq);
}
/**

View file

@ -368,11 +368,6 @@ public class IndividualFiltering implements Individual {
public boolean isVClass(String uri) {
return _innerIndividual.isVClass(uri);
}
@Override
public boolean isMemberOfClassProhibitedFromSearch(ProhibitedFromSearch pfs) {
return _innerIndividual.isMemberOfClassProhibitedFromSearch(pfs);
}
@Override
public void setDataPropertyMap(Map<String, DataProperty> propertyMap) {

View file

@ -28,7 +28,6 @@ import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.shared.Lock;
import com.hp.hpl.jena.util.iterator.ClosableIterator;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
@ -41,7 +40,6 @@ import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.filestorage.model.ImageInfo;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
public class IndividualJena extends IndividualImpl implements Individual {
@ -508,30 +506,6 @@ public class IndividualJena extends IndividualImpl implements Individual {
}
return false;
}
@Override
public boolean isMemberOfClassProhibitedFromSearch(ProhibitedFromSearch pfs) {
ind.getModel().enterCriticalSection(Lock.READ);
try {
StmtIterator stmtIt = ind.listProperties(RDF.type);
try {
while(stmtIt.hasNext()) {
Statement stmt = stmtIt.nextStatement();
if (stmt.getObject().isURIResource()) {
String typeURI = ((Resource)stmt.getObject()).getURI();
if (pfs.isClassProhibitedFromSearch(typeURI)) {
return true;
}
}
}
} finally {
stmtIt.close();
}
return false;
} finally {
ind.getModel().leaveCriticalSection();
}
}
/**
* Overriding the base method so that we can do the sorting by arbitrary property here. An

View file

@ -53,7 +53,6 @@ import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactorySDB.SDBDatasetMode;
import edu.cornell.mannlib.vitro.webapp.filestorage.model.ImageInfo;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
public class IndividualSDB extends IndividualImpl implements Individual {
@ -876,22 +875,6 @@ public class IndividualSDB extends IndividualImpl implements Individual {
return false;
}
@Override
public boolean isMemberOfClassProhibitedFromSearch(ProhibitedFromSearch pfs) {
List<VClass> types = getVClasses(false);
Iterator<VClass> itr = types.iterator();
while(itr.hasNext()) {
String typeURI = itr.next().getURI();
if (pfs.isClassProhibitedFromSearch(typeURI)) {
return true;
}
}
return false;
}
/**
* Overriding the base method so that we can do the sorting by arbitrary property here. An
* IndividualSDB has a reference back to the model; everything else is just a dumb bean (for now).

View file

@ -7,6 +7,8 @@ import javax.servlet.ServletContext;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.ModelChangedListener;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
public class ModelContext {
private static final String ONT_MODEL_SELECTOR = "ontModelSelector";
@ -106,4 +108,10 @@ public class ModelContext {
}
public static OntModel getDisplayModel(ServletContext ctx){
return(OntModel) ctx.getAttribute( DisplayVocabulary.DISPLAY_ONT_MODEL );
}
public static void setDisplayModel(OntModel ontModel, ServletContext ctx){
ctx.setAttribute(DisplayVocabulary.DISPLAY_ONT_MODEL,ontModel);
}
}

View file

@ -1,600 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.elements;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerConfiguration;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import freemarker.template.Configuration;
/**
* This is intended to work in conjunction with a template to create the HTML for a
* datetime with precision and to convert the submitted parameters into
* varname -> Literal and varname -> URI maps.
*
* The variables that get passed to the template are defined in:
* DateTimeWithPrecision.getMapForTemplate()
*
* Two variables will be defined for the N3 edit graphs (These are NOT variables passed to FM templates):
* $fieldname.precision - URI of datetime precision
* $fieldname.value - DateTime literal
*
*/
public class DateTimeWithPrecision extends BaseEditElement {
String fieldName;
/**
* This is the minimum datetime precision that this element
* will accept. If the parameters submitted do not meet this
* requirement, then a validation error will be created.
*/
VitroVocabulary.Precision minimumPrecision;
/**
* This is the maximum precision that the form should
* allow the user to enter. This value is not used by
* DateTimeWithPrecision for validation, it is only passed
* to the template. This should be removed when it can be
* specified in a ftl file.
*
* This could be thought of as the maximum precision to display.
*/
VitroVocabulary.Precision displayRequiredLevel;
VitroVocabulary.Precision DEFAULT_MIN_PRECISION = VitroVocabulary.Precision.DAY;
VitroVocabulary.Precision DEFAULT_DISPLAY_LEVEL = VitroVocabulary.Precision.DAY;
VitroVocabulary.Precision[] precisions = VitroVocabulary.Precision.values();
protected static final String BLANK_SENTINEL = ">SUBMITTED VALUE WAS BLANK<";
public DateTimeWithPrecision(Field field) {
super(field);
fieldName = field.getName();
minimumPrecision = DEFAULT_MIN_PRECISION;
displayRequiredLevel = DEFAULT_DISPLAY_LEVEL;
}
public DateTimeWithPrecision(Field field, VitroVocabulary.Precision minimumPrecision){
this(field);
if( minimumPrecision != null )
this.minimumPrecision = minimumPrecision;
else
this.minimumPrecision = DEFAULT_MIN_PRECISION;
this.displayRequiredLevel = this.minimumPrecision;
}
//it would be nice to have only the version of the constructor that takes the enum
//but this is to quickly get the JSP configuration working.
public DateTimeWithPrecision(Field field, String minimumPrecisionURI, String displayRequiredLevelUri){
this(field);
this.minimumPrecision = toPrecision( minimumPrecisionURI);
if( this.minimumPrecision == null )
throw new IllegalArgumentException(minimumPrecisionURI
+" is not a valid precision for minimumPrecision, see VitroVocabulary.Precision");
this.displayRequiredLevel = toPrecision( displayRequiredLevelUri );
if( this.displayRequiredLevel == null )
throw new IllegalArgumentException(displayRequiredLevelUri
+" is not a valid precision for displayRequiredLevel, see VitroVocabulary.Precision");
// if( this.displayRequiredLevel.ordinal() < this.minimumPrecision.ordinal() ){
// throw new IllegalArgumentException("the display precision level " + this.displayRequiredLevel
// + " is less precise than the required minimum precision of " + this.minimumPrecision);
// }
}
private static final Log log = LogFactory.getLog(DateTimeWithPrecision.class);
protected String TEMPLATE_NAME = "dateTimeWithPrecision.ftl";
@Override
public String draw(String fieldName, EditConfiguration editConfig,
EditSubmission editSub, Configuration fmConfig) {
Map map = getMapForTemplate( editConfig, editSub);
return merge( fmConfig, TEMPLATE_NAME, map);
}
/**
* This produces a map for use in the template.
*/
protected Map getMapForTemplate(EditConfiguration editConfig, EditSubmission editSub) {
Map<String,Object>map = new HashMap<String,Object>();
//always need the fieldName, required precision, and constants
map.put("fieldName", fieldName);
addPrecisionConstants(map);
map.put("minimumPrecision", minimumPrecision.uri());
map.put("requiredLevel", displayRequiredLevel.uri());
String precisionUri = getPrecision(editConfig,editSub);
VitroVocabulary.Precision existingPrec = toPrecision(precisionUri);
if( precisionUri != null && !"".equals(precisionUri) && existingPrec == null ){
log.error("field " + fieldName + ": existing precision uri was " +
"'" + precisionUri + "' but could not convert to Precision object");
}
if( precisionUri == null || precisionUri.isEmpty() || existingPrec == null){
map.put("existingPrecision", "");
/* no precision so there should also be no datetime */
DateTime value = getTimeValue(editConfig,editSub);
if( value != null )
log.info("Unexpected state: Precision for " + fieldName
+ " was '" + precisionUri + "' but date time was " + value);
map.put("year", "");
map.put("month", "");
map.put("day", "");
map.put("hour", "");
map.put("minute", "");
map.put("second", "") ;
} else if( VitroVocabulary.Precision.NONE.uri().equals(precisionUri) ){
//bdc34: not sure what to do with the NONE precision
map.put("existingPrecision", precisionUri);
map.put("year", "");
map.put("month", "");
map.put("day", "");
map.put("hour", "");
map.put("minute", "");
map.put("second", "") ;
}else{
map.put("existingPrecision", precisionUri);
DateTime value = getTimeValue(editConfig,editSub);
/* This is the case where there is a precision so there should be a datetime */
if( value == null )
log.error("Field " + fieldName + " has precision " + precisionUri
+ " but the date time is " + value);
/* only put the values in the map for ones which are significant based on the precision */
if( existingPrec.ordinal() >= VitroVocabulary.Precision.SECOND.ordinal() )
map.put("second", Integer.toString(value.getSecondOfMinute() )) ;
else
map.put("second", "");
if( existingPrec.ordinal() >= VitroVocabulary.Precision.MINUTE.ordinal() )
map.put("minute", Integer.toString(value.getMinuteOfHour()) );
else
map.put("minute", "");
if( existingPrec.ordinal() >= VitroVocabulary.Precision.HOUR.ordinal() )
map.put("hour", Integer.toString(value.getHourOfDay()) );
else
map.put("hour", "");
if( existingPrec.ordinal() >= VitroVocabulary.Precision.DAY.ordinal() )
map.put("day", Integer.toString(value.getDayOfMonth()) );
else
map.put("day", "");
if( existingPrec.ordinal() >= VitroVocabulary.Precision.MONTH.ordinal() )
map.put("month", Integer.toString(value.getMonthOfYear()));
else
map.put("month", "");
if( existingPrec.ordinal() >= VitroVocabulary.Precision.YEAR.ordinal() )
map.put("year", Integer.toString(value.getYear()));
else
map.put("year", "");
}
return map;
}
/** Adds precisionURIs for use by the templates */
private void addPrecisionConstants(Map<String,Object> map){
Map<String,Object> constants = new HashMap<String,Object>();
for( VitroVocabulary.Precision pc: VitroVocabulary.Precision.values()){
constants.put(pc.name().toLowerCase(),pc.uri());
}
map.put("precisionConstants", constants);
}
/**
* Gets the currently set precision. May return null.
*/
private String getPrecision(EditConfiguration editConfig, EditSubmission editSub) {
if( editSub != null ){
String submittedPrecisionURI = editSub.getUrisFromForm().get( getPrecisionVariableName() );
if( submittedPrecisionURI != null ){
return submittedPrecisionURI;
}
}
String existingPrecisionURI = editConfig.getUrisInScope().get( getPrecisionVariableName() );
if( existingPrecisionURI != null ){
return existingPrecisionURI;
}else{
return null;
}
}
private DateTime getTimeValue(EditConfiguration editConfig, EditSubmission editSub) {
if( editSub != null ){
Literal submittedValue = editSub.getLiteralsFromForm().get( getValueVariableName() );
if( submittedValue != null )
return new DateTime( submittedValue.getLexicalForm() );
}
Literal dtValue = editConfig.getLiteralsInScope().get( getValueVariableName() );
if( dtValue != null ){
return new DateTime( dtValue.getLexicalForm() );
}else{
return null;
}
}
/**
* This gets the literals for a submitted form from the queryParmeters.
* It will only be called if getValidationErrors() doesn't return any errors.
*/
@Override
public Map<String, Literal> getLiterals(String fieldName,
EditConfiguration editConfig, Map<String, String[]> queryParameters) {
Map<String,Literal> literalMap = new HashMap<String,Literal>();
Literal datetime =getDateTime( queryParameters);
literalMap.put(fieldName+"-value", datetime);
return literalMap;
}
protected Literal getDateTime( Map<String, String[]> queryParameters ) {
String submittedPrec = BLANK_SENTINEL;
try {
submittedPrec = getSubmittedPrecision( queryParameters);
} catch (Exception e) {
log.error("could not get submitted precsion",e);
}
if( BLANK_SENTINEL.equals( submittedPrec ) )
return null;
Integer year = parseToInt(fieldName+"-year", queryParameters);
//this is the case where date has not been filled out at all.
if( year == null )
return null;
Integer month = parseToInt(fieldName+"-month", queryParameters);
if( month == null || month == 0 )
month = 1;
Integer day = parseToInt(fieldName+"-day", queryParameters);
if( day == null || day == 0 )
day = 1;
Integer hour = parseToInt(fieldName+"-hour", queryParameters);
if( hour == null )
hour = 0;
Integer minute = parseToInt(fieldName+"-minute", queryParameters);
if( minute == null )
minute = 0;
Integer second = parseToInt(fieldName+"-second", queryParameters);
if( second == null )
second = 0;
DateTime value = new DateTime(
year.intValue(),month.intValue(),day.intValue(),
hour.intValue(),minute.intValue(),second.intValue(),0/*millis*/
);
return ResourceFactory.createTypedLiteral(
ISODateTimeFormat.dateHourMinuteSecond().print(value), /*does not include timezone*/
XSDDatatype.XSDdateTime);
}
/**
* This gets the URIs for a submitted form from the queryParmeters.
* It will only be called if getValidationErrors() doesn't return any errors.
*/
@Override
public Map<String, String> getURIs(String fieldName,
EditConfiguration editConfig, Map<String, String[]> queryParameters) {
String precisionUri;
try {
precisionUri = getSubmittedPrecision( queryParameters);
} catch (Exception e) {
log.error("getURIs() should only be called on input that passed getValidationErrors()");
return Collections.emptyMap();
}
Map<String,String> uriMap = new HashMap<String,String>();
if( precisionUri != null )
uriMap.put(fieldName+"-precision", precisionUri);
return uriMap;
}
/**
* Precision is based on the values returned by the form. Throws an exception with
* the error message if the queryParameters cannot make a valid date/precision because
* there are values missing.
*/
protected String getSubmittedPrecision(Map<String, String[]> queryParameters) throws Exception {
Integer year = parseToInt(fieldName+"-year",queryParameters);
Integer month = parseToInt(fieldName+"-month",queryParameters);
Integer day = parseToInt(fieldName+"-day",queryParameters);
Integer hour = parseToInt(fieldName+"-hour",queryParameters);
Integer minute = parseToInt(fieldName+"-minute",queryParameters);
Integer second = parseToInt(fieldName+"-second",queryParameters);
Integer[] values = { year, month, day, hour, minute, second };
/* find the most significant date field that is null. */
int indexOfFirstNull= -1;
for(int i=0; i < values.length ; i++){
if( values[i] == null ){
indexOfFirstNull = i;
break;
}
}
/* the field wasn't filled out at all */
if( indexOfFirstNull == 0 )
//return VitroVocabulary.Precision.NONE.uri();
return BLANK_SENTINEL;
/* if they all had values then we have seconds precision */
if( indexOfFirstNull == -1 )
return VitroVocabulary.Precision.SECOND.uri();
/* check that there are no values after the most significant null field
* that are non-null. */
boolean nonNullAfterFirstNull=false;
for(int i=0; i < values.length ; i++){
if( i > indexOfFirstNull && values[i] != null ){
nonNullAfterFirstNull = true;
break;
}
}
if( nonNullAfterFirstNull )
throw new Exception("Invalid date-time value. When creating a date-time value, there cannot be gaps between any of the selected fields.");
else{
return precisions[ indexOfFirstNull ].uri();
}
}
@Override
public Map<String, String> getValidationMessages(String fieldName,
EditConfiguration editConfig, Map<String, String[]> queryParameters) {
Map<String,String> errorMsgMap = new HashMap<String,String>();
//check that any parameters we got are single values
String[] names = {"year","month","day","hour","minute","second", "precision"};
for( String name:names){
if ( !hasNoneOrSingle(fieldName+"-"+name, queryParameters))
errorMsgMap.put(fieldName+"-"+name, "must have only one value for " + name);
}
String precisionURI = null;
try{
precisionURI = getSubmittedPrecision( queryParameters);
}catch(Exception ex){
errorMsgMap.put(fieldName,ex.getMessage());
return errorMsgMap;
}
errorMsgMap.putAll(checkDate( precisionURI, queryParameters) );
return errorMsgMap;
}
/**
* This checks for invalid date times.
*/
final static String NON_INTEGER_YEAR = "must enter a valid year";
final static String NON_INTEGER_MONTH = "must enter a valid month";
final static String NON_INTEGER_DAY = "must enter a valid day";
final static String NON_INTEGER_HOUR = "must enter a valid hour";
final static String NON_INTEGER_MINUTE = "must enter a valid minute";
final static String NON_INTEGER_SECOND = "must enter a valid second";
private Map<String,String> checkDate( String precisionURI, Map<String, String[]> qp){
if( precisionURI == null )
return Collections.emptyMap();
Map<String,String> errors = new HashMap<String,String>();
Integer year,month,day,hour,minute,second;
//just check if the values for the precision parse to integers
if( precisionURI.equals(VitroVocabulary.Precision.YEAR.uri() ) ){
if( ! canParseToNumber(fieldName+"-year" ,qp))
errors.put(fieldName+"-year", NON_INTEGER_YEAR);
}else if( precisionURI.equals( VitroVocabulary.Precision.MONTH.uri() )){
if( ! canParseToNumber(fieldName+"-year" ,qp))
errors.put(fieldName+"-year", NON_INTEGER_YEAR);
if( ! canParseToNumber(fieldName+"-month" ,qp))
errors.put(fieldName+"-month", NON_INTEGER_MONTH);
}else if( precisionURI.equals( VitroVocabulary.Precision.DAY.uri() )){
if( ! canParseToNumber(fieldName+"-year" ,qp))
errors.put(fieldName+"-year", NON_INTEGER_YEAR);
if( ! canParseToNumber(fieldName+"-month" ,qp))
errors.put(fieldName+"-month", NON_INTEGER_MONTH);
if( ! canParseToNumber(fieldName+"-day" ,qp))
errors.put(fieldName+"-day", NON_INTEGER_DAY);
}else if( precisionURI.equals( VitroVocabulary.Precision.HOUR.uri() )){
if( ! canParseToNumber(fieldName+"-year" ,qp))
errors.put(fieldName+"-year", NON_INTEGER_YEAR);
if( ! canParseToNumber(fieldName+"-month" ,qp))
errors.put(fieldName+"-month", NON_INTEGER_MONTH);
if( ! canParseToNumber(fieldName+"-day" ,qp))
errors.put(fieldName+"-day", NON_INTEGER_DAY);
if( ! canParseToNumber(fieldName+"-hour" ,qp))
errors.put(fieldName+"-hour", NON_INTEGER_HOUR);
}else if( precisionURI.equals( VitroVocabulary.Precision.MINUTE.uri() )){
if( ! canParseToNumber(fieldName+"-year" ,qp))
errors.put(fieldName+"-year", NON_INTEGER_YEAR);
if( ! canParseToNumber(fieldName+"-month" ,qp))
errors.put(fieldName+"-month", NON_INTEGER_MONTH);
if( ! canParseToNumber(fieldName+"-day" ,qp))
errors.put(fieldName+"-day", NON_INTEGER_DAY);
if( ! canParseToNumber(fieldName+"-hour" ,qp))
errors.put(fieldName+"-hour", NON_INTEGER_HOUR);
if( ! canParseToNumber(fieldName+"-minute" ,qp))
errors.put(fieldName+"-minute", NON_INTEGER_HOUR);
}else if( precisionURI.equals( VitroVocabulary.Precision.SECOND.uri() )){
if( ! canParseToNumber(fieldName+"-year" ,qp))
errors.put(fieldName+"-year", NON_INTEGER_YEAR);
if( ! canParseToNumber(fieldName+"-month" ,qp))
errors.put(fieldName+"-month", NON_INTEGER_MONTH);
if( ! canParseToNumber(fieldName+"-day" ,qp))
errors.put(fieldName+"-day", NON_INTEGER_DAY);
if( ! canParseToNumber(fieldName+"-hour" ,qp))
errors.put(fieldName+"-hour", NON_INTEGER_HOUR);
if( ! canParseToNumber(fieldName+"-minute" ,qp))
errors.put(fieldName+"-minute", NON_INTEGER_HOUR);
if( ! canParseToNumber(fieldName+"-second" ,qp))
errors.put(fieldName+"-second", NON_INTEGER_SECOND);
}
//check if we can make a valid date with these integers
year = parseToInt(fieldName+"-year", qp);
if( year == null )
year = 1999;
month= parseToInt(fieldName+"-month", qp);
if(month == null )
month = 1;
day = parseToInt(fieldName+"-day", qp);
if( day == null )
day = 1;
hour = parseToInt(fieldName+"-hour", qp);
if( hour == null )
hour = 0;
minute = parseToInt(fieldName+"-minute",qp);
if( minute == null )
minute = 0;
second = parseToInt(fieldName+"-second", qp);
if( second == null )
second = 0;
//initialize to something so that we can be assured not to get
//system date dependent behavior
DateTime dateTime = new DateTime("1970-01-01T00:00:00Z");
try{
dateTime = dateTime.withYear(year);
}catch(IllegalArgumentException iae){
errors.put(fieldName+"-year", iae.getLocalizedMessage());
}
try{
dateTime = dateTime.withMonthOfYear(month);
}catch(IllegalArgumentException iae){
errors.put(fieldName+"-month", iae.getLocalizedMessage());
}
try{
dateTime = dateTime.withDayOfMonth(day);
}catch(IllegalArgumentException iae){
errors.put(fieldName+"-day", iae.getLocalizedMessage());
}
try{
dateTime = dateTime.withHourOfDay(hour);
}catch(IllegalArgumentException iae){
errors.put(fieldName+"-hour", iae.getLocalizedMessage());
}
try{
dateTime = dateTime.withSecondOfMinute(second);
}catch(IllegalArgumentException iae){
errors.put(fieldName+"-second", iae.getLocalizedMessage());
}
return errors;
}
private boolean fieldMatchesPattern( String fieldName, Map<String,String[]>queryParameters, Pattern pattern){
String[] varg = queryParameters.get(fieldName);
if( varg == null || varg.length != 1 || varg[0] == null)
return false;
String value = varg[0];
Matcher match = pattern.matcher(value);
return match.matches();
}
private boolean emptyOrBlank(String key,Map<String, String[]> queryParameters){
String[] vt = queryParameters.get(key);
return ( vt == null || vt.length ==0 || vt[0] == null || vt[0].length() == 0 );
}
private boolean canParseToNumber(String key,Map<String, String[]> queryParameters){
Integer out = null;
try{
String[] vt = queryParameters.get(key);
if( vt == null || vt.length ==0 || vt[0] == null)
return false;
else{
out = Integer.parseInt(vt[0]);
return true;
}
}catch(IndexOutOfBoundsException iex){
out = null;
}catch(NumberFormatException nfe){
out = null;
}catch(NullPointerException npe){
out = null;
}
return false;
}
private Integer parseToInt(String key,Map<String, String[]> queryParameters){
Integer out = null;
try{
String[] vt = queryParameters.get(key);
if( vt == null || vt.length ==0 || vt[0] == null)
out = null;
else
out = Integer.parseInt(vt[0]);
}catch(IndexOutOfBoundsException iex){
out = null;
}catch(NumberFormatException nfe){
out = null;
}catch(NullPointerException npe){
out = null;
}
return out;
}
public VitroVocabulary.Precision getRequiredMinimumPrecision() {
return minimumPrecision;
}
public void setRequiredMinimumPrecision(
VitroVocabulary.Precision requiredMinimumPrecision) {
this.minimumPrecision = requiredMinimumPrecision;
}
/* returns null if it cannot convert */
public static VitroVocabulary.Precision toPrecision(String precisionUri){
for( VitroVocabulary.Precision precision : VitroVocabulary.Precision.values()){
if( precision.uri().equals(precisionUri))
return precision;
}
return null;
}
public String getValueVariableName(){ return fieldName + "-value" ; }
public String getPrecisionVariableName(){ return fieldName + "-precision" ; }
}

View file

@ -9,6 +9,7 @@ import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

View file

@ -24,6 +24,7 @@ import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.webapp.beans.Datatype;
import edu.cornell.mannlib.vitro.webapp.dao.jena.DatatypeDaoJena;
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;

View file

@ -4,8 +4,8 @@ package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -15,9 +15,6 @@ import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary.Precision;
import edu.cornell.mannlib.vitro.webapp.edit.elements.DateTimeWithPrecision;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
/*
* Assumption for date time interval validation: Only one start field/end field/and precision.
@ -133,9 +130,9 @@ public class DateTimeIntervalValidationVTwo implements N3ValidatorVTwo {
//Currently checks first precision str and then returns response
if(precisionStr.size() > 0) {
String precisionString = precisionStr.get(0);
VitroVocabulary.Precision precision = DateTimeWithPrecision.toPrecision( precisionString );
VitroVocabulary.Precision precision = DateTimeWithPrecisionVTwo.toPrecision( precisionString );
if( precision == null )
log.warn("cannot convert " + precisionStr + " to a precision");
log.debug("cannot convert " + precisionStr + " to a precision");
else
return precision;
} else {

View file

@ -20,6 +20,7 @@ import com.hp.hpl.jena.rdf.model.ResourceFactory;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerConfiguration;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
@ -133,8 +134,10 @@ public class DateTimeWithPrecisionVTwo extends BaseEditElementVTwo {
VitroVocabulary.Precision existingPrec = toPrecision(precisionUri);
if( precisionUri != null && !"".equals(precisionUri) && existingPrec == null ){
log.error("field " + getFieldName() + ": existing precision uri was " +
if( ! BLANK_SENTINEL.equals( precisionUri )){
log.warn("field " + getFieldName() + ": existing precision uri was " +
"'" + precisionUri + "' but could not convert to Precision object");
}
}
if( precisionUri == null || precisionUri.isEmpty() || existingPrec == null){

View file

@ -20,6 +20,7 @@ import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.RdfLiteralHash;
@ -257,7 +258,7 @@ public class EditConfigurationUtils {
//Generate HTML for a specific field name given
public static String generateHTMLForElement(VitroRequest vreq, String fieldName, EditConfigurationVTwo editConfig) {
String html = "";
Configuration fmConfig = FreemarkerConfigurationLoader.getConfig(vreq, vreq.getSession().getServletContext());
Configuration fmConfig = FreemarkerConfigurationLoader.getConfig(vreq);
FieldVTwo field = editConfig == null ? null : editConfig.getField(fieldName);
MultiValueEditSubmission editSub = EditSubmissionUtils.getEditSubmissionFromSession(vreq.getSession(), editConfig);

View file

@ -5,6 +5,7 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
@ -29,6 +30,7 @@ import com.hp.hpl.jena.rdf.model.ResourceFactory;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.ModelSelector;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.StandardModelSelector;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.StandardWDFSelector;
@ -429,11 +431,21 @@ public class EditConfigurationVTwo {
return EditConfigurationUtils.copy(n3Required);
}
//TODO: can we use varargs here?
public void setN3Required(List<String> n3Required) {
this.n3Required = n3Required;
}
public void setN3Required(String ... n3RequiredStrs){
this.n3Required = new ArrayList<String>(Arrays.asList( n3RequiredStrs )); //using ArrayList to allow list to be resized
}
//these methods allow strings to be added to the n3 required list and not just for the list to be set
public void addN3Required(List<String> n3RequiredInput) {
this.n3Required.addAll(n3RequiredInput);
}
public void addN3Required(String ... n3RequiredStrsInput) {
this.n3Required.addAll(Arrays.asList( n3RequiredStrsInput ));
}
/** return a copy of the value so that the configuration is not modified by external code.
* @return
*/
@ -445,6 +457,19 @@ public class EditConfigurationVTwo {
this.n3Optional = n3Optional;
}
public void setN3Optional(String ... n3Strs){
this.n3Optional = new ArrayList<String>(Arrays.asList( n3Strs )); //using ArrayList to allow list to be resized
}
public void addN3Optional(List<String> n3Optional) {
this.n3Optional.addAll(n3Optional);
}
public void addN3Optional(String ... n3Strs){
this.n3Optional.addAll(Arrays.asList( n3Strs ));
}
public Map<String,String> getNewResources() {
return newResources;
}
@ -452,7 +477,21 @@ public class EditConfigurationVTwo {
public void setNewResources(Map<String,String> newResources) {
this.newResources = newResources;
}
public void setNewResources(String ... strs){
if( strs == null || strs.length % 2 != 0 ){
throw new Error(" setNewResources() must have pairs of varName, prefix ");
}
Map<String,String> map = new HashMap<String,String>();
for( int i=0;i<strs.length;i=i+2 ){
map.put(strs[i],strs[i+1]);
}
this.newResources = map;
}
public List<String> getUrisOnform() {
return urisOnform;
}
@ -461,6 +500,19 @@ public class EditConfigurationVTwo {
this.urisOnform = urisOnform;
}
public void setUrisOnForm(String ... strs){
this.urisOnform = new ArrayList<String>(Arrays.asList( strs )); //using ArrayList to allow resizing
}
//This doesn't overwrite or set but adds to existing list
public void addUrisOnForm(List<String> urisOnform) {
this.urisOnform.addAll(urisOnform);
}
public void addUrisOnForm(String ... strs){
this.urisOnform.addAll(Arrays.asList( strs ));
}
public void setFilesOnForm(List<String> filesOnForm){
this.filesOnForm = filesOnForm;
}
@ -477,6 +529,18 @@ public class EditConfigurationVTwo {
this.literalsOnForm = literalsOnForm;
}
public void setLiteralsOnForm(String ... strs){
this.literalsOnForm = new ArrayList<String>(Arrays.asList( strs ));//using ArrayList to allow resizing
}
public void addLiteralsOnForm(List<String> literalsOnForm) {
this.literalsOnForm.addAll(literalsOnForm);
}
public void addLiteralsOnForm(String ... strs){
this.literalsOnForm.addAll(Arrays.asList( strs ));
}
public Map<String, List<String>> getUrisInScope() {
return urisInScope;
}
@ -1034,6 +1098,16 @@ public class EditConfigurationVTwo {
fields.put( field.getName(), field);
}
public void addFields(List<FieldVTwo> fields) {
if( fields != null )
{
for(FieldVTwo f: fields) {
this.addField(f);
}
}
}
@Override
public String toString(){
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);

View file

@ -1,229 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
public class FieldVTwo {
public enum OptionsType {
LITERALS,
HARDCODED_LITERALS,
STRINGS_VIA_DATATYPE_PROPERTY,
INDIVIDUALS_VIA_OBJECT_PROPERTY,
INDIVIDUALS_VIA_VCLASS,
CHILD_VCLASSES,
CHILD_VCLASSES_WITH_PARENT,
VCLASSGROUP,
FILE,
UNDEFINED,
DATETIME,
DATE,
TIME
};
public static String RDF_XML_LITERAL_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral";
private String name;
/**
* List of basic validators. See BaiscValidation.
*/
private List <String> validators = new ArrayList<String>();
/**
* What type of options is this?
*/
private OptionsType optionsType = OptionsType.UNDEFINED;
/**
* Special class to use for option type
*/
private Class customOptionType;
/**
* Used for building Options when OptionsType is INDIVIDUALS_VIA_OBJECT_PROPERTY
*/
private String predicateUri;
/**
* Used for building Options when OptionsType is INDIVIDUALS_VIA_VCLASS
*/
private String objectClassUri;
/**
* Used for holding the expected/required datatype of the predicate when the predicate is a datatype propertyl.
* this can be a explicit URI or a qname.
* example:
* "this is the literal"^^<http://someuri.com/v1.2#type23>
* or
* "this is the literal"^^someprefix:type23
*/
private String rangeDatatypeUri;
/**
* Used for holding the language of the literal when the predicate is a datatype property.
* This is the lang of the literal. lang strings must be: [a-z]+(-[a-z0-9]+)*
*/
private String rangeLang;
/**
* If this is a Select and it is of OptionsType LITERALS, these are the literals.
*/
private List<List<String>> literalOptions;
/**
* Property for special edit element.
*/
private EditElementVTwo editElement=null;;
/* *********************** Constructors ************************** */
public FieldVTwo() {}
private static String[] parameterNames = {"editElement","newResource","validators","optionsType","predicateUri","objectClassUri","rangeDatatypeUri","rangeLang","literalOptions","assertions"};
static{ Arrays.sort(parameterNames); }
public FieldVTwo setEditElement(EditElementVTwo editElement){
this.editElement = editElement;
if( editElement instanceof BaseEditElementVTwo)
((BaseEditElementVTwo) editElement).setField(this);
return this;
}
/* ****************** Getters and Setters ******************************* */
public String getName(){
return name;
}
public List <String> getValidators() {
return validators;
}
public FieldVTwo setValidators(List <String> v) {
validators = v;
return this;
}
public OptionsType getOptionsType() {
return optionsType;
}
public FieldVTwo setOptionsType(OptionsType ot) {
optionsType = ot;
return this;
}
public FieldVTwo setOptionsType(String s) {
setOptionsType( getOptionForString(s));
return this;
}
public static OptionsType getOptionForString(String s){
if( s== null || s.isEmpty() )
return OptionsType.UNDEFINED;
if ("LITERALS".equals(s)) {
return FieldVTwo.OptionsType.LITERALS;
} else if ("HARDCODED_LITERALS".equals(s)) {
return FieldVTwo.OptionsType.HARDCODED_LITERALS;
} else if ("STRINGS_VIA_DATATYPE_PROPERTY".equalsIgnoreCase(s)) {
return FieldVTwo.OptionsType.STRINGS_VIA_DATATYPE_PROPERTY;
} else if ("INDIVIDUALS_VIA_OBJECT_PROPERTY".equalsIgnoreCase(s)) {
return FieldVTwo.OptionsType.INDIVIDUALS_VIA_OBJECT_PROPERTY;
} else if ("INDIVIDUALS_VIA_VCLASS".equalsIgnoreCase(s)) {
return FieldVTwo.OptionsType.INDIVIDUALS_VIA_VCLASS;
} else if ("DATETIME".equalsIgnoreCase(s)) {
return FieldVTwo.OptionsType.DATETIME;
} else if ("CHILD_VCLASSES".equalsIgnoreCase(s)) {
return FieldVTwo.OptionsType.CHILD_VCLASSES;
} else if ("CHILD_VCLASSES_WITH_PARENT".equalsIgnoreCase(s)) {
return FieldVTwo.OptionsType.CHILD_VCLASSES_WITH_PARENT;
} else if ("VCLASSGROUP".equalsIgnoreCase(s)) {
return FieldVTwo.OptionsType.VCLASSGROUP;
} else if ("FILE".equalsIgnoreCase(s)) {
return FieldVTwo.OptionsType.FILE;
} else if ("DATE".equalsIgnoreCase(s)) {
return FieldVTwo.OptionsType.DATE;
} else if ("TIME".equalsIgnoreCase(s)) {
return FieldVTwo.OptionsType.TIME;
} else {
return FieldVTwo.OptionsType.UNDEFINED;
}
}
public String getPredicateUri() {
return predicateUri;
}
public FieldVTwo setPredicateUri(String s) {
predicateUri = s;
return this;
}
public String getObjectClassUri() {
return objectClassUri;
}
public FieldVTwo setObjectClassUri(String s) {
objectClassUri = s;
return this;
}
public String getRangeDatatypeUri() {
return rangeDatatypeUri;
}
public FieldVTwo setRangeDatatypeUri(String r) {
if( rangeLang != null && rangeLang.trim().length() > 0 )
throw new IllegalArgumentException("A Field object may not have both rangeDatatypeUri and rangeLanguage set");
rangeDatatypeUri = r;
return this;
}
public List <List<String>> getLiteralOptions() {
return literalOptions;
}
public FieldVTwo setLiteralOptions(List<List<String>> literalOptions) {
this.literalOptions = literalOptions;
return this;
}
public String getRangeLang() {
return rangeLang;
}
public FieldVTwo setRangeLang(String rangeLang) {
if( rangeDatatypeUri != null && rangeDatatypeUri.trim().length() > 0)
throw new IllegalArgumentException("A Field object may not have both rangeDatatypeUri and rangeLanguage set");
this.rangeLang = rangeLang;
return this;
}
public EditElementVTwo getEditElement(){
return editElement;
}
public FieldVTwo setName(String name){
this.name = name;
return this;
}
@Override
public String toString(){
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}

View file

@ -33,7 +33,7 @@ import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditElementVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.BasicValidation;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.N3Validator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Utils;

View file

@ -1,504 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.vocabulary.OWL;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
import edu.cornell.mannlib.vitro.webapp.dao.jena.pellet.PelletListener;
public class SelectListGeneratorVTwo {
static Log log = LogFactory.getLog(SelectListGeneratorVTwo.class);
public static Map<String,String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact){
if( editConfig == null ){
log.error( "fieldToSelectItemList() must be called with a non-null EditConfigurationVTwo ");
return Collections.EMPTY_MAP;
}
if( fieldName == null ){
log.error( "fieldToSelectItemList() must be called with a non-null fieldName");
return Collections.EMPTY_MAP;
}
FieldVTwo field = editConfig.getField(fieldName);
if (field==null) {
log.error("no field \""+fieldName+"\" found from editConfig in SelectListGenerator.getOptions()");
return Collections.EMPTY_MAP;
}
// now create an empty HashMap to populate and return
HashMap <String,String> optionsMap = new LinkedHashMap<String,String>();
// for debugging, keep a count of the number of options populated
int optionsCount=0;
FieldVTwo.OptionsType optionsType = field.getOptionsType();
String vclassUri = null;
switch (optionsType){
case HARDCODED_LITERALS: // originally not auto-sorted but sorted now, and empty values not removed or replaced
List<List<String>> hardcodedLiteralOptions = field.getLiteralOptions();
if (hardcodedLiteralOptions==null) {
log.error("no literalOptions List found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType HARDCODED_LITERALS specified");
return new HashMap <String,String>();
}
for(Object obj: ((Iterable)hardcodedLiteralOptions)){
List<String> literalPair = (List)obj;
String value=(String)literalPair.get(0);
if( value != null){ // allow empty string as a value
String label=(String)literalPair.get(1);
if (label!=null) {
optionsMap.put(value,label);
} else {
optionsMap.put(value, value);
}
++optionsCount;
}
}
break;
case LITERALS:
List<List<String>> literalOptions = field.getLiteralOptions();
if (literalOptions==null) {
log.error("no literalOptions List found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType LITERALS specified");
return new HashMap <String,String>();
}
for(Object obj: ((Iterable)literalOptions)){
List<String> literalPair = (List)obj;
String value=(String)literalPair.get(0);
if( value != null && value.trim().length() > 0){
String label=(String)literalPair.get(1);
if (label!=null && label.trim().length() > 0) {
optionsMap.put(value,label);
} else {
optionsMap.put(value, value);
}
++optionsCount;
}
}
break;
case STRINGS_VIA_DATATYPE_PROPERTY:
log.debug("processing Field \""+fieldName+"\" optionType as a datatype property predicateUri in SelectListGenerator.getOptions()");
String dataPropUri = field.getPredicateUri();
if (dataPropUri==null || dataPropUri.equals("")){
log.error("no predicate dataPropUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType STRINGS_VIA_DATATYPE_PROPERTY specified");
} else {
/* first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
} */
// now populate the options
log.debug("finding all choices for data property \""+dataPropUri+"\" in SelectListGenerator.getOptions()");
if( wDaoFact == null ) log.error("incoming WebappDaoFactory from request is null in SelectListGenerator.getOptions().");
DataPropertyStatementDao dpsDao = wDaoFact.getDataPropertyStatementDao();
DataPropertyDao dpDao = wDaoFact.getDataPropertyDao();
DataProperty dp = dpDao.getDataPropertyByURI(dataPropUri);
for (Iterator<DataPropertyStatement> i = dpsDao.getDataPropertyStatements(dp).iterator(); i.hasNext();) {
DataPropertyStatement dps = i.next();
if( dps != null ){
optionsMap.put(dps.getData().trim(),dps.getData().trim());
++optionsCount;
}
}
}
break;
case INDIVIDUALS_VIA_OBJECT_PROPERTY:
log.debug("processing Field \""+fieldName+"\" optionType as an object property predicateUri in SelectListGenerator.getOptions()");
String subjectUri = editConfig.getSubjectUri();
if (subjectUri==null || subjectUri.equals("")){
log.error("no subjectUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType INDIVIDUALS_VIA_OBJECTPROPERTY specified");
} else {
String predicateUri = field.getPredicateUri();
if (predicateUri==null || predicateUri.equals("")){
log.error("no predicateUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType INDIVIDUALS_VIA_OBJECTPROPERTY specified");
} else {
// first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
}
// now populate the options
log.debug("finding range individuals for subject \""+subjectUri+"\" and object property \""+predicateUri+"\" in SelectListGenerator.getOptions()");
if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
Individual subject = wDaoFact.getIndividualDao().getIndividualByURI(subjectUri);
if( subject == null ) log.error("could not get individual for subject uri "+subjectUri+" in SelectListGenerator.getOptions()");
ObjectProperty objProp = wDaoFact.getObjectPropertyDao().getObjectPropertyByURI(predicateUri);
if( objProp == null )
log.error("could not get object property for predicate "+predicateUri+" in SelectListGenerator.getOptions()");
List <VClass> vclasses = new ArrayList<VClass>();
vclasses = wDaoFact.getVClassDao().getVClassesForProperty(subject.getVClassURI(),predicateUri);
if( vclasses == null ){
log.error("no owl:Class found for predicate " + predicateUri );
break;
}
if( vclasses.size() == 0 )
log.error("no owl:Class found for predicate " + predicateUri );
List<Individual> individuals = new ArrayList<Individual>();
HashSet<String> uriSet = new HashSet<String>();
long startTime = System.currentTimeMillis();
for ( VClass vclass : vclasses){
for( Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) {
if( !uriSet.contains(ind.getURI())) {
uriSet.add(ind.getURI());
individuals.add(ind);
}
}
}
List<ObjectPropertyStatement> stmts = subject.getObjectPropertyStatements();
if( stmts == null ) log.error("object properties for subject were null in SelectListGenerator.getOptions()");
individuals = removeIndividualsAlreadyInRange(individuals,stmts,predicateUri,editConfig.getObject());
//Collections.sort(individuals,new compareIndividualsByName());
for( Individual ind : individuals ){
String uri = ind.getURI();
if( uri != null ){
optionsMap.put(uri,ind.getName().trim());
++optionsCount;
}
}
}
}
break;
case INDIVIDUALS_VIA_VCLASS: //so we have a vclass URI
vclassUri = field.getObjectClassUri();
if (vclassUri==null || vclassUri.equals("")){
log.error("no vclassUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType INDIVIDUALS_VIA_VCLASS specified");
} else {
// first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
}
// now populate the options
if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
// if reasoning isn't available, we will also need to add
// individuals asserted in subclasses
boolean inferenceAvailable = false;
if (wDaoFact instanceof WebappDaoFactoryJena) {
PelletListener pl = ((WebappDaoFactoryJena) wDaoFact)
.getPelletListener();
if (pl != null && pl.isConsistent()
&& !pl.isInErrorState()
&& !pl.isReasoning()) {
inferenceAvailable = true;
}
}
VClass vclass = wDaoFact.getVClassDao().getVClassByURI( vclassUri );
if( vclass == null ) {
log.error("Cannot find owl:Class " + vclassUri + " in the model" );
optionsMap.put("", "Could not find class " + vclassUri);
}else{
Map<String, Individual> individualMap = new HashMap<String, Individual>();
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) {
if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind);
}
}
if (!inferenceAvailable) {
for (String subclassURI : wDaoFact.getVClassDao().getAllSubClassURIs(vclass.getURI())) {
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(subclassURI,-1,-1)) {
if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind);
}
}
}
}
List<Individual> individuals = new ArrayList<Individual>();
individuals.addAll(individualMap.values());
Collections.sort(individuals);
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) {
if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind);
}
}
if (!inferenceAvailable) {
for (String subclassURI : wDaoFact.getVClassDao().getAllSubClassURIs(vclass.getURI())) {
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(subclassURI,-1,-1)) {
if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind);
}
}
}
}
individuals.addAll(individualMap.values());
Collections.sort(individuals);
if (individuals.size()==0){
log.debug("No individuals of type "+vclass.getName()+" to add to pick list in SelectListGenerator.getOptions()");
optionsMap.put("", "No " + vclass.getName() + " found");
}else{
for( Individual ind : individuals ) {
String uri = ind.getURI();
if( uri != null ) {
optionsMap.put(uri,ind.getName().trim());
++optionsCount;
}
}
}
}
}
break;
case CHILD_VCLASSES: //so we have a vclass URI
vclassUri = field.getObjectClassUri();
if (vclassUri==null || vclassUri.equals("")){
log.error("no vclassUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType CHILD_VCLASSES specified");
} else {
// first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
}
// now populate the options
if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
VClassDao vclassDao = wDaoFact.getVClassDao();
List<String> subClassList = vclassDao.getAllSubClassURIs(vclassUri);
if( subClassList == null || subClassList.size()==0 ) {
log.debug("No subclasses of " + vclassUri + " found in the model so only default value from field's literalOptions will be used" );
} else {
for( String subClassUri : subClassList ) {
VClass subClass = vclassDao.getVClassByURI(subClassUri);
if( subClass != null && !OWL.Nothing.getURI().equals(subClassUri)) {
optionsMap.put(subClassUri,subClass.getName().trim());
++optionsCount;
}
}
}
}
break;
case CHILD_VCLASSES_WITH_PARENT: //so we have a vclass URI
vclassUri = field.getObjectClassUri();
if (vclassUri==null || vclassUri.equals("")){
log.error("no vclassUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType CHILD_VCLASSES specified");
} else {
// first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
}
// now populate the options
if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
VClassDao vclassDao = wDaoFact.getVClassDao();
List<String> subClassList = vclassDao.getAllSubClassURIs(vclassUri);
if( subClassList == null || subClassList.size()==0 ) {
log.debug("No subclasses of " + vclassUri + " found in the model so only default value from field's literalOptions will be used" );
} else {
for( String subClassUri : subClassList ) {
VClass subClass = vclassDao.getVClassByURI(subClassUri);
if( subClass != null && !OWL.Nothing.getURI().equals(subClassUri)) {
optionsMap.put(subClassUri,subClass.getName().trim());
++optionsCount;
}
}
optionsMap.put(vclassUri, "Other");
++optionsCount;
}
}
break;
case VCLASSGROUP:
String classGroupUri = field.getObjectClassUri(); // we're overloading this property to specify the classgroup
if (classGroupUri==null || classGroupUri.equals("")){
log.error("no classGroupUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType VCLASSGROUP specified");
} else {
// first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
}
// now populate the options
if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
VClassGroupDao vcgd = wDaoFact.getVClassGroupDao();
// Need to call this method to populate the classgroups - otherwise the classgroup class list is empty
List vClassGroups = vcgd.getPublicGroupsWithVClasses();
if (vClassGroups == null) {
log.error("No class groups found, so only default value from field's literalOptions will be used.");
} else {
VClassGroup vClassGroup = null;
for (Object o : vClassGroups) {
VClassGroup vcg = (VClassGroup) o;
if (vcg.getURI().equals(classGroupUri)) {
vClassGroup = vcg;
break;
}
}
if (vClassGroup == null) {
log.error("No class group with uri " + classGroupUri + "found, so only default value from field's literalOptions will be used.");
} else {
List<VClass> vClassList = vClassGroup.getVitroClassList();
if( vClassList == null || vClassList.size()==0 ) {
log.debug("No classes in class group " + classGroupUri + " found in the model, so only default value from field's literalOptions will be used" );
} else {
for( VClass vClass : vClassList ) {
String vClassUri = vClass.getURI();
if( vClass != null && !OWL.Nothing.getURI().equals(vClassUri)) {
optionsMap.put(vClassUri,vClass.getName().trim());
++optionsCount;
}
}
}
}
}
}
break;
case UNDEFINED :
log.error("optionsType \"UNDEFINED\" for Field \""+fieldName+"\" in SelectListGenerator.getOptions()");
break;
default: log.error("unknown optionsType "+optionsType.toString()+" for Field \""+fieldName+"\" in SelectListGenerator.getOptions()");
}
log.debug("added "+optionsCount+" options for field \""+fieldName+"\" in SelectListGenerator.getOptions()");
return optionsMap;
}
/**
* The default option is used when a option list is being auto
* generated from a VClass or an ObjectProperty. If there is an
* item in the literals item list then the name of it will be used
* as the text to display for an empty string value option.
*
* Having an option with an empty string for a Field that expects
* a URI will cause the form processing to assume that the field
* was left blank.
*
* @param field
* @return
*/
private static String getDefaultOption(FieldVTwo field) {
List <List<String>> defaultOptions = (List<List<String>>) field.getLiteralOptions();
if (defaultOptions!=null) {
for(Object obj: ((Iterable)defaultOptions)) {
List<String> pair = (List<String>)obj;
String value = pair.get(0);
String label = pair.get(1);
if( label != null && label.trim().length() > 0){
return label; // don't want to return a value
}
}
}
return null;
}
// copied from OptionsForPropertyTag.java in the thought that class may be deprecated
private static List<Individual> removeIndividualsAlreadyInRange(List<Individual> individuals,
List<ObjectPropertyStatement> stmts, String predicateUri, String objectUriBeingEdited){
log.debug("starting to check for duplicate range individuals in SelectListGenerator.removeIndividualsAlreadyInRange() ...");
HashSet<String> range = new HashSet<String>();
for(ObjectPropertyStatement ops : stmts){
if( ops.getPropertyURI().equals(predicateUri))
range.add( ops.getObjectURI() );
}
int removeCount=0;
ListIterator<Individual> it = individuals.listIterator();
while(it.hasNext()){
Individual ind = it.next();
if( range.contains( ind.getURI()) && !(ind.getURI().equals(objectUriBeingEdited)) ) {
it.remove();
++removeCount;
}
}
log.debug("removed "+removeCount+" duplicate range individuals");
return individuals;
}
//Methods to sort the options map
// from http://forum.java.sun.com/thread.jspa?threadID=639077&messageID=4250708
public static Map<String,String> getSortedMap(Map<String,String> hmap){
// first make temporary list of String arrays holding both the key and its corresponding value, so that the list can be sorted with a decent comparator
List<String[]> objectsToSort = new ArrayList<String[]>(hmap.size());
for (String key:hmap.keySet()) {
String[] x = new String[2];
x[0] = key;
x[1] = hmap.get(key);
objectsToSort.add(x);
}
Collections.sort(objectsToSort, new MapPairsComparator());
HashMap<String,String> map = new LinkedHashMap<String,String>(objectsToSort.size());
for (String[] pair:objectsToSort) {
map.put(pair[0],pair[1]);
}
return map;
}
private static class MapPairsComparator implements Comparator<String[]> {
public int compare (String[] s1, String[] s2) {
Collator collator = Collator.getInstance();
if (s2 == null) {
return 1;
} else if (s1 == null) {
return -1;
} else {
if ("".equals(s1[0])) {
return -1;
} else if ("".equals(s2[0])) {
return 1;
}
if (s2[1]==null) {
return 1;
} else if (s1[1] == null){
return -1;
} else {
return collator.compare(s1[1],s2[1]);
}
}
}
}
private static final String LEFT_BLANK = "";
}

View file

@ -0,0 +1,83 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.vocabulary.OWL;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
public class ChildVClassesOptions implements FieldOptions {
private static final String LEFT_BLANK = "";
private String vclassUri;
private String defaultOptionLabel;
static Log log = LogFactory.getLog(ChildVClassesOptions.class);
public ChildVClassesOptions(String vclassUri) {
super();
this.vclassUri = vclassUri;
}
public ChildVClassesOptions setDefaultOptionLabel(String label){
this.defaultOptionLabel = label;
return this;
}
@Override
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact) throws Exception{
// now create an empty HashMap to populate and return
HashMap <String,String> optionsMap = new LinkedHashMap<String,String>();
// for debugging, keep a count of the number of options populated
int optionsCount=0;
if (vclassUri==null || vclassUri.equals("")){
throw new Exception("no vclassUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType CHILD_VCLASSES specified");
} else {
// first test to see whether there's a default "leave blank" value specified with the literal options
if (defaultOptionLabel!=null) {
optionsMap.put(LEFT_BLANK, defaultOptionLabel);
}
// now populate the options
VClassDao vclassDao = wDaoFact.getVClassDao();
List<String> subClassList = vclassDao.getAllSubClassURIs(vclassUri);
if( subClassList == null || subClassList.size()==0 ) {
log.debug("No subclasses of " + vclassUri + " found in the model so only default value from field's literalOptions will be used" );
} else {
for( String subClassUri : subClassList ) {
VClass subClass = vclassDao.getVClassByURI(subClassUri);
if( subClass != null && !OWL.Nothing.getURI().equals(subClassUri)) {
optionsMap.put(subClassUri,subClass.getName().trim());
++optionsCount;
}
}
}
}
log.debug("added "+optionsCount+" options for field \""+fieldName+"\"");
return optionsMap;
}
public String getClassUri(){
return vclassUri;
}
}

View file

@ -0,0 +1,66 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.hp.hpl.jena.vocabulary.OWL;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
public class ChildVClassesWithParent implements FieldOptions {
private static final String LEFT_BLANK = "";
String fieldName;
String classUri;
String defaultOptionLabel = null;
public ChildVClassesWithParent(String classUri) throws Exception {
super();
if (classUri==null || classUri.equals(""))
throw new Exception ("vclassUri not set");
this.classUri = classUri;
}
public ChildVClassesWithParent setDefaultOption(String label){
this.defaultOptionLabel = label;
return this;
}
@Override
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact) throws Exception {
HashMap <String,String> optionsMap = new LinkedHashMap<String,String>();
// first test to see whether there's a default "leave blank" value specified with the literal options
if ( ! StringUtils.isEmpty( defaultOptionLabel ) ){
optionsMap.put(LEFT_BLANK, defaultOptionLabel);
}
optionsMap.put(classUri, "Other");
VClassDao vclassDao = wDaoFact.getVClassDao();
List<String> subClassList = vclassDao.getAllSubClassURIs(classUri);
if (subClassList != null && subClassList.size() > 0) {
for (String subClassUri : subClassList) {
VClass subClass = vclassDao.getVClassByURI(subClassUri);
if (subClass != null && !OWL.Nothing.getURI().equals(subClassUri)) {
optionsMap.put(subClassUri, subClass.getName().trim());
}
}
}
return optionsMap;
}
}

View file

@ -0,0 +1,76 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
public class ConstantFieldOptions implements FieldOptions {
List<List<String>> options;
public ConstantFieldOptions(String ... optionPairs) throws Exception {
super();
if (optionPairs==null)
throw new Exception("Must specify option pairs in ConstantFieldOptions constructor");
if( optionPairs.length % 2 != 0)
throw new Exception("options must be in pairs of (value,lable)");
options = new ArrayList<List<String>>( optionPairs.length / 2 );
for(int i=0; i< optionPairs.length ; i=i+2){
List<String> pair = new ArrayList<String>(2);
pair.add(optionPairs[i]);
pair.add(optionPairs[i+1]);
options.add( pair );
}
}
public ConstantFieldOptions(String fieldName2,
List<List<String>> optionPairs) throws Exception {
for(List<String> literalPair: optionPairs ){
if( literalPair == null)
throw new Exception("no items in optionPairs may be null.");
if( literalPair.size() == 0 )
throw new Exception("no items in optionPairs may be empty lists.");
if( literalPair.size() > 2)
throw new Exception("no items in optionPairs may be lists longer than 2 items.");
}
options = optionPairs;
}
@Override
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact) throws Exception {
// originally not auto-sorted but sorted now, and empty values not removed or replaced
HashMap <String,String> optionsMap = new LinkedHashMap<String,String>();
for(Object obj: ((Iterable)options)){
List<String> literalPair = (List)obj;
String value=(String)literalPair.get(0);
if( value != null){ // allow empty string as a value
String label=(String)literalPair.get(1);
if (label!=null) {
optionsMap.put(value,label);
} else {
optionsMap.put(value, value);
}
}
}
return optionsMap;
}
}

View file

@ -0,0 +1,53 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
/**
* Represents an object that can return a list of options
* for an HTML select list.
*
* @author bdc34
*
*/
public interface FieldOptions {
/**
* Any object that are needed to get the options should
* be passed in the constructor of the implementation.
*
* @return return a map of value->label for the options.
* Should never return null.
*
* @throws Exception
*/
public Map<String,String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact) throws Exception;
}
/*
* lic enum OptionsType {
LITERALS,x
HARDCODED_LITERALS,
STRINGS_VIA_DATATYPE_PROPERTY,
INDIVIDUALS_VIA_OBJECT_PROPERTY, x
INDIVIDUALS_VIA_VCLASS,
CHILD_VCLASSES, x
CHILD_VCLASSES_WITH_PARENT,
VCLASSGROUP,
FILE,
UNDEFINED, x
DATETIME,
DATE,
TIME
*/

View file

@ -0,0 +1,141 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.BaseEditElementVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditElementVTwo;
public class FieldVTwo {
// public enum OptionsType {
// LITERALS,
// HARDCODED_LITERALS,
// STRINGS_VIA_DATATYPE_PROPERTY,
// INDIVIDUALS_VIA_OBJECT_PROPERTY,
// INDIVIDUALS_VIA_VCLASS,
// CHILD_VCLASSES,
// CHILD_VCLASSES_WITH_PARENT,
// VCLASSGROUP,
// FILE,
// UNDEFINED,
// DATETIME,
// DATE,
// TIME
// };
public static String RDF_XML_LITERAL_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral";
private String name;
/**
* List of basic validators. See BaiscValidation.
*/
private List <String> validators = new ArrayList<String>();
/** Object to get options from. */
private FieldOptions fieldOptions;
/**
* Used for holding the expected/required datatype of the predicate when the predicate is a datatype propertyl.
* this can be a explicit URI or a qname.
* example:
* "this is the literal"^^<http://someuri.com/v1.2#type23>
* or
* "this is the literal"^^someprefix:type23
*/
private String rangeDatatypeUri;
/**
* Used for holding the language of the literal when the predicate is a datatype property.
* This is the lang of the literal. lang strings must be: [a-z]+(-[a-z0-9]+)*
*/
private String rangeLang;
/**
* Property for special edit element.
*/
private EditElementVTwo editElement=null;;
/* *********************** Constructors ************************** */
public FieldVTwo() {}
//private static String[] parameterNames = {"editElement","newResource","validators","optionsType","predicateUri","objectClassUri","rangeDatatypeUri","rangeLang","literalOptions","assertions"};
//static{ Arrays.sort(parameterNames); }
/* ****************** Getters and Setters ******************************* */
public FieldVTwo setEditElement(EditElementVTwo editElement){
this.editElement = editElement;
if( editElement instanceof BaseEditElementVTwo)
((BaseEditElementVTwo) editElement).setField(this);
return this;
}
public String getName(){
return name;
}
public List <String> getValidators() {
return validators;
}
public FieldVTwo setValidators(List <String> v) {
validators = v;
return this;
}
public FieldVTwo setOptions( FieldOptions fopts){
this.fieldOptions = fopts;
return this;
}
public FieldOptions getFieldOptions(){
return this.fieldOptions;
}
public String getRangeDatatypeUri() {
return rangeDatatypeUri;
}
public FieldVTwo setRangeDatatypeUri(String r) {
if( rangeLang != null && rangeLang.trim().length() > 0 )
throw new IllegalArgumentException("A Field object may not have both rangeDatatypeUri and rangeLanguage set");
rangeDatatypeUri = r;
return this;
}
public String getRangeLang() {
return rangeLang;
}
public FieldVTwo setRangeLang(String rangeLang) {
if( rangeDatatypeUri != null && rangeDatatypeUri.trim().length() > 0)
throw new IllegalArgumentException("A Field object may not have both rangeDatatypeUri and rangeLanguage set");
this.rangeLang = rangeLang;
return this;
}
public EditElementVTwo getEditElement(){
return editElement;
}
public FieldVTwo setName(String name){
this.name = name;
return this;
}
@Override
public String toString(){
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}

View file

@ -0,0 +1,38 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
public class IndividualsViaClassGroupOptions implements FieldOptions {
String classGroupUri;
String defualtOptionLabel=null;
public IndividualsViaClassGroupOptions(String classGroupUri) {
super();
this.classGroupUri = classGroupUri;
}
public IndividualsViaClassGroupOptions setDefaultOptionLabel(String label){
defualtOptionLabel = label;
return this;
}
@Override
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact) throws Exception {
throw new Error("not implemented");
}
public String getClassGroupUri(){
return classGroupUri;
}
}

View file

@ -0,0 +1,125 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
public class IndividualsViaObjectPropetyOptions implements FieldOptions {
private static final String LEFT_BLANK = "";
private String subjectUri;
private String predicateUri;
private String objectUri;
private String defaultOptionLabel;
public IndividualsViaObjectPropetyOptions(String subjectUri,
String predicateUri, String objectUri) throws Exception {
super();
if (subjectUri == null || subjectUri.equals("")) {
throw new Exception("no subjectUri found for field ");
}
if (predicateUri == null || predicateUri.equals("")) {
throw new Exception("no predicateUri found for field ");
}
this.subjectUri = subjectUri;
this.predicateUri = predicateUri;
this.objectUri = objectUri;
}
public IndividualsViaObjectPropetyOptions setDefaultOptionLabel(String label){
this.defaultOptionLabel = label;
return this;
}
@Override
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact) {
HashMap<String, String> optionsMap = new LinkedHashMap<String, String>();
int optionsCount = 0;
// first test to see whether there's a default "leave blank"
// value specified with the literal options
if ((defaultOptionLabel ) != null) {
optionsMap.put(LEFT_BLANK, defaultOptionLabel);
}
Individual subject = wDaoFact.getIndividualDao().getIndividualByURI(subjectUri);
ObjectProperty objProp = wDaoFact.getObjectPropertyDao().getObjectPropertyByURI(predicateUri);
List<VClass> vclasses = wDaoFact.getVClassDao().getVClassesForProperty(subject.getVClassURI(), predicateUri);
if (vclasses == null || vclasses.size() == 0) {
return optionsMap;
}
List<Individual> individuals = new ArrayList<Individual>();
HashSet<String> uriSet = new HashSet<String>();
for (VClass vclass : vclasses) {
List<Individual> inds = wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(), -1, -1);
for (Individual ind : inds) {
if (!uriSet.contains(ind.getURI())) {
uriSet.add(ind.getURI());
individuals.add(ind);
}
}
}
List<ObjectPropertyStatement> stmts = subject.getObjectPropertyStatements();
individuals = removeIndividualsAlreadyInRange(
individuals, stmts, predicateUri, objectUri);
// Collections.sort(individuals,new compareIndividualsByName());
for (Individual ind : individuals) {
String uri = ind.getURI();
if (uri != null) {
optionsMap.put(uri, ind.getName().trim());
++optionsCount;
}
}
return optionsMap;
}
// copied from OptionsForPropertyTag.java in the thought that class may be deprecated
private static List<Individual> removeIndividualsAlreadyInRange(List<Individual> individuals,
List<ObjectPropertyStatement> stmts, String predicateUri, String objectUriBeingEdited){
HashSet<String> range = new HashSet<String>();
for(ObjectPropertyStatement ops : stmts){
if( ops.getPropertyURI().equals(predicateUri))
range.add( ops.getObjectURI() );
}
int removeCount=0;
ListIterator<Individual> it = individuals.listIterator();
while(it.hasNext()){
Individual ind = it.next();
if( range.contains( ind.getURI()) && !(ind.getURI().equals(objectUriBeingEdited)) ) {
it.remove();
++removeCount;
}
}
return individuals;
}
}

View file

@ -0,0 +1,131 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
import edu.cornell.mannlib.vitro.webapp.dao.jena.pellet.PelletListener;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
public class IndividualsViaVClassOptions implements FieldOptions {
public static final String LEFT_BLANK = "";
private List<String> vclassURIs;
private String defaultOptionLabel;
public IndividualsViaVClassOptions(String ... vclassURIs) throws Exception {
super();
if (vclassURIs==null )
throw new Exception("vclassURIs must not be null or empty ");
this.vclassURIs = new ArrayList<String>(vclassURIs.length);
for(int i=0;i<vclassURIs.length;i++){
if( vclassURIs[i] != null && !vclassURIs[i].trim().isEmpty() )
this.vclassURIs.add(vclassURIs[i]);
}
}
public FieldOptions setDefaultOptionLabel(String label){
this.defaultOptionLabel = label;
return this;
}
@Override
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact) throws Exception {
Map<String, Individual> individualMap = new HashMap<String, Individual>();
for( String vclassURI : this.vclassURIs){
individualMap.putAll( getIndividualsForClass( vclassURI, wDaoFact) );
}
//sort the individuals
List<Individual> individuals = new ArrayList<Individual>();
individuals.addAll(individualMap.values());
Collections.sort(individuals);
Map<String, String> optionsMap = new HashMap<String,String>();
if (defaultOptionLabel != null) {
optionsMap.put(LEFT_BLANK, defaultOptionLabel);
}
if (individuals.size() == 0) {
optionsMap.putAll( notFoundMsg() );
} else {
for (Individual ind : individuals) {
if (ind.getURI() != null) {
optionsMap.put(ind.getURI(), ind.getName().trim());
}
}
}
return optionsMap;
}
private Map<? extends String, ? extends String> notFoundMsg() {
String msg = "No individuals found for "+ (vclassURIs.size() > 1?"types":"type");
for( String uri : vclassURIs ){
msg += " " + uri;
}
return Collections.singletonMap("", msg);
}
protected Map<String,Individual> getIndividualsForClass(String vclassURI, WebappDaoFactory wDaoFact ){
Map<String, Individual> individualMap = new HashMap<String, Individual>();
IndividualDao indDao = wDaoFact.getIndividualDao();
List<Individual> indsForClass= indDao.getIndividualsByVClassURI(vclassURI, -1, -1);
for (Individual ind : indsForClass) {
if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind);
}
}
// if reasoning isn't available, we will also need to add
// individuals asserted in subclasses
individualMap.putAll( addWhenMissingInference(vclassURI, wDaoFact));
return individualMap;
}
protected boolean isReasoningAvailable( WebappDaoFactory wDaoFact){
boolean inferenceAvailable = false;
if (wDaoFact instanceof WebappDaoFactoryJena) {
PelletListener pl = ((WebappDaoFactoryJena) wDaoFact).getPelletListener();
if (pl != null && pl.isConsistent() && !pl.isInErrorState()
&& !pl.isReasoning()) {
inferenceAvailable = true;
}
}
return inferenceAvailable;
}
protected Map<String, Individual> addWhenMissingInference( String classUri , WebappDaoFactory wDaoFact ){
boolean inferenceAvailable = isReasoningAvailable(wDaoFact);
Map<String,Individual> individualMap = new HashMap<String,Individual>();
if ( !inferenceAvailable ) {
for (String subclassURI : wDaoFact.getVClassDao().getAllSubClassURIs(classUri)) {
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(subclassURI, -1, -1)) {
if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind);
}
}
}
}
return individualMap;
}
}

View file

@ -0,0 +1,60 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
public class RdfTypeOptions implements FieldOptions {
String[] typeURIs;
public RdfTypeOptions(String ... superClassURIs)
throws Exception {
super();
if( superClassURIs == null )
throw new Exception("superClassURIs must be supplied "+
"to constructor.");
this.typeURIs = superClassURIs;
}
@Override
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wdf) {
Map<String,String> uriToLabel = new HashMap<String,String>();
for(int i=0;i<typeURIs.length; i++){
String uri = typeURIs[i];
VClass vc = wdf.getVClassDao().getVClassByURI( uri );
if( vc == null ){
uriToLabel.put(uri,uri);
continue;
}
uriToLabel.put(uri,vc.getPickListName());
List<String> subclassUris = wdf.getVClassDao().getAllSubClassURIs( uri );
if( subclassUris == null )
continue;
for( String subUri : subclassUris ){
VClass subVc = wdf.getVClassDao().getVClassByURI( subUri );
if( vc != null ){
uriToLabel.put(subUri,subVc.getPickListName());
}else{
uriToLabel.put(subUri,subUri);
}
}
}
return uriToLabel;
}
}

View file

@ -0,0 +1,542 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.vocabulary.OWL;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
import edu.cornell.mannlib.vitro.webapp.dao.jena.pellet.PelletListener;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
public class SelectListGeneratorVTwo {
static Log log = LogFactory.getLog(SelectListGeneratorVTwo.class);
public static Map<String,String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact){
if( editConfig == null ){
log.error( "fieldToSelectItemList() must be called with a non-null EditConfigurationVTwo ");
return Collections.EMPTY_MAP;
}
if( fieldName == null ){
log.error( "fieldToSelectItemList() must be called with a non-null fieldName");
return Collections.EMPTY_MAP;
}
FieldVTwo field = editConfig.getField(fieldName);
if (field==null) {
log.error("no field \""+fieldName+"\" found from editConfig.");
return Collections.EMPTY_MAP;
}
if( field.getFieldOptions() == null ){
log.error("cannot get options for a field if it has no FieldOption set.");
return Collections.EMPTY_MAP;
}
try {
return field.getFieldOptions().getOptions(editConfig,fieldName,wDaoFact);
} catch (Exception e) {
log.error("Error runing getFieldOptionis()",e);
return Collections.EMPTY_MAP;
}
}
// public static Map<String,String> getOptionsOldVersion(
// EditConfigurationVTwo editConfig,
// String fieldName,
// WebappDaoFactory wDaoFact){
//
//
// if( editConfig == null ){
// log.error( "fieldToSelectItemList() must be called with a non-null EditConfigurationVTwo ");
// return Collections.EMPTY_MAP;
// }
// if( fieldName == null ){
// log.error( "fieldToSelectItemList() must be called with a non-null fieldName");
// return Collections.EMPTY_MAP;
// }
//
// FieldVTwo field = editConfig.getField(fieldName);
// if (field==null) {
// log.error("no field \""+fieldName+"\" found from editConfig in SelectListGenerator.getOptions()");
// return Collections.EMPTY_MAP;
// }
//
// // now create an empty HashMap to populate and return
// HashMap <String,String> optionsMap = new LinkedHashMap<String,String>();
// // for debugging, keep a count of the number of options populated
// int optionsCount=0;
//
// FieldVTwo.OptionsType optionsType = field.getOptionsType();
// String vclassUri = null;
// switch (optionsType){
// case HARDCODED_LITERALS: // originally not auto-sorted but sorted now, and empty values not removed or replaced
// List<List<String>> hardcodedLiteralOptions = field.getLiteralOptions();
// if (hardcodedLiteralOptions==null) {
// log.error("no literalOptions List found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType HARDCODED_LITERALS specified");
// return new HashMap <String,String>();
// }
// for(Object obj: ((Iterable)hardcodedLiteralOptions)){
// List<String> literalPair = (List)obj;
// String value=(String)literalPair.get(0);
// if( value != null){ // allow empty string as a value
// String label=(String)literalPair.get(1);
// if (label!=null) {
// optionsMap.put(value,label);
// } else {
// optionsMap.put(value, value);
// }
// ++optionsCount;
// }
// }
// break;
// case LITERALS:
// List<List<String>> literalOptions = field.getLiteralOptions();
// if (literalOptions==null) {
// log.error("no literalOptions List found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType LITERALS specified");
// return new HashMap <String,String>();
// }
// for(Object obj: ((Iterable)literalOptions)){
// List<String> literalPair = (List)obj;
// String value=(String)literalPair.get(0);
// if( value != null && value.trim().length() > 0){
// String label=(String)literalPair.get(1);
// if (label!=null && label.trim().length() > 0) {
// optionsMap.put(value,label);
// } else {
// optionsMap.put(value, value);
// }
// ++optionsCount;
// }
// }
// break;
// case STRINGS_VIA_DATATYPE_PROPERTY:
// log.debug("processing Field \""+fieldName+"\" optionType as a datatype property predicateUri in SelectListGenerator.getOptions()");
// String dataPropUri = field.getPredicateUri();
// if (dataPropUri==null || dataPropUri.equals("")){
// log.error("no predicate dataPropUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType STRINGS_VIA_DATATYPE_PROPERTY specified");
// } else {
// /* first test to see whether there's a default "leave blank" value specified with the literal options
// String defaultOption=null;
// if ((defaultOption=getDefaultOption(field))!=null) {
// optionsMap.put(LEFT_BLANK, defaultOption);
// } */
// // now populate the options
// log.debug("finding all choices for data property \""+dataPropUri+"\" in SelectListGenerator.getOptions()");
//
// if( wDaoFact == null ) log.error("incoming WebappDaoFactory from request is null in SelectListGenerator.getOptions().");
//
// DataPropertyStatementDao dpsDao = wDaoFact.getDataPropertyStatementDao();
// DataPropertyDao dpDao = wDaoFact.getDataPropertyDao();
// DataProperty dp = dpDao.getDataPropertyByURI(dataPropUri);
// for (Iterator<DataPropertyStatement> i = dpsDao.getDataPropertyStatements(dp).iterator(); i.hasNext();) {
// DataPropertyStatement dps = i.next();
// if( dps != null ){
// optionsMap.put(dps.getData().trim(),dps.getData().trim());
// ++optionsCount;
// }
// }
// }
// break;
// case INDIVIDUALS_VIA_OBJECT_PROPERTY:
// log.debug("processing Field \""+fieldName+"\" optionType as an object property predicateUri in SelectListGenerator.getOptions()");
// String subjectUri = editConfig.getSubjectUri();
// if (subjectUri==null || subjectUri.equals("")){
// log.error("no subjectUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType INDIVIDUALS_VIA_OBJECTPROPERTY specified");
// } else {
// String predicateUri = field.getPredicateUri();
// if (predicateUri==null || predicateUri.equals("")){
// log.error("no predicateUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType INDIVIDUALS_VIA_OBJECTPROPERTY specified");
// } else {
// // first test to see whether there's a default "leave blank" value specified with the literal options
// String defaultOption=null;
// if ((defaultOption=getDefaultOption(field))!=null) {
// optionsMap.put(LEFT_BLANK, defaultOption);
// }
// // now populate the options
// log.debug("finding range individuals for subject \""+subjectUri+"\" and object property \""+predicateUri+"\" in SelectListGenerator.getOptions()");
//
// if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
//
// Individual subject = wDaoFact.getIndividualDao().getIndividualByURI(subjectUri);
// if( subject == null ) log.error("could not get individual for subject uri "+subjectUri+" in SelectListGenerator.getOptions()");
//
// ObjectProperty objProp = wDaoFact.getObjectPropertyDao().getObjectPropertyByURI(predicateUri);
// if( objProp == null )
// log.error("could not get object property for predicate "+predicateUri+" in SelectListGenerator.getOptions()");
//
// List <VClass> vclasses = new ArrayList<VClass>();
// vclasses = wDaoFact.getVClassDao().getVClassesForProperty(subject.getVClassURI(),predicateUri);
// if( vclasses == null ){
// log.error("no owl:Class found for predicate " + predicateUri );
// break;
// }
// if( vclasses.size() == 0 )
// log.error("no owl:Class found for predicate " + predicateUri );
//
// List<Individual> individuals = new ArrayList<Individual>();
// HashSet<String> uriSet = new HashSet<String>();
// long startTime = System.currentTimeMillis();
// for ( VClass vclass : vclasses){
// for( Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) {
// if( !uriSet.contains(ind.getURI())) {
// uriSet.add(ind.getURI());
// individuals.add(ind);
// }
// }
// }
//
// List<ObjectPropertyStatement> stmts = subject.getObjectPropertyStatements();
// if( stmts == null ) log.error("object properties for subject were null in SelectListGenerator.getOptions()");
//
// individuals = removeIndividualsAlreadyInRange(individuals,stmts,predicateUri,editConfig.getObject());
// //Collections.sort(individuals,new compareIndividualsByName());
//
// for( Individual ind : individuals ){
// String uri = ind.getURI();
// if( uri != null ){
// optionsMap.put(uri,ind.getName().trim());
// ++optionsCount;
// }
// }
//
// }
// }
// break;
// case INDIVIDUALS_VIA_VCLASS: //so we have a vclass URI
// vclassUri = field.getObjectClassUri();
// if (vclassUri==null || vclassUri.equals("")){
// log.error("no vclassUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType INDIVIDUALS_VIA_VCLASS specified");
// } else {
// // first test to see whether there's a default "leave blank" value specified with the literal options
// String defaultOption=null;
// if ((defaultOption=getDefaultOption(field))!=null) {
// optionsMap.put(LEFT_BLANK, defaultOption);
// }
// // now populate the options
// if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
//
// // if reasoning isn't available, we will also need to add
// // individuals asserted in subclasses
// boolean inferenceAvailable = false;
// if (wDaoFact instanceof WebappDaoFactoryJena) {
// PelletListener pl = ((WebappDaoFactoryJena) wDaoFact)
// .getPelletListener();
// if (pl != null && pl.isConsistent()
// && !pl.isInErrorState()
// && !pl.isReasoning()) {
// inferenceAvailable = true;
// }
// }
//
// VClass vclass = wDaoFact.getVClassDao().getVClassByURI( vclassUri );
// if( vclass == null ) {
// log.error("Cannot find owl:Class " + vclassUri + " in the model" );
// optionsMap.put("", "Could not find class " + vclassUri);
// }else{
// Map<String, Individual> individualMap = new HashMap<String, Individual>();
//
// for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) {
// if (ind.getURI() != null) {
// individualMap.put(ind.getURI(), ind);
// }
// }
//
// if (!inferenceAvailable) {
// for (String subclassURI : wDaoFact.getVClassDao().getAllSubClassURIs(vclass.getURI())) {
// for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(subclassURI,-1,-1)) {
// if (ind.getURI() != null) {
// individualMap.put(ind.getURI(), ind);
// }
// }
// }
// }
//
// List<Individual> individuals = new ArrayList<Individual>();
// individuals.addAll(individualMap.values());
// Collections.sort(individuals);
//
// for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) {
// if (ind.getURI() != null) {
// individualMap.put(ind.getURI(), ind);
// }
// }
//
// if (!inferenceAvailable) {
// for (String subclassURI : wDaoFact.getVClassDao().getAllSubClassURIs(vclass.getURI())) {
// for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(subclassURI,-1,-1)) {
// if (ind.getURI() != null) {
// individualMap.put(ind.getURI(), ind);
// }
// }
// }
// }
//
// individuals.addAll(individualMap.values());
// Collections.sort(individuals);
//
// if (individuals.size()==0){
// log.debug("No individuals of type "+vclass.getName()+" to add to pick list in SelectListGenerator.getOptions()");
// optionsMap.put("", "No " + vclass.getName() + " found");
// }else{
// for( Individual ind : individuals ) {
// String uri = ind.getURI();
// if( uri != null ) {
// optionsMap.put(uri,ind.getName().trim());
// ++optionsCount;
// }
// }
// }
// }
// }
// break;
// case CHILD_VCLASSES: //so we have a vclass URI
// vclassUri = field.getObjectClassUri();
// if (vclassUri==null || vclassUri.equals("")){
// log.error("no vclassUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType CHILD_VCLASSES specified");
// } else {
// // first test to see whether there's a default "leave blank" value specified with the literal options
// String defaultOption=null;
// if ((defaultOption=getDefaultOption(field))!=null) {
// optionsMap.put(LEFT_BLANK, defaultOption);
// }
// // now populate the options
// if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
//
// VClassDao vclassDao = wDaoFact.getVClassDao();
// List<String> subClassList = vclassDao.getAllSubClassURIs(vclassUri);
// if( subClassList == null || subClassList.size()==0 ) {
// log.debug("No subclasses of " + vclassUri + " found in the model so only default value from field's literalOptions will be used" );
// } else {
// for( String subClassUri : subClassList ) {
// VClass subClass = vclassDao.getVClassByURI(subClassUri);
// if( subClass != null && !OWL.Nothing.getURI().equals(subClassUri)) {
// optionsMap.put(subClassUri,subClass.getName().trim());
// ++optionsCount;
// }
// }
// }
// }
// break;
//
// case CHILD_VCLASSES_WITH_PARENT: //so we have a vclass URI
// vclassUri = field.getObjectClassUri();
// if (vclassUri==null || vclassUri.equals("")){
// log.error("no vclassUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType CHILD_VCLASSES specified");
// } else {
// // first test to see whether there's a default "leave blank" value specified with the literal options
// String defaultOption=null;
// if ((defaultOption=getDefaultOption(field))!=null) {
// optionsMap.put(LEFT_BLANK, defaultOption);
// }
// // now populate the options
// if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
//
// VClassDao vclassDao = wDaoFact.getVClassDao();
// List<String> subClassList = vclassDao.getAllSubClassURIs(vclassUri);
// if( subClassList == null || subClassList.size()==0 ) {
// log.debug("No subclasses of " + vclassUri + " found in the model so only default value from field's literalOptions will be used" );
// } else {
// for( String subClassUri : subClassList ) {
// VClass subClass = vclassDao.getVClassByURI(subClassUri);
// if( subClass != null && !OWL.Nothing.getURI().equals(subClassUri)) {
// optionsMap.put(subClassUri,subClass.getName().trim());
// ++optionsCount;
// }
// }
// optionsMap.put(vclassUri, "Other");
// ++optionsCount;
// }
// }
// break;
//
// case VCLASSGROUP:
//
// String classGroupUri = field.getObjectClassUri(); // we're overloading this property to specify the classgroup
// if (classGroupUri==null || classGroupUri.equals("")){
// log.error("no classGroupUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType VCLASSGROUP specified");
// } else {
// // first test to see whether there's a default "leave blank" value specified with the literal options
// String defaultOption=null;
// if ((defaultOption=getDefaultOption(field))!=null) {
// optionsMap.put(LEFT_BLANK, defaultOption);
// }
// // now populate the options
// if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
//
// VClassGroupDao vcgd = wDaoFact.getVClassGroupDao();
//
// // Need to call this method to populate the classgroups - otherwise the classgroup class list is empty
// List vClassGroups = vcgd.getPublicGroupsWithVClasses();
//
// if (vClassGroups == null) {
// log.error("No class groups found, so only default value from field's literalOptions will be used.");
// } else {
// VClassGroup vClassGroup = null;
// for (Object o : vClassGroups) {
// VClassGroup vcg = (VClassGroup) o;
// if (vcg.getURI().equals(classGroupUri)) {
// vClassGroup = vcg;
// break;
// }
// }
// if (vClassGroup == null) {
// log.error("No class group with uri " + classGroupUri + "found, so only default value from field's literalOptions will be used.");
// } else {
// List<VClass> vClassList = vClassGroup.getVitroClassList();
//
// if( vClassList == null || vClassList.size()==0 ) {
// log.debug("No classes in class group " + classGroupUri + " found in the model, so only default value from field's literalOptions will be used" );
// } else {
// for( VClass vClass : vClassList ) {
// String vClassUri = vClass.getURI();
// if( vClass != null && !OWL.Nothing.getURI().equals(vClassUri)) {
// optionsMap.put(vClassUri,vClass.getName().trim());
// ++optionsCount;
// }
// }
// }
// }
// }
// }
// break;
//
// case UNDEFINED :
// log.error("optionsType \"UNDEFINED\" for Field \""+fieldName+"\" in SelectListGenerator.getOptions()");
// break;
// default: log.error("unknown optionsType "+optionsType.toString()+" for Field \""+fieldName+"\" in SelectListGenerator.getOptions()");
// }
// log.debug("added "+optionsCount+" options for field \""+fieldName+"\" in SelectListGenerator.getOptions()");
// return optionsMap;
// }
/**
* The default option is used when a option list is being auto
* generated from a VClass or an ObjectProperty. If there is an
* item in the literals item list then the name of it will be used
* as the text to display for an empty string value option.
*
* Having an option with an empty string for a Field that expects
* a URI will cause the form processing to assume that the field
* was left blank.
*
* @param field
* @return
*/
// private static String getDefaultOption(FieldVTwo field) {
// List <List<String>> defaultOptions = (List<List<String>>) field.getLiteralOptions();
// if (defaultOptions!=null) {
// for(Object obj: ((Iterable)defaultOptions)) {
// List<String> pair = (List<String>)obj;
// String value = pair.get(0);
// String label = pair.get(1);
// if( label != null && label.trim().length() > 0){
// return label; // don't want to return a value
// }
// }
// }
// return null;
// }
//
// copied from OptionsForPropertyTag.java in the thought that class may be deprecated
private static List<Individual> removeIndividualsAlreadyInRange(List<Individual> individuals,
List<ObjectPropertyStatement> stmts, String predicateUri, String objectUriBeingEdited){
log.debug("starting to check for duplicate range individuals in SelectListGenerator.removeIndividualsAlreadyInRange() ...");
HashSet<String> range = new HashSet<String>();
for(ObjectPropertyStatement ops : stmts){
if( ops.getPropertyURI().equals(predicateUri))
range.add( ops.getObjectURI() );
}
int removeCount=0;
ListIterator<Individual> it = individuals.listIterator();
while(it.hasNext()){
Individual ind = it.next();
if( range.contains( ind.getURI()) && !(ind.getURI().equals(objectUriBeingEdited)) ) {
it.remove();
++removeCount;
}
}
log.debug("removed "+removeCount+" duplicate range individuals");
return individuals;
}
//Methods to sort the options map
// from http://forum.java.sun.com/thread.jspa?threadID=639077&messageID=4250708
public static Map<String,String> getSortedMap(Map<String,String> hmap){
// first make temporary list of String arrays holding both the key and its corresponding value, so that the list can be sorted with a decent comparator
List<String[]> objectsToSort = new ArrayList<String[]>(hmap.size());
for (String key:hmap.keySet()) {
String[] x = new String[2];
x[0] = key;
x[1] = hmap.get(key);
objectsToSort.add(x);
}
Collections.sort(objectsToSort, new MapPairsComparator());
HashMap<String,String> map = new LinkedHashMap<String,String>(objectsToSort.size());
for (String[] pair:objectsToSort) {
map.put(pair[0],pair[1]);
}
return map;
}
private static class MapPairsComparator implements Comparator<String[]> {
public int compare (String[] s1, String[] s2) {
Collator collator = Collator.getInstance();
if (s2 == null) {
return 1;
} else if (s1 == null) {
return -1;
} else {
if ("".equals(s1[0])) {
return -1;
} else if ("".equals(s2[0])) {
return 1;
}
if (s2[1]==null) {
return 1;
} else if (s1[1] == null){
return -1;
} else {
return collator.compare(s1[1],s2[1]);
}
}
}
}
private static final String LEFT_BLANK = "";
}

View file

@ -18,7 +18,7 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalVali
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils;
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;

View file

@ -17,7 +17,7 @@ import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils;
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;

View file

@ -34,8 +34,8 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTw
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.RdfLiteralHash;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditN3GeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.DefaultAddMissingIndividualFormModelPreprocessor;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
@ -319,18 +319,23 @@ public class DefaultAddMissingIndividualFormGenerator implements EditConfigurati
private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) {
Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>();
if(EditConfigurationUtils.isObjectProperty(EditConfigurationUtils.getPredicateUri(vreq), vreq)) {
fields = getObjectPropertyField(editConfiguration, vreq);
//make name field
FieldVTwo field = new FieldVTwo();
field.setName("name");
List<String> validators = new ArrayList<String>();
validators.add("nonempty");
field.setValidators(validators);
fields.put(field.getName(), field);
} else {
log.error("Is not object property so fields not set");
}
editConfiguration.setFields(fields);
}
private String getRangeClassUri(VitroRequest vreq) {
Individual subject = EditConfigurationUtils.getSubjectIndividual(vreq);
@ -355,36 +360,6 @@ public class DefaultAddMissingIndividualFormGenerator implements EditConfigurati
return rangeClass.getURI();
}
private Map<String, FieldVTwo> getObjectPropertyField(
EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>();
FieldVTwo field = new FieldVTwo();
field.setName("name");
//queryForExisting is not being used anywhere in Field
List<String> validators = new ArrayList<String>();
validators.add("nonempty");
field.setValidators(validators);
//subjectUri and subjectClassUri are not being used in Field
field.setOptionsType("UNDEFINED");
//TODO:check why predicate uri is empty on original jsp
field.setPredicateUri("");
field.setObjectClassUri("");
field.setRangeDatatypeUri(null);
field.setRangeLang(null);
field.setLiteralOptions(new ArrayList<List<String>>());
fields.put(field.getName(), field);
return fields;
}
private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
//Here, retrieve model from
Model model = (Model) session.getServletContext().getAttribute("jenaOntModel");

View file

@ -21,7 +21,7 @@ import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.DefaultDataPropEmptyField;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.RdfLiteralHash;
@ -80,7 +80,6 @@ public class DefaultDataPropertyFormGenerator extends BaseEditConfigurationGener
FieldVTwo literalField = new FieldVTwo()
.setName( literalVar )
.setPredicateUri(predicateUri)
.setRangeDatatypeUri(rangeDatatypeUri);
editConfiguration.addField( literalField );

View file

@ -33,8 +33,8 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTw
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.RdfLiteralHash;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditN3GeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;

View file

@ -20,14 +20,15 @@ import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaObjectPropetyOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
@ -57,19 +58,23 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene
}
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) {
HttpSession session) throws Exception {
//Check if create new and return specific edit configuration from that generator.
if(DefaultAddMissingIndividualFormGenerator.isCreateNewIndividual(vreq, session)) {
DefaultAddMissingIndividualFormGenerator generator = new DefaultAddMissingIndividualFormGenerator();
return generator.getEditConfiguration(vreq, session);
}
//TODO: Add a generator for delete: based on command being delete - propDelete.jsp
//Generate a edit conf for the default object property form and return it.
//Generate a edit configuration for the default object property form and return it.
//if(DefaultDeleteGenerator.isDelete( vreq,session)){
// return (new DefaultDeleteGenerator()).getEditConfiguration(vreq,session);
return getDefaultObjectEditConfiguration(vreq, session);
}
private EditConfigurationVTwo getDefaultObjectEditConfiguration(VitroRequest vreq, HttpSession session) {
private EditConfigurationVTwo getDefaultObjectEditConfiguration(VitroRequest vreq, HttpSession session) throws Exception {
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
//process subject, predicate, object parameters
@ -295,112 +300,19 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene
}
private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) {
private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) throws Exception {
Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>();
if(EditConfigurationUtils.isObjectProperty(EditConfigurationUtils.getPredicateUri(vreq), vreq)) {
fields = getObjectPropertyField(editConfiguration, vreq);
} else {
fields = getDataPropertyField(editConfiguration, vreq);
throw new Exception("DefaultObjectPropertyFormGenerator does not handle data properties.");
}
editConfiguration.setFields(fields);
}
private Map<String, FieldVTwo> getDataPropertyField(
EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>();
FieldVTwo field = new FieldVTwo();
field.setName(dataLiteral);
//queryForExisting is not being used anywhere in Field
String rangeDatatypeUri = getRangeDatatypeUri(editConfiguration, vreq);
String rangeLang = getRangeLang(editConfiguration, vreq);
List<String> validators = new ArrayList<String>();
validators.add("datatype:" + rangeDatatypeUri);
field.setValidators(validators);
//subjectUri and subjectClassUri are not being used in Field
field.setOptionsType("LITERALS");
//why isn't predicate uri set for data properties?
field.setPredicateUri(null);
field.setObjectClassUri(null);
field.setRangeDatatypeUri(rangeDatatypeUri);
//have either range datatype uri or range lang
if(rangeDatatypeUri == null) {
field.setRangeLang(rangeLang);
}
field.setLiteralOptions(getLiteralOptions(editConfiguration, vreq));
fields.put(field.getName(), field);
return fields;
}
private List<List<String>> getLiteralOptions(
EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
DataPropertyStatement dps =EditConfigurationUtils.getDataPropertyStatement(vreq, vreq.getSession(), dataHash, predicateUri);
List<List<String>> literalOptions = new ArrayList<List<String>>();
if(dps == null) {
log.debug("No incoming dataproperty statement attribute for property ; adding a new statement");
String rangeDatatypeUri = getRangeDatatypeUri(editConfiguration, vreq);
if(rangeDatatypeUri != null && rangeDatatypeUri.length() > 0) {
String defaultVal = defaultsForXSDtypes.get(rangeDatatypeUri);
List<String> defaultArray = new ArrayList<String>();
defaultArray.add(defaultVal);
literalOptions.add(defaultArray);
}
}
return literalOptions;
}
private String getRangeLang(EditConfigurationVTwo editConfiguration,
VitroRequest vreq) {
String rangeLang = null;
DataPropertyStatement dps =EditConfigurationUtils.getDataPropertyStatement(vreq, vreq.getSession(), dataHash, predicateUri);
if(dps != null) {
rangeLang = dps.getLanguage();
if( rangeLang == null ) {
log.debug("no language attribute on data property statement in DefaultDataPropertyFormGenerator");
}else{
log.debug("language attribute of ["+rangeLang+"] on data property statement in DefaultDataPropertyFormGenerator");
}
}
if( rangeLang != null && rangeLang.trim().length() == 0)
rangeLang = null;
return rangeLang;
}
private String getRangeDatatypeUri(EditConfigurationVTwo editConfiguration,
VitroRequest vreq) {
Individual subject = EditConfigurationUtils.getSubjectIndividual(vreq);
DataProperty prop = EditConfigurationUtils.getDataProperty(vreq);
//rangeDefaultJson goes into literalk options
//validations include dataype:rangedatatypeurijson
//rangeDatatypeUri is rangeDAttypeUriJson
//rangeLang = rangeLanJson
DataPropertyStatement dps =EditConfigurationUtils.getDataPropertyStatement(vreq, vreq.getSession(), dataHash, predicateUri);
String rangeDatatypeUri = vreq.getWebappDaoFactory().getDataPropertyDao().getRequiredDatatypeURI(subject, prop);
if( dps != null ){
rangeDatatypeUri = dps.getDatatypeURI();
if( rangeDatatypeUri == null ){
log.debug("no range datatype uri set on data property statement when property's range datatype is "+prop.getRangeDatatypeURI()+" in DefaultDataPropertyFormGenerator");
} else {
log.debug("range datatype uri of ["+rangeDatatypeUri+"] on data property statement in DefaultDataPropertyFormGenerator");
}
} else {
log.debug("No incoming dataproperty statement attribute for property "+prop.getPublicName()+"; adding a new statement");
}
if( rangeDatatypeUri != null && rangeDatatypeUri.trim().length() == 0)
rangeDatatypeUri = null;
return rangeDatatypeUri;
}
}
private Map<String, FieldVTwo> getObjectPropertyField(
EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
EditConfigurationVTwo editConfiguration, VitroRequest vreq) throws Exception {
Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>();
FieldVTwo field = new FieldVTwo();
field.setName("objectVar");
@ -409,20 +321,13 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene
List<String> validators = new ArrayList<String>();
validators.add("nonempty");
field.setValidators(validators);
//subjectUri and subjectClassUri are not being used in Field
field.setOptionsType("INDIVIDUALS_VIA_OBJECT_PROPERTY");
field.setPredicateUri(predicateUri);
field.setObjectClassUri(null);
field.setRangeDatatypeUri(null);
field.setRangeLang(null);
field.setLiteralOptions(new ArrayList<List<String>>());
fields.put(field.getName(), field);
field.setOptions( new IndividualsViaObjectPropetyOptions(
subjectUri,
predicateUri,
objectUri));
fields.put(field.getName(), field);
return fields;

View file

@ -8,5 +8,5 @@ import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
public interface EditConfigurationGenerator {
public EditConfigurationVTwo getEditConfiguration( VitroRequest vreq, HttpSession session );
public EditConfigurationVTwo getEditConfiguration( VitroRequest vreq, HttpSession session ) throws Exception;
}

View file

@ -0,0 +1,313 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.ManagePagePreprocessor;
import edu.cornell.mannlib.vitro.webapp.utils.dataGetter.DataGetterUtils;
import edu.cornell.mannlib.vitro.webapp.utils.menuManagement.MenuManagementDataUtils;
/**
* Generates the form for adding and editing a page in the display model.
*
*/
public class ManagePageGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator{
private String template = "pageManagement.ftl";
public static final String defaultDisplayNs = DisplayVocabulary.NAMESPACE.getURI() + "n";
@Override
public EditConfigurationVTwo getEditConfiguration( VitroRequest vreq, HttpSession session) {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
conf.setTemplate(template);
//get editkey and url of form
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
//if object uri exists, sets object URI
initObjectPropForm(conf, vreq);
//Depending on whether this is a new individual to be created or editing
//an existing one, the var names will differ
setVarNames(conf);
//Set N3 required and optional
setN3Required(conf);
setN3Optional(conf);
//Designate new resources if any exist
setNewResources(conf);
//Add sparql queries
setSparqlQueries(conf);
// In scope
setUrisAndLiteralsInScope(conf, vreq);
// on Form
setUrisAndLiteralsOnForm(conf, vreq);
//Set the fields
setFields(conf);
//Adding additional data, specifically edit mode
addFormSpecificData(conf, vreq);
//Add preprocessor
conf.addEditSubmissionPreprocessor(new ManagePagePreprocessor(conf));
//Prepare
prepare(vreq, conf);
return conf ;
}
private void setUrisAndLiteralsOnForm(EditConfigurationVTwo conf,
VitroRequest vreq) {
conf.setUrisOnForm(new String[]{"page", "menuItem"}); //new resources: should this be on form for new - should be for existing
conf.setLiteralsOnForm(new String[]{"pageName", "prettyUrl", "menuPosition", "menuLinkText", "customTemplate", "pageContentUnit"}); //page content unit = data getter JSON object
}
private void setUrisAndLiteralsInScope(EditConfigurationVTwo conf,
VitroRequest vreq) {
//URIs
conf.addUrisInScope(conf.getVarNameForSubject(),
Arrays.asList(new String[]{conf.getSubjectUri()}));
conf.addUrisInScope(conf.getVarNameForPredicate(),
Arrays.asList(new String[]{conf.getPredicateUri()}));
}
private void setN3Optional(EditConfigurationVTwo conf) {
//body template is not required, and a given page may or may not be a menu item, but should linked to menu if menu item
conf.setN3Optional(new ArrayList<String>(Arrays.asList(prefixes + pageBodyTemplateN3,
prefixes + menuItemN3 + menuN3)));
}
private void setN3Required(EditConfigurationVTwo conf) {
conf.setN3Required(new ArrayList<String>(Arrays.asList(prefixes + pageN3)));
}
private void setFields(EditConfigurationVTwo conf) {
//Required fields for page include: Page title, page URL Mapping
//Data getter fields will be dealt with in preprocessor/util classes
//Optional fields for page include body template
//required, therefore nonempty
FieldVTwo titleField = new FieldVTwo().setName("pageName").
setValidators(Arrays.asList("nonempty"));
conf.addField(titleField);
FieldVTwo urlField = new FieldVTwo().setName("prettyUrl").setValidators(Arrays.asList("nonempty"));
conf.addField(urlField);
//optional: body template
FieldVTwo bodyTemplateField = new FieldVTwo().setName("customTemplate");
conf.addField(bodyTemplateField);
//For menu item, these are optional b/c they depend on menu item
FieldVTwo menuItemLinkTextField = new FieldVTwo().setName("menuLinkText");
conf.addField(menuItemLinkTextField);
FieldVTwo menuItemPositionField = new FieldVTwo().setName("menuPosition");
conf.addField(menuItemPositionField);
//The actual page content information is stored in this field, and then
//interpreted using the preprocessor
FieldVTwo pageContentUnitField = new FieldVTwo().setName("pageContentUnit");
conf.addField(pageContentUnitField);
//For existing values, will need to include fields here
}
private void setVarNames(EditConfigurationVTwo conf) {
if(conf.getSubjectUri() != null) {
conf.setVarNameForSubject("page");
conf.setVarNameForPredicate("predicate");
} else {
conf.setVarNameForSubject("subjectNotUsed");
conf.setVarNameForPredicate("predicateNotUsed");
}
}
//overriding
@Override
void initPropertyParameters(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
String subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
//For the case of a new page
if(subjectUri == null) {
//Once added, return to pageList
editConfiguration.setUrlToReturnTo("/pageList");
editConfiguration.setEntityToReturnTo("?page");
editConfiguration.setPredicateUri(predicateUri);
} else {
//For the case of an existing page
//Page title pageName or page hasDataGetter dataGetter
editConfiguration.setUrlPatternToReturnTo("/individual");
editConfiguration.setEntityToReturnTo(subjectUri);
}
editConfiguration.setSubjectUri(subjectUri);
editConfiguration.setPredicateUri(predicateUri);
}
//also overriding
@Override
void prepare(VitroRequest vreq, EditConfigurationVTwo editConfig) {
//setup the model selectors for query, write and display models on editConfig
//Double-check if this will even work with over-written model in the case of display model?
setupModelSelectorsFromVitroRequest(vreq, editConfig);
OntModel queryModel = (OntModel)vreq.getAttribute("jenaOntModel");
if (editConfig.getSubjectUri() != null) {
editConfig.prepareForObjPropUpdate(queryModel);
}
else{
//if no subject uri, this is creating a new page
editConfig.prepareForNonUpdate(queryModel);
}
}
//In the case where this is a new page, need to ensure page gets a new
private void setNewResources(EditConfigurationVTwo conf) {
//null makes default namespace be triggered
conf.addNewResource("page", defaultDisplayNs);
conf.addNewResource("menuItem", defaultDisplayNs);
}
//This is for various items
private void setSparqlQueries(EditConfigurationVTwo editConfiguration) {
//Sparql queries defining retrieval of literals etc.
editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap<String, String>());
Map<String, String> urisInScope = new HashMap<String, String>();
editConfiguration.setSparqlForAdditionalUrisInScope(urisInScope);
editConfiguration.setSparqlForExistingLiterals(generateSparqlForExistingLiterals());
editConfiguration.setSparqlForExistingUris(generateSparqlForExistingUris());
}
//Get page uri for object
private HashMap<String, String> generateSparqlForExistingUris() {
HashMap<String, String> map = new HashMap<String, String>();
return map;
}
private HashMap<String, String> generateSparqlForExistingLiterals() {
HashMap<String, String> map = new HashMap<String, String>();
return map;
}
//Form specific data
//In this case, need to get all the different data getter TYPES and labels
//Also need to pass back the map for the options presented to the user
//which is different from the above
//Maybe mapping where it does exist? I.e. sparql query from drop-down IS sparql query data getter
//Class group is hard-coded to class group but otherwise it can be changed
//Based on circumstances - specifically internal class data getter
//Need to get the hash for data getter to label TO the form so
//that can then be read by javascript?
//Also pass back current menu position?
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
//Get options for user: label to data getter type
//For every type of page, will need some "always required" data
addRequiredPageData(vreq, formSpecificData);
//For a new page, we will need to add the following data
addNewPageData(vreq, formSpecificData);
editConfiguration.setFormSpecificData(formSpecificData);
}
private String getTemplate(EditConfigurationVTwo editConfiguration) {
String returnTemplate = "default";
if(editConfiguration.getSubjectUri() != null) {
//Then template is EXISTING template
//TODO: Get existing template value for page
}
return returnTemplate;
}
private void addRequiredPageData(VitroRequest vreq, Map<String, Object> data) {
MenuManagementDataUtils.includeRequiredSystemData(vreq.getSession().getServletContext(), data);
}
private void addNewPageData(VitroRequest vreq, Map<String, Object> data) {
data.put("title", "Add Menu Item");
data.put("menuAction", "Add");
//Generate empty values for fields
data.put("menuItem", "");
data.put("pageName", "");
data.put("prettyUrl", "");
data.put("associatedPage", "");
data.put("associatedPageURI", "");
data.put("classGroup", new ArrayList<String>());
//not a page already assigned a class group
data.put("isClassGroupPage", false);
data.put("includeAllClasses", false);
data.put("classGroups", DataGetterUtils.getClassGroups(vreq.getSession().getServletContext()));
data.put("selectedTemplateType", "default");
//defaults to regular class group page
}
//N3 strings
//For new or existing page
final static String prefixes = "@prefix display: <http://vitro.mannlib.cornell.edu/ontologies/display/1.1#> . \n" +
"@prefix rdfs:<http://www.w3.org/2000/01/rdf-schema#> . \n";
final static String pageN3 = "?page a display:Page ; \n" +
"display:title ?pageName ;\n" +
"display:urlMapping ?prettyUrl .";
//"display:hasDataGetter ?pageDataGetter .";
//A page may also require a body template so we can get that here as well
//That would be optional
final static String pageBodyTemplateN3 = "?page display:requiresBodyTemplate ?customTemplate .";
//Menu position is added dynamically at end by default and can be changed on reordering page
final static String menuItemN3 = "?menuItem a display:NavigationElement ; \n" +
"display:menuPosition ?menuPosition; \n" +
"display:linkText ?menuLinkText; \n" +
"display:toPage ?page .";
//We define n3 here from default menu item up through page, but data getters are added dyamically
//so will be dealt with in the preprocessor
final static String menuN3 = "display:DefaultMenu display:hasElement ?menuItem .";
//These are public static methods that can be used in the preprocessor
public final static String getDataGetterN3(String dataGetterVar) {
return prefixes + "?page display:hasDataGetter " + dataGetterVar + ".";
}
}

View file

@ -29,8 +29,8 @@ import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
import edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils;
@ -371,9 +371,7 @@ public class MenuEditingFormGenerator implements EditConfigurationGenerator {
List<String> validators = new ArrayList<String>();
validators.add("nonempty");
field.setValidators(validators);
field.setOptionsType("LITERALS");
field.setPredicateUri(DisplayVocabulary.DISPLAY_NS + "title");
field.setValidators(validators);
fields.put("title", field);
//Object Var Field

View file

@ -37,8 +37,8 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.RdfLiteralHash;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditN3GeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
@ -243,24 +243,12 @@ public class NewIndividualFormGenerator implements EditConfigurationGenerator {
private void setLabelField(EditConfigurationVTwo editConfiguration,
VitroRequest vreq, Map<String, FieldVTwo> fields) {
FieldVTwo field = new FieldVTwo();
field.setName("label");
//queryForExisting is not being used anywhere in Field
String stringDatatypeUri = XSD.xstring.toString();
field.setName("label");
field.setRangeDatatypeUri( XSD.xstring.toString() );
List<String> validators = new ArrayList<String>();
validators.add("nonempty");
field.setValidators(validators);
//subjectUri and subjectClassUri are not being used in Field
field.setOptionsType("UNDEFINED");
//why isn't predicate uri set for data properties?
field.setPredicateUri(null);
field.setObjectClassUri(null);
field.setRangeDatatypeUri(stringDatatypeUri);
field.setLiteralOptions(new ArrayList<List<String>>());
field.setValidators(validators);
fields.put(field.getName(), field);
editConfiguration.setFields(fields);

View file

@ -34,8 +34,8 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.RdfLiteralHash;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditN3GeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
@ -231,33 +231,19 @@ public class RDFSLabelGenerator implements EditConfigurationGenerator {
String rangeDatatypeUri = getRangeDatatypeUri(editConfiguration, vreq);
String rangeLang = getRangeLang(editConfiguration, vreq);
List<String> validators = getFieldValidators(editConfiguration, vreq);
field.setValidators(validators);
//subjectUri and subjectClassUri are not being used in Field
field.setOptionsType("UNDEFINED");
//why isn't predicate uri set for data properties?
field.setPredicateUri(null);
field.setObjectClassUri(null);
List<String> validators = getFieldValidators(editConfiguration, vreq);
field.setValidators(validators);
field.setRangeDatatypeUri(rangeDatatypeUri);
//have either range datatype uri or range lang, otherwise results in error
if(rangeDatatypeUri == null) {
field.setRangeLang(rangeLang);
}
field.setLiteralOptions(getLiteralOptions(editConfiguration, vreq));
fields.put(field.getName(), field);
return fields;
}
private List<List<String>> getLiteralOptions(
EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
DataPropertyStatement dps =EditConfigurationUtils.getDataPropertyStatement(vreq, vreq.getSession(), dataHash, predicateUri);
List<List<String>> literalOptions = new ArrayList<List<String>>();
return literalOptions;
}
private String getRangeLang(EditConfigurationVTwo editConfiguration,
VitroRequest vreq) {

View file

@ -0,0 +1,49 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import java.util.Arrays;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
public class RdfTypeGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator {
private Log log = LogFactory.getLog(RdfTypeGenerator.class);
@Override
public EditConfigurationVTwo getEditConfiguration( VitroRequest vreq, HttpSession session) {
EditConfigurationVTwo editConfig = new EditConfigurationVTwo();
//get editkey and url of form
initBasics(editConfig, vreq);
initPropertyParameters(vreq, session, editConfig);
initObjectPropForm(editConfig, vreq);
editConfig.addUrisInScope("rdfTypeUri", Arrays.asList( RDF.type.getURI() ) );
editConfig.setN3Required( " ?subject ?rdfTypeUri ?object . ");
//set fields
editConfig.setUrisOnForm("object");
editConfig.addField( new FieldVTwo( )
.setName("object")
.setOptions(
new ChildVClassesOptions(OWL.Class.getURI()) )
);
editConfig.setTemplate("rdfTypeForm.ftl");
return editConfig;
}
}

View file

@ -0,0 +1,274 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.vocabulary.RDFS;
import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.BaseEditSubmissionPreprocessorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.ManagePageGenerator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessDataGetterN3;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessDataGetterN3Utils;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class ManagePagePreprocessor extends
BaseEditSubmissionPreprocessorVTwo {
protected static final Log log = LogFactory
.getLog(ManagePagePreprocessor.class.getName());
private static MultiValueEditSubmission submission = null;
private static EditConfigurationVTwo editConfiguration = null;
private static Map<String, List<String>> transformedLiteralsFromForm = null;
private static Map<String, List<String>> urisFromForm = null;
private static List<String> pageContentUnits = null;//String submission from form
private static List<JSONObject> pageContentUnitsJSON = null;//converted to JSON objects that can be read
// String datatype
// Will be editing the edit configuration as well as edit submission here
public ManagePagePreprocessor(EditConfigurationVTwo editConfig) {
super(editConfig);
editConfiguration = editConfig;
}
public void preprocess(MultiValueEditSubmission inputSubmission) {
submission = inputSubmission;
// Get the input elements for concept node and concept label as well
// as vocab uri (which is based on thge
// For query parameters, check whether CUI
copySubmissionValues();
processDataGetters();
}
//Since we will change the uris and literals from form, we should make copies
//of the original values and store them, this will also make iterations
//and updates to the submission independent from accessing the values
private void copySubmissionValues() {
Map<String, List<Literal>> literalsFromForm = submission.getLiteralsFromForm();
transformedLiteralsFromForm = copyMap(EditConfigurationUtils.transformLiteralMap(literalsFromForm));
urisFromForm = copyMap(submission.getUrisFromForm());
pageContentUnits = transformedLiteralsFromForm.get("pageContentUnit");
}
private Map<String, List<String>> copyMap(
Map<String, List<String>> originalMap) {
Map<String, List<String>> copyMap = new HashMap<String, List<String>>();
copyMap.putAll(originalMap);
return copyMap;
}
private void processDataGetters() {
convertToJson();
int counter = 0;
for(JSONObject jsonObject:pageContentUnitsJSON) {
String dataGetterClass = getDataGetterClass(jsonObject);
ProcessDataGetterN3 pn = ProcessDataGetterN3Utils.getDataGetterProcessorN3(dataGetterClass);
//Add n3 required
addN3Required(pn, counter);
//Add N3 Optional as well
addN3Optional(pn, counter);
// Add URIs on Form and Add Literals On Form
addLiteralsAndUrisOnForm(pn, counter);
// Add fields
addFields(pn, counter);
//Add new resources - data getters need to be new resources
addNewResources(pn, counter);
//Add input values to submission
addInputsToSubmission(pn, counter, jsonObject);
counter++;
}
}
private void addNewResources(ProcessDataGetterN3 pn, int counter) {
// TODO Auto-generated method stub
List<String> newResources = pn.getNewResources(counter);
for(String newResource:newResources) {
editConfiguration.addNewResource(newResource, ManagePageGenerator.defaultDisplayNs);
}
}
private void convertToJson() {
//Iterate through list of inputs
pageContentUnitsJSON = new ArrayList<JSONObject>();
for(String pageContentUnit: pageContentUnits) {
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( pageContentUnit );
pageContentUnitsJSON.add(jsonObject);
}
}
//This is where the actual values will be submitted as if they were separate input fields
//Each field name will correspond to the names of the fileds/uris on form/literals on form
//generated here
private void addInputsToSubmission(ProcessDataGetterN3 pn, int counter, JSONObject jsonObject) {
List<String> literalLabels = pn.getLiteralVarNamesBase();
List<String> uriLabels = pn.getUriVarNamesBase();
for(String literalLabel:literalLabels) {
//TODO: Deal with multiple submission values
//This retrieves the value for this particular json object
String literalValue = jsonObject.getString(literalLabel);
//Var names will depend on which data getter object this is on the page, so depends on counter
String submissionLiteralName = pn.getVarName(literalLabel, counter);
//This adds literal, connecting the field with
submission.addLiteralToForm(editConfiguration, editConfiguration.getField(submissionLiteralName), submissionLiteralName, new String[]{literalValue});
}
for(String uriLabel:uriLabels) {
//TODO: Deal with multiple submission values
//This retrieves the value for this particular json object
String uriValue = jsonObject.getString(uriLabel);
//Var names will depend on which data getter object this is on the page, so depends on counter
String submissionUriName = pn.getVarName(uriLabel, counter);
//This adds literal, connecting the field with
submission.addLiteralToForm(editConfiguration, editConfiguration.getField(submissionUriName), submissionUriName, new String[]{uriValue});
}
//this needs to be different
//Get the literals directly from the processor - which you can get based on counter
//Problem then is we know what the connection is - some way to put that logic within the processor itself?
//It already knows the json object
//--> Get field for this base label, with counter value - that you get from configuration
/*
while(jsonObject.keys().hasNext())
{
//Other than class, all other variables considered a submission value corresponding to field
String key = (String) jsonObject.keys().next();
if(key != "dataGetterClass") {
//not expecting multiple values, so will need to either make this array or
//think about this some more
//TODO: Consider multiple values here
Map<String, String[]> submissionValues = new HashMap<String, String[]>();
submissionValues.put(key, new String[]{jsonObject.getString(key)} );
if(literalLabels.contains(key)) {
submission.addLiteralToForm(editConfiguration.getField(key), field, var, valuesArray)
}
}
}
List<String> uris = pn.retrieveUrissOnForm(counter);
for(String l:literals) {
//json object should have
submissionValues.put(l, new String[]{jsonObject.getString(l)} );
}*/
}
private void addFields(ProcessDataGetterN3 pn, int counter) {
List<FieldVTwo> fields = pn.retrieveFields(counter);
editConfiguration.addFields(fields);
}
//original literals on form: label, uris on form: conceptNode and conceptSource
//This will overwrite the original values in the edit configuration
private void addLiteralsAndUrisOnForm(ProcessDataGetterN3 pn, int counter) {
List<String> literalsOnForm = pn.retrieveLiteralsOnForm(counter);
editConfiguration.addLiteralsOnForm(literalsOnForm);
List<String> urisOnForm = pn.retrieveUrisOnForm(counter);
editConfiguration.addUrisOnForm(urisOnForm);
}
// N3 being reproduced
/*
* ?subject ?predicate ?conceptNode .
*/
//This will overwrite the original with the set of new n3 required
private void addN3Required(ProcessDataGetterN3 pn, int counter) {
//Use the process utils to figure out what class required to retrieve the N3 required
List<String> requiredList = pn.retrieveN3Required(counter);
//Add connection between data getter and page
requiredList.addAll(getPageToDataGetterN3(pn, counter));
if(requiredList != null) {
editConfiguration.addN3Required(requiredList);
}
}
private List<String> getPageToDataGetterN3(
ProcessDataGetterN3 pn, int counter) {
String dataGetterVar = pn.getDataGetterVar(counter);
//Put this method in the generator but can be put elsewhere
String pageToDataGetterN3 = ManagePageGenerator.getDataGetterN3(dataGetterVar);
return Arrays.asList(pageToDataGetterN3);
}
//Add n3 optional
private void addN3Optional(ProcessDataGetterN3 pn, int counter) {
List<String> optionalList = pn.retrieveN3Optional(counter);
if(optionalList != null) {
editConfiguration.addN3Optional(optionalList);
}
}
private String[] convertDelimitedStringToArray(String inputString) {
String[] inputArray = new String[1];
if (inputString.indexOf(",") != -1) {
inputArray = inputString.split(",");
} else {
inputArray[0] = inputString;
}
return inputArray;
}
private Object getFirstElement(List inputList) {
if(inputList == null || inputList.size() == 0)
return null;
return inputList.get(0);
}
//Each JSON Object will indicate the type of the data getter within it
private String getDataGetterClass(JSONObject jsonObject) {
String javaURI = jsonObject.getString("dataGetterClass");
return getQualifiedDataGetterName(javaURI);
}
//Get rid of java: in front of class name
private String getQualifiedDataGetterName(String dataGetterTypeURI) {
String javaURI = "java:";
if(dataGetterTypeURI.startsWith(javaURI)) {
int beginIndex = javaURI.length();
return dataGetterTypeURI.substring(beginIndex);
}
return dataGetterTypeURI;
}
}

View file

@ -0,0 +1,26 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils;
import java.util.ArrayList;
import java.util.List;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
//Returns the appropriate n3 based on data getter
public interface ProcessDataGetterN3 {
public List<String> retrieveN3Required(int counter);
public List<String> retrieveN3Optional(int counter);
public List<String >retrieveLiteralsOnForm(int counter);
public List<String> retrieveUrisOnForm(int counter);
public List<FieldVTwo> retrieveFields(int counter);
public List<String> getLiteralVarNamesBase();
public List<String> getUriVarNamesBase();
public String getVarName(String base, int counter);
public String getDataGetterVar(int counter);
public List<String> getNewResources(int counter);
}

View file

@ -0,0 +1,53 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelContext;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessDataGetterN3;
/*
* This class determines what n3 should be returned for a particular data getter and can be overwritten or extended in VIVO.
*/
public class ProcessDataGetterN3Utils {
private static final Log log = LogFactory.getLog(ProcessDataGetterN3Utils.class);
public static HashMap<String, String> getDataGetterTypeToProcessorMap() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("edu.cornell.mannlib.vitro.webapp.utils.dataGetter.SparqlQueryDataGetter", "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessSparqlDataGetterN3");
return map;
}
public static ProcessDataGetterN3 getDataGetterProcessorN3(String dataGetterClass) {
HashMap<String, String> map = getDataGetterTypeToProcessorMap();
//
if(map.containsKey(dataGetterClass)) {
String processorClass = map.get(dataGetterClass);
try {
Class<?> clz = Class.forName(processorClass);
//Don't actually need to pass in json object since that includes the actual submission values
ProcessDataGetterN3 pn = (ProcessDataGetterN3) clz.getConstructor().newInstance();
return pn;
} catch(Exception ex) {
log.error("Exception occurred in trying to get processor class for n3 for " + dataGetterClass, ex);
return null;
}
}
return null;
}
}

View file

@ -0,0 +1,127 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
//Returns the appropriate n3 based on data getter
public class ProcessSparqlDataGetterN3 implements ProcessDataGetterN3 {
private static String classType = "java:edu.cornell.mannlib.vitro.webapp.utils.dataGetter.SparqlQueryDataGetter";
public ProcessSparqlDataGetterN3(){
}
//Pass in variable that represents the counter
//TODO: ensure correct model returned
//We shouldn't use the ACTUAL values here but generate the n3 required
public List<String> retrieveN3Required(int counter) {
String dataGetterVar = getDataGetterVar(counter);
String n3 = dataGetterVar + " a <" + classType + ">; \n" +
"display:queryModel " + getN3VarName("queryModel", counter) + "; \n" +
"display:saveToVar " + getN3VarName("saveToVar", counter) + "; \n" +
"display:query " + getN3VarName("query", counter) + " .";
List<String> requiredList = new ArrayList<String>();
requiredList.add(getPrefixes() + n3);
return requiredList;
}
public List<String> retrieveN3Optional(int counter) {
return null;
}
//placeholder so need "?" in front of the variable
public String getDataGetterVar(int counter) {
return "?dataGetter" + counter;
}
private String getPrefixes() {
return "@prefix display: <http://vitro.mannlib.cornell.edu/ontologies/display/1.1#> . \n" +
"@prefix rdfs:<http://www.w3.org/2000/01/rdf-schema#> . \n";
}
//Need to add method sfor returning the fields, literals on form, and all that
/*
* addLiteralsAndUrisOnForm(pn, counter);
// Add fields
addFields(pn, counter);
//Add input values to submission
addInputsToSubmission(pn, counter);
*/
public List<String> retrieveLiteralsOnForm(int counter) {
List<String> literalsOnForm = new ArrayList<String>();
literalsOnForm.add(getVarName("saveToVar",counter));
literalsOnForm.add(getVarName("query", counter));
return literalsOnForm;
}
public List<String> retrieveUrisOnForm(int counter) {
List<String> urisOnForm = new ArrayList<String>();
//We have no uris as far as I know.. well query Model is a uri
urisOnForm.add(getVarName("queryModel", counter));
return urisOnForm;
}
public List<FieldVTwo> retrieveFields(int counter) {
List<FieldVTwo> fields = new ArrayList<FieldVTwo>();
//An alternative way of doing this
/*
List<String> allFieldsBase = new ArrayList<String>();
allFieldsBase.addAll(getLiteralVarNamesBase());
allFieldsBase.addAll(getUriVarNamesBase());
for(String varName: allFieldsBase) {
fields.add(new FieldVTwo().setName(getVarName(varName, counter)));
} */
//For existing data getters
//fields.add(new FieldVTwo().setName(getVarName("dataGetter", counter)));
fields.add(new FieldVTwo().setName(getVarName("queryModel", counter)));
fields.add(new FieldVTwo().setName(getVarName("saveToVar", counter)));
fields.add(new FieldVTwo().setName(getVarName("query", counter)));
return fields;
}
public List<String> getLiteralVarNamesBase() {
return Arrays.asList("saveToVar", "query");
}
//these are for the fields ON the form
public List<String> getUriVarNamesBase() {
return Arrays.asList("queryModel");
}
public String getVarName(String base, int counter) {
return base + counter;
}
//For use within n3 strings, need a "?"
public String getN3VarName(String base, int counter) {
return "?" + getVarName(base, counter);
}
//Return name of new resources
public List<String> getNewResources(int counter) {
//Each data getter requires a new resource
List<String> newResources = new ArrayList<String>();
newResources.add("dataGetter" + counter);
return newResources;
}
}

View file

@ -1,154 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.datatypes.xsd.XSDDateTime;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary.Precision;
import edu.cornell.mannlib.vitro.webapp.edit.elements.DateTimeWithPrecision;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
public class DateTimeIntervalValidation implements N3Validator {
private static Log log = LogFactory.getLog(DateTimeIntervalValidation.class);
private String startFieldName;
private String endFieldName;
private String startValueName;
private String endValueName;
private String startPrecisionName;
private String endPrecisionName;
public DateTimeIntervalValidation(String startFieldName, String endFieldName){
this.startFieldName = startFieldName;
this.endFieldName = endFieldName;
startValueName = startFieldName + "-value";
endValueName = endFieldName + "-value";
startPrecisionName = startFieldName + "-precision";
endPrecisionName = endFieldName + "-precision";
}
public Map<String, String> validate(EditConfiguration editConfig,
EditSubmission editSub) {
Map<String, Literal> existingLiterals = editConfig.getLiteralsInScope();
Literal existingStartYear = existingLiterals.get(startValueName);
Literal existingEndYear = existingLiterals.get(endValueName);
Map<String, Literal> literalsFromForm = editSub.getLiteralsFromForm();
Literal formStartYear = literalsFromForm.get(startValueName);
Literal formEndYear = literalsFromForm.get(endValueName);
VitroVocabulary.Precision startPrecision = getPrecision(startPrecisionName, editConfig, editSub);
VitroVocabulary.Precision endPrecision = getPrecision(endPrecisionName, editConfig, editSub);
Map<String, String> errors = new HashMap<String, String>();
// NIHVIVO-2541 Commented out to allow end date with no start date
// if( formStartYear == null && formEndYear != null ){
// errors.put(startFieldName, "If there is an end date, there should be a start date");
// return errors;
// }
if (formStartYear != null && formEndYear != null) {
errors.putAll(checkDateLiterals(formStartYear, formEndYear, startPrecision, endPrecision));
} else if (formStartYear != null && existingEndYear != null) {
errors.putAll(checkDateLiterals(formStartYear, existingEndYear, startPrecision, endPrecision));
} else if (existingStartYear != null && formEndYear != null) {
errors.putAll(checkDateLiterals(existingStartYear, formEndYear, startPrecision, endPrecision));
} else if (existingStartYear != null && existingEndYear != null) {
errors.putAll(checkDateLiterals(existingStartYear, existingEndYear, startPrecision, endPrecision));
}
if (errors.size() != 0)
return errors;
else
return null;
}
private Precision getPrecision(String precisionVarName,
EditConfiguration editConfig, EditSubmission editSub) {
if( editSub != null
&& editSub.getUrisFromForm() != null
&& editSub.getUrisFromForm().containsKey(precisionVarName)){
String precisionStr = editSub.getUrisFromForm().get(precisionVarName);
VitroVocabulary.Precision precision = DateTimeWithPrecision.toPrecision( precisionStr );
if( precision == null )
log.warn("cannot convert " + precisionStr + " to a precision");
else
return precision;
}else if( editConfig != null
&& editConfig.getUrisInScope() != null
&& editConfig.getUrisInScope().containsKey(precisionVarName)){
String precisionStr = editConfig.getUrisInScope().get(precisionVarName);
VitroVocabulary.Precision precision = DateTimeWithPrecision.toPrecision( precisionStr );
if( precision == null )
log.warn("cannot convert " + precisionStr + " to a precision");
else
return precision;
}
//this is what is returned if a precision was not found in the config or submission
return null;
}
private Map<String, String> checkDateLiterals(
Literal startLit, Literal endLit,
VitroVocabulary.Precision startPrecision, VitroVocabulary.Precision endPrecision) {
Map<String, String> errors = new HashMap<String, String>();
if( endPrecision == null ){
//there is no end date, nothing to check
return errors;
}
try{
XSDDateTime startDate = (XSDDateTime)startLit.getValue();
XSDDateTime endDate = (XSDDateTime)endLit.getValue();
if( startDate != null && endDate!= null ){
Calendar startCal = startDate.asCalendar();
Calendar endCal = endDate.asCalendar();
if( endCal != null ){
if( !startCal.before( endCal ) ){
if( startPrecision == VitroVocabulary.Precision.YEAR
&& endPrecision == VitroVocabulary.Precision.YEAR ){
errors.putAll( checkYears(startCal,endCal));
}else{
errors.put(startFieldName, "Start must be before end");
errors.put(endFieldName, "End must be after start");
}
}
}
}
}catch(ClassCastException cce){
errors.put(startFieldName, "could not format start or end date");
errors.put(endFieldName, "could not format start or end date");
log.debug("could not format dates " + cce);
}
return errors;
}
private Map<? extends String, ? extends String> checkYears(
Calendar startCal, Calendar endCal) {
Map<String, String> errors = new HashMap<String, String>();
if( ! (endCal.get(Calendar.YEAR) >= startCal.get(Calendar.YEAR) )){
errors.put(startFieldName, "Start must be before end");
errors.put(endFieldName, "End must be after start");
}
return errors;
}
}

View file

@ -153,7 +153,7 @@ public class EditRequestDispatchController extends FreemarkerHttpServlet {
//TODO: should more of what happens in this method
//happen in the generators?
private EditConfigurationVTwo setupEditConfiguration(String editConfGeneratorName,
VitroRequest vreq) {
VitroRequest vreq) throws Exception {
HttpSession session = vreq.getSession();
EditConfigurationVTwo editConfig =
makeEditConfigurationVTwo( editConfGeneratorName, vreq, session);
@ -362,7 +362,7 @@ public class EditRequestDispatchController extends FreemarkerHttpServlet {
private EditConfigurationVTwo makeEditConfigurationVTwo(
String editConfGeneratorName, VitroRequest vreq, HttpSession session) {
String editConfGeneratorName, VitroRequest vreq, HttpSession session) throws Exception {
EditConfigurationGenerator EditConfigurationVTwoGenerator = null;

View file

@ -25,6 +25,8 @@ import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerConfiguration;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerConfigurationLoader;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
/**
@ -57,7 +59,9 @@ public class FreemarkerEmailFactory {
}
FreemarkerEmailFactory factory = getFactory(vreq);
return new FreemarkerEmailMessage(vreq, factory.getEmailSession(),
FreemarkerConfiguration fConfig = FreemarkerConfigurationLoader
.getConfig(vreq);
return new FreemarkerEmailMessage(fConfig, factory.getEmailSession(),
factory.getReplyToAddress());
}

View file

@ -23,7 +23,6 @@ import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -48,9 +47,6 @@ public class FreemarkerEmailMessage {
private static final Log log = LogFactory
.getLog(FreemarkerEmailMessage.class);
private static final String CONFIG_ATTRIBUTE = "freemarkerConfig";
private final HttpServletRequest req;
private final Session session;
private final FreemarkerConfiguration config;
@ -67,21 +63,11 @@ public class FreemarkerEmailMessage {
/**
* Package access - should only be created by the factory.
*/
FreemarkerEmailMessage(HttpServletRequest req, Session session,
FreemarkerEmailMessage(FreemarkerConfiguration fConfig, Session session,
InternetAddress replyToAddress) {
this.req = req;
this.session = session;
this.replyToAddress = replyToAddress;
Object o = req.getAttribute(CONFIG_ATTRIBUTE);
if (!(o instanceof FreemarkerConfiguration)) {
String oClass = (o == null) ? "null" : o.getClass().getName();
throw new IllegalStateException(
"Request does not contain a Configuration at '"
+ CONFIG_ATTRIBUTE + "': " + oClass);
}
this.config = (FreemarkerConfiguration) o;
this.config = fConfig;
}
public void addRecipient(RecipientType type, String emailAddress) {

View file

@ -146,4 +146,10 @@ public interface RDFService {
* @return ChangeSet an empty ChangeSet object
*/
public ChangeSet manufactureChangeSet();
/**
* Free any resources held by this RDFService object
*/
public void close();
}

View file

@ -0,0 +1,11 @@
package edu.cornell.mannlib.vitro.webapp.rdfservice;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
public interface RDFServiceFactory {
public RDFService getRDFService();
public RDFService getRDFService(VitroRequest vreq);
}

View file

@ -3,24 +3,11 @@
package edu.cornell.mannlib.vitro.webapp.rdfservice.impl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openrdf.model.Resource;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.Update;
import org.openrdf.query.UpdateExecutionException;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.openrdf.repository.http.HTTPRepository;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
@ -29,11 +16,9 @@ import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.sparql.resultset.XMLInput;
import com.hp.hpl.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener;
@ -47,67 +32,12 @@ import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException;
* to allow listening, logging and auditing.
*/
public class RDFServiceImpl implements RDFService {
public abstract class RDFServiceImpl implements RDFService {
private static final Log log = LogFactory.getLog(RDFServiceImpl.class);
private String endpointURI;
private String defaultWriteGraphURI;
private Repository repository;
private ArrayList<ChangeListener> registeredListeners;
/**
* Returns an RDFService for a remote repository
* @param String - URI of the SPARQL endpoint for the knowledge base
* @param String - URI of the default write graph within the knowledge base.
* this is the graph that will be written to when a graph
* is not explicitly specified.
*
* The default read graph is the union of all graphs in the
* knowledge base
*/
public RDFServiceImpl(String endpointURI, String defaultWriteGraphURI) {
this.endpointURI = endpointURI;
this.defaultWriteGraphURI = defaultWriteGraphURI;
this.repository = new HTTPRepository(endpointURI);
this.registeredListeners = new ArrayList<ChangeListener>();
}
protected String defaultWriteGraphURI;
protected ArrayList<ChangeListener> registeredListeners = new ArrayList<ChangeListener>();
/**
* Perform a series of additions to and or removals from specified graphs
* in the RDF store. preConditionSparql will be executed against the
* union of all the graphs in the knowledge base before any updates are made.
* If the precondition query returns a non-empty result no updates
* will be made.
*
* @param ChangeSet - a set of changes to be performed on the RDF store.
*
* @return boolean - indicates whether the precondition was satisfied
*/
@Override
public boolean changeSetUpdate(ChangeSet changeSet) throws RDFServiceException {
if (!isPreconditionSatisfied(changeSet.getPreconditionQuery(), changeSet.getPreconditionQueryType())) {
return false;
}
Iterator<ModelChange> csIt = changeSet.getModelChanges().iterator();
while (csIt.hasNext()) {
ModelChange modelChange = csIt.next();
if (modelChange.getOperation() == ModelChange.Operation.ADD) {
performAdd(modelChange);
} else if (modelChange.getOperation() == ModelChange.Operation.REMOVE) {
performRemove(modelChange);
} else {
log.error("unrecognized operation type");
}
}
return true;
}
/**
* If the given individual already exists in the default graph, throws an
* RDFServiceException, otherwise adds one type assertion to the default
@ -122,206 +52,46 @@ public class RDFServiceImpl implements RDFService {
newIndividual(individualURI, individualTypeURI, defaultWriteGraphURI);
}
/**
* If the given individual already exists in the given graph, throws an
* RDFServiceException, otherwise adds one type assertion to the given
* graph.
*
* @param String individualURI - URI of the individual to be added
* @param String individualTypeURI - URI of the type for the individual
* @param String graphURI - URI of the graph to which to add the individual
*/
@Override
public void newIndividual(String individualURI,
String individualTypeURI,
String graphURI) throws RDFServiceException {
StringBuffer containsQuery = new StringBuffer("ASK { \n");
* If the given individual already exists in the given graph, throws an
* RDFServiceException, otherwise adds one type assertion to the given
* graph.
*
* @param String individualURI - URI of the individual to be added
* @param String individualTypeURI - URI of the type for the individual
* @param String graphURI - URI of the graph to which to add the individual
*/
@Override
public void newIndividual(String individualURI,
String individualTypeURI,
String graphURI) throws RDFServiceException {
StringBuffer containsQuery = new StringBuffer("ASK { \n");
if (graphURI != null) {
containsQuery.append(" GRAPH <" + graphURI + "> { ");
}
containsQuery.append("<");
containsQuery.append(individualURI);
containsQuery.append("> ");
containsQuery.append("?p ?o");
containsQuery.append("<");
containsQuery.append(individualURI);
containsQuery.append("> ");
containsQuery.append("?p ?o");
if (graphURI != null) {
containsQuery.append(" } \n");
}
containsQuery.append("\n}");
if (sparqlAskQuery(containsQuery.toString())) {
throw new RDFServiceException("individual already exists");
throw new RDFServiceException("individual already exists");
} else {
Triple triple = new Triple(Node.createURI(individualURI), RDF.type.asNode(), Node.createURI(individualTypeURI));
addTriple(triple, graphURI);
}
}
Triple triple = new Triple(Node.createURI(individualURI), RDF.type.asNode(), Node.createURI(individualTypeURI));
//addTriple(triple, graphURI);
ChangeSet cs = this.manufactureChangeSet();
cs.addAddition(new ByteArrayInputStream(
sparqlTriple(triple).getBytes()), ModelSerializationFormat.N3, graphURI);
changeSetUpdate(cs);
}
}
/**
* Performs a SPARQL construct query against the knowledge base. The query may have
* an embedded graph identifier.
*
* @param String query - the SPARQL query to be executed against the RDF store
* @param RDFService.ModelSerializationFormat resultFormat - type of serialization for RDF result of the SPARQL query
* @param OutputStream outputStream - the result of the query
*
*/
@Override
public InputStream sparqlConstructQuery(String queryStr,
RDFServiceImpl.ModelSerializationFormat resultFormat) throws RDFServiceException {
Model model = ModelFactory.createDefaultModel();
Query query = QueryFactory.create(queryStr);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpointURI, query);
try {
qe.execConstruct(model);
} finally {
qe.close();
}
ByteArrayOutputStream serializedModel = new ByteArrayOutputStream();
model.write(serializedModel,getSerializationFormatString(resultFormat));
InputStream result = new ByteArrayInputStream(serializedModel.toByteArray());
return result;
}
/**
* Performs a SPARQL describe query against the knowledge base. The query may have
* an embedded graph identifier.
*
* @param String query - the SPARQL query to be executed against the RDF store
* @param RDFService.ModelSerializationFormat resultFormat - type of serialization for RDF result of the SPARQL query
*
* @return InputStream - the result of the query
*
*/
@Override
public InputStream sparqlDescribeQuery(String queryStr,
RDFServiceImpl.ModelSerializationFormat resultFormat) throws RDFServiceException {
Model model = ModelFactory.createDefaultModel();
Query query = QueryFactory.create(queryStr);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpointURI, query);
try {
qe.execDescribe(model);
} finally {
qe.close();
}
ByteArrayOutputStream serializedModel = new ByteArrayOutputStream();
model.write(serializedModel,getSerializationFormatString(resultFormat));
InputStream result = new ByteArrayInputStream(serializedModel.toByteArray());
return result;
}
/**
* Performs a SPARQL select query against the knowledge base. The query may have
* an embedded graph identifier.
*
* @param String query - the SPARQL query to be executed against the RDF store
* @param RDFService.ResultFormat resultFormat - format for the result of the Select query
*
* @return InputStream - the result of the query
*
*/
@Override
public InputStream sparqlSelectQuery(String queryStr, RDFService.ResultFormat resultFormat) throws RDFServiceException {
Query query = QueryFactory.create(queryStr);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpointURI, query);
try {
ResultSet resultSet = qe.execSelect();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
switch (resultFormat) {
case CSV:
ResultSetFormatter.outputAsCSV(outputStream,resultSet);
break;
case TEXT:
ResultSetFormatter.out(outputStream,resultSet);
break;
case JSON:
ResultSetFormatter.outputAsJSON(outputStream, resultSet);
break;
case XML:
ResultSetFormatter.outputAsXML(outputStream, resultSet);
break;
default:
throw new RDFServiceException("unrecognized result format");
}
InputStream result = new ByteArrayInputStream(outputStream.toByteArray());
return result;
} finally {
qe.close();
}
}
/**
* Performs a SPARQL ASK query against the knowledge base. The query may have
* an embedded graph identifier.
*
* @param String query - the SPARQL query to be executed against the RDF store
*
* @return boolean - the result of the SPARQL query
*/
@Override
public boolean sparqlAskQuery(String queryStr) throws RDFServiceException {
Query query = QueryFactory.create(queryStr);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpointURI, query);
try {
return qe.execAsk();
} finally {
qe.close();
}
}
/**
* Get a list of all the graph URIs in the RDF store.
*
* @return List<String> - list of all the graph URIs in the RDF store
*/
//TODO - need to verify that the sesame getContextIDs method is implemented
// in such a way that it works with all triple stores that support the
// graph update API
@Override
public List<String> getGraphURIs() throws RDFServiceException {
List<String> graphNodeList = new ArrayList<String>();
try {
RepositoryConnection conn = getConnection();
try {
RepositoryResult<Resource> conResult = conn.getContextIDs();
while (conResult.hasNext()) {
Resource res = conResult.next();
graphNodeList.add(res.stringValue());
}
} finally {
conn.close();
}
} catch (RepositoryException re) {
throw new RuntimeException(re);
}
return graphNodeList;
}
/**
* TODO - what is the definition of this method?
* @return
*/
@Override
public void getGraphMetadata() throws RDFServiceException {
}
/**
* Get the URI of the default write graph
*
@ -363,79 +133,60 @@ public class RDFServiceImpl implements RDFService {
@Override
public ChangeSet manufactureChangeSet() {
return new ChangeSetImpl();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Non-override methods below
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
protected String getEndpointURI() {
return endpointURI;
}
protected RepositoryConnection getConnection() {
try {
return this.repository.getConnection();
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
}
protected void executeUpdate(String updateString) {
try {
RepositoryConnection conn = getConnection();
try {
Update u = conn.prepareUpdate(QueryLanguage.SPARQL, updateString);
u.execute();
} catch (MalformedQueryException e) {
throw new RuntimeException(e);
} catch (UpdateExecutionException e) {
log.error(e,e);
log.error("Update command: \n" + updateString);
throw new RuntimeException(e);
} finally {
conn.close();
}
} catch (RepositoryException re) {
throw new RuntimeException(re);
}
}
protected void addTriple(Triple t, String graphURI) {
StringBuffer updateString = new StringBuffer();
updateString.append("INSERT DATA { ");
updateString.append((graphURI != null) ? "GRAPH <" + graphURI + "> { " : "" );
updateString.append(sparqlNodeUpdate(t.getSubject(), ""));
updateString.append(" ");
updateString.append(sparqlNodeUpdate(t.getPredicate(), ""));
updateString.append(" ");
updateString.append(sparqlNodeUpdate(t.getObject(), ""));
updateString.append(" }");
updateString.append((graphURI != null) ? " } " : "");
executeUpdate(updateString.toString());
notifyListeners(t, ModelChange.Operation.ADD, graphURI);
}
protected void removeTriple(Triple t, String graphURI) {
StringBuffer updateString = new StringBuffer();
updateString.append("DELETE DATA { ");
updateString.append((graphURI != null) ? "GRAPH <" + graphURI + "> { " : "" );
updateString.append(sparqlNodeUpdate(t.getSubject(), ""));
updateString.append(" ");
updateString.append(sparqlNodeUpdate(t.getPredicate(), ""));
updateString.append(" ");
updateString.append(sparqlNodeUpdate(t.getObject(), ""));
updateString.append(" }");
updateString.append((graphURI != null) ? " } " : "");
executeUpdate(updateString.toString());
notifyListeners(t, ModelChange.Operation.REMOVE, graphURI);
}
protected synchronized void notifyListeners(Triple triple, ModelChange.Operation operation, String graphURI) {
}
public synchronized void notifyListeners(Triple triple, ModelChange.Operation operation, String graphURI) {
Iterator<ChangeListener> iter = registeredListeners.iterator();
while (iter.hasNext()) {
ChangeListener listener = iter.next();
if (operation == ModelChange.Operation.ADD) {
listener.addedStatement(sparqlTriple(triple), graphURI);
} else {
listener.removedStatement(sparqlTriple(triple).toString(), graphURI);
}
}
}
protected boolean isPreconditionSatisfied(String query,
RDFService.SPARQLQueryType queryType)
throws RDFServiceException {
Model model = ModelFactory.createDefaultModel();
switch (queryType) {
case DESCRIBE:
model.read(sparqlDescribeQuery(query,RDFService.ModelSerializationFormat.N3), null);
return !model.isEmpty();
case CONSTRUCT:
model.read(sparqlConstructQuery(query,RDFService.ModelSerializationFormat.N3), null);
return !model.isEmpty();
case SELECT:
return sparqlSelectQueryHasResults(query);
case ASK:
return sparqlAskQuery(query);
default:
throw new RDFServiceException("unrecognized SPARQL query type");
}
}
protected static String getSerializationFormatString(RDFService.ModelSerializationFormat format) {
switch (format) {
case RDFXML:
return "RDFXML";
case N3:
return "N3";
default:
log.error("unexpected format in getFormatString");
return null;
}
}
protected boolean sparqlSelectQueryHasResults(String queryStr) throws RDFServiceException {
ResultSet rs = XMLInput.fromXML(sparqlSelectQuery(queryStr, ResultFormat.XML));
return rs.hasNext();
}
protected static String sparqlTriple(Triple triple) {
StringBuffer serializedTriple = new StringBuffer();
serializedTriple.append(sparqlNodeUpdate(triple.getSubject(), ""));
serializedTriple.append(" ");
@ -443,93 +194,10 @@ public class RDFServiceImpl implements RDFService {
serializedTriple.append(" ");
serializedTriple.append(sparqlNodeUpdate(triple.getObject(), ""));
serializedTriple.append(" .");
Iterator<ChangeListener> iter = registeredListeners.iterator();
while (iter.hasNext()) {
ChangeListener listener = iter.next();
if (operation == ModelChange.Operation.ADD) {
listener.addedStatement(serializedTriple.toString(), graphURI);
} else {
listener.removedStatement(serializedTriple.toString(), graphURI);
}
}
return serializedTriple.toString();
}
protected boolean isPreconditionSatisfied(String query,
RDFService.SPARQLQueryType queryType)
throws RDFServiceException {
Model model = ModelFactory.createDefaultModel();
switch (queryType) {
case DESCRIBE:
model.read(sparqlDescribeQuery(query,RDFService.ModelSerializationFormat.N3), null);
return !model.isEmpty();
case CONSTRUCT:
model.read(sparqlConstructQuery(query,RDFService.ModelSerializationFormat.N3), null);
return !model.isEmpty();
case SELECT:
return sparqlSelectQueryHasResults(query);
case ASK:
return sparqlAskQuery(query);
default:
throw new RDFServiceException("unrecognized SPARQL query type");
}
}
protected boolean sparqlSelectQueryHasResults(String queryStr) throws RDFServiceException {
Query query = QueryFactory.create(queryStr);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpointURI, query);
try {
ResultSet resultSet = qe.execSelect();
return resultSet.hasNext();
} finally {
qe.close();
}
}
protected void performAdd(ModelChange modelChange) throws RDFServiceException {
Model model = ModelFactory.createDefaultModel();
model.read(modelChange.getSerializedModel(),getSerializationFormatString(modelChange.getSerializationFormat()));
StmtIterator stmtIt = model.listStatements();
while (stmtIt.hasNext()) {
Statement stmt = stmtIt.next();
Triple triple = new Triple(stmt.getSubject().asNode(), stmt.getPredicate().asNode(), stmt.getObject().asNode());
addTriple(triple, modelChange.getGraphURI());
}
}
protected void performRemove(ModelChange modelChange) throws RDFServiceException {
Model model = ModelFactory.createDefaultModel();
model.read(modelChange.getSerializedModel(),getSerializationFormatString(modelChange.getSerializationFormat()));
StmtIterator stmtIt = model.listStatements();
while (stmtIt.hasNext()) {
Statement stmt = stmtIt.next();
Triple triple = new Triple(stmt.getSubject().asNode(), stmt.getPredicate().asNode(), stmt.getObject().asNode());
removeTriple(triple, modelChange.getGraphURI());
}
}
protected static String getSerializationFormatString(RDFService.ModelSerializationFormat format) {
switch (format) {
case RDFXML:
return "RDFXML";
case N3:
return "N3";
default:
log.error("unexpected format in getFormatString");
return null;
}
}
protected static String sparqlNodeUpdate(Node node, String varName) {
if (node.isBlank()) {
return "_:" + node.getBlankNodeLabel().replaceAll("\\W", "");

View file

@ -0,0 +1,22 @@
package edu.cornell.mannlib.vitro.webapp.rdfservice.impl;
import javax.servlet.ServletContext;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceFactory;
public class RDFServiceUtils {
private static final String RDFSERVICEFACTORY_ATTR =
RDFServiceUtils.class.getName() + ".RDFServiceFactory";
public RDFServiceFactory getRDFServiceFactory(ServletContext context) {
Object o = context.getAttribute(RDFSERVICEFACTORY_ATTR);
return (o instanceof RDFServiceFactory) ? (RDFServiceFactory) o : null;
}
public void setRDFServiceFactory(ServletContext context,
RDFServiceFactory factory) {
context.setAttribute(RDFSERVICEFACTORY_ATTR, factory);
}
}

View file

@ -0,0 +1,23 @@
package edu.cornell.mannlib.vitro.webapp.rdfservice.impl.sdb;
import org.apache.commons.dbcp.BasicDataSource;
import com.hp.hpl.jena.sdb.StoreDesc;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
public class RDFServiceFactorySDB {
private BasicDataSource bds;
private StoreDesc storeDesc;
public RDFServiceFactorySDB(BasicDataSource dataSource, StoreDesc storeDesc) {
this.bds = dataSource;
this.storeDesc = storeDesc;
}
public RDFService getRDFService() {
return new RDFServiceSDB(bds, storeDesc);
}
}

View file

@ -0,0 +1,267 @@
package edu.cornell.mannlib.vitro.webapp.rdfservice.impl.sdb;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.listeners.StatementListener;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.sdb.SDBFactory;
import com.hp.hpl.jena.sdb.StoreDesc;
import com.hp.hpl.jena.sdb.sql.SDBConnection;
import edu.cornell.mannlib.vitro.webapp.dao.jena.DatasetWrapper;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ModelChange;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.RDFServiceImpl;
public class RDFServiceSDB extends RDFServiceImpl implements RDFService {
private final static Log log = LogFactory.getLog(RDFServiceSDB.class);
private BasicDataSource bds;
private StoreDesc storeDesc;
public RDFServiceSDB(BasicDataSource dataSource, StoreDesc storeDesc) {
this.bds = dataSource;
this.storeDesc = storeDesc;
}
protected DatasetWrapper getDatasetWrapper() {
try {
SDBConnection conn = new SDBConnection(bds.getConnection());
Dataset dataset = SDBFactory.connectDataset(conn, storeDesc);
return new DatasetWrapper(dataset, conn);
} catch (SQLException sqle) {
log.error(sqle, sqle);
throw new RuntimeException(sqle);
}
}
@Override
public boolean changeSetUpdate(ChangeSet changeSet)
throws RDFServiceException {
if (changeSet.getPreconditionQuery() != null
&& !isPreconditionSatisfied(
changeSet.getPreconditionQuery(),
changeSet.getPreconditionQueryType())) {
return false;
}
Iterator<ModelChange> csIt = changeSet.getModelChanges().iterator();
SDBConnection conn = null;
try {
conn = new SDBConnection(bds.getConnection());
} catch (SQLException sqle) {
log.error(sqle, sqle);
throw new RuntimeException(sqle);
}
Dataset dataset = SDBFactory.connectDataset(conn, storeDesc);
boolean transaction = conn.getTransactionHandler().transactionsSupported();
try {
if (transaction) {
conn.getTransactionHandler().begin();
}
while (csIt.hasNext()) {
ModelChange modelChange = csIt.next();
Model model = dataset.getNamedModel(modelChange.getGraphURI());
model.register(new ModelListener(modelChange.getGraphURI(), this));
if (modelChange.getOperation() == ModelChange.Operation.ADD) {
model.add(parseModel(modelChange));
} else if (modelChange.getOperation() == ModelChange.Operation.REMOVE) {
model.remove(parseModel(modelChange));
} else {
log.error("unrecognized operation type");
}
}
} catch (Throwable t) {
if (transaction) {
conn.getTransactionHandler().abort();
}
throw new RuntimeException(t);
} finally {
if (transaction) {
conn.getTransactionHandler().commit();
}
conn.close();
}
return true;
}
private Model parseModel(ModelChange modelChange) {
Model model = ModelFactory.createDefaultModel();
model.read(modelChange.getSerializedModel(),
getSerializationFormatString(modelChange.getSerializationFormat()));
return model;
}
@Override
public void newIndividual(String individualURI, String individualTypeURI,
String graphURI) throws RDFServiceException {
// TODO Auto-generated method stub
}
private InputStream getRDFResultStream(String query, boolean construct,
ModelSerializationFormat resultFormat) throws RDFServiceException {
DatasetWrapper dw = getDatasetWrapper();
try {
Dataset d = dw.getDataset();
Query q = QueryFactory.create(query);
QueryExecution qe = QueryExecutionFactory.create(q, d);
ByteArrayOutputStream serializedModel = new ByteArrayOutputStream();
try {
// TODO pipe this
Model m = construct ? qe.execConstruct() : qe.execDescribe();
m.write(serializedModel, getSerializationFormatString(resultFormat));
InputStream result = new ByteArrayInputStream(serializedModel.toByteArray());
return result;
} finally {
qe.close();
}
} finally {
dw.close();
}
}
private static final boolean CONSTRUCT = true;
private static final boolean DESCRIBE = false;
@Override
public InputStream sparqlConstructQuery(String query,
ModelSerializationFormat resultFormat) throws RDFServiceException {
return getRDFResultStream(query, CONSTRUCT, resultFormat);
}
@Override
public InputStream sparqlDescribeQuery(String query,
ModelSerializationFormat resultFormat) throws RDFServiceException {
return getRDFResultStream(query, DESCRIBE, resultFormat);
}
@Override
public InputStream sparqlSelectQuery(String query, ResultFormat resultFormat)
throws RDFServiceException {
DatasetWrapper dw = getDatasetWrapper();
try {
Dataset d = dw.getDataset();
Query q = QueryFactory.create(query);
QueryExecution qe = QueryExecutionFactory.create(q, d);
try {
ResultSet resultSet = qe.execSelect();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
switch (resultFormat) {
case CSV:
ResultSetFormatter.outputAsCSV(outputStream,resultSet);
break;
case TEXT:
ResultSetFormatter.out(outputStream,resultSet);
break;
case JSON:
ResultSetFormatter.outputAsJSON(outputStream, resultSet);
break;
case XML:
ResultSetFormatter.outputAsXML(outputStream, resultSet);
break;
default:
throw new RDFServiceException("unrecognized result format");
}
InputStream result = new ByteArrayInputStream(outputStream.toByteArray());
return result;
} finally {
qe.close();
}
} finally {
dw.close();
}
}
@Override
public boolean sparqlAskQuery(String query) throws RDFServiceException {
DatasetWrapper dw = getDatasetWrapper();
try {
Dataset d = dw.getDataset();
Query q = QueryFactory.create(query);
QueryExecution qe = QueryExecutionFactory.create(q, d);
try {
return qe.execAsk();
} finally {
qe.close();
}
} finally {
dw.close();
}
}
@Override
public List<String> getGraphURIs() throws RDFServiceException {
DatasetWrapper dw = getDatasetWrapper();
try {
Dataset d = dw.getDataset();
List<String> graphURIs = new ArrayList<String>();
Iterator<String> nameIt = d.listNames();
while (nameIt.hasNext()) {
graphURIs.add(nameIt.next());
}
return graphURIs;
} finally {
dw.close();
}
}
@Override
public void getGraphMetadata() throws RDFServiceException {
// TODO Auto-generated method stub
}
@Override
public void close() {
// nothing
}
private class ModelListener extends StatementListener {
private String graphURI;
private RDFServiceImpl s;
public ModelListener(String graphURI, RDFServiceImpl s) {
this.graphURI = graphURI;
this.s = s;
}
public void addedStatement(Statement stmt) {
s.notifyListeners(stmt.asTriple(), ModelChange.Operation.ADD, graphURI);
}
public void removedStatement(Statement stmt) {
s.notifyListeners(stmt.asTriple(), ModelChange.Operation.REMOVE, graphURI);
}
}
}

View file

@ -0,0 +1,460 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.rdfservice.impl.sparql;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openrdf.model.Resource;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.Update;
import org.openrdf.query.UpdateExecutionException;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.openrdf.repository.http.HTTPRepository;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ModelChange;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.ChangeSetImpl;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.RDFServiceImpl;
/*
* API to write, read, and update Vitro's RDF store, with support
* to allow listening, logging and auditing.
*/
public class RDFServiceSparql extends RDFServiceImpl implements RDFService {
private static final Log log = LogFactory.getLog(RDFServiceImpl.class);
private String endpointURI;
private Repository repository;
/**
* Returns an RDFService for a remote repository
* @param String - URI of the SPARQL endpoint for the knowledge base
* @param String - URI of the default write graph within the knowledge base.
* this is the graph that will be written to when a graph
* is not explicitly specified.
*
* The default read graph is the union of all graphs in the
* knowledge base
*/
public RDFServiceSparql(String endpointURI, String defaultWriteGraphURI) {
this.endpointURI = endpointURI;
this.repository = new HTTPRepository(endpointURI);
}
public void close() {
try {
this.repository.shutDown();
} catch (RepositoryException re) {
log.error(re, re);
}
}
/**
* Perform a series of additions to and or removals from specified graphs
* in the RDF store. preConditionSparql will be executed against the
* union of all the graphs in the knowledge base before any updates are made.
* If the precondition query returns a non-empty result no updates
* will be made.
*
* @param ChangeSet - a set of changes to be performed on the RDF store.
*
* @return boolean - indicates whether the precondition was satisfied
*/
@Override
public boolean changeSetUpdate(ChangeSet changeSet) throws RDFServiceException {
if (changeSet.getPreconditionQuery() != null
&& !isPreconditionSatisfied(
changeSet.getPreconditionQuery(),
changeSet.getPreconditionQueryType())) {
return false;
}
Iterator<ModelChange> csIt = changeSet.getModelChanges().iterator();
while (csIt.hasNext()) {
ModelChange modelChange = csIt.next();
if (modelChange.getOperation() == ModelChange.Operation.ADD) {
performAdd(modelChange);
} else if (modelChange.getOperation() == ModelChange.Operation.REMOVE) {
performRemove(modelChange);
} else {
log.error("unrecognized operation type");
}
}
return true;
}
/**
* Performs a SPARQL construct query against the knowledge base. The query may have
* an embedded graph identifier.
*
* @param String query - the SPARQL query to be executed against the RDF store
* @param RDFService.ModelSerializationFormat resultFormat - type of serialization for RDF result of the SPARQL query
* @param OutputStream outputStream - the result of the query
*
*/
@Override
public InputStream sparqlConstructQuery(String queryStr,
RDFServiceImpl.ModelSerializationFormat resultFormat) throws RDFServiceException {
Model model = ModelFactory.createDefaultModel();
Query query = QueryFactory.create(queryStr);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpointURI, query);
try {
qe.execConstruct(model);
} finally {
qe.close();
}
ByteArrayOutputStream serializedModel = new ByteArrayOutputStream();
model.write(serializedModel,getSerializationFormatString(resultFormat));
InputStream result = new ByteArrayInputStream(serializedModel.toByteArray());
return result;
}
/**
* Performs a SPARQL describe query against the knowledge base. The query may have
* an embedded graph identifier.
*
* @param String query - the SPARQL query to be executed against the RDF store
* @param RDFService.ModelSerializationFormat resultFormat - type of serialization for RDF result of the SPARQL query
*
* @return InputStream - the result of the query
*
*/
@Override
public InputStream sparqlDescribeQuery(String queryStr,
RDFServiceImpl.ModelSerializationFormat resultFormat) throws RDFServiceException {
Model model = ModelFactory.createDefaultModel();
Query query = QueryFactory.create(queryStr);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpointURI, query);
try {
qe.execDescribe(model);
} finally {
qe.close();
}
ByteArrayOutputStream serializedModel = new ByteArrayOutputStream();
model.write(serializedModel,getSerializationFormatString(resultFormat));
InputStream result = new ByteArrayInputStream(serializedModel.toByteArray());
return result;
}
/**
* Performs a SPARQL select query against the knowledge base. The query may have
* an embedded graph identifier.
*
* @param String query - the SPARQL query to be executed against the RDF store
* @param RDFService.ResultFormat resultFormat - format for the result of the Select query
*
* @return InputStream - the result of the query
*
*/
@Override
public InputStream sparqlSelectQuery(String queryStr, RDFService.ResultFormat resultFormat) throws RDFServiceException {
Query query = QueryFactory.create(queryStr);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpointURI, query);
try {
ResultSet resultSet = qe.execSelect();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
switch (resultFormat) {
case CSV:
ResultSetFormatter.outputAsCSV(outputStream,resultSet);
break;
case TEXT:
ResultSetFormatter.out(outputStream,resultSet);
break;
case JSON:
ResultSetFormatter.outputAsJSON(outputStream, resultSet);
break;
case XML:
ResultSetFormatter.outputAsXML(outputStream, resultSet);
break;
default:
throw new RDFServiceException("unrecognized result format");
}
InputStream result = new ByteArrayInputStream(outputStream.toByteArray());
return result;
} finally {
qe.close();
}
}
/**
* Performs a SPARQL ASK query against the knowledge base. The query may have
* an embedded graph identifier.
*
* @param String query - the SPARQL query to be executed against the RDF store
*
* @return boolean - the result of the SPARQL query
*/
@Override
public boolean sparqlAskQuery(String queryStr) throws RDFServiceException {
Query query = QueryFactory.create(queryStr);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpointURI, query);
try {
return qe.execAsk();
} finally {
qe.close();
}
}
/**
* Get a list of all the graph URIs in the RDF store.
*
* @return List<String> - list of all the graph URIs in the RDF store
*/
//TODO - need to verify that the sesame getContextIDs method is implemented
// in such a way that it works with all triple stores that support the
// graph update API
@Override
public List<String> getGraphURIs() throws RDFServiceException {
List<String> graphNodeList = new ArrayList<String>();
try {
RepositoryConnection conn = getConnection();
try {
RepositoryResult<Resource> conResult = conn.getContextIDs();
while (conResult.hasNext()) {
Resource res = conResult.next();
graphNodeList.add(res.stringValue());
}
} finally {
conn.close();
}
} catch (RepositoryException re) {
throw new RuntimeException(re);
}
return graphNodeList;
}
/**
* TODO - what is the definition of this method?
* @return
*/
@Override
public void getGraphMetadata() throws RDFServiceException {
}
/**
* Get the URI of the default write graph
*
* @return String URI of default write graph
*/
@Override
public String getDefaultWriteGraphURI() throws RDFServiceException {
return defaultWriteGraphURI;
}
/**
* Register a listener to listen to changes in any graph in
* the RDF store.
*
*/
@Override
public synchronized void registerListener(ChangeListener changeListener) throws RDFServiceException {
if (!registeredListeners.contains(changeListener)) {
registeredListeners.add(changeListener);
}
}
/**
* Unregister a listener from listening to changes in any graph
* in the RDF store.
*
*/
@Override
public synchronized void unregisterListener(ChangeListener changeListener) throws RDFServiceException {
registeredListeners.remove(changeListener);
}
/**
* Create a ChangeSet object
*
* @return a ChangeSet object
*/
@Override
public ChangeSet manufactureChangeSet() {
return new ChangeSetImpl();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Non-override methods below
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
protected String getEndpointURI() {
return endpointURI;
}
protected RepositoryConnection getConnection() {
try {
return this.repository.getConnection();
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
}
protected void executeUpdate(String updateString) {
try {
RepositoryConnection conn = getConnection();
try {
Update u = conn.prepareUpdate(QueryLanguage.SPARQL, updateString);
u.execute();
} catch (MalformedQueryException e) {
throw new RuntimeException(e);
} catch (UpdateExecutionException e) {
log.error(e,e);
log.error("Update command: \n" + updateString);
throw new RuntimeException(e);
} finally {
conn.close();
}
} catch (RepositoryException re) {
throw new RuntimeException(re);
}
}
protected void addTriple(Triple t, String graphURI) {
StringBuffer updateString = new StringBuffer();
updateString.append("INSERT DATA { ");
updateString.append((graphURI != null) ? "GRAPH <" + graphURI + "> { " : "" );
updateString.append(sparqlNodeUpdate(t.getSubject(), ""));
updateString.append(" ");
updateString.append(sparqlNodeUpdate(t.getPredicate(), ""));
updateString.append(" ");
updateString.append(sparqlNodeUpdate(t.getObject(), ""));
updateString.append(" }");
updateString.append((graphURI != null) ? " } " : "");
executeUpdate(updateString.toString());
notifyListeners(t, ModelChange.Operation.ADD, graphURI);
}
protected void removeTriple(Triple t, String graphURI) {
StringBuffer updateString = new StringBuffer();
updateString.append("DELETE DATA { ");
updateString.append((graphURI != null) ? "GRAPH <" + graphURI + "> { " : "" );
updateString.append(sparqlNodeUpdate(t.getSubject(), ""));
updateString.append(" ");
updateString.append(sparqlNodeUpdate(t.getPredicate(), ""));
updateString.append(" ");
updateString.append(sparqlNodeUpdate(t.getObject(), ""));
updateString.append(" }");
updateString.append((graphURI != null) ? " } " : "");
executeUpdate(updateString.toString());
notifyListeners(t, ModelChange.Operation.REMOVE, graphURI);
}
@Override
protected boolean isPreconditionSatisfied(String query,
RDFService.SPARQLQueryType queryType)
throws RDFServiceException {
Model model = ModelFactory.createDefaultModel();
switch (queryType) {
case DESCRIBE:
model.read(sparqlDescribeQuery(query,RDFService.ModelSerializationFormat.N3), null);
return !model.isEmpty();
case CONSTRUCT:
model.read(sparqlConstructQuery(query,RDFService.ModelSerializationFormat.N3), null);
return !model.isEmpty();
case SELECT:
return sparqlSelectQueryHasResults(query);
case ASK:
return sparqlAskQuery(query);
default:
throw new RDFServiceException("unrecognized SPARQL query type");
}
}
@Override
protected boolean sparqlSelectQueryHasResults(String queryStr) throws RDFServiceException {
Query query = QueryFactory.create(queryStr);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpointURI, query);
try {
ResultSet resultSet = qe.execSelect();
return resultSet.hasNext();
} finally {
qe.close();
}
}
protected void performAdd(ModelChange modelChange) throws RDFServiceException {
Model model = ModelFactory.createDefaultModel();
model.read(modelChange.getSerializedModel(),getSerializationFormatString(modelChange.getSerializationFormat()));
StmtIterator stmtIt = model.listStatements();
while (stmtIt.hasNext()) {
Statement stmt = stmtIt.next();
Triple triple = new Triple(stmt.getSubject().asNode(), stmt.getPredicate().asNode(), stmt.getObject().asNode());
addTriple(triple, modelChange.getGraphURI());
}
}
protected void performRemove(ModelChange modelChange) throws RDFServiceException {
Model model = ModelFactory.createDefaultModel();
model.read(modelChange.getSerializedModel(),getSerializationFormatString(modelChange.getSerializationFormat()));
StmtIterator stmtIt = model.listStatements();
while (stmtIt.hasNext()) {
Statement stmt = stmtIt.next();
Triple triple = new Triple(stmt.getSubject().asNode(), stmt.getPredicate().asNode(), stmt.getObject().asNode());
removeTriple(triple, modelChange.getGraphURI());
}
}
}

View file

@ -25,8 +25,6 @@ public class VitroSearchTermNames {
public static String ALLTEXTUNSTEMMED = "ALLTEXTUNSTEMMED";
/** Does the individual have a thumbnail image? 1=yes 0=no */
public static final String THUMBNAIL = "THUMBNAIL";
/** Should individual be included in full text search results? 1=yes 0=no */
public static final String PROHIBITED_FROM_TEXT_RESULTS = "PROHIBITED_FROM_TEXT_RESULTS";
/** class names in human readable form of an individual*/
public static final String CLASSLOCALNAMELOWERCASE = "classLocalNameLowerCase";
/** class names in human readable form of an individual*/

View file

@ -1,8 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.search.beans;
public interface IndividualProhibitedFromSearch {
public boolean isIndividualProhibited(String uri);
}

View file

@ -1,84 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.search.beans;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.shared.Lock;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelContext;
public class IndividualProhibitedFromSearchImpl implements IndividualProhibitedFromSearch {
protected OntModel fullModel;
protected static Log log = LogFactory.getLog(IndividualProhibitedFromSearchImpl.class);
public IndividualProhibitedFromSearchImpl( ServletContext context ){
this.fullModel = ModelContext.getUnionOntModelSelector(context).getFullModel();
}
public IndividualProhibitedFromSearchImpl( OntModel fullModel ){
this.fullModel = fullModel;
}
public boolean isIndividualProhibited(String uri){
if( uri == null || uri.isEmpty() )
return true;
boolean prohibited = false;
QueryExecution qexec = null;
try {
fullModel.getLock().enterCriticalSection(Lock.READ);
Query query = makeAskQueryForUri( uri );
qexec = QueryExecutionFactory.create( query, fullModel);
prohibited = qexec.execAsk();
} finally {
if( qexec != null ) qexec.close();
fullModel.getLock().leaveCriticalSection();
}
if( prohibited )
log.debug("prohibited " + uri);
return prohibited;
}
private Query makeAskQueryForUri( String uri ){
String queryString =
"PREFIX fn: <http://www.w3.org/2005/xpath-functions#> \n" +
"ASK { \n" +
" <"+uri+"> <" + RDF.type.getURI() + "> ?type . \n" +
" FILTER ( \n" +
" ( fn:starts-with( str(?type), \"" + VitroVocabulary.vitroURI + "\" ) \n" +
" && \n"+
" ! fn:starts-with( str(?type), \"" + VitroVocabulary.vitroURI + "Flag\" ) ) || \n" +
" fn:starts-with( str(?type), \"" + VitroVocabulary.PUBLIC + "\" ) || \n" +
" str(?type) = \"" + OWL.ObjectProperty.getURI() + "\" || \n" +
" str(?type) = \"" + OWL.DatatypeProperty.getURI() + "\" || \n" +
" str(?type) = \"" + OWL.AnnotationProperty.getURI() + "\" \n" +
" )\n" +
"}" ;
return QueryFactory.create( queryString );
}
}

View file

@ -51,7 +51,6 @@ import edu.cornell.mannlib.vitro.webapp.search.beans.VitroQueryFactory;
import edu.cornell.mannlib.vitro.webapp.search.solr.SolrSetup;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.LinkTemplateModel;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.searchresult.IndividualSearchResult;
import freemarker.template.Configuration;
/**
* Paged search controller that uses Solr
@ -104,12 +103,11 @@ public class PagedSearchController extends FreemarkerHttpServlet {
super.doGet(vreq,response);
}else{
try {
Configuration config = getConfig(vreq);
ResponseValues rvalues = processRequest(vreq);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/xml;charset=UTF-8");
writeTemplate(rvalues.getTemplateName(), rvalues.getMap(), config, request, response);
writeTemplate(rvalues.getTemplateName(), rvalues.getMap(), request, response);
} catch (Exception e) {
log.error(e, e);
}

View file

@ -0,0 +1,34 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.search.solr;
import java.util.Arrays;
import java.util.List;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
/**
* Skip individual if its URI is from any of the excludeNamepsaces
*
*/
public class ExcludeBasedOnNamespace implements SearchIndexExcluder {
List<String> excludeNamepsaces;
public ExcludeBasedOnNamespace(String ... excludeNamepsaces) {
super();
this.excludeNamepsaces = Arrays.asList(excludeNamepsaces);
}
@Override
public String checkForExclusion(Individual ind) {
for( String ns: excludeNamepsaces){
if( ns.equals( ind.getNamespace() ) ){
return "skipping because of namespace " ;
}
}
return null;
}
}

View file

@ -0,0 +1,60 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.search.solr;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
/**
* Exclude individual from search index if
* it is a member of any of the the types.
* @author bdc34
*
*/
public class ExcludeBasedOnType implements SearchIndexExcluder {
List<String> typeURIs;
public ExcludeBasedOnType(String ... typeURIs) {
setExcludedTypes( typeURIs );
}
@Override
public String checkForExclusion(Individual ind) {
if( ind != null ) {
List<VClass> vclasses = ind.getVClasses();
if( vclasses != null && ! Collections.disjoint(vclasses, typeURIs) ){
return("skipping due to type.");
}
}
return null;
}
public void setExcludedTypes(String ... typeURIs){
setExcludedTypes(Arrays.asList(typeURIs));
}
public void setExcludedTypes(List<String> typeURIs){
synchronized(this){
this.typeURIs = new ArrayList<String>(typeURIs);
}
}
protected void addTypeToExclude(String typeURI){
if( typeURI != null && !typeURI.isEmpty()){
synchronized(this){
typeURIs.add(typeURI);
}
}
}
protected void removeTypeToExclude(String typeURI){
synchronized(this){
typeURIs.remove(typeURI);
}
}
}

View file

@ -0,0 +1,58 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.search.solr;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.solr.common.SolrInputDocument;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
/**
* Exclude individuals based on the namespaces of their types.
*/
public class ExcludeBasedOnTypeNamespace implements SearchIndexExcluder {
final List<String> namespaces;
Pattern nsRegexPattern;
public ExcludeBasedOnTypeNamespace(String ... namespaces) {
super();
this.namespaces = Collections.unmodifiableList(Arrays.asList( namespaces ));
String nsOrPattern = "";
for( int i=0; i<namespaces.length; i++){
String ns = namespaces[i];
nsOrPattern = nsOrPattern + (i!=0?"|":"") + Pattern.quote(ns) + "[^/#]*$";
}
this.nsRegexPattern = Pattern.compile(nsOrPattern);
}
@Override
public String checkForExclusion(Individual ind) {
if( ind != null && ind.getVClasses() != null ){
for( VClass vclass : ind.getVClasses() ){
String excludeMsg = checkForSkip(ind, vclass);
if(excludeMsg != null)
return excludeMsg;
}
}
return null;
}
String checkForSkip(Individual individual, VClass vclass) {
if( vclass != null && vclass.getURI() != null ){
Matcher match=nsRegexPattern.matcher( vclass.getURI() );
if( match.matches() ){
return "Skipping because it is of a type in an excluded namespace.";
}
}
return null;
}
}

View file

@ -0,0 +1,44 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.search.solr;
import java.util.List;
import org.apache.solr.common.SolrInputDocument;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
/**
* Exclude individuals with types from the Vitro namespace from the
* search index. (Other than old vitro Flag types).
*/
public class ExcludeNonFlagVitro implements SearchIndexExcluder {
@Override
public String checkForExclusion(Individual ind) {
if( ind != null && ind.getVClasses() != null ) {
String excludeMsg = skipIfVitro(ind, ind.getVClasses() );
if( excludeMsg != null)
return excludeMsg;
}
return null;
}
String skipIfVitro(Individual ind, List<VClass> vclasses) {
for( VClass type: vclasses ){
if( type != null && type.getURI() != null ){
String typeURI = type.getURI();
if(typeURI.startsWith( VitroVocabulary.vitroURI )
&& ! typeURI.startsWith(VitroVocabulary.vitroURI + "Flag") ){
return "Skipped " + ind.getURI()+" because in "
+ VitroVocabulary.vitroURI + " namespace";
}
}
}
return null;
}
}

View file

@ -2,8 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.search.solr;
import org.jsoup.Jsoup;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
@ -14,6 +12,7 @@ import org.apache.commons.logging.LogFactory;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.joda.time.DateTime;
import org.jsoup.Jsoup;
import com.hp.hpl.jena.vocabulary.OWL;
@ -26,50 +25,35 @@ import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.search.IndexingException;
import edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames;
import edu.cornell.mannlib.vitro.webapp.search.beans.ClassProhibitedFromSearch;
import edu.cornell.mannlib.vitro.webapp.search.beans.IndividualProhibitedFromSearch;
public class IndividualToSolrDocument {
public static final Log log = LogFactory.getLog(IndividualToSolrDocument.class.getName());
public static VitroSearchTermNames term = new VitroSearchTermNames();
protected static String entClassName = Individual.class.getName();
protected ClassProhibitedFromSearch classesProhibitedFromSearch;
protected IndividualProhibitedFromSearch individualProhibitedFromSearch;
public static VitroSearchTermNames term = new VitroSearchTermNames();
protected final String label = "http://www.w3.org/2000/01/rdf-schema#label";
protected List<DocumentModifier> documentModifiers = new ArrayList<DocumentModifier>();
public IndividualToSolrDocument(
ClassProhibitedFromSearch classesProhibitedFromSearch,
IndividualProhibitedFromSearch individualProhibitedFromSearch){
this( classesProhibitedFromSearch,
individualProhibitedFromSearch,
Collections.EMPTY_LIST);
}
public IndividualToSolrDocument(
ClassProhibitedFromSearch classesProhibitedFromSearch,
IndividualProhibitedFromSearch individualProhibitedFromSearch,
List<DocumentModifier> docModifiers){
this.classesProhibitedFromSearch = classesProhibitedFromSearch;
this.individualProhibitedFromSearch = individualProhibitedFromSearch;
this.documentModifiers = docModifiers;
}
protected List<SearchIndexExcluder> excludes;
public IndividualToSolrDocument(List<SearchIndexExcluder> excludes, List<DocumentModifier> docModifiers){
this.excludes = excludes;
this.documentModifiers = docModifiers;
}
@SuppressWarnings("static-access")
public SolrInputDocument translate(Individual ind) throws IndexingException{
try{
log.debug("translating " + ind.getURI());
checkForSkipBasedOnNS( ind );
String excludeMsg = checkExcludes( ind );
if( excludeMsg != DONT_EXCLUDE){
log.debug(excludeMsg);
return null;
}
SolrInputDocument doc = new SolrInputDocument();
//DocID
@ -77,44 +61,30 @@ public class IndividualToSolrDocument {
//vitro id
doc.addField(term.URI, ind.getURI());
//java class
doc.addField(term.JCLASS, entClassName);
//Individual Label
addLabel( ind, doc );
//add classes, classgroups get if prohibied becasue of its class
StringBuffer classPublicNames = new StringBuffer("");
boolean prohibited = addClasses(ind, doc, classPublicNames);
//filter out class groups, owl:ObjectProperties etc..
if(individualProhibitedFromSearch.isIndividualProhibited( ind.getURI() )){
return null;
}
addClasses(ind, doc, classPublicNames);
// collecting URIs and rdfs:labels of objects of statements
StringBuffer objectNames = new StringBuffer("");
StringBuffer addUri = new StringBuffer("");
addObjectPropertyText(ind, doc, objectNames, addUri);
//add if the individual has a thumbnail or not.
addThumbnailExistance(ind, doc);
addObjectPropertyText(ind, doc, objectNames, addUri);
//time of index in millis past epoc
doc.addField(term.INDEXEDTIME, new Long( (new DateTime()).getMillis() ) );
if(!prohibited){
addAllText( ind, doc, classPublicNames, objectNames );
addAllText( ind, doc, classPublicNames, objectNames );
runAdditionalDocModifers(ind,doc,addUri);
//boost for entity
if(documentModifiers == null || documentModifiers.isEmpty() &&
(ind.getSearchBoost() != null && ind.getSearchBoost() != 0)) {
doc.setDocumentBoost(ind.getSearchBoost());
}
}
//boost for entity
if(ind.getSearchBoost() != null && ind.getSearchBoost() != 0) {
doc.setDocumentBoost(ind.getSearchBoost());
}
runAdditionalDocModifers(ind,doc,addUri);
return doc;
}catch(SkipIndividualException ex){
@ -122,7 +92,7 @@ public class IndividualToSolrDocument {
log.debug(ex);
return null;
}catch(Throwable th){
//Odd exceptions from jena get thrown on shutdown
//Odd exceptions can get thrown on shutdown
if( log != null )
log.debug(th);
return null;
@ -130,7 +100,20 @@ public class IndividualToSolrDocument {
}
protected void runAdditionalDocModifers( Individual ind, SolrInputDocument doc, StringBuffer addUri )
protected String checkExcludes(Individual ind) {
for( SearchIndexExcluder excluder : excludes){
try{
String msg = excluder.checkForExclusion(ind);
if( msg != DONT_EXCLUDE)
return msg;
}catch (Exception e) {
return e.getMessage();
}
}
return DONT_EXCLUDE;
}
protected void runAdditionalDocModifers( Individual ind, SolrInputDocument doc, StringBuffer addUri )
throws SkipIndividualException{
//run the document modifiers
if( documentModifiers != null && !documentModifiers.isEmpty()){
@ -140,18 +123,6 @@ public class IndividualToSolrDocument {
}
}
protected void checkForSkipBasedOnNS(Individual ind) throws SkipIndividualException {
String id = ind.getURI();
if(id == null){
throw new SkipIndividualException("cannot add individuals without URIs to search index");
}else if( id.startsWith(VitroVocabulary.vitroURI) ||
id.startsWith(VitroVocabulary.VITRO_PUBLIC) ||
id.startsWith(VitroVocabulary.PSEUDO_BNODE_NS) ||
id.startsWith(OWL.NS)){
throw new SkipIndividualException("not indexing because of namespace:" + id);
}
}
protected void addAllText(Individual ind, SolrInputDocument doc, StringBuffer classPublicNames, StringBuffer objectNames) {
String t=null;
//ALLTEXT, all of the 'full text'
@ -210,19 +181,7 @@ public class IndividualToSolrDocument {
// NAME_LOWERCASE, NAME_UNSTEMMED, NAME_STEMMED, NAME_PHONETIC, AC_NAME_UNTOKENIZED, AC_NAME_STEMMED
}
/**
* Adds if the individual has a thumbnail image or not.
*/
protected void addThumbnailExistance(Individual ind, SolrInputDocument doc) {
try{
if(ind.hasThumb())
doc.addField(term.THUMBNAIL, "1");
else
doc.addField(term.THUMBNAIL, "0");
}catch(Exception ex){
log.debug("could not index thumbnail: " + ex);
}
}
/**
* Get the rdfs:labes for objects of statements and put in objectNames.
@ -258,32 +217,24 @@ public class IndividualToSolrDocument {
* @returns true if prohibited from search
* @throws SkipIndividualException
*/
protected boolean addClasses(Individual ind, SolrInputDocument doc, StringBuffer classPublicNames) throws SkipIndividualException{
protected void addClasses(Individual ind, SolrInputDocument doc, StringBuffer classPublicNames) throws SkipIndividualException{
ArrayList<String> superClassNames = null;
// Types and classgroups
boolean prohibited = false;
List<VClass> vclasses = ind.getVClasses(false);
superClassNames = new ArrayList<String>();
if( vclasses == null || vclasses.isEmpty() ){
throw new SkipIndividualException("Not indexing because individual has no super classes");
}
for(VClass clz : vclasses){
String superLclName = clz.getLocalName();
superClassNames.add(superLclName);
if(clz.getURI() == null){
continue;
}else if(OWL.Thing.getURI().equals(clz.getURI())){
//index individuals of type owl:Thing, just don't add owl:Thing as the type field in the index
//don't add owl:Thing as the type in the index
continue;
} else if(clz.getURI().startsWith(OWL.NS)){
throw new SkipIndividualException("not indexing " + ind.getURI() + " because of type " + clz.getURI() );
}
// do not index individuals of type Role, AdvisingRelationShip, Authorship, etc.(see search.n3 for more information)
else if(classesProhibitedFromSearch.isClassProhibitedFromSearch(clz.getURI())){
throw new SkipIndividualException("not indexing " + ind.getURI() + " because of prohibited type " + clz.getURI() );
} else {
if( !prohibited && classesProhibitedFromSearch.isClassProhibitedFromSearch(clz.getURI()))
prohibited = true;
if( clz.getSearchBoost() != null)
} else {
if( clz.getSearchBoost() != null){
doc.setDocumentBoost(doc.getDocumentBoost() + clz.getSearchBoost());
}
doc.addField(term.RDFTYPE, clz.getURI());
@ -302,14 +253,7 @@ public class IndividualToSolrDocument {
doc.addField(term.CLASSGROUP_URI,clz.getGroupURI());
}
}
}
if(superClassNames.isEmpty()){
throw new SkipIndividualException("Not indexing because individual has no super classes");
}
doc.addField(term.PROHIBITED_FROM_TEXT_RESULTS, prohibited?"1":"0");
return prohibited;
}
}
public Object getIndexId(Object obj) {
@ -318,7 +262,7 @@ public class IndividualToSolrDocument {
public String getIdForUri(String uri){
if( uri != null ){
return entClassName + uri;
return "vitroIndividual:" + uri;
}else{
return null;
}
@ -352,6 +296,5 @@ public class IndividualToSolrDocument {
}
}
public static float NAME_BOOST = 1.2F;
protected static final String DONT_EXCLUDE =null;
}

View file

@ -10,10 +10,21 @@ import edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames;
public class NameBoost implements DocumentModifier {
static VitroSearchTermNames term = new VitroSearchTermNames();
/**
* These are the fields in the solr Document that
* are related to the name. If you modify the schema,
* please consider if you need to change this list
* of name fields to boost.
*/
static final VitroSearchTermNames term = new VitroSearchTermNames();
String[] fieldsToBoost = {term.NAME_RAW,term.NAME_LOWERCASE,term.NAME_UNSTEMMED,term.NAME_STEMMED};
static final float NAME_BOOST = (float) 1.2;
final float boost;
public NameBoost(float boost){
this.boost = boost;
}
@Override
public void modifyDocument(Individual individual, SolrInputDocument doc,
@ -21,8 +32,9 @@ public class NameBoost implements DocumentModifier {
for( String fieldName : fieldsToBoost){
SolrInputField field = doc.getField(fieldName);
if( field != null )
field.setBoost(field.getBoost() * NAME_BOOST);
if( field != null ){
field.setBoost(field.getBoost() + boost);
}
}
}

Some files were not shown because too many files have changed in this diff Show more