view src/de/mpiwg/itgroup/nimanager/persons/PersonByNameService.java @ 6:290d859f036b

ID search
author dwinter
date Thu, 29 Dec 2011 15:20:37 +0100
parents cdc4c12262b1
children
line wrap: on
line source

package de.mpiwg.itgroup.nimanager.persons;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.openrdf.model.Statement;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.restlet.Context;
import org.restlet.data.ClientInfo;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.engine.component.ChildContext;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.Options;
import org.restlet.resource.ServerResource;

import de.mpiwg.itgroup.triplestoremanager.exceptions.TripleStoreHandlerException;
import de.mpiwg.itgroup.triplestoremanager.owl.TripleStoreHandler;

import virtuoso.jdbc4.VirtuosoResultSet;


public class PersonByNameService extends ServerResource {

	private String VIRTUOSO_PW;
	private String VIRTUOSO_USER;
	private String virtuoso_server_url;
	private String RELATION_FOR_NAME_SEARCH = "http://xmlns.com/foaf/0.1/name";
	private String PERSONS_CONTEXT;
	private TripleStoreHandler th;

	public PersonByNameService() {
		ChildContext context = (ChildContext)Context.getCurrent();
		virtuoso_server_url = context.getParameters().getFirstValue("de.mpwig.itgroup.personSearch.virtuoso.url");
		VIRTUOSO_PW = context.getParameters().getFirstValue("de.mpwig.itgroup.personSearch.virtuoso.pw");
		VIRTUOSO_USER = context.getParameters().getFirstValue("de.mpwig.itgroup.personSearch.virtuoso.user");
		PERSONS_CONTEXT = context.getParameters().getFirstValue("de.mpwig.itgroup.personSearch.virtuoso.personsGraphURI");
		//th = TripleStoreHandler.getInstance("jdbc:virtuoso://virtuoso.mpiwg-berlin.mpg.de:1111", "dba", "dba");
		try {
			th = new TripleStoreHandler(virtuoso_server_url, VIRTUOSO_USER, VIRTUOSO_PW);
		} catch (TripleStoreHandlerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Options
	public void doOptions(Representation entity) {
		Form responseHeaders = (Form) getResponse().getAttributes().get(
		"org.restlet.http.headers");
		if (responseHeaders == null) {
			responseHeaders = new Form();
			getResponse().getAttributes().put("org.restlet.http.headers",
					responseHeaders);
		}
		responseHeaders.add("Access-Control-Allow-Origin", "*");
		responseHeaders.add("Access-Control-Allow-Methods", "POST,OPTIONS,GET");
		responseHeaders.add("Access-Control-Allow-Headers", "Content-Type");
		responseHeaders.add("Access-Control-Allow-Credentials", "false");
		responseHeaders.add("Access-Control-Max-Age", "60");
	}

	public Representation getTest() {
		return new StringRepresentation("TEST");
	}

	@Get("json")
	public Representation getJson() {
		Form responseHeaders = (Form) getResponse().getAttributes().get(
		"org.restlet.http.headers");
		if (responseHeaders == null) {
			responseHeaders = new Form();
			getResponse().getAttributes().put("org.restlet.http.headers",
					responseHeaders);
		}
		responseHeaders.add("Access-Control-Allow-Origin", "*");

		JSONArray resultsJsonArray = new JSONArray();
		try {
			String id = (String) getRequest().getAttributes().get("name");
			id = URLDecoder.decode(id, "utf-8");

			//InputStream is = getClass().getResourceAsStream("de/mpiwg/itgroup/nimanager/persons/personQueryString");
			InputStream is = getClass().getResourceAsStream("personQueryString");
			Writer sw = new StringWriter();
			IOUtils.copy(is, sw,"utf-8");

			String queryPersonWPMD=String.format(sw.toString(), id,id);

			java.sql.Statement smt = th.sqlCon.createStatement();


			smt.execute(queryPersonWPMD);
			VirtuosoResultSet rs = (VirtuosoResultSet) smt.getResultSet();
			Map<String,String> resultMap = new HashMap<String, String>();
			while(rs.next()){
				if (rs.getString("person")!=null){
					resultMap.put("person",rs.getString("person"));
				}else  {
					resultMap.put("person","");
				}
				if (rs.getString("objects")!=null){
					resultMap.put("wikipedia",rs.getString("objects"));
				} else  {
					resultMap.put("wikipedia","");
				}
				if (rs.getString("gnd")!=null){
					resultMap.put("gnd",rs.getString("gnd"));
				} else  {
					resultMap.put("gnd","");
				}
				if (rs.getString("birthDate")!=null){
					resultMap.put("birthDate",rs.getString("birthDate"));
				} else {
					resultMap.put("birthDate","");
				}
				if (rs.getString("deathDate")!=null){
					resultMap.put("deathDate",rs.getString("deathDate"));
				} else {
					resultMap.put("deathDate","");
				}
				resultMap.put("name",id);
				resultsJsonArray.put(resultMap);
			}

			return new JsonRepresentation(resultsJsonArray);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			setStatus(Status.SERVER_ERROR_INTERNAL, "REPOSITORY ERROR");
			return new JsonRepresentation(new JSONArray());

		} catch (SQLException e) {

			e.printStackTrace();
			setStatus(Status.SERVER_ERROR_INTERNAL, "REPOSITORY SQL ERROR");
			return new JsonRepresentation(new JSONArray());

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			setStatus(Status.SERVER_ERROR_INTERNAL);
			return new JsonRepresentation(new JSONArray());
		}


	}

	@Get("xml")
	public Representation getXML() {
		List<MediaType> supported=new ArrayList<MediaType>();
		supported.add(MediaType.APPLICATION_JSON);

		ClientInfo ci = getRequest().getClientInfo();

		if(ci==null){ //don't know why this can happen, but sometimes does
			setStatus(Status.SERVER_ERROR_INTERNAL);
			return null;
		}
		MediaType types = getRequest().getClientInfo().getPreferredMediaType(supported);
		if (types.equals(MediaType.APPLICATION_JSON))
			return getJson();

		try {
			String id = (String) getRequest().getAttributes().get("name");
			id = URLDecoder.decode(id, "utf-8");
			RepositoryResult<Statement> statements = th.getStatements(null,
					th.createUri(RELATION_FOR_NAME_SEARCH),
					th.createLiteral(id, "en"), PERSONS_CONTEXT);
			String ret = "<results>";
			while (statements.hasNext()) {
				Statement statement = statements.next();
				ret += "<result subj=\"" + statement.getSubject().stringValue()
				+ "\"/>";
			}
			ret += "</results>";

			return new StringRepresentation(ret, MediaType.TEXT_XML);

		} catch (RepositoryException e) {

			e.printStackTrace();
			setStatus(Status.SERVER_ERROR_INTERNAL, "REPOSITORY ERROR");
			return new StringRepresentation(
					"<xml><error>Repository Error</error></xml>",
					MediaType.TEXT_XML);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			setStatus(Status.SERVER_ERROR_INTERNAL, "REPOSITORY ERROR");
			return new StringRepresentation(
					"<xml><error>Unsupported encoding</error></xml>",
					MediaType.TEXT_XML);
		}
	}

	@Get("html")
	public Representation getHTML() {

		List<MediaType> supported=new ArrayList<MediaType>();
		supported.add(MediaType.APPLICATION_JSON);

		ClientInfo ci = getRequest().getClientInfo();

		if(ci==null){ //don't know why this can happen, but sometimes does
			setStatus(Status.SERVER_ERROR_INTERNAL);
			return null;
		}
		MediaType types = ci.getPreferredMediaType(supported);
		if (types!=null)
			if (types.equals(MediaType.APPLICATION_JSON))
				return getJson();

		Form responseHeaders = (Form) getResponse().getAttributes().get(
		"org.restlet.http.headers");
		if (responseHeaders == null) {
			responseHeaders = new Form();
			getResponse().getAttributes().put("org.restlet.http.headers",
					responseHeaders);
		}
		responseHeaders.add("Access-Control-Allow-Origin", "*");
		try {
			String id = (String) getRequest().getAttributes().get("name");
			id = URLDecoder.decode(id, "utf-8");
			
			InputStream is = getClass().getResourceAsStream("personQueryStringFull");
			Writer sw = new StringWriter();
			IOUtils.copy(is, sw,"utf-8");

			String queryPersonWPMD=String.format(sw.toString(), id,id);

			java.sql.Statement smt = th.sqlCon.createStatement();


			smt.execute(queryPersonWPMD);
			VirtuosoResultSet rs = (VirtuosoResultSet) smt.getResultSet();
			
			
			String person="";
			String bd="";
			String dd="";
			
			String ret = "";
			
			List<String> alternateMPIWGAdresses = new ArrayList<String>();
			
			while(rs.next()){
				person= rs.getString("person");
				String gnd= rs.getString("gnd");
				
			
				String bdNew= rs.getString("birthDate"); // setzte Geburtsdatum, falls noch nicht geschehen
				if (bdNew!=null && bd.equals("")){
					bd=bdNew;
				}
				String ddNew= rs.getString("deathDate");  // setzte Todesdatum, falls noch nicht geschehen
				if (ddNew!=null && dd.equals("")){
					dd=ddNew;
				}
				
				String person2=rs.getString("person2"); // get alternative MPIWG ID
				if (person2!=null){
					alternateMPIWGAdresses.add(person2);
				}
				ret+=String.format("<li>external ID:<a href=\"%s\">%s </a></li>",gnd,gnd);
				
				String sameID = rs.getString("gndSame");
				if (sameID!=null){
					ret+=String.format("<li>external ID: <a href=\"%s\">%s </a></li>",sameID,sameID);
				}
			}

			ret = "<html><body><div id=\"resultNames\">"+
			String.format("<div>%s (%s-%s)</div>",id,bd,dd)+
			String.format("<div>MPIWG ID:<a href=\"%s\">%s </a></div><ul>",person,person)+
			ret+
			"</ul>";
			if(alternateMPIWGAdresses.size()>0){
				ret+="<div><div>Alternative MPIWG addresses (don't use)</div><ul>";
				for (String alt: alternateMPIWGAdresses){
					ret+=String.format("<li><a href=\"%s\">%s </a></li>",alt,alt);
				}
				ret+="</ul></div>";
			}
			
			ret+="</div></body></html>";

			return new StringRepresentation(ret, MediaType.TEXT_HTML);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			setStatus(Status.SERVER_ERROR_INTERNAL, "REPOSITORY ERROR");
			return new StringRepresentation(
					"<xml><error>Unsupported encoding</error></xml>",
					MediaType.TEXT_HTML);
		} catch (SQLException e) {

			e.printStackTrace();
			setStatus(Status.SERVER_ERROR_INTERNAL, "REPOSITORY SQL ERROR");
			return new StringRepresentation(
					"<xml><error>Unsupported encoding</error></xml>",
					MediaType.TEXT_HTML);
		} catch (IOException e) {
			e.printStackTrace();
			setStatus(Status.SERVER_ERROR_INTERNAL);
			return null;
		}
	}

	public List<Map<String,String>> getMaps(String id){
		ArrayList<Map<String, String>> retList = new ArrayList<Map<String,String>>();
		try {


			//InputStream is = getClass().getResourceAsStream("de/mpiwg/itgroup/nimanager/persons/personQueryString");
			InputStream is = getClass().getResourceAsStream("personQueryString");
			Writer sw = new StringWriter();
			IOUtils.copy(is, sw,"utf-8");

			String queryPersonWPMD=String.format(sw.toString(), id,id);

			java.sql.Statement smt = th.sqlCon.createStatement();


			smt.execute(queryPersonWPMD);
			VirtuosoResultSet rs = (VirtuosoResultSet) smt.getResultSet();
			Map<String,String> resultMap = new HashMap<String, String>();
			while(rs.next()){
				if (rs.getString("person")!=null){
					resultMap.put("person",rs.getString("person"));
				}else  {
					resultMap.put("person","");
				}
				if (rs.getString("objects")!=null){
					resultMap.put("wikipedia",rs.getString("objects"));
				} else  {
					resultMap.put("wikipedia","");
				}
				if (rs.getString("gnd")!=null){
					resultMap.put("gnd",rs.getString("gnd"));
				} else  {
					resultMap.put("gnd","");
				}
				if (rs.getString("birthDate")!=null){
					resultMap.put("birthDate",rs.getString("birthDate"));
				} else {
					resultMap.put("birthDate","");
				}
				if (rs.getString("deathDate")!=null){
					resultMap.put("deathDate",rs.getString("deathDate"));
				} else {
					resultMap.put("deathDate","");
				}
				resultMap.put("name",id);
			retList.add(resultMap);	
			}

		return retList;

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			
			return null;

		} catch (SQLException e) {

			e.printStackTrace();
			
			return null;

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			setStatus(Status.SERVER_ERROR_INTERNAL);
			return null;
		}


	

	}
}