view src/de/mpiwg/itgroup/annotationManager/restlet/AnnotatorSearch.java @ 13:9393c9c9b916

saves annotations now!
author casties
date Wed, 21 Mar 2012 15:23:57 +0100
parents 2f8c72ae4c43
children 6c7c4140630d
line wrap: on
line source

/**
 * Implements the "search" uri of the Annotator API.
 */
package de.mpiwg.itgroup.annotationManager.restlet;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;

import de.mpiwg.itgroup.annotationManager.Errors.TripleStoreSearchError;
import de.mpiwg.itgroup.annotationManager.RDFHandling.Convert;
import de.mpiwg.itgroup.annotationManager.RDFHandling.RDFSearcher;
import de.mpiwg.itgroup.triplestoremanager.exceptions.TripleStoreHandlerException;

/**
 * Implements the "search" uri of the Annotator API. see
 * <https://github.com/okfn/annotator/wiki/Storage>
 * 
 * @author casties
 * 
 */
public class AnnotatorSearch extends AnnotatorResourceImpl {

    protected String getAllowedMethodsForHeader() {
        return "OPTIONS,GET";
    }

    /**
     * result for JSON content-type. optional search parameters: uri user limit
     * offset
     * 
     * @param entity
     * @return
     */
    @Get("json")
    public Representation doGetJSON(Representation entity) {

        doOptions(entity);
        //TODO: what to do with authentication? 
        boolean authenticated = isAuthenticated(entity);
        logger.debug("request authenticated="+authenticated);

        Form form = getRequest().getResourceRef().getQueryAsForm();
        String uri = form.getFirstValue("uri");
        String user = form.getFirstValue("user");

        String limit = form.getFirstValue("limit");
        String offset = form.getFirstValue("offset");

        RDFSearcher searcher = new RDFSearcher("file:///annotations"); // TODO should go into config file

        JSONArray ja;
        try {

            List<Convert.Annotation> annots = searcher.search(uri, user, limit, offset);

            ja = new JSONArray();
            for (Convert.Annotation annot : annots) {
                JSONObject jo = createAnnotatorJson(annot);
                if (jo != null) {
                    ja.put(createAnnotatorJson(annot));
                } else {
                    setStatus(Status.SERVER_ERROR_INTERNAL, "JSON Error");
                    return null;
                }
            }
        } catch (TripleStoreHandlerException e) {
            e.printStackTrace();
            setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreHandler Error");
            return null;
        } catch (TripleStoreSearchError e) {
            e.printStackTrace();
            setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreSearch Error");
            return null;
        }

        JSONObject result = new JSONObject();
        try {
            result.put("rows", ja);
            result.put("total", ja.length());
        } catch (JSONException e) {
            e.printStackTrace();
            setStatus(Status.SERVER_ERROR_INTERNAL, "JSON Error");
            return null;
        }

        logger.debug("sending:");
        logger.debug(result);
        return new JsonRepresentation(result);
    }

    /**
     * result for HTML content-type.
     * 
     * @param entity
     * @return
     */
    @Get("html")
    public Representation doGetHTML(Representation entity) {

        doOptions(entity);
        Form form = getRequest().getResourceRef().getQueryAsForm();
        String uri = form.getFirstValue("uri");
        String user = form.getFirstValue("user");

        String limit = form.getFirstValue("limit");
        String offset = form.getFirstValue("offset");

        try {
            if (uri != null) {
                uri = URLDecoder.decode(uri, "utf-8");
            }
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE);
            return null;
        }

        RDFSearcher searcher = new RDFSearcher("file:///annotations"); // TODO
                                                                       // should
                                                                       // ge
                                                                       // into
                                                                       // config
                                                                       // file

        String retString = "<html><body><table>";
        String lineFormat = "<tr><td><a href=\"%s\">%s</a></td>"
                + "<td><a href=\"%s\">%s</a></td><td>%s</td><td>%s</td><td><a href=\"%s\">%s</a></td><td><a href=\"%s\">%s</a></td></div>";
        try {

            List<Convert.Annotation> annots = searcher.search(uri, user, limit, offset);

            for (Convert.Annotation annot : annots) {

                RestServer restServer = (RestServer) getApplication();
                String userName = restServer.getUserNameFromLdap(annot.creator);
                List<String> xpointer = new ArrayList<String>();

                if (annot.xpointers == null || annot.xpointers.size() == 0)
                    retString += String.format(lineFormat, userName, userName, annot.url, annot.url, annot.time, annot.text,
                            annot.xpointer, annot.xpointer, annot.annotationUri, annot.annotationUri);
                else {
                    for (String xpointerString : annot.xpointers) {
                        retString += String.format(lineFormat, userName, userName, annot.url, annot.url, annot.time, annot.text,
                                xpointerString, xpointerString, annot.annotationUri, annot.annotationUri);
                    }
                }

            }
        } catch (TripleStoreHandlerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreHandler Error");
            return null;
        } catch (TripleStoreSearchError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreSearch Error");
            return null;
        }

        retString += "</table></body></html>";

        logger.debug("sending:");
        logger.debug(retString);
        return new StringRepresentation(retString, MediaType.TEXT_HTML);
    }

}