view src/main/java/de/mpiwg/itgroup/annotations/restlet/AnnotatorSearch.java @ 14:629e15b345aa

permissions mostly work. need more server-side checking.
author casties
date Fri, 13 Jul 2012 20:41:02 +0200
parents 3599b29c393f
children 58357a4b86de
line wrap: on
line source

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

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Form;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;

import de.mpiwg.itgroup.annotations.Annotation;

/**
 * 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) {
        logger.debug("AnnotatorSearch doGetJSON!");
        setCorsHeaders();
        // do authentication
        String authUser = this.checkAuthToken(entity);
        logger.debug("request authenticated=" + authUser);

        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");

        JSONArray results = new JSONArray();
        // do search
        logger.debug(String.format("searching for uri=%s user=%s", uri, user));
        List<Annotation> annots = getAnnotationStore().searchByUriUser(uri, user, limit, offset);
        for (Annotation annot : annots) {
            // check permission
            if (!annot.isActionAllowed("read", authUser)) continue;
            JSONObject jo = createAnnotatorJson(annot, (authUser == null));
            if (jo != null) {
                results.put(jo);
            } else {
                setStatus(Status.SERVER_ERROR_INTERNAL, "JSON Error");
                return null;
            }
        }
        // assemble result object
        JSONObject result = new JSONObject();
        try {
            result.put("rows", results);
            result.put("total", results.length());
        } catch (JSONException e) {
            setStatus(Status.SERVER_ERROR_INTERNAL, "JSON Error");
            return null;
        }

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

}