Changing the DataGetter and PageDataGetter utuils to not log unnecessary errors. Adding unit tests for DataGetters and PageDataGetters.

This commit is contained in:
briancaruso 2012-02-15 17:57:01 +00:00
parent 3b95705d97
commit c30e883f7e
15 changed files with 478 additions and 151 deletions

View file

@ -525,9 +525,10 @@ public class JsonServlet extends VitroHttpServlet {
/** /**
* Gets data based on data getter for page uri and returns in the form of Json objects * Gets data based on data getter for page uri and returns in the form of Json objects
* @param req * @param req
* @param resp * @param resp
*/ */
private void getDataForPage(HttpServletRequest req, HttpServletResponse resp) { private void getDataForPage(HttpServletRequest req, HttpServletResponse resp)
throws Exception{
VitroRequest vreq = new VitroRequest(req); VitroRequest vreq = new VitroRequest(req);
String errorMessage = null; String errorMessage = null;
JSONObject rObj = null; JSONObject rObj = null;

View file

@ -23,10 +23,10 @@ public class HomePageController extends FreemarkerHttpServlet {
private static final String BODY_TEMPLATE = "home.ftl"; private static final String BODY_TEMPLATE = "home.ftl";
@Override @Override
protected ResponseValues processRequest(VitroRequest vreq) { protected ResponseValues processRequest(VitroRequest vreq) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Map<String, Object> body = new HashMap<String, Object>(); Map<String, Object> body = new HashMap<String, Object>();
List<PageDataGetter> dataGetters = PageDataGetterUtils.getDataGetterObjects(vreq, DisplayVocabulary.HOME_PAGE_URI); List<PageDataGetter> dataGetters = PageDataGetterUtils.getPageDataGetterObjects(vreq, DisplayVocabulary.HOME_PAGE_URI);
for(PageDataGetter dataGetter: dataGetters) { for(PageDataGetter dataGetter: dataGetters) {
if( dataGetter != null ){ if( dataGetter != null ){
String uriOfPageInDisplayModel = "not defined"; String uriOfPageInDisplayModel = "not defined";

View file

@ -3,6 +3,7 @@
package edu.cornell.mannlib.vitro.webapp.controller.freemarker; package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -72,7 +73,7 @@ public class PageController extends FreemarkerHttpServlet{
} }
private void executeDataGetters(String pageUri, VitroRequest vreq, ServletContext context, Map<String, Object> mapForTemplate) private void executeDataGetters(String pageUri, VitroRequest vreq, ServletContext context, Map<String, Object> mapForTemplate)
throws InstantiationException, IllegalAccessException, ClassNotFoundException { throws Exception {
List<DataGetter> dgList = DataGetterUtils.getDataGettersForPage(vreq.getDisplayModel(), pageUri); List<DataGetter> dgList = DataGetterUtils.getDataGettersForPage(vreq.getDisplayModel(), pageUri);
for( DataGetter dg : dgList){ for( DataGetter dg : dgList){
@ -83,7 +84,8 @@ public class PageController extends FreemarkerHttpServlet{
} }
} }
private void executePageDataGetters(String pageUri, VitroRequest vreq, ServletContext context, Map<String, Object> mapForTemplate) { private void executePageDataGetters(String pageUri, VitroRequest vreq, ServletContext context, Map<String, Object> mapForTemplate)
throws Exception{
mapForTemplate.putAll( PageDataGetterUtils.getDataForPage(pageUri, vreq, context) ); mapForTemplate.putAll( PageDataGetterUtils.getDataForPage(pageUri, vreq, context) );
} }

View file

@ -696,39 +696,18 @@ public class JenaIngestController extends BaseEditController {
} }
} }
protected ModelMaker getVitroJenaModelMaker(HttpServletRequest request) { protected ModelMaker getVitroJenaModelMaker(HttpServletRequest request){
ModelMaker myVjmm = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker"); return JenaIngestController.getVitroJenaModelMaker(request,getServletContext());
myVjmm = (myVjmm == null) ? (ModelMaker) getServletContext().getAttribute("vitroJenaSDBModelMaker") : myVjmm;
return new VitroJenaSpecialModelMaker(myVjmm, request);
} }
protected Model getModel(String name, HttpServletRequest request) {
if ("vitro:jenaOntModel".equals(name)) {
Object sessionOntModel = request.getSession().getAttribute("jenaOntModel"); protected Model getModel( String name, HttpServletRequest request ){
if (sessionOntModel != null && sessionOntModel instanceof OntModel) { return JenaIngestController.getModel(name, request, getServletContext());
return (OntModel) sessionOntModel;
} else {
return (OntModel) getServletContext().getAttribute("jenaOntModel");
}
} else if ("vitro:baseOntModel".equals(name)) {
Object sessionOntModel = request.getSession().getAttribute("baseOntModel");
if (sessionOntModel != null && sessionOntModel instanceof OntModel) {
return (OntModel) sessionOntModel;
} else {
return (OntModel) getServletContext().getAttribute("baseOntModel");
}
} else if ("vitro:inferenceOntModel".equals(name)) {
Object sessionOntModel = request.getSession().getAttribute("inferenceOntModel");
if (sessionOntModel != null && sessionOntModel instanceof OntModel) {
return (OntModel) sessionOntModel;
} else {
return (OntModel) getServletContext().getAttribute("inferenceOntModel");
}
} else {
return getVitroJenaModelMaker(request).getModel(name);
}
} }
protected String getModelType(VitroRequest vreq, ModelMaker maker) { protected String getModelType(VitroRequest vreq, ModelMaker maker) {
String modelType = vreq.getParameter("modelType"); String modelType = vreq.getParameter("modelType");
maker = (maker instanceof VitroJenaSpecialModelMaker) maker = (maker instanceof VitroJenaSpecialModelMaker)
@ -1252,5 +1231,37 @@ public class JenaIngestController extends BaseEditController {
} }
} }
public static Model getModel(String name, HttpServletRequest request, ServletContext context) {
if ("vitro:jenaOntModel".equals(name)) {
Object sessionOntModel = request.getSession().getAttribute("jenaOntModel");
if (sessionOntModel != null && sessionOntModel instanceof OntModel) {
return (OntModel) sessionOntModel;
} else {
return (OntModel) context.getAttribute("jenaOntModel");
}
} else if ("vitro:baseOntModel".equals(name)) {
Object sessionOntModel = request.getSession().getAttribute("baseOntModel");
if (sessionOntModel != null && sessionOntModel instanceof OntModel) {
return (OntModel) sessionOntModel;
} else {
return (OntModel) context.getAttribute("baseOntModel");
}
} else if ("vitro:inferenceOntModel".equals(name)) {
Object sessionOntModel = request.getSession().getAttribute("inferenceOntModel");
if (sessionOntModel != null && sessionOntModel instanceof OntModel) {
return (OntModel) sessionOntModel;
} else {
return (OntModel) context.getAttribute("inferenceOntModel");
}
} else {
return getVitroJenaModelMaker(request,context).getModel(name);
}
}
protected static ModelMaker getVitroJenaModelMaker(HttpServletRequest request, ServletContext context) {
ModelMaker myVjmm = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
myVjmm = (myVjmm == null) ? (ModelMaker) context.getAttribute("vitroJenaSDBModelMaker") : myVjmm;
return new VitroJenaSpecialModelMaker(myVjmm, request);
}
} }

View file

@ -572,7 +572,7 @@ public class PagedSearchController extends FreemarkerHttpServlet {
/** /**
* Makes a message to display to user for a bad search term. * Makes a message to display to user for a bad search term.
* @param query * @param queryText
* @param exceptionMsg * @param exceptionMsg
*/ */
private String makeBadSearchMessage(String querytext, String exceptionMsg){ private String makeBadSearchMessage(String querytext, String exceptionMsg){

View file

@ -19,9 +19,15 @@ import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
* *
* Using this interface is preferred over PageDataGetter because then the DataGetter can be associated with * Using this interface is preferred over PageDataGetter because then the DataGetter can be associated with
* things other than pages. * things other than pages.
*
* Constructors: Objects that implement this interface will be constructed by reflection with the following
* constructor signatures in the following order:
* DataGetter( Model displayModel, String dataGetterURI )
* DataGetter()
*
*/ */
public interface DataGetter { public interface DataGetter {
/** /**
* Get data. Throwing an Exception is acceptable. * Get data. Throwing an Exception is acceptable.
* *
@ -30,23 +36,6 @@ public interface DataGetter {
* @param valueMap - any values already generated by data getters or the controller. * @param valueMap - any values already generated by data getters or the controller.
* @return data to add to valueMap. Should not be null. * @return data to add to valueMap. Should not be null.
*/ */
Map<String,Object> getData(ServletContext context, VitroRequest vreq, Map<String, Object> valueMap ); Map<String,Object> getData(ServletContext context, VitroRequest vreq, Map<String, Object> valueMap );
/**
* Configure the DataGetter for a specific Resource.
*
* In order to create and configure instances of classes that implement this interface,
* we need a constructor like method. But interfaces cannot define constructors. A
* method like this is not ideal. Maybe this should be moved to a factory.
*
* To create an instance of a class that implements this interface, instantiate an object
* of the class, then call this method. If there are any problems calling configure, consider
* the object useless.
*
* @param displayModel - source of configuration info for resource with dataGetterURI
* @param dataGetterURI - URI of resource to use to configure this object.
*/
void configure(Model displayModel, String dataGetterURI);
} }

View file

@ -0,0 +1,45 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.dataGetter;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.commons.lang.StringUtils;
import com.hp.hpl.jena.rdf.model.Model;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.jena.JenaIngestController;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VitroJenaModelMaker;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VitroJenaSDBModelMaker;
public abstract class DataGetterBase implements DataGetter {
/**
* Get the model to use based on a model URI.
*/
protected Model getModel(ServletContext context, VitroRequest vreq , String modelName) {
//if not set use jenaOntModel from the request
if( StringUtils.isEmpty(modelName) ){
return vreq.getJenaOntModel();
}else if(REQUEST_DISPLAY_MODEL.equals(modelName)){
return vreq.getDisplayModel();
}else if( REQUEST_JENA_ONT_MODEL.equals(modelName)){
return vreq.getJenaOntModel();
}else if( ! StringUtils.isEmpty( modelName)){
Model model = JenaIngestController.getModel( modelName, vreq, context);
if( model == null )
throw new IllegalAccessError("Cannot get model <" + modelName +"> for DataGetter.");
else
return model;
}else{
//default is just the JeanOntModel from the vreq.
return vreq.getJenaOntModel();
}
}
public final static String REQUEST_DISPLAY_MODEL = "vitro:requestDisplayModel";
public final static String REQUEST_JENA_ONT_MODEL = "vitro:requestJenaOntModel";
}

View file

@ -1,6 +1,8 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.dataGetter; package edu.cornell.mannlib.vitro.webapp.utils.dataGetter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -28,8 +30,13 @@ public class DataGetterUtils {
final static Log log = LogFactory.getLog(DataGetterUtils.class); final static Log log = LogFactory.getLog(DataGetterUtils.class);
/**
* Get a list of DataGetter objects that are associated with a page.
* This should not return PageDataGetters and should not throw an
* exception if a page has PageDataGetters.
*/
public static List<DataGetter> getDataGettersForPage( Model displayModel, String pageURI) public static List<DataGetter> getDataGettersForPage( Model displayModel, String pageURI)
throws InstantiationException, IllegalAccessException, ClassNotFoundException{ throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException{
//get data getter uris for pageURI //get data getter uris for pageURI
List<String> dgUris = getDataGetterURIsForPageURI( displayModel, pageURI); List<String> dgUris = getDataGetterURIsForPageURI( displayModel, pageURI);
@ -43,15 +50,62 @@ public class DataGetterUtils {
} }
/** /**
* May return null. * Tests if classInQuestion implements interFace.
*/ */
public static DataGetter dataGetterForURI(Model displayModel, String dataGetterURI) throws InstantiationException, IllegalAccessException, ClassNotFoundException { public static boolean isInstanceOfInterface( Class classInQuestion, Class interFace){
if( classInQuestion == null || interFace == null )
throw new IllegalAccessError("classInQuestion or interFace must not be null");
//figure out if it implements interface
Class[] interfaces = classInQuestion.getInterfaces();
if( interfaces == null )
return false;
boolean foundIface = false;
for( Class cz : interfaces ){
if( interFace.equals( cz ) ){
return true;
}
}
return false;
}
/**
* Returns a DataGetter using information in the
* displayModel for the individual with the URI given by dataGetterURI
* to configure it.
*
* May return null.
* This should not throw an exception if the URI exists and has a type
* that does not implement the DataGetter interface.
*/
public static DataGetter dataGetterForURI(Model displayModel, String dataGetterURI)
throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException, SecurityException, NoSuchMethodException
{
//get java class for dataGetterURI //get java class for dataGetterURI
String dgClassName = getJClassForDataGetterURI(displayModel, dataGetterURI); String dgClassName = getJClassForDataGetterURI(displayModel, dataGetterURI);
//construct class //figure out if it implements interface DataGetter
Object obj = Class.forName(dgClassName).newInstance(); Class dgClass = Class.forName(dgClassName);
if( ! isInstanceOfInterface( dgClass, DataGetter.class) ){
return null;
}
//try to run constructor with (Model, String) parameters
Class partypes[] = { Model.class , String.class };
Constructor ct = dgClass.getConstructor( partypes );
Object obj = null;
if( ct != null ){
Object[] initargs = new Object[2];
initargs[0]= displayModel;
initargs[1] = dataGetterURI;
obj = ct.newInstance(initargs);
} else {
log.debug("no constructor with signature " +
"(Model displayModel,String URI) found, trying empty constructor");
obj = dgClass.newInstance();
}
if( !(obj instanceof DataGetter) ){ if( !(obj instanceof DataGetter) ){
log.debug("For <" + dataGetterURI + "> the class " + log.debug("For <" + dataGetterURI + "> the class " +
@ -59,9 +113,7 @@ public class DataGetterUtils {
return null; return null;
} }
DataGetter dg = (DataGetter)obj; return (DataGetter)obj;
dg.configure(displayModel, dataGetterURI);
return dg;
} }
public static String getJClassForDataGetterURI(Model displayModel, String dataGetterURI) throws IllegalAccessException { public static String getJClassForDataGetterURI(Model displayModel, String dataGetterURI) throws IllegalAccessException {

View file

@ -30,68 +30,79 @@ import com.hp.hpl.jena.shared.Lock;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
public class SparqlQueryDataGetter implements DataGetter{ public class SparqlQueryDataGetter extends DataGetterBase implements DataGetter{
String pageUri; String dataGetterURI;
String query; String queryText;
String saveToVar; String saveToVar;
String modelUri; String modelURI;
final static Log log = LogFactory.getLog(SparqlQueryDataGetter.class); final static Log log = LogFactory.getLog(SparqlQueryDataGetter.class);
/**
* Constructor with display model and data getter URI that will be called by reflection.
*/
public SparqlQueryDataGetter(Model displayModel, String dataGetterURI){
this.configure(displayModel,dataGetterURI);
}
@Override @Override
public Map<String, Object> getData(ServletContext context, VitroRequest vreq, Map<String, Object> pageData) { public Map<String, Object> getData(ServletContext context, VitroRequest vreq, Map<String, Object> pageData) {
if( pageUri == null ) return doQuery( vreq.getParameterMap(), getModel(context, vreq, modelURI));
throw new IllegalAccessError("configure() must be called before getData()");
return doQuery( vreq.getParameterMap(),getModelToRunQueryOn(context, vreq ));
} }
@Override /**
public void configure(Model model, String dataGetterURI) { * Configure this instance based on the URI and display model.
if( model == null ) */
protected void configure(Model displayModel, String dataGetterURI) {
if( displayModel == null )
throw new IllegalArgumentException("Display Model may not be null."); throw new IllegalArgumentException("Display Model may not be null.");
if( dataGetterURI == null ) if( dataGetterURI == null )
throw new IllegalArgumentException("PageUri may not be null."); throw new IllegalArgumentException("PageUri may not be null.");
this.pageUri = dataGetterURI; this.dataGetterURI = dataGetterURI;
QuerySolutionMap initBindings = new QuerySolutionMap(); QuerySolutionMap initBindings = new QuerySolutionMap();
initBindings.add("pageUri", ResourceFactory.createResource(this.pageUri)); initBindings.add("dataGetterURI", ResourceFactory.createResource(this.dataGetterURI));
int count = 0; int count = 0;
Query query = QueryFactory.create(pageQuery) ; Query dataGetterConfigurationQuery = QueryFactory.create(dataGetterQuery) ;
model.enterCriticalSection(Lock.READ); displayModel.enterCriticalSection(Lock.READ);
try{ try{
QueryExecution qexec = QueryExecutionFactory.create(query, model, initBindings) ; QueryExecution qexec = QueryExecutionFactory.create(
dataGetterConfigurationQuery, displayModel, initBindings) ;
ResultSet res = qexec.execSelect(); ResultSet res = qexec.execSelect();
try{ try{
while( res.hasNext() ){ while( res.hasNext() ){
count++; count++;
QuerySolution soln = res.next(); QuerySolution soln = res.next();
//query is not OPTIONAL //query is NOT OPTIONAL
Literal value = soln.getLiteral("query"); Literal value = soln.getLiteral("query");
if( query == null ) if( dataGetterConfigurationQuery == null )
log.error("no query defined for page " + this.pageUri); log.error("no query defined for page " + this.dataGetterURI);
else else
this.query = value.getLexicalForm(); this.queryText = value.getLexicalForm();
//model is OPTIONAL //model is OPTIONAL
RDFNode node = soln.getResource("model"); RDFNode node = soln.getResource("model");
if( node != null && node.isURIResource() ){ if( node != null && node.isURIResource() ){
this.modelUri = node.asResource().getURI(); this.modelURI = node.asResource().getURI();
}else if( node != null && node.isLiteral() ){ }else if( node != null && node.isLiteral() ){
this.modelUri = node.asLiteral().getLexicalForm(); this.modelURI = node.asLiteral().getLexicalForm();
}else{
this.modelURI = null;
} }
//saveToVar is OPTIONAL //saveToVar is OPTIONAL
node = soln.getResource("saveToVar"); Literal saveTo = soln.getLiteral("saveToVar");
if( node != null && node.isLiteral() ){ if( saveTo != null && saveTo.isLiteral() ){
this.saveToVar= node.asLiteral().getLexicalForm(); this.saveToVar = saveTo.asLiteral().getLexicalForm();
}else{
this.saveToVar = defaultVarNameForResults;
} }
} }
}finally{ qexec.close(); } }finally{ qexec.close(); }
}finally{ model.leaveCriticalSection(); } }finally{ displayModel.leaveCriticalSection(); }
} }
/** /**
@ -100,20 +111,13 @@ public class SparqlQueryDataGetter implements DataGetter{
*/ */
private Map<String, Object> doQuery(Map<String, String[]>parameterMap, Model queryModel){ private Map<String, Object> doQuery(Map<String, String[]>parameterMap, Model queryModel){
if( this.query == null ){ if( this.queryText == null ){
log.error("no SPARQL query defined for page " + this.pageUri); log.error("no SPARQL query defined for page " + this.dataGetterURI);
//TODO: return an error message?
return Collections.emptyMap(); return Collections.emptyMap();
} }
Query query = null; //this may throw an error
try{ Query query = QueryFactory.create( this.queryText );
query = QueryFactory.create( this.query );
}catch(Exception ex){
//TODO: return an error message?
log.error( "for page " + this.pageUri, ex );
return Collections.emptyMap();
}
//build query bindings //build query bindings
QuerySolutionMap initialBindings = createBindings( parameterMap); QuerySolutionMap initialBindings = createBindings( parameterMap);
@ -177,25 +181,13 @@ public class SparqlQueryDataGetter implements DataGetter{
} }
} }
private Model getModelToRunQueryOn(ServletContext context, VitroRequest vreq ) {
//just use JenaOntModel for now. in the future specify the
//query model from the DataGetter's RDF configuration.
return vreq.getJenaOntModel();
}
private Model getDisplayModel(VitroRequest vreq, ServletContext context) {
return vreq.getDisplayModel(); private QuerySolutionMap createBindings(Map<String, String[]>parameterMap) {
}
private QuerySolutionMap createBindings(Map<String, String[]>parameterMap) {
QuerySolutionMap initBindings = new QuerySolutionMap(); QuerySolutionMap initBindings = new QuerySolutionMap();
initBindings.add("pageUri", ResourceFactory.createResource(pageUri));
//could have bindings from HTTP parameters //could have bindings from HTTP parameters
for( String var : parameterMap.keySet() ) { for( String var : parameterMap.keySet() ) {
String[] values = parameterMap.get(var); String[] values = parameterMap.get(var);
if( values != null && values.length == 1 ){ if( values != null && values.length == 1 ){
//what do do when we don't want a Resource? //what do do when we don't want a Resource?
@ -203,16 +195,20 @@ public class SparqlQueryDataGetter implements DataGetter{
}else if( values.length > 1){ }else if( values.length > 1){
log.error("more than 1 http parameter for " + var); log.error("more than 1 http parameter for " + var);
} }
} }
return initBindings; return initBindings;
} }
private static final String queryPropertyURI = "<" + DisplayVocabulary.QUERY + ">"; private static final String queryPropertyURI = "<" + DisplayVocabulary.QUERY + ">";
private static final String saveToVarPropertyURI= "<" + DisplayVocabulary.SAVE_TO_VAR+ ">"; private static final String saveToVarPropertyURI= "<" + DisplayVocabulary.SAVE_TO_VAR+ ">";
private static final String queryModelPropertyURI= "<" + DisplayVocabulary.QUERY_MODEL+ ">"; private static final String queryModelPropertyURI= "<" + DisplayVocabulary.QUERY_MODEL+ ">";
public static final String defaultVarNameForResults = "results";
private static final String pageQuery = /**
* Query to get the definition of the SparqlDataGetter for a given URI.
*/
private static final String dataGetterQuery =
"PREFIX display: <" + DisplayVocabulary.DISPLAY_NS +"> \n" + "PREFIX display: <" + DisplayVocabulary.DISPLAY_NS +"> \n" +
"SELECT ?query ?saveToVar ?model WHERE { \n" + "SELECT ?query ?saveToVar ?model WHERE { \n" +
" ?pageUri "+queryPropertyURI+" ?query . \n" + " ?pageUri "+queryPropertyURI+" ?query . \n" +

View file

@ -31,17 +31,18 @@ import edu.cornell.mannlib.vitro.webapp.controller.freemarker.IndividualListCont
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache; import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache;
import edu.cornell.mannlib.vitro.webapp.utils.dataGetter.DataGetterUtils;
public class PageDataGetterUtils { public class PageDataGetterUtils {
protected static final String DATA_GETTER_MAP = "pageTypeToDataGetterMap"; protected static final String DATA_GETTER_MAP = "pageTypeToDataGetterMap";
private static final Log log = LogFactory.getLog(PageDataGetterUtils.class); private static final Log log = LogFactory.getLog(PageDataGetterUtils.class);
public static Map<String,Object> getDataForPage(String pageUri, VitroRequest vreq, ServletContext context) { public static Map<String,Object> getDataForPage(String pageUri, VitroRequest vreq, ServletContext context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
//Based on page type get the appropriate data getter //Based on page type get the appropriate data getter
Map<String, Object> page = vreq.getWebappDaoFactory().getPageDao().getPage(pageUri); Map<String, Object> page = vreq.getWebappDaoFactory().getPageDao().getPage(pageUri);
Map<String,Object> data = new HashMap<String,Object>(); Map<String,Object> data = new HashMap<String,Object>();
List<PageDataGetter> dataGetters = getDataGetterObjects(vreq, pageUri); List<PageDataGetter> dataGetters = getPageDataGetterObjects(vreq, pageUri);
for(PageDataGetter getter: dataGetters) { for(PageDataGetter getter: dataGetters) {
try{ try{
Map<String,Object> moreData = null; Map<String,Object> moreData = null;
@ -59,15 +60,14 @@ public class PageDataGetterUtils {
* *
* Convert data to JSON for page uri based on type and related datagetters * Convert data to JSON for page uri based on type and related datagetters
* TODO: How to handle different data getters? Will this replace json fields or add to them? * TODO: How to handle different data getters? Will this replace json fields or add to them?
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/ */
public static JSONObject covertDataToJSONForPage(String pageUri, Map<String, Object> data, VitroRequest vreq, ServletContext context) { public static JSONObject covertDataToJSONForPage(String pageUri, Map<String, Object> data, VitroRequest vreq, ServletContext context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
//Based on page type get the appropriate data getter //Get PageDataGetter types associated with pageUri
Map<String, Object> page = vreq.getWebappDaoFactory().getPageDao().getPage(pageUri); JSONObject rObj = null;
List<PageDataGetter> dataGetters = getPageDataGetterObjects(vreq, pageUri);
//Get types associated with page
JSONObject rObj = null;
List<String> types = (List<String>)page.get("types");
List<PageDataGetter> dataGetters = getDataGetterObjects(vreq, pageUri);
for(PageDataGetter getter: dataGetters) { for(PageDataGetter getter: dataGetters) {
JSONObject typeObj = null; JSONObject typeObj = null;
try{ try{
@ -110,30 +110,35 @@ public class PageDataGetterUtils {
} }
/*** /***
* For the page, get the actual Data Getters to be employed * For the page, get the actual Data Getters to be employed.
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/ */
public static List<PageDataGetter> getDataGetterObjects(VitroRequest vreq, String pageUri) { public static List<PageDataGetter> getPageDataGetterObjects(VitroRequest vreq, String pageUri) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
List<PageDataGetter> dataGetterObjects = new ArrayList<PageDataGetter>(); List<PageDataGetter> dataGetterObjects = new ArrayList<PageDataGetter>();
try {
List<String> dataGetterClassNames = vreq.getWebappDaoFactory().getPageDao().getDataGetterClass(pageUri); List<String> dataGetterClassNames = vreq.getWebappDaoFactory().getPageDao().getDataGetterClass(pageUri);
if( dataGetterClassNames == null )
return Collections.emptyList();
for(String dgClassName: dataGetterClassNames) {
String className = getClassNameFromUri(dgClassName); for(String dgClassName: dataGetterClassNames) {
Object obj = Class.forName(className).newInstance(); String className = getClassNameFromUri(dgClassName);
if(obj != null && obj instanceof PageDataGetter) { Class clz = Class.forName(className);
PageDataGetter pg = (PageDataGetter) obj;
dataGetterObjects.add(pg); if( DataGetterUtils.isInstanceOfInterface(clz, PageDataGetter.class)){
} Object obj = clz.newInstance();
} if(obj != null && obj instanceof PageDataGetter) {
} PageDataGetter pg = (PageDataGetter) obj;
catch(Exception ex) { dataGetterObjects.add(pg);
log.error("Error occurred in retrieving data getter class names for "+ pageUri, ex); }
} }// else skip if class does not implement PageDataGetter
}
return dataGetterObjects; return dataGetterObjects;
} }
//Class uris returned include "java:" and to instantiate object need to remove java: portion //Class URIs returned include "java:" and to instantiate object need to remove java: portion
public static String getClassNameFromUri(String dataGetterClassUri) { public static String getClassNameFromUri(String dataGetterClassUri) {
if( !StringUtils.isEmpty(dataGetterClassUri) && dataGetterClassUri.contains("java:")) { if( !StringUtils.isEmpty(dataGetterClassUri) && dataGetterClassUri.contains("java:")) {
String[] splitArray = dataGetterClassUri.split("java:"); String[] splitArray = dataGetterClassUri.split("java:");
@ -157,8 +162,7 @@ public class PageDataGetterUtils {
*/ */
public static JSONObject processVclassResultsJSON(Map<String, Object> map, VitroRequest vreq, boolean multipleVclasses) { public static JSONObject processVclassResultsJSON(Map<String, Object> map, VitroRequest vreq, boolean multipleVclasses) {
JSONObject rObj = new JSONObject(); JSONObject rObj = new JSONObject();
VClass vclass=null; VClass vclass=null;
String errorMessage = null;
try { try {
@ -191,7 +195,7 @@ public class PageDataGetterUtils {
vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vclassId); vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vclassId);
if (vclass == null) { if (vclass == null) {
log.error("Couldn't retrieve vclass "); log.error("Couldn't retrieve vclass ");
throw new Exception (errorMessage = "Class " + vclassId + " not found"); throw new Exception ("Class " + vclassId + " not found");
} }
} }
}else{ }else{

View file

@ -0,0 +1,77 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.dataGetter;
import static org.junit.Assert.fail;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.impl.RDFDefaultErrorHandler;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
public class DataGetterUtilsTest extends AbstractTestClass{
OntModel displayModel;
String testDataGetterURI_1 = "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#query1data";
String pageURI_1 = "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#SPARQLPage";
String pageX = "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#pageX";
String dataGetterX = "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#pageDataGetterX";
@Before
public void setUp() throws Exception {
// Suppress error logging.
setLoggerLevel(RDFDefaultErrorHandler.class, Level.OFF);
Model model = ModelFactory.createDefaultModel();
InputStream in = DataGetterUtilsTest.class.getResourceAsStream("resources/dataGetterTest.n3");
model.read(in,"","N3");
displayModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM,model);
}
@Test
public void testGetJClassForDataGetterURI() throws IllegalAccessException {
String fullJavaClassName = DataGetterUtils.getJClassForDataGetterURI(displayModel, testDataGetterURI_1);
Assert.assertNotNull(fullJavaClassName);
Assert.assertTrue("java class name should not be empty", ! StringUtils.isEmpty(fullJavaClassName));
Assert.assertEquals(SparqlQueryDataGetter.class.getName(), fullJavaClassName);
}
@Test
public void testDataGetterForURI() throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException {
DataGetter dg = DataGetterUtils.dataGetterForURI(displayModel, testDataGetterURI_1);
Assert.assertNotNull(dg);
}
@Test
public void testGetDataGettersForPage() throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException {
List<DataGetter> dgList =
DataGetterUtils.getDataGettersForPage(displayModel, pageURI_1);
Assert.assertNotNull(dgList);
Assert.assertTrue("List of DataGetters was empty, it should not be.", dgList.size() > 0);
}
@Test
public void testNonPageDataGetter() throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException{
DataGetter dg = DataGetterUtils.dataGetterForURI(displayModel,dataGetterX);
Assert.assertNull(dg);
List<DataGetter> dgList =
DataGetterUtils.getDataGettersForPage(displayModel, pageX);
Assert.assertNotNull(dgList);
Assert.assertTrue("List should be, it was not", dgList.size() == 0);
}
}

View file

@ -0,0 +1,33 @@
# $This file is distributed under the terms of the license in /doc/license.txt$
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix display: <http://vitro.mannlib.cornell.edu/ontologies/display/1.1#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix core: <http://vivoweb.org/ontology/core#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
### This file is for the test DataGetterUtilsTest.java
display:SPARQLPage
a display:Page ;
display:title "TestQuery" ;
display:urlMapping "/query1" ;
display:hasDataGetter display:query1data .
display:query1data
a <java:edu.cornell.mannlib.vitro.webapp.utils.dataGetter.SparqlQueryDataGetter>;
display:query "SELECT * WHERE { ?uri a <http://xmlns.com/foaf/0.1/Person> } " ;
display:saveToVar "people" .
### test of what happens with a PageDataGetter instead of a DataGetter ###
display:pageX
a display:Page ;
display:title "A PageDataGetter, not a DataGetter" ;
display:urlMapping "/query2" ;
display:hasDataGetter display:pageDataGetterX .
display:pageDataGetterX
a <java:edu.cornell.mannlib.vitro.webapp.utils.pageDataGetter.ClassGroupPageData> .

View file

@ -0,0 +1,67 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.pageDataGetter;
import java.io.InputStream;
import java.util.List;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.javax.servlet.http.HttpServletRequestStub;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.impl.RDFDefaultErrorHandler;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.SimpleOntModelSelector;
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
public class PageDataGetterUtilsTest extends AbstractTestClass{
OntModel displayModel;
WebappDaoFactory wdf;
String pageURI = "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#pageX";
String pageURI_2 = "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#SPARQLPage";
@Before
public void setUp() throws Exception {
// Suppress error logging.
setLoggerLevel(RDFDefaultErrorHandler.class, Level.OFF);
OntModel model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM);
InputStream in = PageDataGetterUtilsTest.class.getResourceAsStream("resources/pageDataGetter.n3");
model.read(in,"","N3");
displayModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM,model);
SimpleOntModelSelector sos = new SimpleOntModelSelector( ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM));
sos.setDisplayModel(displayModel);
wdf = new WebappDaoFactoryJena(sos);
}
@Test
public void testGetPageDataGetterObjects() throws Exception{
VitroRequest vreq = new VitroRequest( new HttpServletRequestStub() );
vreq.setWebappDaoFactory(wdf);
List<PageDataGetter> pdgList = PageDataGetterUtils.getPageDataGetterObjects(vreq, pageURI);
Assert.assertNotNull(pdgList);
Assert.assertTrue("should have one PageDataGetter", pdgList.size() == 1);
}
@Test
public void testGetNonPageDataGetterObjects() throws Exception{
VitroRequest vreq = new VitroRequest( new HttpServletRequestStub() );
vreq.setWebappDaoFactory(wdf);
List<PageDataGetter> pdgList = PageDataGetterUtils.getPageDataGetterObjects(vreq, pageURI_2);
Assert.assertNotNull(pdgList);
Assert.assertTrue("should have no PageDataGetters", pdgList.size() == 0);
}
}

View file

@ -0,0 +1,20 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.pageDataGetter;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class SparqlQueryDataGetterTest {
@Before
public void setUp() throws Exception {
}
@Test
public void testGetData() {
fail("Not yet implemented");
}
}

View file

@ -0,0 +1,30 @@
# $This file is distributed under the terms of the license in /doc/license.txt$
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix display: <http://vitro.mannlib.cornell.edu/ontologies/display/1.1#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix core: <http://vivoweb.org/ontology/core#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
### This file is for the test PageDataGetterUtilsTest.java
display:SPARQLPage
a display:Page ;
display:title "TestQuery" ;
display:urlMapping "/query1" ;
display:hasDataGetter display:query1data .
display:query1data
a <java:edu.cornell.mannlib.vitro.webapp.utils.dataGetter.SparqlQueryDataGetter>;
display:query "SELECT * WHERE { ?uri a <http://xmlns.com/foaf/0.1/Person> } " ;
display:saveToVar "people" .
display:pageX
a display:Page ;
display:title "A PageDataGetter, not a DataGetter" ;
display:urlMapping "/query2" ;
display:hasDataGetter display:pageDataGetterX .
display:pageDataGetterX
a <java:edu.cornell.mannlib.vitro.webapp.utils.pageDataGetter.ClassGroupPageData> .