1. Code Cleanup & Refactor.

This commit is contained in:
cdtank 2010-07-27 23:46:42 +00:00
parent dc22d38eaa
commit d55b88c2f6
27 changed files with 1171 additions and 1337 deletions

View file

@ -31,7 +31,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
@ -47,20 +46,23 @@ import com.hp.hpl.jena.query.DatasetFactory;
import com.hp.hpl.jena.query.Syntax;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelMaker;
import com.hp.hpl.jena.sparql.resultset.ResultSetFormat;
import edu.cornell.mannlib.vedit.beans.LoginFormBean;
import edu.cornell.mannlib.vedit.controller.BaseEditController;
import edu.cornell.mannlib.vitro.webapp.beans.Portal;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.CoAuthorshipRequestHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.collegepubcount.CollegePublicationCountRequestHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.personlevel.PersonLevelRequestHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.PersonPublicationCountRequestHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.utilities.UtilitiesRequestHandler;
/**
* Services a sparql query. This will return a simple error message and a 501 if
* Services a visualization request. This will return a simple error message and a 501 if
* there is no jena Model.
*
* @author bdc34
*
* @author cdtank
*/
public class VisualizationController extends BaseEditController {
@ -74,35 +76,7 @@ public class VisualizationController extends BaseEditController {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
protected static HashMap<String,ResultSetFormat> formatSymbols = new HashMap<String,ResultSetFormat>();
static{
formatSymbols.put( ResultSetFormat.syntaxXML.getSymbol(), ResultSetFormat.syntaxXML);
formatSymbols.put( ResultSetFormat.syntaxRDF_XML.getSymbol(), ResultSetFormat.syntaxRDF_XML);
formatSymbols.put( ResultSetFormat.syntaxRDF_N3.getSymbol(), ResultSetFormat.syntaxRDF_N3);
formatSymbols.put( ResultSetFormat.syntaxText.getSymbol() , ResultSetFormat.syntaxText);
formatSymbols.put( ResultSetFormat.syntaxJSON.getSymbol() , ResultSetFormat.syntaxJSON);
formatSymbols.put( "vitro:csv", null);
}
protected static HashMap<String,String> rdfFormatSymbols = new HashMap<String,String>();
static {
rdfFormatSymbols.put( "RDF/XML", "application/rdf+xml" );
rdfFormatSymbols.put( "RDF/XML-ABBREV", "application/rdf+xml" );
rdfFormatSymbols.put( "N3", "text/n3" );
rdfFormatSymbols.put( "N-TRIPLE", "text/plain" );
rdfFormatSymbols.put( "TTL", "application/x-turtle" );
}
protected static HashMap<String, String> mimeTypes = new HashMap<String,String>();
static{
mimeTypes.put( ResultSetFormat.syntaxXML.getSymbol() , "text/xml" );
mimeTypes.put( ResultSetFormat.syntaxRDF_XML.getSymbol(), "application/rdf+xml" );
mimeTypes.put( ResultSetFormat.syntaxRDF_N3.getSymbol(), "text/plain" );
mimeTypes.put( ResultSetFormat.syntaxText.getSymbol() , "text/plain");
mimeTypes.put( ResultSetFormat.syntaxJSON.getSymbol(), "application/javascript" );
mimeTypes.put( "vitro:csv", "text/csv");
}
//TODO: For later, might want to improve these names for clarity.
public static final String PERSON_PUBLICATION_COUNT_VIS_URL_VALUE
= "person_pub_count";
@ -125,25 +99,24 @@ public class VisualizationController extends BaseEditController {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doGet(request,response);
throws ServletException, IOException {
this.doGet(request, response);
}
//TODO: Set it up so visualizations register themselves with this object. Don't tie this class to each visualization.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
throws ServletException, IOException {
super.doGet(request, response);
VitroRequest vreq = handleLoginAuthentication(request, response);
String visTypeURLHandle = vreq.getParameter(VIS_TYPE_URL_HANDLE);
if (PERSON_PUBLICATION_COUNT_VIS_URL_VALUE.equalsIgnoreCase(visTypeURLHandle)) {
if (PERSON_PUBLICATION_COUNT_VIS_URL_VALUE
.equalsIgnoreCase(vreq.getParameter(VIS_TYPE_URL_HANDLE))) {
edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.VisualizationRequestHandler visRequestHandler =
new edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.VisualizationRequestHandler(vreq, request, response, log);
PersonPublicationCountRequestHandler visRequestHandler =
new PersonPublicationCountRequestHandler(vreq, request, response, log);
String rdfResultFormatParam = "RDF/XML-ABBREV";
@ -153,7 +126,7 @@ public class VisualizationController extends BaseEditController {
rdfResultFormatParam);
if (dataSource != null) {
/*
* This is side-effecting because the visualization content is added
* to the request object.
@ -165,11 +138,10 @@ public class VisualizationController extends BaseEditController {
log.error("ERROR! Data Model Empty");
}
} else if (COLLEGE_PUBLICATION_COUNT_VIS_URL_VALUE
.equalsIgnoreCase(vreq.getParameter(VIS_TYPE_URL_HANDLE))) {
} else if (COLLEGE_PUBLICATION_COUNT_VIS_URL_VALUE.equalsIgnoreCase(visTypeURLHandle)) {
edu.cornell.mannlib.vitro.webapp.visualization.collegepubcount.VisualizationRequestHandler visRequestHandler =
new edu.cornell.mannlib.vitro.webapp.visualization.collegepubcount.VisualizationRequestHandler(vreq, request, response, log);
CollegePublicationCountRequestHandler visRequestHandler =
new CollegePublicationCountRequestHandler(vreq, request, response, log);
String rdfResultFormatParam = "RDF/XML-ABBREV";
@ -190,11 +162,10 @@ public class VisualizationController extends BaseEditController {
log.error("ERROR! data model empoty");
}
} else if (COAUTHORSHIP_VIS_URL_VALUE
.equalsIgnoreCase(vreq.getParameter(VIS_TYPE_URL_HANDLE))) {
} else if (COAUTHORSHIP_VIS_URL_VALUE.equalsIgnoreCase(visTypeURLHandle)) {
edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.VisualizationRequestHandler visRequestHandler =
new edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.VisualizationRequestHandler(vreq, request, response, log);
CoAuthorshipRequestHandler visRequestHandler =
new CoAuthorshipRequestHandler(vreq, request, response, log);
String rdfResultFormatParam = "RDF/XML-ABBREV";
@ -215,11 +186,10 @@ public class VisualizationController extends BaseEditController {
log.error("ERROR! data model empoty");
}
} else if (PERSON_LEVEL_VIS_URL_VALUE
.equalsIgnoreCase(vreq.getParameter(VIS_TYPE_URL_HANDLE))) {
} else if (PERSON_LEVEL_VIS_URL_VALUE.equalsIgnoreCase(visTypeURLHandle)) {
edu.cornell.mannlib.vitro.webapp.visualization.personlevel.VisualizationRequestHandler visRequestHandler =
new edu.cornell.mannlib.vitro.webapp.visualization.personlevel.VisualizationRequestHandler(vreq, request, response, log);
PersonLevelRequestHandler visRequestHandler =
new PersonLevelRequestHandler(vreq, request, response, log);
String rdfResultFormatParam = "RDF/XML-ABBREV";
@ -240,14 +210,11 @@ public class VisualizationController extends BaseEditController {
log.error("ERROR! data model empoty");
}
} else if (PDF_REPORT_VIS_URL_VALUE
.equalsIgnoreCase(vreq.getParameter(VIS_TYPE_URL_HANDLE))) {
} else if (UTILITIES_URL_VALUE
.equalsIgnoreCase(vreq.getParameter(VIS_TYPE_URL_HANDLE))) {
.equalsIgnoreCase(visTypeURLHandle)) {
edu.cornell.mannlib.vitro.webapp.visualization.utilities.VisualizationRequestHandler visRequestHandler =
new edu.cornell.mannlib.vitro.webapp.visualization.utilities.VisualizationRequestHandler(vreq, request, response, log);
UtilitiesRequestHandler visRequestHandler =
new UtilitiesRequestHandler(vreq, request, response, log);
String rdfResultFormatParam = "RDF/XML-ABBREV";
@ -279,7 +246,9 @@ public class VisualizationController extends BaseEditController {
* added to the request object. From where it is redirected to
* the error page.
* */
handleMalformedParameters("Inappropriate query parameters were submitted. ", request, response);
handleMalformedParameters("Inappropriate query parameters were submitted. ",
request,
response);
}
return;
@ -301,9 +270,10 @@ public class VisualizationController extends BaseEditController {
LoginFormBean loginHandler = null;
if( obj != null && obj instanceof LoginFormBean )
loginHandler = ((LoginFormBean)obj);
if (obj != null && obj instanceof LoginFormBean) {
loginHandler = ((LoginFormBean) obj);
}
/*
* what is the speciality of 5 in the conditions?
*
@ -327,33 +297,34 @@ public class VisualizationController extends BaseEditController {
String rdfResultFormatParam) {
Model model = vreq.getJenaOntModel(); // getModel()
if( model == null ){
doNoModelInContext(request,response);
if (model == null) {
doNoModelInContext(request, response);
return null;
}
log.debug("rdfResultFormat was: " + rdfResultFormatParam);
DataSource dataSource = DatasetFactory.create() ;
DataSource dataSource = DatasetFactory.create();
ModelMaker maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
dataSource.setDefaultModel(model) ;
dataSource.setDefaultModel(model);
return dataSource;
}
private void doNoModelInContext(HttpServletRequest request, HttpServletResponse res){
private void doNoModelInContext(HttpServletRequest request, HttpServletResponse res) {
try {
res.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
ServletOutputStream sos = res.getOutputStream();
sos.println("<html><body>this service is not supporeted by the current " +
"webapp configuration. A jena model is required in the servlet context.</body></html>" );
sos.println("<html><body>this service is not supporeted by the current "
+ "webapp configuration. A jena model is required in the "
+ "servlet context.</body></html>");
} catch (IOException e) {
log.error("Could not write to ServletOutputStream");
}
}
private void handleMalformedParameters(String errorMessage, HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

View file

@ -17,6 +17,12 @@ public class VisualizationFrameworkConstants {
public static final String DATA_RENDER_MODE_URL_VALUE = "data";
public static final String PDF_RENDER_MODE_URL_VALUE = "pdf";
public static final String IMAGE_VIS_MODE_URL_VALUE = "image";
public static final String SPARKLINE_VIS_MODE_URL_VALUE = "sparkline";
public static final String COAUTHORSLIST_VIS_MODE_URL_VALUE = "coauthors";
public static final String PROFILE_INFO_UTILS_VIS_MODE = "PROFILE_INFO";
public static final String PROFILE_UTILS_VIS_MODE = "PROFILE_URL";
public static final String COAUTHOR_UTILS_VIS_MODE = "COAUTHORSHIP_URL";
public static final String PERSON_LEVEL_UTILS_VIS_MODE = "PERSON_LEVEL_URL";
public static final String IMAGE_UTILS_VIS_MODE = "IMAGE_URL";
}

View file

@ -12,6 +12,7 @@ import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationController;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.CoAuthorshipVOContainer;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Edge;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Node;
@ -27,7 +28,7 @@ public class CoAuthorshipGraphMLWriter {
private final String GRAPHML_FOOTER = "</graphml>";
public CoAuthorshipGraphMLWriter(VisVOContainer visVOContainer) {
public CoAuthorshipGraphMLWriter(CoAuthorshipVOContainer visVOContainer) {
coAuthorshipGraphMLContent = createCoAuthorshipGraphMLContent(visVOContainer);
@ -38,7 +39,7 @@ public class CoAuthorshipGraphMLWriter {
}
private StringBuilder createCoAuthorshipGraphMLContent(
VisVOContainer visVOContainer) {
CoAuthorshipVOContainer visVOContainer) {
StringBuilder graphMLContent = new StringBuilder();
@ -62,7 +63,7 @@ public class CoAuthorshipGraphMLWriter {
return graphMLContent;
}
private void generateGraphContent(VisVOContainer visVOContainer,
private void generateGraphContent(CoAuthorshipVOContainer visVOContainer,
StringBuilder graphMLContent) {
graphMLContent.append("\n<graph edgedefault=\"undirected\">\n");
@ -82,7 +83,7 @@ public class CoAuthorshipGraphMLWriter {
}
private void generateEdgeSectionContent(VisVOContainer visVOContainer,
private void generateEdgeSectionContent(CoAuthorshipVOContainer visVOContainer,
StringBuilder graphMLContent) {
graphMLContent.append("<!-- edges -->\n");
@ -118,8 +119,13 @@ public class CoAuthorshipGraphMLWriter {
+ "target=\"" + currentEdge.getTargetNode().getNodeID() + "\" "
+ ">\n");
graphMLContent.append("\t<data key=\"collaborator1\">" + currentEdge.getSourceNode().getNodeName() + "</data>\n");
graphMLContent.append("\t<data key=\"collaborator2\">" + currentEdge.getTargetNode().getNodeName() + "</data>\n");
graphMLContent.append("\t<data key=\"collaborator1\">"
+ currentEdge.getSourceNode().getNodeName()
+ "</data>\n");
graphMLContent.append("\t<data key=\"collaborator2\">"
+ currentEdge.getTargetNode().getNodeName()
+ "</data>\n");
graphMLContent.append("\t<data key=\"number_of_coauthored_works\">"
+ currentEdge.getNumOfCoAuthoredWorks()
@ -132,8 +138,8 @@ public class CoAuthorshipGraphMLWriter {
* we are sure to have only one entry on the map. So using the for loop.
* I am feeling dirty just about now.
* */
for (Map.Entry<String, Integer> publicationInfo :
currentEdge.getEarliestCollaborationYearCount().entrySet()) {
for (Map.Entry<String, Integer> publicationInfo
: currentEdge.getEarliestCollaborationYearCount().entrySet()) {
graphMLContent.append("\t<data key=\"earliest_collaboration\">"
+ publicationInfo.getKey()
@ -150,8 +156,8 @@ public class CoAuthorshipGraphMLWriter {
if (currentEdge.getLatestCollaborationYearCount() != null) {
for (Map.Entry<String, Integer> publicationInfo :
currentEdge.getLatestCollaborationYearCount().entrySet()) {
for (Map.Entry<String, Integer> publicationInfo
: currentEdge.getLatestCollaborationYearCount().entrySet()) {
graphMLContent.append("\t<data key=\"latest_collaboration\">"
+ publicationInfo.getKey()
@ -177,7 +183,7 @@ public class CoAuthorshipGraphMLWriter {
}
private void generateNodeSectionContent(VisVOContainer visVOContainer,
private void generateNodeSectionContent(CoAuthorshipVOContainer visVOContainer,
StringBuilder graphMLContent) {
graphMLContent.append("<!-- nodes -->\n");
@ -251,8 +257,8 @@ public class CoAuthorshipGraphMLWriter {
* we are sure to have only one entry on the map. So using the for loop.
* I am feeling dirty just about now.
* */
for (Map.Entry<String, Integer> publicationInfo :
node.getEarliestPublicationYearCount().entrySet()) {
for (Map.Entry<String, Integer> publicationInfo
: node.getEarliestPublicationYearCount().entrySet()) {
graphMLContent.append("\t<data key=\"earliest_publication\">"
+ publicationInfo.getKey()
@ -269,8 +275,8 @@ public class CoAuthorshipGraphMLWriter {
if (node.getLatestPublicationYearCount() != null) {
for (Map.Entry<String, Integer> publicationInfo :
node.getLatestPublicationYearCount().entrySet()) {
for (Map.Entry<String, Integer> publicationInfo
: node.getLatestPublicationYearCount().entrySet()) {
graphMLContent.append("\t<data key=\"latest_publication\">"
+ publicationInfo.getKey()
@ -296,7 +302,7 @@ public class CoAuthorshipGraphMLWriter {
graphMLContent.append("</node>\n");
}
private void generateKeyDefinitionContent(VisVOContainer visVOContainer,
private void generateKeyDefinitionContent(CoAuthorshipVOContainer visVOContainer,
StringBuilder graphMLContent) {
/*
@ -319,7 +325,8 @@ public class CoAuthorshipGraphMLWriter {
graphMLContent.append("\n<key ");
for (Map.Entry<String, String> currentAttributeKey : currentNodeSchemaAttribute.entrySet()) {
for (Map.Entry<String, String> currentAttributeKey
: currentNodeSchemaAttribute.entrySet()) {
graphMLContent.append(currentAttributeKey.getKey()
+ "=\"" + currentAttributeKey.getValue()

View file

@ -9,8 +9,8 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import com.hp.hpl.jena.iri.IRI;
@ -30,9 +30,11 @@ import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.BiboDocument;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.CoAuthorshipVOContainer;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Edge;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Node;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.VivoCollegeOrSchool;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UniqueIDGenerator;
@ -40,12 +42,14 @@ import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UniqueIDGenerator
/**
* @author cdtank
*/
public class QueryHandler {
public class CoAuthorshipQueryHandler implements QueryHandler<CoAuthorshipVOContainer> {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
private String egoURLParam, resultFormatParam, rdfResultFormatParam;
private Map<String, VivoCollegeOrSchool> collegeURLToVO = new HashMap<String, VivoCollegeOrSchool>();
private String egoURLParam;
private Map<String, VivoCollegeOrSchool> collegeURLToVO =
new HashMap<String, VivoCollegeOrSchool>();
private DataSource dataSource;
private Log log;
@ -54,13 +58,10 @@ public class QueryHandler {
private UniqueIDGenerator edgeIDGenerator;
public QueryHandler(String egoURLParam,
String resultFormatParam, String rdfResultFormatParam,
public CoAuthorshipQueryHandler(String egoURLParam,
DataSource dataSource, Log log) {
this.egoURLParam = egoURLParam;
this.resultFormatParam = resultFormatParam;
this.rdfResultFormatParam = rdfResultFormatParam;
this.dataSource = dataSource;
this.log = log;
@ -69,7 +70,7 @@ public class QueryHandler {
}
private VisVOContainer createJavaValueObjects(ResultSet resultSet) {
private CoAuthorshipVOContainer createJavaValueObjects(ResultSet resultSet) {
Set<Node> nodes = new HashSet<Node>();
@ -85,7 +86,6 @@ public class QueryHandler {
while (resultSet.hasNext()) {
QuerySolution solution = resultSet.nextSolution();
/*
* We only want to create only ONE ego node.
* */
@ -158,10 +158,12 @@ public class QueryHandler {
Set<Node> coAuthorsForCurrentBiboDocument;
if (biboDocumentURLToCoAuthors.containsKey(biboDocument.getDocumentURL())) {
coAuthorsForCurrentBiboDocument = biboDocumentURLToCoAuthors.get(biboDocument.getDocumentURL());
coAuthorsForCurrentBiboDocument = biboDocumentURLToCoAuthors
.get(biboDocument.getDocumentURL());
} else {
coAuthorsForCurrentBiboDocument = new HashSet<Node>();
biboDocumentURLToCoAuthors.put(biboDocument.getDocumentURL(), coAuthorsForCurrentBiboDocument);
biboDocumentURLToCoAuthors.put(biboDocument.getDocumentURL(),
coAuthorsForCurrentBiboDocument);
}
coAuthorsForCurrentBiboDocument.add(coAuthorNode);
@ -169,9 +171,9 @@ public class QueryHandler {
Edge egoCoAuthorEdge = getExistingEdge(egoNode, coAuthorNode, edgeUniqueIdentifierToVO);
/*
* If "egoCoAuthorEdge" is null it means that no edge exists in between the egoNode & current
* coAuthorNode. Else create a new edge, add it to the edges set & add the collaborator document
* to it.
* If "egoCoAuthorEdge" is null it means that no edge exists in between the egoNode
* & current coAuthorNode. Else create a new edge, add it to the edges set & add
* the collaborator document to it.
* */
if (egoCoAuthorEdge != null) {
egoCoAuthorEdge.addCollaboratorDocument(biboDocument);
@ -196,9 +198,10 @@ public class QueryHandler {
* A - B
*
* We are side-effecting "edges" here. The only reason to do this is because we are adding
* edges en masse for all the co-authors on all the publications considered so far. The other
* reason being we dont want to compare against 2 sets of edges (edges created before & co-
* author edges created during the course of this method) when we are creating a new edge.
* edges en masse for all the co-authors on all the publications considered so far. The
* other reason being we dont want to compare against 2 sets of edges (edges created before
* & co-author edges created during the course of this method) when we are creating a new
* edge.
* */
createCoAuthorEdges(biboDocumentURLToVO,
biboDocumentURLToCoAuthors,
@ -206,7 +209,7 @@ public class QueryHandler {
edgeUniqueIdentifierToVO);
return new VisVOContainer(egoNode, nodes, edges);
return new CoAuthorshipVOContainer(egoNode, nodes, edges);
}
private void createCoAuthorEdges(
@ -214,10 +217,11 @@ public class QueryHandler {
Map<String, Set<Node>> biboDocumentURLToCoAuthors, Set<Edge> edges,
Map<String, Edge> edgeUniqueIdentifierToVO) {
for (Map.Entry<String, Set<Node>> currentBiboDocumentEntry : biboDocumentURLToCoAuthors.entrySet()) {
for (Map.Entry<String, Set<Node>> currentBiboDocumentEntry
: biboDocumentURLToCoAuthors.entrySet()) {
/*
* If there was only one co-author (other than ego) then we dont have to create any edges. so
* the below condition will take care of that.
* If there was only one co-author (other than ego) then we dont have to create any
* edges. so the below condition will take care of that.
* */
if (currentBiboDocumentEntry.getValue().size() > 1) {
@ -225,8 +229,8 @@ public class QueryHandler {
Set<Edge> newlyAddedEdges = new HashSet<Edge>();
/*
* In order to leverage the nested "for loop" for making edges between all the co-authors
* we need to create a list out of the set first.
* In order to leverage the nested "for loop" for making edges between all the
* co-authors we need to create a list out of the set first.
* */
List<Node> coAuthorNodes = new ArrayList<Node>(currentBiboDocumentEntry.getValue());
Collections.sort(coAuthorNodes, new NodeComparator());
@ -239,15 +243,21 @@ public class QueryHandler {
Node coAuthor1 = coAuthorNodes.get(ii);
Node coAuthor2 = coAuthorNodes.get(jj);
Edge coAuthor1_2Edge = getExistingEdge(coAuthor1, coAuthor2, edgeUniqueIdentifierToVO);
Edge coAuthor1_2Edge = getExistingEdge(coAuthor1,
coAuthor2,
edgeUniqueIdentifierToVO);
BiboDocument currentBiboDocument = biboDocumentURLToVO
.get(currentBiboDocumentEntry.getKey());
.get(currentBiboDocumentEntry
.getKey());
if (coAuthor1_2Edge != null) {
coAuthor1_2Edge.addCollaboratorDocument(currentBiboDocument);
} else {
coAuthor1_2Edge = new Edge(coAuthor1, coAuthor2, currentBiboDocument, edgeIDGenerator);
coAuthor1_2Edge = new Edge(coAuthor1,
coAuthor2,
currentBiboDocument,
edgeIDGenerator);
newlyAddedEdges.add(coAuthor1_2Edge);
edgeUniqueIdentifierToVO.put(
getEdgeUniqueIdentifier(coAuthor1.getNodeID(),
@ -314,7 +324,8 @@ public class QueryHandler {
biboDocument.setPublicationYear(publicationYearNode.toString());
}
RDFNode publicationYearMonthNode = solution.get(QueryFieldLabels.DOCUMENT_PUBLICATION_YEAR_MONTH);
RDFNode publicationYearMonthNode = solution.get(QueryFieldLabels
.DOCUMENT_PUBLICATION_YEAR_MONTH);
if (publicationYearMonthNode != null) {
biboDocument.setPublicationYearMonth(publicationYearMonthNode.toString());
}
@ -328,29 +339,24 @@ public class QueryHandler {
}
private ResultSet executeQuery(String queryText,
String resultFormatParam,
String rdfResultFormatParam,
DataSource dataSource) {
QueryExecution queryExecution = null;
try{
try {
Query query = QueryFactory.create(queryText, SYNTAX);
// QuerySolutionMap qs = new QuerySolutionMap();
// qs.add("authPerson", queryParam); // bind resource to s
queryExecution = QueryExecutionFactory.create(query, dataSource);
//remocve this if loop after knowing what is describe & construct sparql stuff.
if (query.isSelectType()){
if (query.isSelectType()) {
return queryExecution.execSelect();
}
} finally {
if(queryExecution != null) {
if (queryExecution != null) {
queryExecution.close();
}
}
return null;
}
@ -359,34 +365,39 @@ public class QueryHandler {
// Resource uri1 = ResourceFactory.createResource(queryURI);
String sparqlQuery = QueryConstants.getSparqlPrefixQuery()
+ "SELECT "
+ " (str(<" + queryURI + ">) as ?" + QueryFieldLabels.AUTHOR_URL + ") "
+ " (str(?authorLabel) as ?" + QueryFieldLabels.AUTHOR_LABEL + ") "
+ " (str(?coAuthorPerson) as ?" + QueryFieldLabels.CO_AUTHOR_URL + ") "
+ " (str(?coAuthorPersonLabel) as ?" + QueryFieldLabels.CO_AUTHOR_LABEL + ") "
+ " (str(?document) as ?" + QueryFieldLabels.DOCUMENT_URL + ") "
+ " (str(?documentLabel) as ?" + QueryFieldLabels.DOCUMENT_LABEL + ") "
+ " (str(?documentMoniker) as ?" + QueryFieldLabels.DOCUMENT_MONIKER + ") "
+ " (str(?documentBlurb) as ?" + QueryFieldLabels.DOCUMENT_BLURB + ") "
+ " (str(?publicationYear) as ?" + QueryFieldLabels.DOCUMENT_PUBLICATION_YEAR + ") "
+ " (str(?publicationYearMonth) as ?" + QueryFieldLabels.DOCUMENT_PUBLICATION_YEAR_MONTH + ") "
+ " (str(?publicationDate) as ?" + QueryFieldLabels.DOCUMENT_PUBLICATION_DATE + ") "
+ "WHERE { "
+ "<" + queryURI + "> rdf:type foaf:Person ; rdfs:label ?authorLabel ; core:authorInAuthorship ?authorshipNode . "
+ "?authorshipNode rdf:type core:Authorship ; core:linkedInformationResource ?document . "
+ "?document rdf:type bibo:Document . "
+ "?document rdfs:label ?documentLabel . "
+ "?document core:informationResourceInAuthorship ?coAuthorshipNode . "
+ "?coAuthorshipNode core:linkedAuthor ?coAuthorPerson . "
+ "?coAuthorPerson rdfs:label ?coAuthorPersonLabel . "
+ "OPTIONAL { ?document core:year ?publicationYear } . "
+ "OPTIONAL { ?document core:yearMonth ?publicationYearMonth } . "
+ "OPTIONAL { ?document core:date ?publicationDate } . "
+ "OPTIONAL { ?document vitro:moniker ?documentMoniker } . "
+ "OPTIONAL { ?document vitro:blurb ?documentBlurb } . "
+ "OPTIONAL { ?document vitro:description ?documentDescription } "
+ "} "
+ "ORDER BY ?document ?coAuthorPerson";
+ "SELECT "
+ " (str(<" + queryURI + ">) as ?" + QueryFieldLabels.AUTHOR_URL + ") "
+ " (str(?authorLabel) as ?" + QueryFieldLabels.AUTHOR_LABEL + ") "
+ " (str(?coAuthorPerson) as ?" + QueryFieldLabels.CO_AUTHOR_URL + ") "
+ " (str(?coAuthorPersonLabel) as ?" + QueryFieldLabels.CO_AUTHOR_LABEL + ") "
+ " (str(?document) as ?" + QueryFieldLabels.DOCUMENT_URL + ") "
+ " (str(?documentLabel) as ?" + QueryFieldLabels.DOCUMENT_LABEL + ") "
+ " (str(?documentMoniker) as ?" + QueryFieldLabels.DOCUMENT_MONIKER + ") "
+ " (str(?documentBlurb) as ?" + QueryFieldLabels.DOCUMENT_BLURB + ") "
+ " (str(?publicationYear) as ?" + QueryFieldLabels.DOCUMENT_PUBLICATION_YEAR + ") "
+ " (str(?publicationYearMonth) as ?"
+ QueryFieldLabels.DOCUMENT_PUBLICATION_YEAR_MONTH + ") "
+ " (str(?publicationDate) as ?"
+ QueryFieldLabels.DOCUMENT_PUBLICATION_DATE + ") "
+ "WHERE { "
+ "<" + queryURI + "> rdf:type foaf:Person ;"
+ " rdfs:label ?authorLabel ;"
+ " core:authorInAuthorship ?authorshipNode . "
+ "?authorshipNode rdf:type core:Authorship ;"
+ " core:linkedInformationResource ?document . "
+ "?document rdf:type bibo:Document . "
+ "?document rdfs:label ?documentLabel . "
+ "?document core:informationResourceInAuthorship ?coAuthorshipNode . "
+ "?coAuthorshipNode core:linkedAuthor ?coAuthorPerson . "
+ "?coAuthorPerson rdfs:label ?coAuthorPersonLabel . "
+ "OPTIONAL { ?document core:year ?publicationYear } . "
+ "OPTIONAL { ?document core:yearMonth ?publicationYearMonth } . "
+ "OPTIONAL { ?document core:date ?publicationDate } . "
+ "OPTIONAL { ?document vitro:moniker ?documentMoniker } . "
+ "OPTIONAL { ?document vitro:blurb ?documentBlurb } . "
+ "OPTIONAL { ?document vitro:description ?documentDescription } "
+ "} "
+ "ORDER BY ?document ?coAuthorPerson";
System.out.println("COAUTHORSHIP QUERY - " + sparqlQuery);
@ -394,84 +405,36 @@ public class QueryHandler {
}
public VisVOContainer getVisualizationJavaValueObjects()
public CoAuthorshipVOContainer getVisualizationJavaValueObjects()
throws MalformedQueryParametersException {
/*
System.out.println("***************************************************************************************");
System.out.println("Entered into coauthorship query handler at " + System.currentTimeMillis());
System.out.println("***************************************************************************************");
*/
if (this.egoURLParam == null || "".equals(egoURLParam)) {
throw new MalformedQueryParametersException("URI parameter is either null or empty.");
} else {
/*
if (StringUtils.isNotBlank(this.egoURLParam)) {
/*
* To test for the validity of the URI submitted.
* */
IRIFactory iRIFactory = IRIFactory.jenaImplementation();
IRI iri = iRIFactory.create(this.egoURLParam);
if (iri.hasViolation(false)) {
String errorMsg = ((Violation)iri.violations(false).next()).getShortMessage()+" ";
String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage();
log.error("Ego Co-Authorship Vis Query " + errorMsg);
throw new MalformedQueryParametersException("URI provided for an individual is malformed.");
throw new MalformedQueryParametersException(
"URI provided for an individual is malformed.");
}
} else {
throw new MalformedQueryParametersException("URI parameter is either null or empty.");
}
ResultSet resultSet = executeQuery(generateEgoCoAuthorshipSparqlQuery(this.egoURLParam),
this.resultFormatParam,
this.rdfResultFormatParam,
this.dataSource);
/*
System.out.println("***************************************************************************************");
System.out.println("***************************************************************************************");
*/return createJavaValueObjects(resultSet);
*/
return createJavaValueObjects(resultSet);
}
public Map<String, Integer> getYearToPublicationCount(
Set<BiboDocument> authorDocuments) {
/*
* Create a map from the year to number of publications. Use the BiboDocument's
* parsedPublicationYear to populate the data.
*
* I am pushing the logic to check for validity of year in "getPublicationYear" itself
* because,
* 1. We will be using getPub... multiple times & this will save us duplication of code
* 2. If we change the logic of validity of a pub year we would not have to make changes
* all throughout the codebase.
* 3. We are asking for a publication year & we should get a proper one or NOT at all.
* */
Map<String, Integer> yearToPublicationCount = new TreeMap<String, Integer>();
for (BiboDocument curr : authorDocuments) {
/*
* Increment the count because there is an entry already available for
* that particular year.
* */
String publicationYear;
if (curr.getPublicationYear() != null) {
publicationYear = curr.getPublicationYear();
} else {
publicationYear = curr.getParsedPublicationYear();
}
if (yearToPublicationCount.containsKey(publicationYear)) {
yearToPublicationCount.put(publicationYear,
yearToPublicationCount
.get(publicationYear) + 1);
} else {
yearToPublicationCount.put(publicationYear, 1);
}
}
return yearToPublicationCount;
}
}

View file

@ -25,52 +25,47 @@ import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.CoAuthorshipVOContainer;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Node;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
public class VisualizationRequestHandler {
public class CoAuthorshipRequestHandler extends VisualizationRequestHandler {
private VitroRequest vitroRequest;
private HttpServletRequest request;
private HttpServletResponse response;
private Log log;
public VisualizationRequestHandler(VitroRequest vitroRequest,
public CoAuthorshipRequestHandler(VitroRequest vitroRequest,
HttpServletRequest request, HttpServletResponse response, Log log) {
this.vitroRequest = vitroRequest;
this.request = request;
this.response = response;
this.log = log;
super(vitroRequest, request, response, log);
}
public void generateVisualization(DataSource dataSource) {
String resultFormatParam = "RS_TEXT";
String rdfResultFormatParam = "RDF/XML-ABBREV";
VitroRequest vitroRequest = super.getVitroRequest();
String egoURIParam = vitroRequest.getParameter(
VisualizationFrameworkConstants
.INDIVIDUAL_URI_URL_HANDLE);
String egoURIParam = vitroRequest.getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_URL_HANDLE);
String renderMode = vitroRequest.getParameter(
VisualizationFrameworkConstants
.RENDER_MODE_URL_HANDLE);
String visMode = vitroRequest.getParameter(
VisualizationFrameworkConstants
.VIS_MODE_URL_HANDLE);
String renderMode = vitroRequest.getParameter(VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE);
String visMode = vitroRequest.getParameter(VisualizationFrameworkConstants.VIS_MODE_URL_HANDLE);
String visContainer = vitroRequest.getParameter(VisualizationFrameworkConstants.VIS_CONTAINER_URL_HANDLE);
String sparklineVisMode = "sparkline";
QueryHandler queryManager =
new QueryHandler(egoURIParam,
resultFormatParam,
rdfResultFormatParam,
Log log = super.getLog();
QueryHandler<CoAuthorshipVOContainer> queryManager =
new CoAuthorshipQueryHandler(egoURIParam,
dataSource,
log);
try {
VisVOContainer authorNodesAndEdges = queryManager.getVisualizationJavaValueObjects();
CoAuthorshipVOContainer authorNodesAndEdges =
queryManager.getVisualizationJavaValueObjects();
/*
* In order to avoid unneeded computations we have pushed this "if" condition up.
@ -79,15 +74,17 @@ public class VisualizationRequestHandler {
* It is ugly!
* */
if (VisualizationFrameworkConstants.DATA_RENDER_MODE_URL_VALUE.equalsIgnoreCase(renderMode)) {
if (VisualizationFrameworkConstants.DATA_RENDER_MODE_URL_VALUE
.equalsIgnoreCase(renderMode)) {
/*
* We will be using the same visualization package for both sparkline & coauthorship flash
* vis. We will use "VIS_MODE_URL_HANDLE" as a modifier to differentiate between these two.
* The defualt will be to render the coauthorship network vis.
* We will be using the same visualization package for both sparkline & coauthorship
* flash vis. We will use "VIS_MODE_URL_HANDLE" as a modifier to differentiate
* between these two. The defualt will be to render the coauthorship network vis.
* */
if (sparklineVisMode.equalsIgnoreCase(visMode)) {
if (VisualizationFrameworkConstants.SPARKLINE_VIS_MODE_URL_VALUE
.equalsIgnoreCase(visMode)) {
/*
* When the csv file is required - based on which sparkline visualization will
* be rendered.
@ -97,62 +94,14 @@ public class VisualizationRequestHandler {
} else {
/*
* When the graphML file is required - based on which coauthorship network visualization
* will be rendered.
* When the graphML file is required - based on which coauthorship network
* visualization will be rendered.
* */
prepareVisualizationQueryNetworkDataResponse(authorNodesAndEdges);
return;
}
}
/*
* Computations required to generate HTML for the sparklines & related context.
* */
/*
* This is required because when deciding the range of years over which the vis
* was rendered we dont want to be influenced by the "DEFAULT_PUBLICATION_YEAR".
* */
// publishedYearsForCollege.remove(VOConstants.DEFAULT_PUBLICATION_YEAR);
/*
VisualizationCodeGenerator visualizationCodeGenerator =
new VisualizationCodeGenerator(yearToPublicationCount, log);
String visContentCode = visualizationCodeGenerator
.getMainVisualizationCode(authorDocuments,
publishedYears,
visMode,
visContainer);
String visContextCode = visualizationCodeGenerator
.getVisualizationContextCode(vitroRequest.getRequestURI(),
collegeURIParam,
visMode);
*/
/*
* This is side-effecting because the response of this method is just to redirect to
* a page with visualization on it.
* */
RequestDispatcher requestDispatcher = null;
prepareVisualizationQueryStandaloneResponse(egoURIParam, request, response, vitroRequest);
// requestDispatcher = request.getRequestDispatcher(Controllers.BASIC_JSP);
requestDispatcher = request.getRequestDispatcher("/templates/page/blankPage.jsp");
try {
requestDispatcher.forward(request, response);
} catch (Exception e) {
log.error("EntityEditController could not forward to view.");
log.error(e.getMessage());
log.error(e.getStackTrace());
}
} catch (MalformedQueryParametersException e) {
try {
handleMalformedParameters(e.getMessage());
@ -166,22 +115,23 @@ public class VisualizationRequestHandler {
}
private void prepareVisualizationQueryNetworkDataResponse(VisVOContainer authorNodesAndEdges) {
private void prepareVisualizationQueryNetworkDataResponse(
CoAuthorshipVOContainer authorNodesAndEdges) {
response.setContentType("text/xml");
super.getResponse().setContentType("text/xml");
try {
PrintWriter responseWriter = response.getWriter();
PrintWriter responseWriter = super.getResponse().getWriter();
/*
* We are side-effecting responseWriter since we are directly manipulating the response
* object of the servlet.
* */
CoAuthorshipGraphMLWriter coAuthorshipGraphMLWriter =
new CoAuthorshipGraphMLWriter(authorNodesAndEdges);
CoAuthorshipGraphMLWriter coAuthorShipGraphMLWriter = new CoAuthorshipGraphMLWriter(authorNodesAndEdges);
responseWriter.append(coAuthorShipGraphMLWriter.getCoAuthorshipGraphMLContent());
responseWriter.append(coAuthorshipGraphMLWriter.getCoAuthorshipGraphMLContent());
responseWriter.close();
@ -190,28 +140,29 @@ public class VisualizationRequestHandler {
}
}
private void prepareVisualizationQuerySparklineDataResponse(VisVOContainer authorNodesAndEdges) {
private void prepareVisualizationQuerySparklineDataResponse(
CoAuthorshipVOContainer authorNodesAndEdges) {
String outputFileName = "";
String outputFileName;
Map<String, Set<Node>> yearToCoauthors = new TreeMap<String, Set<Node>>();
if (authorNodesAndEdges.getNodes() == null || authorNodesAndEdges.getNodes().size() < 1 ) {
if (authorNodesAndEdges.getNodes() != null && authorNodesAndEdges.getNodes().size() > 0) {
outputFileName = "no_coauthors-per-year" + ".csv";
} else {
outputFileName = UtilityFunctions.slugify(authorNodesAndEdges.getEgoNode().getNodeName())
outputFileName = UtilityFunctions.slugify(authorNodesAndEdges
.getEgoNode().getNodeName())
+ "_coauthors-per-year" + ".csv";
yearToCoauthors = getCoAuthorsStats(authorNodesAndEdges);
} else {
outputFileName = "no_coauthors-per-year" + ".csv";
}
HttpServletResponse response = super.getResponse();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + outputFileName);
response.setHeader("Content-Disposition",
"attachment;filename=" + outputFileName);
try {
@ -231,7 +182,8 @@ public class VisualizationRequestHandler {
}
}
private void generateCsvFileBuffer(Map<String, Set<Node>> yearToCoauthors, PrintWriter printWriter) {
private void generateCsvFileBuffer(Map<String, Set<Node>> yearToCoauthors,
PrintWriter printWriter) {
printWriter.append("\"Year\", \"Number of Co-Authors\", \"Co-Author(s)\"\n");
@ -241,12 +193,9 @@ public class VisualizationRequestHandler {
+ "\"" + currentEntry.getValue().size() + "\","
+ "\"" + getCoauthorsString(currentEntry.getValue()) + "\"\n"
);
}
printWriter.flush();
}
private String getCoauthorsString(Set<Node> coAuthors) {
@ -261,7 +210,7 @@ public class VisualizationRequestHandler {
return StringUtils.removeEnd(coAuthorsMerged.toString(), coAuthorSeparator);
}
private Map<String, Set<Node>> getCoAuthorsStats(VisVOContainer authorNodesAndEdges) {
private Map<String, Set<Node>> getCoAuthorsStats(CoAuthorshipVOContainer authorNodesAndEdges) {
Map<String, Set<Node>> yearToCoAuthors = new TreeMap<String, Set<Node>>();
@ -295,39 +244,29 @@ public class VisualizationRequestHandler {
}
}
return yearToCoAuthors;
}
private void prepareVisualizationQueryStandaloneResponse(String egoURIParam,
HttpServletRequest request,
HttpServletResponse response,
VitroRequest vreq) {
Portal portal = vreq.getPortal();
request.setAttribute("egoURIParam", egoURIParam);
request.setAttribute("bodyJsp", "/templates/visualization/co_authorship.jsp");
request.setAttribute("portalBean", portal);
}
private void handleMalformedParameters(String errorMessage)
throws ServletException, IOException {
Portal portal = vitroRequest.getPortal();
Portal portal = super.getVitroRequest().getPortal();
HttpServletRequest request = super.getRequest();
request.setAttribute("error", errorMessage);
RequestDispatcher requestDispatcher = request.getRequestDispatcher(Controllers.BASIC_JSP);
request.setAttribute("bodyJsp", "/templates/visualization/visualization_error.jsp");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher(Controllers.BASIC_JSP);
request.setAttribute("bodyJsp",
"/templates/visualization/visualization_error.jsp");
request.setAttribute("portalBean", portal);
request.setAttribute("title", "Visualization Query Error - Individual Publication Count");
request.setAttribute("title",
"Visualization Query Error - Individual Publication Count");
try {
requestDispatcher.forward(request, response);
requestDispatcher.forward(request, super.getResponse());
} catch (Exception e) {
Log log = super.getLog();
log.error("EntityEditController could not forward to view.");
log.error(e.getMessage());
log.error(e.getStackTrace());

View file

@ -22,18 +22,20 @@ import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Node;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.SparklineVOContainer;
public class VisualizationCodeGenerator {
public class CoAuthorshipVisCodeGenerator {
private final static Map<String, String> visDivNames = new HashMap<String, String>() {{
private static final int MINIMUM_YEARS_CONSIDERED = 10;
private static final Map<String, String> VIS_DIV_NAMES = new HashMap<String, String>() { {
put("SHORT_SPARK", "unique_coauthors_short_sparkline_vis");
put("FULL_SPARK", "unique_coauthors_full_sparkline_vis");
}};
} };
private static final String visualizationStyleClass = "sparkline_style";
private static final String VISUALIZATION_STYLE_CLASS = "sparkline_style";
private static final String defaultVisContainerDivID = "unique_coauthors_vis_container";
private static final String DEFAULT_VISCONTAINER_DIV_ID = "unique_coauthors_vis_container";
public static final String SHORT_SPARKLINE_MODE_URL_HANDLE = "short";
@ -49,7 +51,7 @@ public class VisualizationCodeGenerator {
private String individualURIParam;
public VisualizationCodeGenerator(String contextPath,
public CoAuthorshipVisCodeGenerator(String contextPath,
String individualURIParam,
String visMode,
String visContainer,
@ -65,11 +67,7 @@ public class VisualizationCodeGenerator {
this.log = log;
generateVisualizationCode(visMode,
visContainer);
generateVisualizationCode(visMode, visContainer);
}
private void generateVisualizationCode(String visMode,
@ -88,7 +86,7 @@ public class VisualizationCodeGenerator {
int numOfYearsToBeRendered = 0;
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int shortSparkMinYear = currentYear - 10 + 1;
int shortSparkMinYear = currentYear - MINIMUM_YEARS_CONSIDERED + 1;
/*
* This is required because when deciding the range of years over which the vis
@ -108,14 +106,15 @@ public class VisualizationCodeGenerator {
StringBuilder visualizationCode = new StringBuilder();
// System.out.println(yearToPublicationCount);
if (yearToUniqueCoauthors.size() > 0) {
try {
minPublishedYear = Integer.parseInt(Collections.min(publishedYears));
} catch (NoSuchElementException e1) {
log.debug("vis: " + e1.getMessage() + " error occurred for " + yearToUniqueCoauthors.toString());
log.debug("vis: " + e1.getMessage() + " error occurred for "
+ yearToUniqueCoauthors.toString());
} catch (NumberFormatException e2) {
log.debug("vis: " + e2.getMessage() + " error occurred for " + yearToUniqueCoauthors.toString());
log.debug("vis: " + e2.getMessage() + " error occurred for "
+ yearToUniqueCoauthors.toString());
}
}
@ -135,62 +134,38 @@ public class VisualizationCodeGenerator {
numOfYearsToBeRendered = currentYear - minPubYearConsidered + 1;
visualizationCode.append("<style type='text/css'>" +
"." + visualizationStyleClass + " table{" +
" margin: 0;" +
" padding: 0;" +
" width: auto;" +
" border-collapse: collapse;" +
" border-spacing: 0;" +
" vertical-align: inherit;" +
"}" +
".incomplete-data-holder {" +
"" +
"}" +
/*".sparkline_wrapper_table table{" +
" vertical-align: bottom;" +
"}" +*/
"td.sparkline_number { text-align:right; padding-right:5px; }" +
"td.sparkline_text {text-align:left;}" +
/*"#sparkline_data_table {" +
"width: auto;" +
"}" +
"#sparkline_data_table tfoot {" +
"color: red;" +
"font-size:0.9em;" +
"}" +
".sparkline_text {" +
"margin-left:72px;" +
"position:absolute;" +
"}" +
".sparkline_range {" +
"color:#7BA69E;" +
"font-size:0.9em;" +
"font-style:italic;" +
"}" +*/
"</style>\n");
visualizationCode.append("<style type='text/css'>"
+ "." + VISUALIZATION_STYLE_CLASS + " table{"
+ " margin: 0;"
+ " padding: 0;"
+ " width: auto;"
+ " border-collapse: collapse;"
+ " border-spacing: 0;"
+ " vertical-align: inherit;"
+ "}"
+ ".incomplete-data-holder {"
+ ""
+ "}"
+ "td.sparkline_number { text-align:right; "
+ "padding-right:5px; }"
+ "td.sparkline_text {text-align:left;}"
+ "</style>\n");
// .sparkline {display:inline; margin:0; padding:0; width:600px }
// td.sparkline-img {margin:0; padding:0; }
visualizationCode.append("<script type=\"text/javascript\">\n" +
"function drawUniqueCoauthorCountVisualization(providedSparklineImgTD) {\n" +
"var data = new google.visualization.DataTable();\n" +
"data.addColumn('string', 'Year');\n" +
"data.addColumn('number', 'Unique co-authors');\n" +
"data.addRows(" + numOfYearsToBeRendered + ");\n");
visualizationCode.append("<script type=\"text/javascript\">\n"
+ "function drawUniqueCoauthorCountVisualization(providedSparklineImgTD) {\n"
+ "var data = new google.visualization.DataTable();\n"
+ "data.addColumn('string', 'Year');\n"
+ "data.addColumn('number', 'Unique co-authors');\n"
+ "data.addRows(" + numOfYearsToBeRendered + ");\n");
int uniqueCoAuthorCounter = 0;
int totalUniqueCoAuthors = 0;
int renderedFullSparks = 0;
Set<Node> allCoAuthorsWithKnownAuthorshipYears = new HashSet<Node>();
for (int publicationYear = minPubYearConsidered; publicationYear <= currentYear; publicationYear++) {
for (int publicationYear = minPubYearConsidered;
publicationYear <= currentYear;
publicationYear++) {
String stringPublishedYear = String.valueOf(publicationYear);
Set<Node> currentCoAuthors = yearToUniqueCoauthors.get(stringPublishedYear);
@ -232,21 +207,22 @@ public class VisualizationCodeGenerator {
* */
Integer unknownYearCoauthors = 0;
if (yearToUniqueCoauthors.get(VOConstants.DEFAULT_PUBLICATION_YEAR) != null) {
totalUniqueCoAuthors += yearToUniqueCoauthors.get(VOConstants.DEFAULT_PUBLICATION_YEAR).size();
unknownYearCoauthors = yearToUniqueCoauthors.get(VOConstants.DEFAULT_PUBLICATION_YEAR).size();
totalUniqueCoAuthors += yearToUniqueCoauthors
.get(VOConstants.DEFAULT_PUBLICATION_YEAR).size();
unknownYearCoauthors = yearToUniqueCoauthors
.get(VOConstants.DEFAULT_PUBLICATION_YEAR).size();
}
String sparklineDisplayOptions = "{width: 63, height: 21, showAxisLines: false, " +
"showValueLabels: false, labelPosition: 'none'}";
String sparklineDisplayOptions = "{width: 63, height: 21, showAxisLines: false, "
+ "showValueLabels: false, labelPosition: 'none'}";
if (providedVisContainerID != null) {
visContainerID = providedVisContainerID;
} else {
visContainerID = defaultVisContainerDivID;
visContainerID = DEFAULT_VISCONTAINER_DIV_ID;
}
/*
* By default these represents the range of the rendered sparks. Only in case of
* "short" sparkline mode we will set the Earliest RenderedPublication year to
@ -263,8 +239,8 @@ public class VisualizationCodeGenerator {
/*
* Since building StringBuilder objects (which is being used to store the vis code) is
* essentially a side-effecting process, we have both the activators method as side-effecting.
* They both side-effect "visualizationCode"
* essentially a side-effecting process, we have both the activators method as
* side-effecting. They both side-effect "visualizationCode"
* */
if (SHORT_SPARKLINE_MODE_URL_HANDLE.equalsIgnoreCase(visMode)) {
@ -282,19 +258,11 @@ public class VisualizationCodeGenerator {
visContainerID,
visualizationCode,
unknownYearCoauthors,
totalUniqueCoAuthors,
renderedFullSparks,
renderedFullSparks,
sparklineDisplayOptions);
}
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
log.debug(visualizationCode);
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return visualizationCode.toString();
}
@ -307,37 +275,38 @@ public class VisualizationCodeGenerator {
/*
* Create a view of the data containing only the column pertaining to publication count.
* */
visualizationCode.append("var shortSparklineView = new google.visualization.DataView(data);\n" +
"shortSparklineView.setColumns([1]);\n");
visualizationCode.append("var shortSparklineView = "
+ "new google.visualization.DataView(data);\n"
+ "shortSparklineView.setColumns([1]);\n");
/*
* For the short view we only want the last 10 year's view of publication count,
* hence we filter the data we actually want to use for render.
* */
visualizationCode.append("shortSparklineView.setRows(" +
"data.getFilteredRows([{column: 0, " +
"minValue: '" + shortSparkMinYear + "', " +
"maxValue: '" + currentYear+ "'}])" +
");\n");
visualizationCode.append("shortSparklineView.setRows("
+ "data.getFilteredRows([{column: 0, "
+ "minValue: '" + shortSparkMinYear + "', "
+ "maxValue: '" + currentYear + "'}])"
+ ");\n");
/*
* Create the vis object and draw it in the div pertaining to short-sparkline.
* */
visualizationCode.append("var short_spark = new google.visualization.ImageSparkLine(" +
// "document.getElementById('" + visDivNames.get("SHORT_SPARK") + "')" +
"providedSparklineImgTD[0]" +
");\n" +
"short_spark.draw(shortSparklineView, " + sparklineDisplayOptions + ");\n");
visualizationCode.append("var short_spark = new google.visualization.ImageSparkLine("
+ "providedSparklineImgTD[0]"
+ ");\n"
+ "short_spark.draw(shortSparklineView, "
+ sparklineDisplayOptions + ");\n");
/*
* We want to display how many publication counts were considered, so this is used
* to calculate this.
* */
visualizationCode.append("var shortSparkRows = shortSparklineView.getViewRows();\n" +
"var renderedShortSparks = 0;\n" +
"$.each(shortSparkRows, function(index, value) {" +
"renderedShortSparks += data.getValue(value, 1);" +
"});\n");
visualizationCode.append("var shortSparkRows = shortSparklineView.getViewRows();\n"
+ "var renderedShortSparks = 0;\n"
+ "$.each(shortSparkRows, function(index, value) {"
+ "renderedShortSparks += data.getValue(value, 1);"
+ "});\n");
@ -345,35 +314,44 @@ public class VisualizationCodeGenerator {
* Generate the text introducing the vis.
* */
String imcompleteDataText = "This information is based solely on publications which have been loaded into the VIVO system. " +
"This may only be a small sample of the person\\'s total work.";
String imcompleteDataText = "This information is based solely on publications which "
+ "have been loaded into the VIVO system. "
+ "This may only be a small sample of the person\\'s "
+ "total work.";
visualizationCode.append("$('#" + visDivNames.get("SHORT_SPARK") + " td.sparkline_number').text(parseInt(renderedShortSparks) + parseInt(" + unknownYearCoauthors + "));");
visualizationCode.append("var shortSparksText = ''" +
"+ ' co-author(s) within the last 10 years '" +
"<span class=\"incomplete-data-holder\" title=\"" + imcompleteDataText + "\">incomplete data</span>'" +
/*"+ ' " + totalUniqueCoAuthors + " '" +
"+ ' total " +
"<span class=\"sparkline_range\">" +
"(" + shortSparkMinYear + " - " + currentYear + ")" +
"</span>'" +*/
"+ '';" +
"$('#" + visDivNames.get("SHORT_SPARK") + " td.sparkline_text').html(shortSparksText);");
visualizationCode.append("$('#" + VIS_DIV_NAMES.get("SHORT_SPARK")
+ " td.sparkline_number')" + ".text("
+ "parseInt(renderedShortSparks) + "
+ "parseInt(" + unknownYearCoauthors + "));");
visualizationCode.append("var shortSparksText = ''"
+ "+ ' co-author(s) within the last 10 years '"
+ "<span class=\"incomplete-data-holder\" title=\""
+ imcompleteDataText + "\">incomplete data</span>'"
+ "+ '';"
+ "$('#" + VIS_DIV_NAMES.get("SHORT_SPARK")
+ " td.sparkline_text').html(shortSparksText);");
visualizationCode.append("}\n ");
/*
* Generate the code that will activate the visualization. It takes care of creating div elements to hold
* the actual sparkline image and then calling the drawUniqueCoauthorCountVisualization function.
* Generate the code that will activate the visualization. It takes care of creating div
* elements to hold the actual sparkline image and then calling the
* drawUniqueCoauthorCountVisualization function.
* */
visualizationCode.append(generateVisualizationActivator(visDivNames.get("SHORT_SPARK"), visContainerID));
visualizationCode.append(generateVisualizationActivator(VIS_DIV_NAMES.get("SHORT_SPARK"),
visContainerID));
}
private void generateFullSparklineVisualizationContent(
int currentYear, int minPubYearConsidered, String visContainerID, StringBuilder visualizationCode,
int unknownYearCoauthors, int totalUniqueCoAuthors, int renderedFullSparks,
int currentYear,
int minPubYearConsidered,
String visContainerID,
StringBuilder visualizationCode,
int unknownYearCoauthors,
int renderedFullSparks,
String sparklineDisplayOptions) {
String csvDownloadURLHref = "";
@ -381,7 +359,8 @@ public class VisualizationCodeGenerator {
try {
if (getCSVDownloadURL() != null) {
csvDownloadURLHref = "<a href=\"" + getCSVDownloadURL() + "\" class=\"inline_href\">(.CSV File)</a>";
csvDownloadURLHref = "<a href=\"" + getCSVDownloadURL()
+ "\" class=\"inline_href\">(.CSV File)</a>";
} else {
@ -393,84 +372,83 @@ public class VisualizationCodeGenerator {
csvDownloadURLHref = "";
}
visualizationCode.append("var fullSparklineView = "
+ "new google.visualization.DataView(data);\n"
+ "fullSparklineView.setColumns([1]);\n");
visualizationCode.append("var fullSparklineView = new google.visualization.DataView(data);\n" +
"fullSparklineView.setColumns([1]);\n");
visualizationCode.append("var full_spark = new google.visualization.ImageSparkLine("
+ "providedSparklineImgTD[0]"
+ ");\n"
+ "full_spark.draw(fullSparklineView, "
+ sparklineDisplayOptions + ");\n");
visualizationCode.append("var full_spark = new google.visualization.ImageSparkLine(" +
"providedSparklineImgTD[0]" +
");\n" +
"full_spark.draw(fullSparklineView, " + sparklineDisplayOptions + ");\n");
visualizationCode.append("$('#" + VIS_DIV_NAMES.get("FULL_SPARK")
+ " td.sparkline_number')"
+ ".text('" + (renderedFullSparks
+ unknownYearCoauthors) + "');");
visualizationCode.append("$('#" + visDivNames.get("FULL_SPARK") + " td.sparkline_number').text('" + (renderedFullSparks + unknownYearCoauthors) + "');");
visualizationCode.append("var allSparksText = ''" +
"+ ' co-author(s) from '" +
"+ ' <span class=\"sparkline_range\">" +
"" + minPubYearConsidered + " to " + currentYear + "" +
"</span> '" +
"+ ' " + csvDownloadURLHref + " ';" +
"$('#" + visDivNames.get("FULL_SPARK") + " td.sparkline_text').html(allSparksText);");
visualizationCode.append("var allSparksText = ''"
+ "+ ' co-author(s) from '"
+ "+ ' <span class=\"sparkline_range\">"
+ "" + minPubYearConsidered + " to " + currentYear + ""
+ "</span> '"
+ "+ ' " + csvDownloadURLHref + " ';"
+ "$('#" + VIS_DIV_NAMES.get("FULL_SPARK")
+ " td.sparkline_text').html(allSparksText);");
visualizationCode.append("}\n ");
visualizationCode.append(generateVisualizationActivator(visDivNames.get("FULL_SPARK"), visContainerID));
visualizationCode.append(generateVisualizationActivator(VIS_DIV_NAMES.get("FULL_SPARK"),
visContainerID));
}
private String generateVisualizationActivator(String sparklineID, String visContainerID) {
String sparklineTableWrapper = "\n" +
"var table = $('<table>');" +
"table.attr('class', 'sparkline_wrapper_table');" +
"var row = $('<tr>');" +
"sparklineImgTD = $('<td>');" +
"sparklineImgTD.attr('id', '" + sparklineID + "_img');" +
"sparklineImgTD.attr('width', '65');" +
"sparklineImgTD.attr('align', 'right');" +
"sparklineImgTD.attr('class', '" + visualizationStyleClass + "');" +
"row.append(sparklineImgTD);" +
"var sparklineNumberTD = $('<td>');" +
"sparklineNumberTD.attr('width', '30');" +
"sparklineNumberTD.attr('align', 'right');" +
"sparklineNumberTD.attr('class', 'sparkline_number');" +
"row.append(sparklineNumberTD);" +
"var sparklineTextTD = $('<td>');" +
"sparklineTextTD.attr('width', '350');" +
"sparklineTextTD.attr('class', 'sparkline_text');" +
"row.append(sparklineTextTD);" +
"table.append(row);" +
"table.prependTo('#" + sparklineID + "');\n";
String sparklineTableWrapper = "\n"
+ "var table = $('<table>');"
+ "table.attr('class', 'sparkline_wrapper_table');"
+ "var row = $('<tr>');"
+ "sparklineImgTD = $('<td>');"
+ "sparklineImgTD.attr('id', '" + sparklineID + "_img');"
+ "sparklineImgTD.attr('width', '65');"
+ "sparklineImgTD.attr('align', 'right');"
+ "sparklineImgTD.attr('class', '" + VISUALIZATION_STYLE_CLASS + "');"
+ "row.append(sparklineImgTD);"
+ "var sparklineNumberTD = $('<td>');"
+ "sparklineNumberTD.attr('width', '30');"
+ "sparklineNumberTD.attr('align', 'right');"
+ "sparklineNumberTD.attr('class', 'sparkline_number');"
+ "row.append(sparklineNumberTD);"
+ "var sparklineTextTD = $('<td>');"
+ "sparklineTextTD.attr('width', '350');"
+ "sparklineTextTD.attr('class', 'sparkline_text');"
+ "row.append(sparklineTextTD);"
+ "table.append(row);"
+ "table.prependTo('#" + sparklineID + "');\n";
return "$(document).ready(function() {" +
"var sparklineImgTD; " +
/*
* This is a nuclear option (creating the container in which everything goes)
* the only reason this will be ever used is the API user never submitted a
* container ID in which everything goes. The alternative was to let the
* vis not appear in the calling page at all. So now atleast vis appears but
* appended at the bottom of the body.
* */
"if ($('#" + visContainerID + "').length === 0) {" +
" $('<div/>', {'id': '" + visContainerID + "'" +
" }).appendTo('body');" +
"}" +
"if ($('#" + sparklineID + "').length === 0) {" +
"$('<div/>', {'id': '" + sparklineID + "'," +
"'class': '" + visualizationStyleClass + "'" +
"}).prependTo('#" + visContainerID + "');" +
sparklineTableWrapper +
"}" +
"drawUniqueCoauthorCountVisualization(sparklineImgTD);" +
"});" +
"</script>\n";
return "$(document).ready(function() {"
+ "var sparklineImgTD; "
/*
* This is a nuclear option (creating the container in which everything goes)
* the only reason this will be ever used is the API user never submitted a
* container ID in which everything goes. The alternative was to let the
* vis not appear in the calling page at all. So now atleast vis appears but
* appended at the bottom of the body.
* */
+ "if ($('#" + visContainerID + "').length === 0) {"
+ " $('<div/>', {'id': '" + visContainerID + "'"
+ " }).appendTo('body');"
+ "}"
+ "if ($('#" + sparklineID + "').length === 0) {"
+ "$('<div/>', {'id': '" + sparklineID + "',"
+ "'class': '" + VISUALIZATION_STYLE_CLASS + "'"
+ "}).prependTo('#" + visContainerID + "');"
+ sparklineTableWrapper
+ "}"
+ "drawUniqueCoauthorCountVisualization(sparklineImgTD);"
+ "});"
+ "</script>\n";
}
private String getVisualizationContextCode(String visMode) {
@ -481,15 +459,8 @@ public class VisualizationCodeGenerator {
} else {
visualizationContextCode = generateFullVisContext();
}
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
log.debug(visualizationContextCode);
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return visualizationContextCode;
}
@ -505,7 +476,8 @@ public class VisualizationCodeGenerator {
try {
if (getCSVDownloadURL() != null) {
csvDownloadURLHref = "Download data as <a href='" + getCSVDownloadURL() + "'>.csv</a> file.<br />";
csvDownloadURLHref = "Download data as <a href='"
+ getCSVDownloadURL() + "'>.csv</a> file.<br />";
valueObjectContainer.setDownloadDataLink(getCSVDownloadURL());
} else {
@ -518,20 +490,18 @@ public class VisualizationCodeGenerator {
csvDownloadURLHref = "";
}
} else {
csvDownloadURLHref = "No data available to export.<br />";
}
String tableCode = generateDataTable();
divContextCode.append("<p>" + tableCode +
csvDownloadURLHref + "</p>");
divContextCode.append("<p>" + tableCode
+ csvDownloadURLHref + "</p>");
valueObjectContainer.setTable(tableCode);
return divContextCode.toString();
}
private String getCSVDownloadURL()
@ -546,22 +516,20 @@ public class VisualizationCodeGenerator {
String downloadURL = contextPath
+ secondaryContextPath
+ "?" + VisualizationFrameworkConstants.INDIVIDUAL_URI_URL_HANDLE
+ "=" + URLEncoder.encode(individualURIParam,
VisualizationController.URL_ENCODING_SCHEME).toString()
+ "&" + VisualizationFrameworkConstants.VIS_TYPE_URL_HANDLE
+ "=" + URLEncoder.encode(VisualizationController
.COAUTHORSHIP_VIS_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME).toString()
+ "&" + VisualizationFrameworkConstants.VIS_MODE_URL_HANDLE
+ "=" + URLEncoder.encode("sparkline",
VisualizationController.URL_ENCODING_SCHEME).toString()
+ "&" + VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE
+ "=" + URLEncoder.encode(VisualizationFrameworkConstants.DATA_RENDER_MODE_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME).toString();
// System.out.println(" ----- >>>> " + contextPath + " XX " + individualURIParam + " XX " + downloadURL);
+ secondaryContextPath
+ "?" + VisualizationFrameworkConstants.INDIVIDUAL_URI_URL_HANDLE
+ "=" + URLEncoder.encode(individualURIParam,
VisualizationController.URL_ENCODING_SCHEME).toString()
+ "&" + VisualizationFrameworkConstants.VIS_TYPE_URL_HANDLE
+ "=" + URLEncoder.encode(VisualizationController
.COAUTHORSHIP_VIS_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME).toString()
+ "&" + VisualizationFrameworkConstants.VIS_MODE_URL_HANDLE
+ "=" + URLEncoder.encode("sparkline",
VisualizationController.URL_ENCODING_SCHEME).toString()
+ "&" + VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE
+ "=" + URLEncoder.encode(VisualizationFrameworkConstants.DATA_RENDER_MODE_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME).toString();
return downloadURL;
} else {
@ -570,7 +538,6 @@ public class VisualizationCodeGenerator {
}
private String generateShortVisContext() {
StringBuilder divContextCode = new StringBuilder();
@ -598,15 +565,16 @@ public class VisualizationCodeGenerator {
+ "&"
+ VisualizationFrameworkConstants.VIS_CONTAINER_URL_HANDLE
+ "=" + URLEncoder.encode("ego_sparkline",
VisualizationController.URL_ENCODING_SCHEME).toString()
VisualizationController.URL_ENCODING_SCHEME).toString()
+ "&"
+ VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE
+ "=" + URLEncoder.encode(VisualizationFrameworkConstants.STANDALONE_RENDER_MODE_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME).toString();
+ "=" + URLEncoder.encode(
VisualizationFrameworkConstants
.STANDALONE_RENDER_MODE_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME).toString();
System.out.println("context parth full n/w " + contextPath);
fullTimelineLink = "<a href='" + fullTimelineNetworkURL + "'>View full timeline and co-author network</a><br />";
fullTimelineLink = "<a href='" + fullTimelineNetworkURL
+ "'>View full timeline and co-author network</a><br />";
valueObjectContainer.setFullTimelineNetworkLink(fullTimelineNetworkURL);
@ -619,11 +587,10 @@ public class VisualizationCodeGenerator {
divContextCode.append("<p>" + fullTimelineLink + "</p>");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
log.error(e);
}
return divContextCode.toString();
}
@ -631,34 +598,25 @@ public class VisualizationCodeGenerator {
StringBuilder dataTable = new StringBuilder();
dataTable.append("<table id='sparkline_data_table'>" +
"<caption>Unique Co-Authors per year</caption>" +
"<thead>" +
"<tr>" +
"<th>Year</th>" +
"<th>Count</th>" +
"</tr>" +
"</thead>" +
"<tbody>");
dataTable.append("<table id='sparkline_data_table'>"
+ "<caption>Unique Co-Authors per year</caption>"
+ "<thead>"
+ "<tr>"
+ "<th>Year</th>"
+ "<th>Count</th>"
+ "</tr>"
+ "</thead>"
+ "<tbody>");
for (Entry<String, Set<Node>> currentEntry : yearToUniqueCoauthors.entrySet()) {
dataTable.append("<tr>" +
"<td>" + currentEntry.getKey() + "</td>" +
"<td>" + currentEntry.getValue().size() + "</td>" +
"</tr>");
dataTable.append("<tr>"
+ "<td>" + currentEntry.getKey() + "</td>"
+ "<td>" + currentEntry.getValue().size() + "</td>"
+ "</tr>");
}
dataTable.append("</tbody>\n" +
// "<tfoot>" +
// "<tr><td colspan='2'>*DNA - Data not available</td></tr>" +
// "</tfoot>\n" +
"</table>\n");
dataTable.append("</tbody>\n </table>\n");
return dataTable.toString();
}
}

View file

@ -7,6 +7,7 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import com.hp.hpl.jena.iri.IRI;
@ -30,6 +31,7 @@ import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.BiboDocument;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.VivoCollegeOrSchool;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.VivoDepartmentOrDivision;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.VivoEmployee;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryHandler;
@ -37,23 +39,21 @@ import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.VivoEmployee;
* @author cdtank
*
*/
public class QueryHandler {
public class CollegePublicationCountQueryHandler implements QueryHandler<Set<VivoEmployee>> {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
private String collegeURIParam, resultFormatParam, rdfResultFormatParam;
private Map<String, VivoCollegeOrSchool> collegeURLToVO = new HashMap<String, VivoCollegeOrSchool>();
private String collegeURIParam;
private Map<String, VivoCollegeOrSchool> collegeURLToVO =
new HashMap<String, VivoCollegeOrSchool>();
private DataSource dataSource;
private Log log;
public QueryHandler(String collegeURIParam,
String resultFormatParam, String rdfResultFormatParam,
public CollegePublicationCountQueryHandler(String collegeURIParam,
DataSource dataSource, Log log) {
this.collegeURIParam = collegeURIParam;
this.resultFormatParam = resultFormatParam;
this.rdfResultFormatParam = rdfResultFormatParam;
this.dataSource = dataSource;
this.log = log;
@ -63,7 +63,8 @@ public class QueryHandler {
Set<VivoEmployee> collegeAcademicEmployees = new HashSet<VivoEmployee>();
Map<String, VivoDepartmentOrDivision> departmentURLToVO = new HashMap<String, VivoDepartmentOrDivision>();
Map<String, VivoDepartmentOrDivision> departmentURLToVO =
new HashMap<String, VivoDepartmentOrDivision>();
Map<String, VivoEmployee> employeeURLToVO = new HashMap<String, VivoEmployee>();
while (resultSet.hasNext()) {
@ -119,7 +120,9 @@ public class QueryHandler {
currentEmployee = employeeURLToVO.get(employeeNode.toString());
currentEmployee.addParentDepartment(currentDepartment);
} else {
currentEmployee = new VivoEmployee(employeeNode.toString(), currentEmployeeType, currentDepartment);
currentEmployee = new VivoEmployee(employeeNode.toString(),
currentEmployeeType,
currentDepartment);
RDFNode authorLabelNode = solution.get(QueryFieldLabels.AUTHOR_LABEL);
if (authorLabelNode != null) {
currentEmployee.setIndividualLabel(authorLabelNode.toString());
@ -131,17 +134,19 @@ public class QueryHandler {
if (documentNode != null) {
/*
* A document can have multiple authors but if the same author serves in multiple departments
* then we need to account for "An Authored Document" only once. This check will make sure that
* a document by same author is not added twice just because that author serves in 2 distinct
* department.
* A document can have multiple authors but if the same author serves in
* multiple departments then we need to account for "An Authored Document"
* only once. This check will make sure that a document by same author is
* not added twice just because that author serves in 2 distinct department.
* */
boolean isNewDocumentAlreadyAdded = testForDuplicateEntryOfDocument(
currentEmployee,
documentNode);
if (!isNewDocumentAlreadyAdded) {
currentEmployee.addAuthorDocument(createAuthorDocumentsVO(solution, documentNode.toString()));
currentEmployee.addAuthorDocument(
createAuthorDocumentsVO(solution,
documentNode.toString()));
}
}
@ -149,14 +154,6 @@ public class QueryHandler {
collegeAcademicEmployees.add(currentEmployee);
}
/* System.out.println(collegeURLToVO);
System.out.println("------------------------------------------------------------");
System.out.println(departmentURLToVO);
System.out.println("------------------------------------------------------------");
System.out.println(employeeURLToVO);
System.out.println("------------------------------------------------------------");
*/
return collegeAcademicEmployees;
}
@ -165,7 +162,8 @@ public class QueryHandler {
boolean isNewDocumentAlreadyAdded = false;
for (BiboDocument currentAuthoredDocument : currentEmployee.getAuthorDocuments()) {
if (currentAuthoredDocument.getDocumentURL().equalsIgnoreCase(documentNode.toString())) {
if (currentAuthoredDocument.getDocumentURL()
.equalsIgnoreCase(documentNode.toString())) {
isNewDocumentAlreadyAdded = true;
break;
}
@ -206,7 +204,9 @@ public class QueryHandler {
biboDocument.setPublicationYear(publicationYearNode.toString());
}
RDFNode publicationYearMonthNode = solution.get(QueryFieldLabels.DOCUMENT_PUBLICATION_YEAR_MONTH);
RDFNode publicationYearMonthNode = solution.get(
QueryFieldLabels
.DOCUMENT_PUBLICATION_YEAR_MONTH);
if (publicationYearMonthNode != null) {
biboDocument.setPublicationYearMonth(publicationYearMonthNode.toString());
}
@ -220,29 +220,24 @@ public class QueryHandler {
}
private ResultSet executeQuery(String queryText,
String resultFormatParam,
String rdfResultFormatParam,
DataSource dataSource) {
QueryExecution queryExecution = null;
try{
try {
Query query = QueryFactory.create(queryText, SYNTAX);
// QuerySolutionMap qs = new QuerySolutionMap();
// qs.add("authPerson", queryParam); // bind resource to s
queryExecution = QueryExecutionFactory.create(query, dataSource);
//remocve this if loop after knowing what is describe & construct sparql stuff.
if (query.isSelectType()){
if (query.isSelectType()) {
return queryExecution.execSelect();
}
} finally {
if(queryExecution != null) {
if (queryExecution != null) {
queryExecution.close();
}
}
return null;
}
@ -304,25 +299,23 @@ public class QueryHandler {
public Set<VivoEmployee> getVisualizationJavaValueObjects()
throws MalformedQueryParametersException {
if (this.collegeURIParam == null || "".equals(collegeURIParam)) {
throw new MalformedQueryParametersException("URI parameter is either null or empty.");
} else {
if (StringUtils.isNotBlank(this.collegeURIParam)) {
/*
* To test for the validity of the URI submitted.
* */
IRIFactory iRIFactory = IRIFactory.jenaImplementation();
IRI iri = iRIFactory.create(this.collegeURIParam);
if (iri.hasViolation(false)) {
String errorMsg = ((Violation)iri.violations(false).next()).getShortMessage()+" ";
String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage();
log.error("Pub Count Vis Query " + errorMsg);
throw new MalformedQueryParametersException("URI provided for an individual is malformed.");
throw new MalformedQueryParametersException(
"URI provided for an individual is malformed.");
}
} else {
throw new MalformedQueryParametersException("URI parameter is either null or empty.");
}
ResultSet resultSet = executeQuery(generateCollegeEmployeeSparqlQuery(this.collegeURIParam),
this.resultFormatParam,
this.rdfResultFormatParam,
this.dataSource);
return createJavaValueObjects(resultSet);

View file

@ -17,6 +17,7 @@ import java.util.Map.Entry;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -33,7 +34,6 @@ import edu.cornell.mannlib.vitro.webapp.beans.Portal;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.PDFDocument;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.VOConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.BiboDocument;
@ -41,44 +41,39 @@ import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Individual;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.VivoCollegeOrSchool;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.VivoDepartmentOrDivision;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.VivoEmployee;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.PDFDocument;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
public class VisualizationRequestHandler {
public class CollegePublicationCountRequestHandler extends VisualizationRequestHandler {
private VitroRequest vitroRequest;
private HttpServletRequest request;
private HttpServletResponse response;
private Log log;
public VisualizationRequestHandler(VitroRequest vitroRequest,
public CollegePublicationCountRequestHandler(VitroRequest vitroRequest,
HttpServletRequest request, HttpServletResponse response, Log log) {
this.vitroRequest = vitroRequest;
this.request = request;
this.response = response;
this.log = log;
super(vitroRequest, request, response, log);
}
public void generateVisualization(DataSource dataSource) {
String resultFormatParam = "RS_TEXT";
String rdfResultFormatParam = "RDF/XML-ABBREV";
String collegeURIParam = vitroRequest.getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_URL_HANDLE);
String renderMode = vitroRequest.getParameter(VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE);
ServletRequest vitroRequest = super.getVitroRequest();
String visMode = vitroRequest.getParameter(VisualizationFrameworkConstants.VIS_MODE_URL_HANDLE);
String collegeURIParam = vitroRequest.getParameter(
VisualizationFrameworkConstants.INDIVIDUAL_URI_URL_HANDLE);
String visContainer = vitroRequest.getParameter(VisualizationFrameworkConstants.VIS_CONTAINER_URL_HANDLE);
String renderMode = vitroRequest.getParameter(
VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE);
String visMode = vitroRequest.getParameter(
VisualizationFrameworkConstants.VIS_MODE_URL_HANDLE);
QueryHandler queryManager =
new QueryHandler(collegeURIParam,
resultFormatParam,
rdfResultFormatParam,
String visContainer = vitroRequest.getParameter(
VisualizationFrameworkConstants.VIS_CONTAINER_URL_HANDLE);
Log log = super.getLog();
QueryHandler<Set<VivoEmployee>> queryManager =
new CollegePublicationCountQueryHandler(collegeURIParam,
dataSource,
log);
@ -87,34 +82,35 @@ public class VisualizationRequestHandler {
Set<VivoEmployee> employees = queryManager.getVisualizationJavaValueObjects();
Map<VivoDepartmentOrDivision, Map<String, Integer>> departmentToPublicationsOverTime =
new HashMap<VivoDepartmentOrDivision, Map<String,Integer>>();
new HashMap<VivoDepartmentOrDivision, Map<String, Integer>>();
Set<String> publishedYearsForCollege = new HashSet<String>();
for (VivoEmployee currentEmployee : employees) {
Map<String, Integer> currentEmployeeYearToPublicationCount =
UtilityFunctions.getYearToPublicationCount(currentEmployee.getAuthorDocuments());
UtilityFunctions.getYearToPublicationCount(
currentEmployee.getAuthorDocuments());
if (currentEmployeeYearToPublicationCount.size() > 0) {
publishedYearsForCollege.addAll(currentEmployeeYearToPublicationCount.keySet());
for (VivoDepartmentOrDivision currentDepartment : currentEmployee.getParentDepartments()) {
for (VivoDepartmentOrDivision currentDepartment
: currentEmployee.getParentDepartments()) {
departmentToPublicationsOverTime.put(currentDepartment,
getUpdatedDepartmentPublicationsOverTime(
currentEmployeeYearToPublicationCount,
departmentToPublicationsOverTime
.get(currentDepartment)));
departmentToPublicationsOverTime
.put(currentDepartment,
getUpdatedDepartmentPublicationsOverTime(
currentEmployeeYearToPublicationCount,
departmentToPublicationsOverTime
.get(currentDepartment)));
}
}
}
/*
* In order to avoid unneeded computations we have pushed this "if" condition up.
* This case arises when the render mode is data. In that case we dont want to generate
@ -124,7 +120,7 @@ public class VisualizationRequestHandler {
if (VisualizationFrameworkConstants.DATA_RENDER_MODE_URL_VALUE.equalsIgnoreCase(renderMode)) {
prepareVisualizationQueryDataResponse(
departmentToPublicationsOverTime,
queryManager.getCollegeURLToVO());
((CollegePublicationCountQueryHandler) queryManager).getCollegeURLToVO());
log.debug(publishedYearsForCollege);
return;
@ -150,52 +146,6 @@ public class VisualizationRequestHandler {
* */
publishedYearsForCollege.remove(VOConstants.DEFAULT_PUBLICATION_YEAR);
/*
VisualizationCodeGenerator visualizationCodeGenerator =
new VisualizationCodeGenerator(yearToPublicationCount, log);
String visContentCode = visualizationCodeGenerator
.getMainVisualizationCode(authorDocuments,
publishedYears,
visMode,
visContainer);
String visContextCode = visualizationCodeGenerator
.getVisualizationContextCode(vitroRequest.getRequestURI(),
collegeURIParam,
visMode);
*/
/*
* This is side-effecting because the response of this method is just to redirect to
* a page with visualization on it.
* */
/*
RequestDispatcher requestDispatcher = null;
if (DYNAMIC_RENDER_MODE_URL_VALUE.equalsIgnoreCase(renderMode)) {
prepareVisualizationQueryDynamicResponse(request, response, vitroRequest,
visContentCode, visContextCode);
requestDispatcher = request.getRequestDispatcher("/templates/page/blankPage.jsp");
} else {
prepareVisualizationQueryStandaloneResponse(request, response, vitroRequest,
visContentCode, visContextCode);
requestDispatcher = request.getRequestDispatcher(Controllers.BASIC_JSP);
}
try {
requestDispatcher.forward(request, response);
} catch (Exception e) {
log.error("EntityEditController could not forward to view.");
log.error(e.getMessage());
log.error(e.getStackTrace());
}
*/
} catch (MalformedQueryParametersException e) {
try {
handleMalformedParameters(e.getMessage());
@ -210,30 +160,30 @@ public class VisualizationRequestHandler {
}
private Map<String, Integer> getUpdatedDepartmentPublicationsOverTime(
Map<String, Integer> currentEmployeeYearToPublicationCount,
Map<String, Integer> currentDepartmentYearToPublicationCount) {
Map<String, Integer> currentEmployeeYearToPublicationCount,
Map<String, Integer> currentDepartmentYearToPublicationCount) {
Map<String, Integer> departmentYearToPublicationCount;
// System.out.println("inside get updated dept pub obr time");
/*
* In case this is the first time we are consolidating publication counts over time for a department.
* In case this is the first time we are consolidating publication counts
* over time for a department.
* */
if (currentDepartmentYearToPublicationCount == null) {
departmentYearToPublicationCount = new TreeMap<String, Integer>();
// System.out.println("new dept yr pub cnt");
} else {
departmentYearToPublicationCount = currentDepartmentYearToPublicationCount;
}
Iterator employeePubCountIterator = currentEmployeeYearToPublicationCount.entrySet().iterator();
Iterator employeePubCountIterator = currentEmployeeYearToPublicationCount
.entrySet().iterator();
while (employeePubCountIterator.hasNext()) {
Map.Entry<String, Integer> employeePubCountEntry = (Map.Entry) employeePubCountIterator.next();
Map.Entry<String, Integer> employeePubCountEntry =
(Map.Entry) employeePubCountIterator.next();
String employeePublicationYear = employeePubCountEntry.getKey();
Integer employeePublicationCount = employeePubCountEntry.getValue();
@ -246,7 +196,10 @@ public class VisualizationRequestHandler {
+ employeePublicationCount);
} else {
departmentYearToPublicationCount.put(employeePublicationYear, employeePublicationCount);
departmentYearToPublicationCount.put(employeePublicationYear,
employeePublicationCount);
}
} catch (Exception e) {
e.printStackTrace();
@ -280,8 +233,9 @@ public class VisualizationRequestHandler {
String outputFileName = UtilityFunctions.slugify(authorName + "-report")
+ ".pdf";
HttpServletResponse response = super.getResponse();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition","attachment;filename=" + outputFileName);
response.setHeader("Content-Disposition", "attachment;filename=" + outputFileName);
ServletOutputStream responseOutputStream;
try {
@ -316,8 +270,8 @@ public class VisualizationRequestHandler {
}
private void prepareVisualizationQueryDataResponse(
Map<VivoDepartmentOrDivision, Map<String, Integer>> departmentToPublicationsOverTime,
Map<String, VivoCollegeOrSchool> collegeURLToVO) {
Map<VivoDepartmentOrDivision, Map<String, Integer>> departmentToPublicationsOverTime,
Map<String, VivoCollegeOrSchool> collegeURLToVO) {
String collegeName = null;
@ -325,9 +279,12 @@ public class VisualizationRequestHandler {
* To protect against cases where there are no author documents associated with the
* individual.
* */
// System.out.println(collegeURLToVO);
if (collegeURLToVO.size() > 0) {
collegeName = ((VivoCollegeOrSchool) collegeURLToVO.values().iterator().next()).getCollegeLabel();
collegeName = ((VivoCollegeOrSchool) collegeURLToVO.values()
.iterator().next()).getCollegeLabel();
}
/*
@ -339,8 +296,9 @@ public class VisualizationRequestHandler {
String outputFileName = UtilityFunctions.slugify(collegeName) + "depts-pub-count" + ".csv";
HttpServletResponse response = super.getResponse();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=" + outputFileName);
response.setHeader("Content-Disposition", "attachment;filename=" + outputFileName);
try {
@ -377,14 +335,16 @@ public class VisualizationRequestHandler {
String collegeLabel = college.getCollegeLabel();
for (VivoDepartmentOrDivision currentDepartment : college.getDepartments()) {
Map<String, Integer> currentDepartmentPublicationsOverTime = departmentToPublicationsOverTime.get(currentDepartment);
Map<String, Integer> currentDepartmentPublicationsOverTime =
departmentToPublicationsOverTime.get(currentDepartment);
/*
* This because many departments might not have any publication.
* */
if (currentDepartmentPublicationsOverTime != null) {
for (Entry<String, Integer> currentEntry : currentDepartmentPublicationsOverTime.entrySet()) {
for (Entry<String, Integer> currentEntry
: currentDepartmentPublicationsOverTime.entrySet()) {
csvWriter.append(new Object[]{collegeLabel,
currentDepartment.getDepartmentLabel(),
currentEntry.getKey(),
@ -437,8 +397,9 @@ public class VisualizationRequestHandler {
private void handleMalformedParameters(String errorMessage)
throws ServletException, IOException {
Portal portal = vitroRequest.getPortal();
Portal portal = super.getVitroRequest().getPortal();
HttpServletRequest request = super.getRequest();
request.setAttribute("error", errorMessage);
RequestDispatcher requestDispatcher = request.getRequestDispatcher(Controllers.BASIC_JSP);
@ -447,8 +408,9 @@ public class VisualizationRequestHandler {
request.setAttribute("title", "Visualization Query Error - Individual Publication Count");
try {
requestDispatcher.forward(request, response);
requestDispatcher.forward(request, super.getResponse());
} catch (Exception e) {
Log log = super.getLog();
log.error("EntityEditController could not forward to view.");
log.error(e.getMessage());
log.error(e.getStackTrace());

View file

@ -7,7 +7,7 @@ import java.util.Map;
public class QueryConstants {
public static final Map<String, String> PREFIX_TO_NAMESPACE = new HashMap<String, String>() {{
public static final Map<String, String> PREFIX_TO_NAMESPACE = new HashMap<String, String>() { {
put("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
put("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
@ -41,14 +41,15 @@ public class QueryConstants {
put("j.1", "http://aims.fao.org/aos/geopolitical.owl#");
put("j.2", "http://vitro.mannlib.cornell.edu/ns/vitro/public#");
}};
} };
public static String getSparqlPrefixQuery() {
StringBuilder prefixSection = new StringBuilder();
for (Map.Entry prefixEntry : PREFIX_TO_NAMESPACE.entrySet()) {
prefixSection.append("PREFIX " + prefixEntry.getKey() + ": <" + prefixEntry.getValue() + ">\n");
prefixSection.append("PREFIX " + prefixEntry.getKey()
+ ": <" + prefixEntry.getValue() + ">\n");
}

View file

@ -13,6 +13,4 @@ public class VOConstants {
ACADEMIC_FACULTY_EMPLOYEE, ACADEMIC_STAFF_EMPLOYEE
}
}

View file

@ -6,5 +6,8 @@ public class VisConstants {
public static final int MAX_NAME_TEXT_LENGTH = 20;
public static final String RESULT_FORMAT_PARAM = "RS_TEXT";
public static final String RDF_RESULT_FORMAT_PARAM = "RDF/XML-ABBREV";
}

View file

@ -25,65 +25,60 @@ import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.CoAuthorshipGraphMLWriter;
import edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.VisVOContainer;
import edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.CoAuthorshipQueryHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.CoAuthorshipVisCodeGenerator;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
import edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.VisualizationCodeGenerator;
import edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.PersonPublicationCountQueryHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.PersonPublicationCountVisCodeGenerator;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.BiboDocument;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.CoAuthorshipVOContainer;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Node;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.SparklineVOContainer;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
public class VisualizationRequestHandler {
public class PersonLevelRequestHandler extends VisualizationRequestHandler {
private VitroRequest vitroRequest;
private HttpServletRequest request;
private HttpServletResponse response;
private Log log;
public VisualizationRequestHandler(VitroRequest vitroRequest,
private static final String EGO_PUB_SPARKLINE_VIS_CONTAINER_ID = "ego_pub_sparkline";
private static final String UNIQUE_COAUTHORS_SPARKLINE_VIS_CONTAINER_ID =
"unique_coauthors_sparkline";
public PersonLevelRequestHandler(VitroRequest vitroRequest,
HttpServletRequest request, HttpServletResponse response, Log log) {
this.vitroRequest = vitroRequest;
this.request = request;
this.response = response;
this.log = log;
super(vitroRequest, request, response, log);
}
public void generateVisualization(DataSource dataSource) {
String resultFormatParam = "RS_TEXT";
String rdfResultFormatParam = "RDF/XML-ABBREV";
VitroRequest vitroRequest = super.getVitroRequest();
String egoURIParam = vitroRequest.getParameter(
VisualizationFrameworkConstants.INDIVIDUAL_URI_URL_HANDLE);
String egoURIParam = vitroRequest.getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_URL_HANDLE);
String renderMode = vitroRequest.getParameter(VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE);
String renderMode = vitroRequest.getParameter(
VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE);
String visMode = vitroRequest.getParameter(VisualizationFrameworkConstants.VIS_MODE_URL_HANDLE);
String visMode = vitroRequest.getParameter(
VisualizationFrameworkConstants.VIS_MODE_URL_HANDLE);
String coAuthorsListMode = "coauthors";
String egoPubSparklineVisContainerID = "ego_pub_sparkline";
String uniqueCoauthorsSparklineVisContainerID = "unique_coauthors_sparkline";
Log log = super.getLog();
QueryHandler<CoAuthorshipVOContainer>
coAuthorshipQueryManager =
new CoAuthorshipQueryHandler(egoURIParam,
dataSource,
log);
edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.QueryHandler coAuthorshipQueryManager =
new edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.QueryHandler(egoURIParam,
resultFormatParam,
rdfResultFormatParam,
dataSource,
log);
edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.QueryHandler publicationQueryManager =
new edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.QueryHandler(egoURIParam,
resultFormatParam,
rdfResultFormatParam,
dataSource,
log);
QueryHandler<List<BiboDocument>> publicationQueryManager =
new PersonPublicationCountQueryHandler(egoURIParam,
dataSource,
log);
try {
edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.VisVOContainer coAuthorshipVO =
coAuthorshipQueryManager.getVisualizationJavaValueObjects();
CoAuthorshipVOContainer coAuthorshipVO = coAuthorshipQueryManager
.getVisualizationJavaValueObjects();
/*
* In order to avoid unneeded computations we have pushed this "if" condition up.
@ -91,27 +86,30 @@ public class VisualizationRequestHandler {
* HTML code to render sparkline, tables etc. Ideally I would want to avoid this flow.
* It is ugly!
* */
if (VisualizationFrameworkConstants.DATA_RENDER_MODE_URL_VALUE.equalsIgnoreCase(renderMode)) {
if (VisualizationFrameworkConstants.DATA_RENDER_MODE_URL_VALUE
.equalsIgnoreCase(renderMode)) {
/*
* We will be using the same visualization package for providing data for both
* list of unique coauthors & network of coauthors (used in the flash vis). We will
* use "VIS_MODE_URL_HANDLE" as a modifier to differentiate between these two.
* The defualt will be to provide data used to render the coauthorship network vis.
* list of unique coauthors & network of coauthors (used in the flash vis).
* We will use "VIS_MODE_URL_HANDLE" as a modifier to differentiate between
* these two. The defualt will be to provide data used to render the co-
* authorship network vis.
* */
if (coAuthorsListMode.equalsIgnoreCase(visMode)) {
if (VisualizationFrameworkConstants.COAUTHORSLIST_VIS_MODE_URL_VALUE
.equalsIgnoreCase(visMode)) {
/*
* When the csv file is required - containing the unique co-authors vs how many times
* they have co-authored with the ego.
* When the csv file is required - containing the unique co-authors vs how
* many times they have co-authored with the ego.
* */
prepareVisualizationQueryListCoauthorsDataResponse(coAuthorshipVO);
return;
} else {
/*
* When the graphML file is required - based on which coauthorship network visualization
* will be rendered.
* When the graphML file is required - based on which co-authorship
* network visualization will be rendered.
* */
prepareVisualizationQueryNetworkDataResponse(coAuthorshipVO);
return;
@ -120,17 +118,15 @@ public class VisualizationRequestHandler {
}
List<BiboDocument> authorDocuments = publicationQueryManager.getVisualizationJavaValueObjects();
List<BiboDocument> authorDocuments = publicationQueryManager
.getVisualizationJavaValueObjects();
/*
* Create a map from the year to number of publications. Use the BiboDocument's
* parsedPublicationYear to populate the data.
* */
Map<String, Integer> yearToPublicationCount = publicationQueryManager
.getYearToPublicationCount(authorDocuments);
// Map<String, Integer> yearToUniqueCoauthorCount = getUniqueCoauthorsCountPerYear(coAuthorshipVO);
Map<String, Integer> yearToPublicationCount =
((PersonPublicationCountQueryHandler) publicationQueryManager)
.getYearToPublicationCount(authorDocuments);
/*
* Computations required to generate HTML for the sparklines & related context.
@ -139,23 +135,23 @@ public class VisualizationRequestHandler {
SparklineVOContainer publicationSparklineVO = new SparklineVOContainer();
SparklineVOContainer uniqueCoauthorsSparklineVO = new SparklineVOContainer();
edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.VisualizationCodeGenerator personPubCountVisCodeGenerator =
new edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.VisualizationCodeGenerator(
PersonPublicationCountVisCodeGenerator personPubCountVisCodeGenerator =
new PersonPublicationCountVisCodeGenerator(
vitroRequest.getRequestURI(),
egoURIParam,
VisualizationCodeGenerator.FULL_SPARKLINE_MODE_URL_HANDLE,
egoPubSparklineVisContainerID,
PersonPublicationCountVisCodeGenerator.FULL_SPARKLINE_MODE_URL_HANDLE,
EGO_PUB_SPARKLINE_VIS_CONTAINER_ID,
authorDocuments,
yearToPublicationCount,
publicationSparklineVO,
log);
edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.VisualizationCodeGenerator uniqueCoauthorsVisCodeGenerator =
new edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.VisualizationCodeGenerator(
CoAuthorshipVisCodeGenerator uniqueCoauthorsVisCodeGenerator =
new CoAuthorshipVisCodeGenerator(
vitroRequest.getRequestURI(),
egoURIParam,
VisualizationCodeGenerator.FULL_SPARKLINE_MODE_URL_HANDLE,
uniqueCoauthorsSparklineVisContainerID,
PersonPublicationCountVisCodeGenerator.FULL_SPARKLINE_MODE_URL_HANDLE,
UNIQUE_COAUTHORS_SPARKLINE_VIS_CONTAINER_ID,
getUniqueCoAuthorsPerYear(coAuthorshipVO),
uniqueCoauthorsSparklineVO,
log);
@ -163,21 +159,20 @@ public class VisualizationRequestHandler {
RequestDispatcher requestDispatcher = null;
prepareVisualizationQueryStandaloneResponse(egoURIParam,
publicationSparklineVO,
uniqueCoauthorsSparklineVO,
coAuthorshipVO,
egoPubSparklineVisContainerID,
uniqueCoauthorsSparklineVisContainerID,
request,
response,
vitroRequest);
HttpServletRequest request = super.getRequest();
prepareVisualizationQueryStandaloneResponse(
egoURIParam,
publicationSparklineVO,
uniqueCoauthorsSparklineVO,
coAuthorshipVO,
EGO_PUB_SPARKLINE_VIS_CONTAINER_ID,
UNIQUE_COAUTHORS_SPARKLINE_VIS_CONTAINER_ID);
// requestDispatcher = request.getRequestDispatcher("/templates/page/blankPage.jsp");
requestDispatcher = request.getRequestDispatcher(Controllers.BASIC_JSP);
try {
requestDispatcher.forward(request, response);
requestDispatcher.forward(request, super.getResponse());
} catch (Exception e) {
log.error("EntityEditController could not forward to view.");
log.error(e.getMessage());
@ -194,10 +189,10 @@ public class VisualizationRequestHandler {
}
return;
}
}
private Map<String, Set<Node>> getUniqueCoAuthorsPerYear(edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.VisVOContainer authorNodesAndEdges) {
private Map<String, Set<Node>> getUniqueCoAuthorsPerYear(
CoAuthorshipVOContainer authorNodesAndEdges) {
Map<String, Set<Node>> yearToCoAuthors = new TreeMap<String, Set<Node>>();
@ -230,27 +225,26 @@ public class VisualizationRequestHandler {
}
}
return yearToCoAuthors;
}
private void prepareVisualizationQueryNetworkDataResponse(VisVOContainer coAuthorsipVO) {
private void prepareVisualizationQueryNetworkDataResponse(
CoAuthorshipVOContainer coAuthorsipVO) {
String outputFileName = "";
if (coAuthorsipVO.getNodes() == null || coAuthorsipVO.getNodes().size() < 1) {
if (coAuthorsipVO.getNodes() != null && coAuthorsipVO.getNodes().size() > 0) {
outputFileName = "no_coauthor-network.graphml" + ".xml";
outputFileName = UtilityFunctions.slugify(coAuthorsipVO.getEgoNode().getNodeName())
+ "_coauthor-network.graphml" + ".xml";
} else {
outputFileName = UtilityFunctions.slugify(coAuthorsipVO.getEgoNode().getNodeName())
+ "_coauthor-network.graphml" + ".xml";
outputFileName = "no_coauthor-network.graphml" + ".xml";
}
HttpServletResponse response = super.getResponse();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + outputFileName);
@ -262,7 +256,8 @@ public class VisualizationRequestHandler {
* We are side-effecting responseWriter since we are directly manipulating the response
* object of the servlet.
* */
CoAuthorshipGraphMLWriter coAuthorShipGraphMLWriter = new CoAuthorshipGraphMLWriter(coAuthorsipVO);
CoAuthorshipGraphMLWriter coAuthorShipGraphMLWriter =
new CoAuthorshipGraphMLWriter(coAuthorsipVO);
responseWriter.append(coAuthorShipGraphMLWriter.getCoAuthorshipGraphMLContent());
@ -273,24 +268,26 @@ public class VisualizationRequestHandler {
}
}
private void prepareVisualizationQueryListCoauthorsDataResponse(VisVOContainer coAuthorsipVO) {
private void prepareVisualizationQueryListCoauthorsDataResponse(
CoAuthorshipVOContainer coAuthorshipVO) {
String outputFileName = "";
Map<String, Integer> coAuthorsToCount = new TreeMap<String, Integer>();
if (coAuthorsipVO.getNodes() == null || coAuthorsipVO.getNodes().size() < 1 ) {
if (coAuthorshipVO.getNodes() != null && coAuthorshipVO.getNodes().size() > 0) {
outputFileName = "no_coauthors" + ".csv";
outputFileName = UtilityFunctions.slugify(coAuthorshipVO.getEgoNode().getNodeName())
+ "_coauthors" + ".csv";
coAuthorsToCount = getCoAuthorsList(coAuthorshipVO);
} else {
outputFileName = UtilityFunctions.slugify(coAuthorsipVO.getEgoNode().getNodeName())
+ "_coauthors" + ".csv";
coAuthorsToCount = getCoAuthorsList(coAuthorsipVO);
outputFileName = "no_coauthors" + ".csv";
}
HttpServletResponse response = super.getResponse();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + outputFileName);
@ -313,7 +310,7 @@ public class VisualizationRequestHandler {
}
private Map<String, Integer> getCoAuthorsList(VisVOContainer coAuthorsipVO) {
private Map<String, Integer> getCoAuthorsList(CoAuthorshipVOContainer coAuthorsipVO) {
Map<String, Integer> coAuthorsToCount = new TreeMap<String, Integer>();
@ -327,14 +324,12 @@ public class VisualizationRequestHandler {
coAuthorsToCount.put(currNode.getNodeName(), currNode.getNumOfAuthoredWorks());
}
}
return coAuthorsToCount;
}
private void generateCsvFileBuffer(Map<String, Integer> coAuthorsToCount, PrintWriter printWriter) {
private void generateCsvFileBuffer(Map<String, Integer> coAuthorsToCount,
PrintWriter printWriter) {
printWriter.append("\"Co-Author\", \"Count\"\n");
@ -348,20 +343,17 @@ public class VisualizationRequestHandler {
printWriter.flush();
}
private void prepareVisualizationQueryStandaloneResponse(
String egoURIParam,
SparklineVOContainer egoPubSparklineVO,
SparklineVOContainer uniqueCoauthorsSparklineVO,
VisVOContainer coAuthorshipVO,
String egoPubSparklineVisContainer,
String uniqueCoauthorsSparklineVisContainer,
HttpServletRequest request,
HttpServletResponse response,
VitroRequest vreq) {
String egoURIParam,
SparklineVOContainer egoPubSparklineVO,
SparklineVOContainer uniqueCoauthorsSparklineVO,
CoAuthorshipVOContainer coAuthorshipVO,
String egoPubSparklineVisContainer,
String uniqueCoauthorsSparklineVisContainer) {
Portal portal = vreq.getPortal();
Portal portal = super.getVitroRequest().getPortal();
HttpServletRequest request = super.getRequest();
request.setAttribute("egoURIParam", egoURIParam);
String title = "";
@ -379,7 +371,8 @@ public class VisualizationRequestHandler {
request.setAttribute("uniqueCoauthorsSparklineVO", uniqueCoauthorsSparklineVO);
request.setAttribute("egoPubSparklineContainerID", egoPubSparklineVisContainer);
request.setAttribute("uniqueCoauthorsSparklineVisContainerID", uniqueCoauthorsSparklineVisContainer);
request.setAttribute("uniqueCoauthorsSparklineVisContainerID",
uniqueCoauthorsSparklineVisContainer);
request.setAttribute("title", "Person Level Visualization " + title);
request.setAttribute("portalBean", portal);
@ -391,8 +384,9 @@ public class VisualizationRequestHandler {
private void handleMalformedParameters(String errorMessage)
throws ServletException, IOException {
Portal portal = vitroRequest.getPortal();
Portal portal = super.getVitroRequest().getPortal();
HttpServletRequest request = super.getRequest();
request.setAttribute("error", errorMessage);
RequestDispatcher requestDispatcher = request.getRequestDispatcher(Controllers.BASIC_JSP);
@ -401,8 +395,9 @@ public class VisualizationRequestHandler {
request.setAttribute("title", "Visualization Query Error - Individual Publication Count");
try {
requestDispatcher.forward(request, response);
requestDispatcher.forward(request, super.getResponse());
} catch (Exception e) {
Log log = super.getLog();
log.error("EntityEditController could not forward to view.");
log.error(e.getMessage());
log.error(e.getStackTrace());

View file

@ -7,6 +7,7 @@ import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import com.hp.hpl.jena.iri.IRI;
@ -27,6 +28,7 @@ import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.BiboDocument;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Individual;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryHandler;
@ -34,11 +36,11 @@ import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Individual;
* @author cdtank
*
*/
public class QueryHandler {
public class PersonPublicationCountQueryHandler implements QueryHandler<List<BiboDocument>> {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
private String queryParam, resultFormatParam, rdfResultFormatParam;
private String queryParam;
private DataSource dataSource;
private Individual author;
@ -49,34 +51,31 @@ public class QueryHandler {
private Log log;
private static final String SPARQL_QUERY_COMMON_SELECT_CLAUSE = "" +
"SELECT (str(?authorLabel) as ?authorLabelLit) " +
" (str(?document) as ?documentLit) " +
" (str(?documentMoniker) as ?documentMonikerLit) " +
" (str(?documentLabel) as ?documentLabelLit) " +
" (str(?documentBlurb) as ?documentBlurbLit) " +
" (str(?publicationYear) as ?publicationYearLit) " +
" (str(?publicationYearMonth) as ?publicationYearMonthLit) " +
" (str(?publicationDate) as ?publicationDateLit) " +
" (str(?documentDescription) as ?documentDescriptionLit) ";
private static final String SPARQL_QUERY_COMMON_SELECT_CLAUSE = ""
+ "SELECT (str(?authorLabel) as ?authorLabelLit) "
+ " (str(?document) as ?documentLit) "
+ " (str(?documentMoniker) as ?documentMonikerLit) "
+ " (str(?documentLabel) as ?documentLabelLit) "
+ " (str(?documentBlurb) as ?documentBlurbLit) "
+ " (str(?publicationYear) as ?publicationYearLit) "
+ " (str(?publicationYearMonth) as ?publicationYearMonthLit) "
+ " (str(?publicationDate) as ?publicationDateLit) "
+ " (str(?documentDescription) as ?documentDescriptionLit) ";
private static final String SPARQL_QUERY_COMMON_WHERE_CLAUSE = "" +
"?document rdf:type bibo:Document ." +
"?document rdfs:label ?documentLabel ." +
"OPTIONAL { ?document core:year ?publicationYear } ." +
"OPTIONAL { ?document core:yearMonth ?publicationYearMonth } ." +
"OPTIONAL { ?document core:date ?publicationDate } ." +
"OPTIONAL { ?document vitro:moniker ?documentMoniker } ." +
"OPTIONAL { ?document vitro:blurb ?documentBlurb } ." +
"OPTIONAL { ?document vitro:description ?documentDescription }";
private static final String SPARQL_QUERY_COMMON_WHERE_CLAUSE = ""
+ "?document rdf:type bibo:Document ."
+ "?document rdfs:label ?documentLabel ."
+ "OPTIONAL { ?document core:year ?publicationYear } ."
+ "OPTIONAL { ?document core:yearMonth ?publicationYearMonth } ."
+ "OPTIONAL { ?document core:date ?publicationDate } ."
+ "OPTIONAL { ?document vitro:moniker ?documentMoniker } ."
+ "OPTIONAL { ?document vitro:blurb ?documentBlurb } ."
+ "OPTIONAL { ?document vitro:description ?documentDescription }";
public QueryHandler(String queryParam,
String resultFormatParam, String rdfResultFormatParam,
public PersonPublicationCountQueryHandler(String queryParam,
DataSource dataSource, Log log) {
this.queryParam = queryParam;
this.resultFormatParam = resultFormatParam;
this.rdfResultFormatParam = rdfResultFormatParam;
this.dataSource = dataSource;
this.log = log;
@ -118,7 +117,9 @@ public class QueryHandler {
biboDocument.setPublicationYear(publicationYearNode.toString());
}
RDFNode publicationYearMonthNode = solution.get(QueryFieldLabels.DOCUMENT_PUBLICATION_YEAR_MONTH);
RDFNode publicationYearMonthNode = solution.get(
QueryFieldLabels
.DOCUMENT_PUBLICATION_YEAR_MONTH);
if (publicationYearMonthNode != null) {
biboDocument.setPublicationYearMonth(publicationYearMonthNode.toString());
}
@ -149,10 +150,10 @@ public class QueryHandler {
}
private ResultSet executeQuery(String queryURI,
String resultFormatParam, String rdfResultFormatParam, DataSource dataSource) {
DataSource dataSource) {
QueryExecution queryExecution = null;
try{
try {
Query query = QueryFactory.create(generateSparqlQuery(queryURI), SYNTAX);
// QuerySolutionMap qs = new QuerySolutionMap();
@ -161,15 +162,13 @@ public class QueryHandler {
queryExecution = QueryExecutionFactory.create(query, dataSource);
//remocve this if loop after knowing what is describe & construct sparql stuff.
if( query.isSelectType() ){
if (query.isSelectType()) {
return queryExecution.execSelect();
}
} finally {
if(queryExecution != null) {
if (queryExecution != null) {
queryExecution.close();
}
}
return null;
}
@ -181,22 +180,22 @@ public class QueryHandler {
+ SPARQL_QUERY_COMMON_SELECT_CLAUSE
+ "(str(<" + queryURI + ">) as ?authPersonLit) "
+ "WHERE { "
+ "<" + queryURI + "> rdf:type foaf:Person ; rdfs:label ?authorLabel ; core:authorInAuthorship ?authorshipNode . "
+ " ?authorshipNode rdf:type core:Authorship ; core:linkedInformationResource ?document . "
+ "<" + queryURI + "> rdf:type foaf:Person ;"
+ " rdfs:label ?authorLabel ;"
+ " core:authorInAuthorship ?authorshipNode . "
+ " ?authorshipNode rdf:type core:Authorship ;"
+ " core:linkedInformationResource ?document . "
+ SPARQL_QUERY_COMMON_WHERE_CLAUSE
+ "}";
// System.out.println("SPARQL query for person pub count -> \n" + sparqlQuery);
return sparqlQuery;
}
public List<BiboDocument> getVisualizationJavaValueObjects()
throws MalformedQueryParametersException {
if(this.queryParam == null || "".equals(queryParam)) {
throw new MalformedQueryParametersException("URL parameter is either null or empty.");
} else {
if (StringUtils.isNotBlank(this.queryParam)) {
/*
* To test for the validity of the URI submitted.
@ -204,15 +203,17 @@ public class QueryHandler {
IRIFactory iRIFactory = IRIFactory.jenaImplementation();
IRI iri = iRIFactory.create(this.queryParam);
if (iri.hasViolation(false)) {
String errorMsg = ((Violation)iri.violations(false).next()).getShortMessage()+" ";
String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage();
log.error("Pub Count vis Query " + errorMsg);
throw new MalformedQueryParametersException("URI provided for an individual is malformed.");
throw new MalformedQueryParametersException(
"URI provided for an individual is malformed.");
}
} else {
throw new MalformedQueryParametersException("URL parameter is either null or empty.");
}
ResultSet resultSet = executeQuery(this.queryParam,
this.resultFormatParam,
this.rdfResultFormatParam,
this.dataSource);
return createJavaValueObjects(resultSet);
@ -238,8 +239,8 @@ public class QueryHandler {
* I am pushing the logic to check for validity of year in "getPublicationYear" itself
* because,
* 1. We will be using getPub... multiple times & this will save us duplication of code
* 2. If we change the logic of validity of a pub year we would not have to make changes
* all throughout the codebase.
* 2. If we change the logic of validity of a pub year we would not have to make
* changes all throughout the codebase.
* 3. We are asking for a publication year & we should get a proper one or NOT at all.
* */
String publicationYear;

View file

@ -28,49 +28,46 @@ import edu.cornell.mannlib.vitro.webapp.beans.Portal;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.PDFDocument;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.BiboDocument;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Individual;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.SparklineVOContainer;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.PDFDocument;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
public class VisualizationRequestHandler {
public class PersonPublicationCountRequestHandler extends VisualizationRequestHandler {
private VitroRequest vitroRequest;
private HttpServletRequest request;
private HttpServletResponse response;
private Log log;
public VisualizationRequestHandler(VitroRequest vitroRequest,
public PersonPublicationCountRequestHandler(VitroRequest vitroRequest,
HttpServletRequest request, HttpServletResponse response, Log log) {
this.vitroRequest = vitroRequest;
this.request = request;
this.response = response;
this.log = log;
super(vitroRequest, request, response, log);
}
public void generateVisualization(DataSource dataSource) {
VitroRequest vitroRequest = super.getVitroRequest();
String individualURIParam = vitroRequest.getParameter(
VisualizationFrameworkConstants
.INDIVIDUAL_URI_URL_HANDLE);
String resultFormatParam = "RS_TEXT";
String rdfResultFormatParam = "RDF/XML-ABBREV";
String individualURIParam = vitroRequest.getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_URL_HANDLE);
String renderMode = vitroRequest.getParameter(VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE);
String renderMode = vitroRequest.getParameter(
VisualizationFrameworkConstants
.RENDER_MODE_URL_HANDLE);
String visMode = vitroRequest.getParameter(VisualizationFrameworkConstants.VIS_MODE_URL_HANDLE);
String visMode = vitroRequest.getParameter(
VisualizationFrameworkConstants
.VIS_MODE_URL_HANDLE);
String visContainer = vitroRequest.getParameter(VisualizationFrameworkConstants.VIS_CONTAINER_URL_HANDLE);
String visContainer = vitroRequest.getParameter(
VisualizationFrameworkConstants
.VIS_CONTAINER_URL_HANDLE);
QueryHandler queryManager =
new QueryHandler(individualURIParam,
resultFormatParam,
rdfResultFormatParam,
Log log = super.getLog();
QueryHandler<List<BiboDocument>> queryManager =
new PersonPublicationCountQueryHandler(individualURIParam,
dataSource,
log);
@ -82,7 +79,8 @@ public class VisualizationRequestHandler {
* parsedPublicationYear to populate the data.
* */
Map<String, Integer> yearToPublicationCount =
queryManager.getYearToPublicationCount(authorDocuments);
((PersonPublicationCountQueryHandler) queryManager)
.getYearToPublicationCount(authorDocuments);
/*
* In order to avoid unneeded computations we have pushed this "if" condition up.
@ -90,16 +88,21 @@ public class VisualizationRequestHandler {
* HTML code to render sparkline, tables etc. Ideally I would want to avoid this flow.
* It is ugly!
* */
if (VisualizationFrameworkConstants.DATA_RENDER_MODE_URL_VALUE.equalsIgnoreCase(renderMode)) {
prepareVisualizationQueryDataResponse(queryManager.getAuthor(),
Individual author = ((PersonPublicationCountQueryHandler) queryManager).getAuthor();
if (VisualizationFrameworkConstants.DATA_RENDER_MODE_URL_VALUE
.equalsIgnoreCase(renderMode)) {
prepareVisualizationQueryDataResponse(author,
authorDocuments,
yearToPublicationCount);
return;
}
if (VisualizationFrameworkConstants.PDF_RENDER_MODE_URL_VALUE.equalsIgnoreCase(renderMode)) {
prepareVisualizationQueryPDFResponse(queryManager.getAuthor(),
if (VisualizationFrameworkConstants.PDF_RENDER_MODE_URL_VALUE
.equalsIgnoreCase(renderMode)) {
prepareVisualizationQueryPDFResponse(author,
authorDocuments,
yearToPublicationCount);
return;
@ -111,8 +114,8 @@ public class VisualizationRequestHandler {
SparklineVOContainer valueObjectContainer = new SparklineVOContainer();
VisualizationCodeGenerator visualizationCodeGenerator =
new VisualizationCodeGenerator(vitroRequest.getContextPath(),
PersonPublicationCountVisCodeGenerator visualizationCodeGenerator =
new PersonPublicationCountVisCodeGenerator(vitroRequest.getContextPath(),
individualURIParam,
visMode,
visContainer,
@ -127,8 +130,11 @@ public class VisualizationRequestHandler {
* a page with visualization on it.
* */
RequestDispatcher requestDispatcher = null;
if (VisualizationFrameworkConstants.DYNAMIC_RENDER_MODE_URL_VALUE.equalsIgnoreCase(renderMode)) {
HttpServletRequest request = super.getRequest();
HttpServletResponse response = super.getResponse();
if (VisualizationFrameworkConstants.DYNAMIC_RENDER_MODE_URL_VALUE
.equalsIgnoreCase(renderMode)) {
prepareVisualizationQueryDynamicResponse(request, response, vitroRequest,
valueObjectContainer, yearToPublicationCount);
@ -162,8 +168,10 @@ public class VisualizationRequestHandler {
}
private void prepareVisualizationQueryPDFResponse(Individual author, List<BiboDocument> authorDocuments,
Map<String, Integer> yearToPublicationCount) {
private void prepareVisualizationQueryPDFResponse(
Individual author,
List<BiboDocument> authorDocuments,
Map<String, Integer> yearToPublicationCount) {
String authorName = null;
@ -179,10 +187,11 @@ public class VisualizationRequestHandler {
* To make sure that null/empty records for author names do not cause any mischief.
* */
if (authorName == null) {
authorName = "";
authorName = "no";
}
String outputFileName = UtilityFunctions.slugify(authorName) + "report" + ".pdf";
String outputFileName = UtilityFunctions.slugify(authorName) + "_report" + ".pdf";
HttpServletResponse response = super.getResponse();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=" + outputFileName);
@ -197,7 +206,10 @@ public class VisualizationRequestHandler {
PdfWriter pdfWriter = PdfWriter.getInstance(document, baos);
document.open();
PDFDocument pdfDocument = new PDFDocument(authorName, yearToPublicationCount, document, pdfWriter);
PDFDocument pdfDocument = new PDFDocument(authorName,
yearToPublicationCount,
document,
pdfWriter);
document.close();
@ -218,8 +230,10 @@ public class VisualizationRequestHandler {
}
}
private void prepareVisualizationQueryDataResponse(Individual author, List<BiboDocument> authorDocuments,
Map<String, Integer> yearToPublicationCount) {
private void prepareVisualizationQueryDataResponse(
Individual author,
List<BiboDocument> authorDocuments,
Map<String, Integer> yearToPublicationCount) {
String authorName = null;
@ -235,13 +249,15 @@ public class VisualizationRequestHandler {
* To make sure that null/empty records for author names do not cause any mischief.
* */
if (authorName == null) {
authorName = "author";
authorName = "no-author";
}
String outputFileName = UtilityFunctions.slugify(authorName) + "_publications-per-year" + ".csv";
String outputFileName = UtilityFunctions.slugify(authorName)
+ "_publications-per-year" + ".csv";
HttpServletResponse response = super.getResponse();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=" + outputFileName);
response.setHeader("Content-Disposition", "attachment;filename=" + outputFileName);
try {
@ -295,8 +311,11 @@ public class VisualizationRequestHandler {
}
private void prepareVisualizationQueryDynamicResponse(HttpServletRequest request,
HttpServletResponse response, VitroRequest vreq, SparklineVOContainer valueObjectContainer,
private void prepareVisualizationQueryDynamicResponse(
HttpServletRequest request,
HttpServletResponse response,
VitroRequest vreq,
SparklineVOContainer valueObjectContainer,
Map<String, Integer> yearToPublicationCount) {
Portal portal = vreq.getPortal();
@ -317,8 +336,9 @@ public class VisualizationRequestHandler {
private void handleMalformedParameters(String errorMessage)
throws ServletException, IOException {
Portal portal = vitroRequest.getPortal();
Portal portal = super.getVitroRequest().getPortal();
HttpServletRequest request = super.getRequest();
request.setAttribute("error", errorMessage);
RequestDispatcher requestDispatcher = request.getRequestDispatcher(Controllers.BASIC_JSP);
@ -327,8 +347,9 @@ public class VisualizationRequestHandler {
request.setAttribute("title", "Visualization Query Error - Individual Publication Count");
try {
requestDispatcher.forward(request, response);
requestDispatcher.forward(request, super.getResponse());
} catch (Exception e) {
Log log = super.getLog();
log.error("EntityEditController could not forward to view.");
log.error(e.getMessage());
log.error(e.getStackTrace());

View file

@ -23,18 +23,20 @@ import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.BiboDocument;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.SparklineVOContainer;
public class VisualizationCodeGenerator {
public class PersonPublicationCountVisCodeGenerator {
private final static Map<String, String> visDivNames = new HashMap<String, String>() {{
private static final int MINIMUM_YEARS_CONSIDERED = 10;
private static final Map<String, String> VIS_DIV_NAMES = new HashMap<String, String>() { {
put("SHORT_SPARK", "pub_count_short_sparkline_vis");
put("FULL_SPARK", "pub_count_full_sparkline_vis");
}};
} };
private static final String visualizationStyleClass = "sparkline_style";
private static final String VISUALIZATION_STYLE_CLASS = "sparkline_style";
private static final String defaultVisContainerDivID = "pub_count_vis_container";
private static final String DEFAULT_VIS_CONTAINER_DIV_ID = "pub_count_vis_container";
public static final String SHORT_SPARKLINE_MODE_URL_HANDLE = "short";
@ -50,7 +52,7 @@ public class VisualizationCodeGenerator {
private String individualURIParam;
public VisualizationCodeGenerator(String contextPath,
public PersonPublicationCountVisCodeGenerator(String contextPath,
String individualURIParam,
String visMode,
String visContainer,
@ -94,7 +96,7 @@ public class VisualizationCodeGenerator {
int numOfYearsToBeRendered = 0;
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int shortSparkMinYear = currentYear - 10 + 1;
int shortSparkMinYear = currentYear - MINIMUM_YEARS_CONSIDERED + 1;
/*
* This is required because when deciding the range of years over which the vis
@ -114,14 +116,15 @@ public class VisualizationCodeGenerator {
StringBuilder visualizationCode = new StringBuilder();
// System.out.println(yearToPublicationCount);
if (yearToPublicationCount.size() > 0) {
try {
minPublishedYear = Integer.parseInt(Collections.min(publishedYears));
} catch (NoSuchElementException e1) {
log.debug("vis: " + e1.getMessage() + " error occurred for " + yearToPublicationCount.toString());
log.debug("vis: " + e1.getMessage() + " error occurred for "
+ yearToPublicationCount.toString());
} catch (NumberFormatException e2) {
log.debug("vis: " + e2.getMessage() + " error occurred for " + yearToPublicationCount.toString());
log.debug("vis: " + e2.getMessage() + " error occurred for "
+ yearToPublicationCount.toString());
}
}
@ -141,64 +144,45 @@ public class VisualizationCodeGenerator {
numOfYearsToBeRendered = currentYear - minPubYearConsidered + 1;
visualizationCode.append("<style type='text/css'>" +
"." + visualizationStyleClass + " table{" +
" margin: 0;" +
" padding: 0;" +
" width: auto;" +
" border-collapse: collapse;" +
" border-spacing: 0;" +
" vertical-align: inherit;" +
"}" +
"table.sparkline_wrapper_table td, th {" +
" vertical-align: bottom;" +
"}" +
".vis_link a{" +
" padding-top: 5px;" +
"}" +
"td.sparkline_number { text-align:right; padding-right:5px; }" +
"td.sparkline_text {text-align:left;}" +
".incomplete-data-holder {" +
"" +
"}" +
/*"#sparkline_data_table {" +
"width: auto;" +
"}" +
"#sparkline_data_table tfoot {" +
"color: red;" +
"font-size:0.9em;" +
"}" +
".sparkline_text {" +
"margin-left:72px;" +
"position:absolute;" +
"}" +
".sparkline_range {" +
"color:#7BA69E;" +
"font-size:0.9em;" +
"font-style:italic;" +
"}" +*/
"</style>\n");
visualizationCode.append("<style type='text/css'>"
+ "." + VISUALIZATION_STYLE_CLASS + " table{"
+ " margin: 0;"
+ " padding: 0;"
+ " width: auto;"
+ " border-collapse: collapse;"
+ " border-spacing: 0;"
+ " vertical-align: inherit;"
+ "}"
+ "table.sparkline_wrapper_table td, th {"
+ " vertical-align: bottom;"
+ "}"
+ ".vis_link a{"
+ " padding-top: 5px;"
+ "}"
+ "td.sparkline_number { text-align:right; "
+ "padding-right:5px; }"
+ "td.sparkline_text {text-align:left;}"
+ ".incomplete-data-holder {"
+ ""
+ "}"
+ "</style>\n");
// .sparkline {display:inline; margin:0; padding:0; width:600px }
// td.sparkline-img {margin:0; padding:0; }
visualizationCode.append("<script type=\"text/javascript\">\n" +
"function drawPubCountVisualization(providedSparklineImgTD) {\n" +
"var data = new google.visualization.DataTable();\n" +
"data.addColumn('string', 'Year');\n" +
"data.addColumn('number', 'Publications');\n" +
"data.addRows(" + numOfYearsToBeRendered + ");\n");
visualizationCode.append("<script type=\"text/javascript\">\n"
+ "function drawPubCountVisualization(providedSparklineImgTD) "
+ "{\n"
+ "var data = new google.visualization.DataTable();\n"
+ "data.addColumn('string', 'Year');\n"
+ "data.addColumn('number', 'Publications');\n"
+ "data.addRows(" + numOfYearsToBeRendered + ");\n");
int publicationCounter = 0;
int totalPublications = 0;
int renderedFullSparks = 0;
for (int publicationYear = minPubYearConsidered; publicationYear <= currentYear; publicationYear++) {
for (int publicationYear = minPubYearConsidered;
publicationYear <= currentYear;
publicationYear++) {
String stringPublishedYear = String.valueOf(publicationYear);
Integer currentPublications = yearToPublicationCount.get(stringPublishedYear);
@ -236,16 +220,17 @@ public class VisualizationCodeGenerator {
Integer unknownYearPublications = 0;
if (yearToPublicationCount.get(VOConstants.DEFAULT_PUBLICATION_YEAR) != null) {
totalPublications += yearToPublicationCount.get(VOConstants.DEFAULT_PUBLICATION_YEAR);
unknownYearPublications = yearToPublicationCount.get(VOConstants.DEFAULT_PUBLICATION_YEAR);
unknownYearPublications = yearToPublicationCount
.get(VOConstants.DEFAULT_PUBLICATION_YEAR);
}
String sparklineDisplayOptions = "{width: 63, height: 21, showAxisLines: false, " +
"showValueLabels: false, labelPosition: 'none'}";
String sparklineDisplayOptions = "{width: 63, height: 21, showAxisLines: false, "
+ "showValueLabels: false, labelPosition: 'none'}";
if (providedVisContainerID != null) {
visContainerID = providedVisContainerID;
} else {
visContainerID = defaultVisContainerDivID;
visContainerID = DEFAULT_VIS_CONTAINER_DIV_ID;
}
@ -265,8 +250,8 @@ public class VisualizationCodeGenerator {
/*
* Since building StringBuilder objects (which is being used to store the vis code) is
* essentially a side-effecting process, we have both the activators method as side-effecting.
* They both side-effect "visualizationCode"
* essentially a side-effecting process, we have both the activators method as side-
* effecting. They both side-effect "visualizationCode"
* */
if (SHORT_SPARKLINE_MODE_URL_HANDLE.equalsIgnoreCase(visMode)) {
@ -276,7 +261,6 @@ public class VisualizationCodeGenerator {
visContainerID,
visualizationCode,
unknownYearPublications,
totalPublications,
sparklineDisplayOptions);
} else {
generateFullSparklineVisualizationContent(currentYear,
@ -284,100 +268,98 @@ public class VisualizationCodeGenerator {
visContainerID,
visualizationCode,
unknownYearPublications,
totalPublications,
renderedFullSparks,
sparklineDisplayOptions);
}
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
log.debug(visualizationCode);
// System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return visualizationCode.toString();
}
private void generateShortSparklineVisualizationContent(int currentYear,
int shortSparkMinYear, String visContainerID,
StringBuilder visualizationCode, int unknownYearPublications,
int totalPublications, String sparklineDisplayOptions) {
int shortSparkMinYear,
String visContainerID,
StringBuilder visualizationCode,
int unknownYearPublications,
String sparklineDisplayOptions) {
/*
* Create a view of the data containing only the column pertaining to publication count.
* */
visualizationCode.append("var shortSparklineView = new google.visualization.DataView(data);\n" +
"shortSparklineView.setColumns([1]);\n");
visualizationCode.append("var shortSparklineView = "
+ "new google.visualization.DataView(data);\n"
+ "shortSparklineView.setColumns([1]);\n");
/*
* For the short view we only want the last 10 year's view of publication count,
* hence we filter the data we actually want to use for render.
* */
visualizationCode.append("shortSparklineView.setRows(" +
"data.getFilteredRows([{column: 0, " +
"minValue: '" + shortSparkMinYear + "', " +
"maxValue: '" + currentYear+ "'}])" +
");\n");
visualizationCode.append("shortSparklineView.setRows("
+ "data.getFilteredRows([{column: 0, "
+ "minValue: '" + shortSparkMinYear + "', "
+ "maxValue: '" + currentYear + "'}])"
+ ");\n");
/*
* Create the vis object and draw it in the div pertaining to short-sparkline.
* */
visualizationCode.append("var short_spark = new google.visualization.ImageSparkLine(" +
// "document.getElementById('" + visDivNames.get("SHORT_SPARK") + "')" +
"providedSparklineImgTD[0]" +
");\n" +
"short_spark.draw(shortSparklineView, " + sparklineDisplayOptions + ");\n");
visualizationCode.append("var short_spark = new google.visualization.ImageSparkLine("
+ "providedSparklineImgTD[0]"
+ ");\n"
+ "short_spark.draw(shortSparklineView, "
+ sparklineDisplayOptions + ");\n");
/*
* We want to display how many publication counts were considered, so this is used
* to calculate this.
* */
visualizationCode.append("var shortSparkRows = shortSparklineView.getViewRows();\n" +
"var renderedShortSparks = 0;\n" +
"$.each(shortSparkRows, function(index, value) {" +
"renderedShortSparks += data.getValue(value, 1);" +
"});\n");
visualizationCode.append("var shortSparkRows = shortSparklineView.getViewRows();\n"
+ "var renderedShortSparks = 0;\n"
+ "$.each(shortSparkRows, function(index, value) {"
+ "renderedShortSparks += data.getValue(value, 1);"
+ "});\n");
/*
* Generate the text introducing the vis.
* */
String imcompleteDataText = "This information is based solely on publications which have been loaded into the VIVO system. " +
"This may only be a small sample of the person\\'s total work.";
String imcompleteDataText = "This information is based solely on publications which "
+ "have been loaded into the VIVO system. "
+ "This may only be a small sample of the person\\'s "
+ "total work.";
visualizationCode.append("$('#" + visDivNames.get("SHORT_SPARK") + " td.sparkline_number').text(parseInt(renderedShortSparks) + parseInt(" + unknownYearPublications + "));");
visualizationCode.append("var shortSparksText = ''" +
"+ ' publication(s) within the last 10 years " +
"<span class=\"incomplete-data-holder\" title=\"" + imcompleteDataText + "\">incomplete data</span>'" +
/*"+ ' " + totalPublications + " '" +
"+ ' total " +
"<span class=\"sparkline_range\">" +
"(" + shortSparkMinYear + " - " + currentYear + ")" +
"</span>'" +*/
"+ '';" +
"$('#" + visDivNames.get("SHORT_SPARK") + " td.sparkline_text').html(shortSparksText);");
visualizationCode.append("$('#" + VIS_DIV_NAMES.get("SHORT_SPARK")
+ " td.sparkline_number').text("
+ "parseInt(renderedShortSparks) "
+ "+ parseInt(" + unknownYearPublications + "));");
visualizationCode.append("var shortSparksText = ''"
+ "+ ' publication(s) within the last 10 years "
+ "<span class=\"incomplete-data-holder\" title=\""
+ imcompleteDataText + "\">incomplete data</span>'"
+ "+ '';"
+ "$('#" + VIS_DIV_NAMES.get("SHORT_SPARK") + " "
+ "td.sparkline_text').html(shortSparksText);");
visualizationCode.append("}\n ");
/*
* Generate the code that will activate the visualization. It takes care of creating div elements to hold
* the actual sparkline image and then calling the drawPubCountVisualization function.
* Generate the code that will activate the visualization. It takes care of creating
* div elements to hold the actual sparkline image and then calling the
* drawPubCountVisualization function.
* */
visualizationCode.append(generateVisualizationActivator(visDivNames.get("SHORT_SPARK"), visContainerID));
visualizationCode.append(generateVisualizationActivator(VIS_DIV_NAMES.get("SHORT_SPARK"),
visContainerID));
}
private void generateFullSparklineVisualizationContent(
int currentYear, int minPubYearConsidered, String visContainerID,
int currentYear,
int minPubYearConsidered,
String visContainerID,
StringBuilder visualizationCode,
int unknownYearPublications,
int totalPublications, int renderedFullSparks,
int renderedFullSparks,
String sparklineDisplayOptions) {
String csvDownloadURLHref = "";
@ -385,7 +367,8 @@ public class VisualizationCodeGenerator {
try {
if (getCSVDownloadURL() != null) {
csvDownloadURLHref = "<a href=\"" + getCSVDownloadURL() + "\" class=\"inline_href\">(.CSV File)</a>";
csvDownloadURLHref = "<a href=\"" + getCSVDownloadURL()
+ "\" class=\"inline_href\">(.CSV File)</a>";
} else {
@ -398,86 +381,85 @@ public class VisualizationCodeGenerator {
}
visualizationCode.append("var fullSparklineView = new google.visualization.DataView(data);\n" +
"fullSparklineView.setColumns([1]);\n");
visualizationCode.append("var fullSparklineView = "
+ "new google.visualization.DataView(data);\n"
+ "fullSparklineView.setColumns([1]);\n");
visualizationCode.append("var full_spark = new google.visualization.ImageSparkLine(" +
// "document.getElementById('" + visDivNames.get("FULL_SPARK") + "')" +
"providedSparklineImgTD[0]" +
");\n" +
"full_spark.draw(fullSparklineView, " + sparklineDisplayOptions + ");\n");
visualizationCode.append("var full_spark = new google.visualization.ImageSparkLine("
+ "providedSparklineImgTD[0]"
+ ");\n"
+ "full_spark.draw(fullSparklineView, "
+ sparklineDisplayOptions + ");\n");
visualizationCode.append("$('#" + visDivNames.get("FULL_SPARK") + " td.sparkline_number').text('" + (renderedFullSparks + unknownYearPublications) + "');");
visualizationCode.append("$('#" + VIS_DIV_NAMES.get("FULL_SPARK")
+ " td.sparkline_number').text('" + (renderedFullSparks
+ unknownYearPublications) + "');");
visualizationCode.append("var allSparksText = ''" +
"+ ' publication(s) '" +
/*"+ ' " + totalPublications + " '" +*/
"+ ' from " +
"<span class=\"sparkline_range\">" +
"" + minPubYearConsidered + " to " + currentYear + "" +
"</span> '" +
"+ ' " + csvDownloadURLHref + " ';" +
"$('#" + visDivNames.get("FULL_SPARK") + " td.sparkline_text').html(allSparksText);");
visualizationCode.append("var allSparksText = ''"
+ "+ ' publication(s) '"
+ "+ ' from "
+ "<span class=\"sparkline_range\">"
+ "" + minPubYearConsidered + " to " + currentYear + ""
+ "</span> '"
+ "+ ' " + csvDownloadURLHref + " ';"
+ "$('#" + VIS_DIV_NAMES.get("FULL_SPARK")
+ " td.sparkline_text').html(allSparksText);");
visualizationCode.append("}\n ");
visualizationCode.append(generateVisualizationActivator(visDivNames.get("FULL_SPARK"), visContainerID));
visualizationCode.append(generateVisualizationActivator(VIS_DIV_NAMES.get("FULL_SPARK"),
visContainerID));
}
private String generateVisualizationActivator(String sparklineID, String visContainerID) {
String sparklineTableWrapper = "\n" +
"var table = $('<table>');" +
"table.attr('class', 'sparkline_wrapper_table');" +
"var row = $('<tr>');" +
"sparklineImgTD = $('<td>');" +
"sparklineImgTD.attr('id', '" + sparklineID + "_img');" +
"sparklineImgTD.attr('width', '65');" +
"sparklineImgTD.attr('align', 'right');" +
"sparklineImgTD.attr('class', '" + visualizationStyleClass + "');" +
"row.append(sparklineImgTD);" +
"var sparklineNumberTD = $('<td>');" +
"sparklineNumberTD.attr('width', '30');" +
"sparklineNumberTD.attr('align', 'right');" +
"sparklineNumberTD.attr('class', 'sparkline_number');" +
"row.append(sparklineNumberTD);" +
"var sparklineTextTD = $('<td>');" +
"sparklineTextTD.attr('width', '350');" +
"sparklineTextTD.attr('class', 'sparkline_text');" +
"row.append(sparklineTextTD);" +
"table.append(row);" +
"table.prependTo('#" + sparklineID + "');\n";
String sparklineTableWrapper = "\n"
+ "var table = $('<table>');"
+ "table.attr('class', 'sparkline_wrapper_table');"
+ "var row = $('<tr>');"
+ "sparklineImgTD = $('<td>');"
+ "sparklineImgTD.attr('id', '" + sparklineID + "_img');"
+ "sparklineImgTD.attr('width', '65');"
+ "sparklineImgTD.attr('align', 'right');"
+ "sparklineImgTD.attr('class', '" + VISUALIZATION_STYLE_CLASS + "');"
+ "row.append(sparklineImgTD);"
+ "var sparklineNumberTD = $('<td>');"
+ "sparklineNumberTD.attr('width', '30');"
+ "sparklineNumberTD.attr('align', 'right');"
+ "sparklineNumberTD.attr('class', 'sparkline_number');"
+ "row.append(sparklineNumberTD);"
+ "var sparklineTextTD = $('<td>');"
+ "sparklineTextTD.attr('width', '350');"
+ "sparklineTextTD.attr('class', 'sparkline_text');"
+ "row.append(sparklineTextTD);"
+ "table.append(row);"
+ "table.prependTo('#" + sparklineID + "');\n";
return "$(document).ready(function() {" +
"var sparklineImgTD; " +
return "$(document).ready(function() {"
+ "var sparklineImgTD; "
/*
* This is a nuclear option (creating the container in which everything goes)
* the only reason this will be ever used is the API user never submitted a
* container ID in which everything goes. The alternative was to let the
* vis not appear in the calling page at all. So now atleast vis appears but
* appended at the bottom of the body.
* */
"if ($('#" + visContainerID + "').length === 0) {" +
" $('<div/>', {'id': '" + visContainerID + "'" +
" }).appendTo('body');" +
"}" +
"if ($('#" + sparklineID + "').length === 0) {" +
"$('<div/>', {'id': '" + sparklineID + "'," +
"'class': '" + visualizationStyleClass + "'" +
"}).prependTo('#" + visContainerID + "');" +
sparklineTableWrapper +
"}" +
"drawPubCountVisualization(sparklineImgTD);" +
"});" +
"</script>\n";
/*
* This is a nuclear option (creating the container in which everything goes)
* the only reason this will be ever used is the API user never submitted a
* container ID in which everything goes. The alternative was to let the
* vis not appear in the calling page at all. So now atleast vis appears but
* appended at the bottom of the body.
* */
+ "if ($('#" + visContainerID + "').length === 0) {"
+ " $('<div/>', {'id': '" + visContainerID + "'"
+ " }).appendTo('body');"
+ "}"
+ "if ($('#" + sparklineID + "').length === 0) {"
+ "$('<div/>', {'id': '" + sparklineID + "',"
+ "'class': '" + VISUALIZATION_STYLE_CLASS + "'"
+ "}).prependTo('#" + visContainerID + "');"
+ sparklineTableWrapper
+ "}"
+ "drawPubCountVisualization(sparklineImgTD);"
+ "});"
+ "</script>\n";
}
private String getVisualizationContextCode(String visMode) {
@ -505,7 +487,8 @@ public class VisualizationCodeGenerator {
try {
if (getCSVDownloadURL() != null) {
csvDownloadURLHref = "Download data as <a href='" + getCSVDownloadURL() + "'>.csv</a> file.<br />";
csvDownloadURLHref = "Download data as <a href='"
+ getCSVDownloadURL() + "'>.csv</a> file.<br />";
valueObjectContainer.setDownloadDataLink(getCSVDownloadURL());
} else {
@ -525,8 +508,7 @@ public class VisualizationCodeGenerator {
String tableCode = generateDataTable();
divContextCode.append("<p>" + tableCode +
csvDownloadURLHref + "</p>");
divContextCode.append("<p>" + tableCode + csvDownloadURLHref + "</p>");
valueObjectContainer.setTable(tableCode);
@ -549,23 +531,25 @@ public class VisualizationCodeGenerator {
+ secondaryContextPath
+ "?" + VisualizationFrameworkConstants.INDIVIDUAL_URI_URL_HANDLE
+ "=" + URLEncoder.encode(individualURIParam,
VisualizationController.URL_ENCODING_SCHEME).toString()
VisualizationController.URL_ENCODING_SCHEME)
.toString()
+ "&" + VisualizationFrameworkConstants.VIS_TYPE_URL_HANDLE
+ "=" + URLEncoder.encode(VisualizationController
.PERSON_PUBLICATION_COUNT_VIS_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME).toString()
+ "=" + URLEncoder.encode(
VisualizationController
.PERSON_PUBLICATION_COUNT_VIS_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME)
.toString()
+ "&" + VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE
+ "=" + URLEncoder.encode(VisualizationFrameworkConstants.DATA_RENDER_MODE_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME).toString();
// System.out.println(" ----- >>>> " + contextPath + " XX " + individualURIParam + " XX " + downloadURL);
+ "=" + URLEncoder.encode(VisualizationFrameworkConstants
.DATA_RENDER_MODE_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME)
.toString();
return downloadURL;
} else {
return null;
}
}
private String generateShortVisContext() {
StringBuilder divContextCode = new StringBuilder();
@ -592,10 +576,12 @@ public class VisualizationCodeGenerator {
VisualizationController.URL_ENCODING_SCHEME).toString()
+ "&"
+ VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE
+ "=" + URLEncoder.encode(VisualizationFrameworkConstants.STANDALONE_RENDER_MODE_URL_VALUE,
+ "=" + URLEncoder.encode(VisualizationFrameworkConstants
.STANDALONE_RENDER_MODE_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME).toString();
fullTimelineLink = "<a href='" + fullTimelineNetworkURL + "'>View all VIVO publications and corresponding co-author network</a>.<br />";
fullTimelineLink = "<a href='" + fullTimelineNetworkURL + "'>View all VIVO "
+ "publications and corresponding co-author network</a>.<br />";
valueObjectContainer.setFullTimelineNetworkLink(fullTimelineNetworkURL);
@ -608,14 +594,13 @@ public class VisualizationCodeGenerator {
divContextCode.append("<span class=\"vis_link\">" + fullTimelineLink + "</span>");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
log.error(e);
}
return divContextCode.toString();
}
private String generateDataTable() {
String csvDownloadURLHref = "";
@ -637,26 +622,24 @@ public class VisualizationCodeGenerator {
StringBuilder dataTable = new StringBuilder();
dataTable.append("<table id='sparkline_data_table'>" +
"<caption>Publications per year " + csvDownloadURLHref + "</caption>" +
"<thead>" +
"<tr>" +
"<th>Year</th>" +
"<th>Publications</th>" +
"</tr>" +
"</thead>" +
"<tbody>");
dataTable.append("<table id='sparkline_data_table'>"
+ "<caption>Publications per year " + csvDownloadURLHref + "</caption>"
+ "<thead>"
+ "<tr>"
+ "<th>Year</th>"
+ "<th>Publications</th>"
+ "</tr>"
+ "</thead>"
+ "<tbody>");
for (Entry<String, Integer> currentEntry : yearToPublicationCount.entrySet()) {
dataTable.append("<tr>" +
"<td>" + currentEntry.getKey() + "</td>" +
"<td>" + currentEntry.getValue() + "</td>" +
"</tr>");
dataTable.append("<tr>"
+ "<td>" + currentEntry.getKey() + "</td>"
+ "<td>" + currentEntry.getValue() + "</td>"
+ "</tr>");
}
dataTable.append("</tbody>\n" +
"</table>\n");
dataTable.append("</tbody>\n </table>\n");
return dataTable.toString();
}

View file

@ -33,69 +33,64 @@ import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryP
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.GenericQueryMap;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.AllPropertiesQueryHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.GenericQueryHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryHandler;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
public class VisualizationRequestHandler {
public class UtilitiesRequestHandler extends VisualizationRequestHandler {
private VitroRequest vitroRequest;
private HttpServletRequest request;
private HttpServletResponse response;
private Log log;
public VisualizationRequestHandler(VitroRequest vitroRequest,
public UtilitiesRequestHandler(VitroRequest vitroRequest,
HttpServletRequest request, HttpServletResponse response, Log log) {
this.vitroRequest = vitroRequest;
this.request = request;
this.response = response;
this.log = log;
super(vitroRequest, request, response, log);
}
public void generateVisualization(DataSource dataSource) {
String individualURIParam = vitroRequest.getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_URL_HANDLE);
VitroRequest vitroRequest = super.getVitroRequest();
String individualURIParam = vitroRequest.getParameter(
VisualizationFrameworkConstants
.INDIVIDUAL_URI_URL_HANDLE);
String visMode = vitroRequest.getParameter(VisualizationFrameworkConstants.VIS_MODE_URL_HANDLE);
String visMode = vitroRequest.getParameter(VisualizationFrameworkConstants
.VIS_MODE_URL_HANDLE);
String profileInfoMode = "PROFILE_INFO";
String profileVisMode = "PROFILE_URL";
String coAuthorVisMode = "COAUTHORSHIP_URL";
String personLevelVisMode = "PERSON_LEVEL_URL";
String imageVisMode = "IMAGE_URL";
String resultFormatParam = "RS_TEXT";
String rdfResultFormatParam = "RDF/XML-ABBREV";
String preparedURL = "";
Log log = super.getLog();
HttpServletRequest request = super.getRequest();
try {
/*
* If the info being requested is about a profile which includes the name, moniker
* & image url.
* */
if (profileInfoMode.equalsIgnoreCase(visMode)) {
if (VisualizationFrameworkConstants.PROFILE_INFO_UTILS_VIS_MODE
.equalsIgnoreCase(visMode)) {
String filterRule = "?predicate = j.2:mainImage || ?predicate = vitro:moniker || ?predicate = rdfs:label";
AllPropertiesQueryHandler profileQueryHandler = new AllPropertiesQueryHandler(individualURIParam,
filterRule,
resultFormatParam,
rdfResultFormatParam,
dataSource,
log);
String filterRule = "?predicate = j.2:mainImage "
+ "|| ?predicate = vitro:moniker "
+ "|| ?predicate = rdfs:label";
QueryHandler<GenericQueryMap> profileQueryHandler =
new AllPropertiesQueryHandler(individualURIParam,
filterRule,
dataSource,
log);
try {
GenericQueryMap profilePropertiesToValues = profileQueryHandler.getJavaValueObjects();
GenericQueryMap profilePropertiesToValues =
profileQueryHandler.getVisualizationJavaValueObjects();
profilePropertiesToValues.addEntry("imageContextPath", request.getContextPath());
profilePropertiesToValues.addEntry("imageContextPath",
request.getContextPath());
Gson profileInformation = new Gson();
prepareVisualizationQueryResponse(profileInformation.toJson(profilePropertiesToValues));
prepareVisualizationQueryResponse(profileInformation
.toJson(profilePropertiesToValues));
return;
@ -112,36 +107,39 @@ public class VisualizationRequestHandler {
}
} else if (imageVisMode.equalsIgnoreCase(visMode)) {
} else if (VisualizationFrameworkConstants.IMAGE_UTILS_VIS_MODE
.equalsIgnoreCase(visMode)) {
/*
* If the url being requested is about a standalone image, which is used when we want
* to render an image & other info for a co-author OR ego for that matter.
* If the url being requested is about a standalone image, which is used when we
* want to render an image & other info for a co-author OR ego for that matter.
* */
Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
fieldLabelToOutputFieldLabel.put("downloadLocation", QueryFieldLabels.THUMBNAIL_LOCATION_URL);
fieldLabelToOutputFieldLabel.put("downloadLocation",
QueryFieldLabels.THUMBNAIL_LOCATION_URL);
fieldLabelToOutputFieldLabel.put("fileName", QueryFieldLabels.THUMBNAIL_FILENAME);
String whereClause = "<" + individualURIParam + "> j.2:thumbnailImage ?thumbnailImage . "
+ "?thumbnailImage j.2:downloadLocation ?downloadLocation ; j.2:filename ?fileName .";
String whereClause = "<" + individualURIParam
+ "> j.2:thumbnailImage ?thumbnailImage . "
+ "?thumbnailImage j.2:downloadLocation "
+ "?downloadLocation ; j.2:filename ?fileName .";
GenericQueryHandler imageQueryHandler = new GenericQueryHandler(individualURIParam,
fieldLabelToOutputFieldLabel,
whereClause,
resultFormatParam,
rdfResultFormatParam,
dataSource,
log);
QueryHandler<ResultSet> imageQueryHandler =
new GenericQueryHandler(individualURIParam,
fieldLabelToOutputFieldLabel,
whereClause,
dataSource,
log);
try {
String thumbnailAccessURL = getThumbnailInformation(
imageQueryHandler.getResultSet(),
fieldLabelToOutputFieldLabel);
String thumbnailAccessURL =
getThumbnailInformation(
imageQueryHandler.getVisualizationJavaValueObjects(),
fieldLabelToOutputFieldLabel);
// System.out.println("thumbnail access URL " + thumbnailAccessURL);
prepareVisualizationQueryResponse(thumbnailAccessURL);
return;
@ -158,10 +156,11 @@ public class VisualizationRequestHandler {
}
} else if (coAuthorVisMode.equalsIgnoreCase(visMode)) {
} else if (VisualizationFrameworkConstants.COAUTHOR_UTILS_VIS_MODE
.equalsIgnoreCase(visMode)) {
/*
* By default we will be generating profile url else some specific url like coAuthorShip vis
* url for that individual.
* By default we will be generating profile url else some specific url like
* coAuthorShip vis url for that individual.
* */
preparedURL += request.getContextPath()
@ -176,17 +175,20 @@ public class VisualizationRequestHandler {
VisualizationController.URL_ENCODING_SCHEME).toString()
+ "&"
+ VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE
+ "=" + URLEncoder.encode(VisualizationFrameworkConstants.STANDALONE_RENDER_MODE_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME).toString();
+ "=" + URLEncoder.encode(VisualizationFrameworkConstants
.STANDALONE_RENDER_MODE_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME)
.toString();
prepareVisualizationQueryResponse(preparedURL);
return;
} else if (personLevelVisMode.equalsIgnoreCase(visMode)) {
} else if (VisualizationFrameworkConstants.PERSON_LEVEL_UTILS_VIS_MODE
.equalsIgnoreCase(visMode)) {
/*
* By default we will be generating profile url else some specific url like coAuthorShip vis
* url for that individual.
* By default we will be generating profile url else some specific url like
* coAuthorShip vis url for that individual.
* */
preparedURL += request.getContextPath()
@ -201,7 +203,8 @@ public class VisualizationRequestHandler {
VisualizationController.URL_ENCODING_SCHEME).toString()
+ "&"
+ VisualizationFrameworkConstants.RENDER_MODE_URL_HANDLE
+ "=" + URLEncoder.encode(VisualizationFrameworkConstants.STANDALONE_RENDER_MODE_URL_VALUE,
+ "=" + URLEncoder.encode(VisualizationFrameworkConstants
.STANDALONE_RENDER_MODE_URL_VALUE,
VisualizationController.URL_ENCODING_SCHEME).toString();
prepareVisualizationQueryResponse(preparedURL);
@ -227,8 +230,8 @@ public class VisualizationRequestHandler {
}
private String getThumbnailInformation(ResultSet resultSet,
Map<String, String> fieldLabelToOutputFieldLabel) {
private String getThumbnailInformation(ResultSet resultSet,
Map<String, String> fieldLabelToOutputFieldLabel) {
String finalThumbNailLocation = "";
@ -236,13 +239,16 @@ public class VisualizationRequestHandler {
QuerySolution solution = resultSet.nextSolution();
RDFNode downloadLocationNode = solution.get(fieldLabelToOutputFieldLabel.get("downloadLocation"));
RDFNode downloadLocationNode = solution.get(
fieldLabelToOutputFieldLabel
.get("downloadLocation"));
RDFNode fileNameNode = solution.get(fieldLabelToOutputFieldLabel.get("fileName"));
if (downloadLocationNode != null && fileNameNode != null) {
finalThumbNailLocation = FileServingHelper
.getBytestreamAliasUrl(downloadLocationNode.toString(),
fileNameNode.toString());
finalThumbNailLocation =
FileServingHelper
.getBytestreamAliasUrl(downloadLocationNode.toString(),
fileNameNode.toString());
}
}
@ -252,11 +258,11 @@ public class VisualizationRequestHandler {
private void prepareVisualizationQueryResponse(String preparedURL) {
response.setContentType("text/plain");
super.getResponse().setContentType("text/plain");
try {
PrintWriter responseWriter = response.getWriter();
PrintWriter responseWriter = super.getResponse().getWriter();
responseWriter.append(preparedURL);
@ -270,8 +276,9 @@ public class VisualizationRequestHandler {
private void handleMalformedParameters(String errorMessage)
throws ServletException, IOException {
Portal portal = vitroRequest.getPortal();
Portal portal = super.getVitroRequest().getPortal();
HttpServletRequest request = super.getRequest();
request.setAttribute("error", errorMessage);
RequestDispatcher requestDispatcher = request.getRequestDispatcher(Controllers.BASIC_JSP);
@ -280,8 +287,9 @@ public class VisualizationRequestHandler {
request.setAttribute("title", "Visualization Query Error - Individual Publication Count");
try {
requestDispatcher.forward(request, response);
requestDispatcher.forward(request, super.getResponse());
} catch (Exception e) {
Log log = super.getLog();
log.error("EntityEditController could not forward to view.");
log.error(e.getMessage());
log.error(e.getStackTrace());

View file

@ -12,8 +12,9 @@ import edu.cornell.mannlib.vitro.webapp.visualization.constants.VOConstants;
* @author cdtank
*
*/
public class BiboDocument extends Individual{
public class BiboDocument extends Individual {
private static final int NUM_CHARS_IN_YEAR_FORMAT = 4;
public static final int MINIMUM_PUBLICATION_YEAR = 1800;
private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR);
@ -116,18 +117,20 @@ public class BiboDocument extends Individual{
* core:yearMonth points to internally.
* */
if (publicationYearMonth != null
&& publicationYearMonth.length() >= 4
&& isValidPublicationYear(publicationYearMonth.substring(0, 4))) {
&& publicationYearMonth.length() >= NUM_CHARS_IN_YEAR_FORMAT
&& isValidPublicationYear(publicationYearMonth.substring(
0,
NUM_CHARS_IN_YEAR_FORMAT))) {
return publicationYearMonth.substring(0, 4);
return publicationYearMonth.substring(0, NUM_CHARS_IN_YEAR_FORMAT);
}
if (publicationDate != null
&& publicationDate.length() >= 4
&& isValidPublicationYear(publicationDate.substring(0, 4))) {
&& publicationDate.length() >= NUM_CHARS_IN_YEAR_FORMAT
&& isValidPublicationYear(publicationDate.substring(0, NUM_CHARS_IN_YEAR_FORMAT))) {
return publicationDate.substring(0, 4);
return publicationDate.substring(0, NUM_CHARS_IN_YEAR_FORMAT);
}
/*
@ -137,8 +140,8 @@ public class BiboDocument extends Individual{
}
/*
* This publicationYear value is directly from the data supported by the ontology. If this is empty only
* then use the parsedPublicationYear.
* This publicationYear value is directly from the data supported by the ontology.
* If this is empty only then use the parsedPublicationYear.
* */
public String getPublicationYear() {
if (publicationYear != null && isValidPublicationYear(publicationYear)) {
@ -172,7 +175,7 @@ public class BiboDocument extends Individual{
private boolean isValidPublicationYear(String testPublicationYear) {
if (testPublicationYear.length() != 0
&& testPublicationYear.trim().length() == 4
&& testPublicationYear.trim().length() == NUM_CHARS_IN_YEAR_FORMAT
&& testPublicationYear.matches("\\d+")
&& Integer.parseInt(testPublicationYear) >= MINIMUM_PUBLICATION_YEAR) {
return true;

View file

@ -1,16 +1,14 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.visualization.coauthorship;
package edu.cornell.mannlib.vitro.webapp.visualization.valueobjects;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Edge;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Node;
public class VisVOContainer {
public class CoAuthorshipVOContainer {
private Set<Node> nodes;
private Set<Edge> edges;
@ -18,7 +16,7 @@ public class VisVOContainer {
private Set<Map<String, String>> NODE_SCHEMA;
private Set<Map<String, String>> EDGE_SCHEMA;
public VisVOContainer(Node egoNode, Set<Node> nodes, Set<Edge> edges) {
public CoAuthorshipVOContainer(Node egoNode, Set<Node> nodes, Set<Edge> edges) {
this.egoNode = egoNode;
this.nodes = nodes;
this.edges = edges;
@ -62,7 +60,7 @@ public class VisVOContainer {
private Set<Map<String, String>> initializeEdgeSchema() {
Set<Map<String, String>> edgeSchema = new HashSet<Map<String,String>>();
Set<Map<String, String>> edgeSchema = new HashSet<Map<String, String>>();
Map<String, String> schemaAttributes = new LinkedHashMap<String, String>();
@ -142,7 +140,7 @@ public class VisVOContainer {
private Set<Map<String, String>> initializeNodeSchema() {
Set<Map<String, String>> nodeSchema = new HashSet<Map<String,String>>();
Set<Map<String, String>> nodeSchema = new HashSet<Map<String, String>>();
Map<String, String> schemaAttributes = new LinkedHashMap<String, String>();
@ -153,17 +151,6 @@ public class VisVOContainer {
nodeSchema.add(schemaAttributes);
/*
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "name");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "name");
schemaAttributes.put("attr.type", "string");
nodeSchema.add(schemaAttributes);
*/
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "label");
@ -240,6 +227,4 @@ public class VisVOContainer {
return nodeSchema;
}
}

View file

@ -66,7 +66,8 @@ public class Edge {
@SuppressWarnings("serial")
public Map<String, Integer> getEarliestCollaborationYearCount() {
if (yearToPublicationCount == null) {
yearToPublicationCount = UtilityFunctions.getYearToPublicationCount(collaboratorDocuments);
yearToPublicationCount = UtilityFunctions
.getYearToPublicationCount(collaboratorDocuments);
}
/*
@ -87,9 +88,9 @@ public class Edge {
final String earliestYear = Collections.min(yearsToBeConsidered);
final Integer earliestYearPubCount = yearToPublicationCount.get(earliestYear);
return new HashMap<String, Integer>(){{
return new HashMap<String, Integer>() { {
put(earliestYear, earliestYearPubCount);
}};
} };
} else {
return null;
}
@ -98,7 +99,8 @@ public class Edge {
@SuppressWarnings("serial")
public Map<String, Integer> getLatestCollaborationYearCount() {
if (yearToPublicationCount == null) {
yearToPublicationCount = UtilityFunctions.getYearToPublicationCount(collaboratorDocuments);
yearToPublicationCount = UtilityFunctions
.getYearToPublicationCount(collaboratorDocuments);
}
/*
@ -119,9 +121,9 @@ public class Edge {
final String latestYear = Collections.max(yearsToBeConsidered);
final Integer latestYearPubCount = yearToPublicationCount.get(latestYear);
return new HashMap<String, Integer>(){{
return new HashMap<String, Integer>() { {
put(latestYear, latestYearPubCount);
}};
} };
} else {
return null;
}
@ -130,10 +132,12 @@ public class Edge {
@SuppressWarnings("serial")
public Integer getUnknownCollaborationYearCount() {
if (yearToPublicationCount == null) {
yearToPublicationCount = UtilityFunctions.getYearToPublicationCount(collaboratorDocuments);
yearToPublicationCount = UtilityFunctions
.getYearToPublicationCount(collaboratorDocuments);
}
Integer unknownYearPubCount = yearToPublicationCount.get(VOConstants.DEFAULT_PUBLICATION_YEAR);
Integer unknownYearPubCount = yearToPublicationCount
.get(VOConstants.DEFAULT_PUBLICATION_YEAR);
/*
* If there is no unknown year available then we should imply so by returning a "null".

View file

@ -95,9 +95,9 @@ public class Node extends Individual {
final String earliestYear = Collections.min(yearsToBeConsidered);
final Integer earliestYearPubCount = yearToPublicationCount.get(earliestYear);
return new HashMap<String, Integer>(){{
return new HashMap<String, Integer>() { {
put(earliestYear, earliestYearPubCount);
}};
} };
} else {
return null;
}
@ -127,9 +127,9 @@ public class Node extends Individual {
final String latestYear = Collections.max(yearsToBeConsidered);
final Integer latestYearPubCount = yearToPublicationCount.get(latestYear);
return new HashMap<String, Integer>(){{
return new HashMap<String, Integer>() { {
put(latestYear, latestYearPubCount);
}};
} };
} else {
return null;
}
@ -141,7 +141,8 @@ public class Node extends Individual {
yearToPublicationCount = UtilityFunctions.getYearToPublicationCount(authorDocuments);
}
Integer unknownYearPubCount = yearToPublicationCount.get(VOConstants.DEFAULT_PUBLICATION_YEAR);
Integer unknownYearPubCount = yearToPublicationCount
.get(VOConstants.DEFAULT_PUBLICATION_YEAR);
/*
* If there is no unknown year available then we should imply so by returning a "null".

View file

@ -16,7 +16,8 @@ import edu.cornell.mannlib.vitro.webapp.visualization.constants.VOConstants.Empl
public class VivoEmployee extends Individual {
private EmployeeType employeeType;
private Set<VivoDepartmentOrDivision> parentDepartments = new HashSet<VivoDepartmentOrDivision>();
private Set<VivoDepartmentOrDivision> parentDepartments =
new HashSet<VivoDepartmentOrDivision>();
private Set<BiboDocument> authorDocuments = new HashSet<BiboDocument>();
public VivoEmployee(String employeeURL,

View file

@ -2,6 +2,7 @@
package edu.cornell.mannlib.vitro.webapp.visualization.visutils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import com.hp.hpl.jena.iri.IRI;
@ -29,26 +30,22 @@ import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.GenericQueryM
* @author cdtank
*
*/
public class AllPropertiesQueryHandler {
public class AllPropertiesQueryHandler implements QueryHandler<GenericQueryMap> {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
private String filterRule, individualURLParam, resultFormatParam, rdfResultFormatParam;
private String filterRule, individualURLParam;
private DataSource dataSource;
private Log log;
public AllPropertiesQueryHandler(String individualURLParam,
String filterRule,
String resultFormatParam,
String rdfResultFormatParam,
DataSource dataSource,
Log log) {
this.individualURLParam = individualURLParam;
this.filterRule = filterRule;
this.resultFormatParam = resultFormatParam;
this.rdfResultFormatParam = rdfResultFormatParam;
this.dataSource = dataSource;
this.log = log;
@ -77,12 +74,10 @@ public class AllPropertiesQueryHandler {
private ResultSet executeQuery(String queryText,
String resultFormatParam,
String rdfResultFormatParam,
DataSource dataSource) {
QueryExecution queryExecution = null;
try{
try {
Query query = QueryFactory.create(queryText, SYNTAX);
// QuerySolutionMap qs = new QuerySolutionMap();
@ -90,13 +85,11 @@ public class AllPropertiesQueryHandler {
queryExecution = QueryExecutionFactory.create(query, dataSource);
//remocve this if loop after knowing what is describe & construct sparql stuff.
if (query.isSelectType()){
if (query.isSelectType()) {
return queryExecution.execSelect();
}
} finally {
if(queryExecution != null) {
if (queryExecution != null) {
queryExecution.close();
}
@ -108,10 +101,10 @@ public class AllPropertiesQueryHandler {
// Resource uri1 = ResourceFactory.createResource(queryURI);
String filterClause;
if (filterRule == null || filterRule.trim().isEmpty()) {
filterClause = "";
} else {
if (StringUtils.isNotBlank(filterRule)) {
filterClause = "FILTER ( " + filterRule + " ) . ";
} else {
filterClause = "";
}
String sparqlQuery = QueryConstants.getSparqlPrefixQuery()
@ -127,28 +120,28 @@ public class AllPropertiesQueryHandler {
}
public GenericQueryMap getJavaValueObjects()
throws MalformedQueryParametersException {
if (this.individualURLParam == null || "".equals(individualURLParam)) {
throw new MalformedQueryParametersException("URI parameter is either null or empty.");
} else {
public GenericQueryMap getVisualizationJavaValueObjects()
throws MalformedQueryParametersException {
if (StringUtils.isNotBlank(this.individualURLParam)) {
/*
* To test for the validity of the URI submitted.
* */
IRIFactory iRIFactory = IRIFactory.jenaImplementation();
IRI iri = iRIFactory.create(this.individualURLParam);
if (iri.hasViolation(false)) {
String errorMsg = ((Violation)iri.violations(false).next()).getShortMessage()+" ";
String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage();
log.error("Generic Query " + errorMsg);
throw new MalformedQueryParametersException("URI provided for an individual is malformed.");
throw new MalformedQueryParametersException(
"URI provided for an individual is malformed.");
}
} else {
throw new MalformedQueryParametersException("URI parameter is either null or empty.");
}
ResultSet resultSet = executeQuery(generateGenericSparqlQuery(this.individualURLParam, this.filterRule),
this.resultFormatParam,
this.rdfResultFormatParam,
ResultSet resultSet = executeQuery(generateGenericSparqlQuery(
this.individualURLParam,
this.filterRule),
this.dataSource);
return createJavaValueObjects(resultSet);

View file

@ -4,6 +4,7 @@ package edu.cornell.mannlib.vitro.webapp.visualization.visutils;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import com.hp.hpl.jena.iri.IRI;
@ -26,11 +27,11 @@ import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryP
* @author cdtank
*
*/
public class GenericQueryHandler {
public class GenericQueryHandler implements QueryHandler<ResultSet> {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
private String whereClause, individualURLParam, resultFormatParam, rdfResultFormatParam;
private String whereClause, individualURLParam;
private DataSource dataSource;
private Log log;
@ -40,28 +41,22 @@ public class GenericQueryHandler {
public GenericQueryHandler(String individualURLParam,
Map<String, String> fieldLabelToOutputFieldLabel,
String whereClause,
String resultFormatParam,
String rdfResultFormatParam,
DataSource dataSource,
Log log) {
this.individualURLParam = individualURLParam;
this.fieldLabelToOutputFieldLabel = fieldLabelToOutputFieldLabel;
this.whereClause = whereClause;
this.resultFormatParam = resultFormatParam;
this.rdfResultFormatParam = rdfResultFormatParam;
this.dataSource = dataSource;
this.log = log;
}
private ResultSet executeQuery(String queryText,
String resultFormatParam,
String rdfResultFormatParam,
DataSource dataSource) {
QueryExecution queryExecution = null;
try{
try {
Query query = QueryFactory.create(queryText, SYNTAX);
// QuerySolutionMap qs = new QuerySolutionMap();
@ -71,11 +66,11 @@ public class GenericQueryHandler {
//remocve this if loop after knowing what is describe & construct sparql stuff.
if (query.isSelectType()){
if (query.isSelectType()) {
return queryExecution.execSelect();
}
} finally {
if(queryExecution != null) {
if (queryExecution != null) {
queryExecution.close();
}
@ -95,7 +90,7 @@ public class GenericQueryHandler {
: this.fieldLabelToOutputFieldLabel.entrySet()) {
sparqlQuery.append("\t(str(?" + currentfieldLabelToOutputFieldLabel.getKey() + ") as ?"
+ currentfieldLabelToOutputFieldLabel.getValue() + ")\n");
+ currentfieldLabelToOutputFieldLabel.getValue() + ")\n");
}
@ -105,34 +100,29 @@ public class GenericQueryHandler {
sparqlQuery.append("}\n");
// System.out.println("GENERIC QEURY >>>>> " + sparqlQuery);
return sparqlQuery.toString();
}
public ResultSet getResultSet()
throws MalformedQueryParametersException {
if (this.individualURLParam == null || "".equals(individualURLParam)) {
throw new MalformedQueryParametersException("URI parameter is either null or empty.");
} else {
public ResultSet getVisualizationJavaValueObjects()
throws MalformedQueryParametersException {
if (StringUtils.isNotBlank(this.individualURLParam)) {
/*
* To test for the validity of the URI submitted.
* */
IRIFactory iRIFactory = IRIFactory.jenaImplementation();
IRI iri = iRIFactory.create(this.individualURLParam);
if (iri.hasViolation(false)) {
String errorMsg = ((Violation)iri.violations(false).next()).getShortMessage()+" ";
String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage();
log.error("Generic Query " + errorMsg);
throw new MalformedQueryParametersException("URI provided for an individual is malformed.");
}
throw new MalformedQueryParametersException(
"URI provided for an individual is malformed.");
}
} else {
throw new MalformedQueryParametersException("URI parameter is either null or empty.");
}
ResultSet resultSet = executeQuery(generateGenericSparqlQuery(),
this.resultFormatParam,
this.rdfResultFormatParam,
this.dataSource);
return resultSet;

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.visualization;
package edu.cornell.mannlib.vitro.webapp.visualization.visutils;
import java.awt.BasicStroke;
import java.awt.Color;
@ -29,7 +29,7 @@ import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class PDFDocument{
public class PDFDocument {
static Stroke stroke = new BasicStroke(5.f, BasicStroke.CAP_ROUND,

View file

@ -0,0 +1,9 @@
package edu.cornell.mannlib.vitro.webapp.visualization.visutils;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
public interface QueryHandler<QueryResponse> {
QueryResponse getVisualizationJavaValueObjects() throws MalformedQueryParametersException;
}

View file

@ -16,8 +16,6 @@ public class UtilityFunctions {
public static Map<String, Integer> getYearToPublicationCount(
Set<BiboDocument> authorDocuments) {
//List<Integer> publishedYears = new ArrayList<Integer>();
/*
* Create a map from the year to number of publications. Use the BiboDocument's
* parsedPublicationYear to populate the data.
@ -53,10 +51,6 @@ public class UtilityFunctions {
yearToPublicationCount.put(publicationYear, 1);
}
// if (!parsedPublicationYear.equalsIgnoreCase(BiboDocument.DEFAULT_PUBLICATION_YEAR)) {
// publishedYears.add(Integer.parseInt(parsedPublicationYear));
// }
}
return yearToPublicationCount;

View file

@ -0,0 +1,45 @@
package edu.cornell.mannlib.vitro.webapp.visualization.visutils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import com.hp.hpl.jena.query.DataSource;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
public abstract class VisualizationRequestHandler {
private VitroRequest vitroRequest;
private HttpServletRequest request;
private HttpServletResponse response;
private Log log;
public VisualizationRequestHandler(VitroRequest vitroRequest,
HttpServletRequest request, HttpServletResponse response, Log log) {
this.vitroRequest = vitroRequest;
this.request = request;
this.response = response;
this.log = log;
}
public abstract void generateVisualization(DataSource dataSource);
public VitroRequest getVitroRequest() {
return vitroRequest;
}
public HttpServletRequest getRequest() {
return request;
}
public HttpServletResponse getResponse() {
return response;
}
public Log getLog() {
return log;
}
}