Changeset 4:3599b29c393f in AnnotationManagerN4J for src


Ignore:
Timestamp:
Jul 2, 2012, 8:39:46 PM (12 years ago)
Author:
casties
Branch:
default
Message:

store seems to work now :-)

Location:
src/main/java/de/mpiwg/itgroup/annotations
Files:
4 added
3 edited

Legend:

Unmodified
Added
Removed
  • src/main/java/de/mpiwg/itgroup/annotations/restlet/AnnotatorAnnotations.java

    r3 r4  
    66
    77import java.io.IOException;
    8 import java.util.ArrayList;
    9 import java.util.List;
    108
    119import org.json.JSONArray;
    1210import org.json.JSONException;
    1311import org.json.JSONObject;
    14 import org.restlet.Context;
    15 import org.restlet.data.Form;
    16 import org.restlet.data.MediaType;
    17 import org.restlet.data.Reference;
    1812import org.restlet.data.Status;
    1913import org.restlet.ext.json.JsonRepresentation;
    2014import org.restlet.representation.Representation;
    21 import org.restlet.representation.StringRepresentation;
    2215import org.restlet.resource.Delete;
    2316import org.restlet.resource.Get;
    2417import org.restlet.resource.Post;
    2518import org.restlet.resource.Put;
    26 import org.restlet.security.User;
    27 
    28 import de.mpiwg.itgroup.annotationManager.Constants.NS;
    29 import de.mpiwg.itgroup.annotationManager.Errors.TripleStoreSearchError;
    30 import de.mpiwg.itgroup.annotationManager.Errors.TripleStoreStoreError;
    31 import de.mpiwg.itgroup.annotationManager.RDFHandling.Annotation;
    32 import de.mpiwg.itgroup.annotationManager.RDFHandling.Convert;
    33 import de.mpiwg.itgroup.annotationManager.RDFHandling.RDFSearcher;
    34 import de.mpiwg.itgroup.annotationManager.drupal.AnnotationHandler;
    35 import de.mpiwg.itgroup.annotationManager.drupal.UnknowUserException;
    36 import de.mpiwg.itgroup.triplestoremanager.exceptions.TripleStoreHandlerException;
     19
     20import de.mpiwg.itgroup.annotations.Annotation;
     21import de.mpiwg.itgroup.annotations.neo4j.AnnotationStore;
    3722
    3823/**
    39  * Implements the "annotations" uri of the Annotator API. see <https://github.com/okfn/annotator/wiki/Storage>
     24 * Implements the "annotations" uri of the Annotator API. see
     25 * <https://github.com/okfn/annotator/wiki/Storage>
    4026 *
    4127 * @author dwinter, casties
     
    6955        logger.debug("request authenticated=" + authenticated);
    7056
    71         RDFSearcher searcher = new RDFSearcher(NS.MPIWG_ANNOT_CTX); // TODO should ge into config file
    72 
    73         try {
    74             List<Annotation> annots = searcher.searchById(id);
    75             if (annots.size() == 1) {
    76                 // there should be only one
    77                 JSONObject result = createAnnotatorJson(annots.get(0));
    78                 logger.debug("sending:");
    79                 logger.debug(result);
    80                 return new JsonRepresentation(result);
    81             } else {
    82                 JSONArray results;
    83                 results = new JSONArray();
    84                 for (Annotation annot : annots) {
    85                     JSONObject jo = createAnnotatorJson(annot);
    86                     if (jo != null) {
    87                         results.put(createAnnotatorJson(annot));
    88                     } else {
    89                         setStatus(Status.SERVER_ERROR_INTERNAL, "JSon Error");
    90                         return null;
    91                     }
    92                 }
    93                 // annotator read request returns a list of annotation objects
    94                 logger.debug("sending:");
    95                 logger.debug(results);
    96                 return new JsonRepresentation(results);
    97             }
    98         } catch (TripleStoreHandlerException e) {
    99             e.printStackTrace();
    100             setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreHandler Error");
    101             return null;
    102         } catch (TripleStoreSearchError e) {
    103             e.printStackTrace();
    104             setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreSearch Error");
    105             return null;
     57        Annotation annots = getAnnotationStore().getAnnotationById(id);
     58        if (annots != null) {
     59            // there should be only one
     60            JSONObject result = createAnnotatorJson(annots);
     61            logger.debug("sending:");
     62            logger.debug(result);
     63            return new JsonRepresentation(result);
     64        } else {
     65            JSONArray results = new JSONArray();
     66            // annotator read request returns a list of annotation objects
     67            logger.debug("sending:");
     68            logger.debug(results);
     69            return new JsonRepresentation(results);
    10670        }
    10771    }
     
    11074     * POST with JSON content-type.
    11175     *
    112      * json hash: username: name des users xpointer: xpointer auf den Ausschnitt (incl. der URL des Dokumentes) text: text der
    113      * annotation annoturl: url auf eine Annotation falls extern
     76     * json hash: username: name des users xpointer: xpointer auf den Ausschnitt
     77     * (incl. der URL des Dokumentes) text: text der annotation annoturl: url
     78     * auf eine Annotation falls extern
    11479     *
    11580     * @return
     
    139104            return null;
    140105        }
    141         if (annot == null || annot.xpointer == null || annot.creator == null) {
     106        if (annot == null) {
    142107            setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    143108            return null;
    144109        }
    145110        Annotation storedAnnot;
    146         try {
    147             // store Annotation
    148             storedAnnot = new Convert(NS.MPIWG_ANNOT_CTX).storeAnnotation(annot);
    149         } catch (TripleStoreStoreError e) {
    150             e.printStackTrace();
    151             setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStore Error");
    152             return null;
    153         }
    154         /* according to https://github.com/okfn/annotator/wiki/Storage
    155          * we should return 303: see other.
    156          * For now we return the annotation.
     111        // store Annotation
     112        storedAnnot = getAnnotationStore().storeAnnotation(annot);
     113        /*
     114         * according to https://github.com/okfn/annotator/wiki/Storage we should
     115         * return 303: see other. For now we return the annotation.
    157116         */
    158117        JSONObject jo = createAnnotatorJson(storedAnnot);
     
    160119        return retRep;
    161120    }
    162 
    163     /**
    164      * POST with HTML content-type.
    165      *
    166      * @param entity
    167      * @return
    168      */
    169     @Post("html")
    170     public Representation doPostHtml(Representation entity) {
    171         logger.debug("AnnotatorAnnotations doPostHtml!");
    172         Annotation annot;
    173         annot = handleForm(entity);
    174         if (annot.xpointer == null || annot.creator == null) {
    175             setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    176 
    177             return null;
    178         }
    179 
    180         Annotation retValAnnot;
    181         try {
    182             retValAnnot = new Convert(NS.MPIWG_ANNOT_CTX).storeAnnotation(annot);
    183         } catch (TripleStoreStoreError e) {
    184             e.printStackTrace();
    185             setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStore Error");
    186             return null;
    187         }
    188         if (retValAnnot == null) {
    189             return null;
    190         }
    191         String retVal = retValAnnot.getAnnotationUri();
    192         if (retVal == null) {
    193             return null;
    194         }
    195 
    196         String text = String.format("<html><body><a href=\"%s\">%s</a></body></html>", retVal.replace(">", "").replace("<", ""),
    197                 retVal.replace(">", "&gt;").replace("<", "&lt;"));
    198         Representation retRep = new StringRepresentation(text, MediaType.TEXT_HTML);
    199         return retRep;
    200     }
    201 
    202     /**
    203      *
    204      * @param entity
    205      *            should contain a form with the parameters "username", "password", "xpointer","text","uri","type"
    206      *
    207      *            username,password is optional, if not given BasicAuthentification is used.
    208      *
    209      *            If username given as a URI, the username will be transformed to an URI, username will be added to the MPIWG
    210      *            namespace defined in de.mpiwg.itgroup.annotationManager.Constants.NS
    211      *
    212      * @return
    213      */
    214     protected Annotation handleForm(Representation entity) {
    215         Annotation annot;
    216         Form form = new Form(entity);
    217         String username = form.getValues("username");
    218         String mode = form.getValues("mode");
    219         String password = form.getValues("password");
    220         String xpointer = form.getValues("xpointer");
    221         String text = form.getValues("text");
    222         String title = form.getValues("title");
    223         String url = form.getValues("url");
    224         String type = form.getValues("type");
    225         RestServer restServer = (RestServer) getApplication();
    226 
    227         // falls user and password nicht null sind:
    228         User userFromForm = null;
    229         if (username != null && password != null) {
    230             if (restServer.authenticate(username, password, getRequest())) {
    231                 userFromForm = new User(username);
    232             }
    233         }
    234         User authUser = null;
    235 
    236         if (userFromForm == null) {
    237             authUser = getHttpAuthUser(entity);
    238         }
    239 
    240         // weder BasicAuth noch FormAuth
    241         if (authUser == null && userFromForm == null) {
    242             setStatus(Status.CLIENT_ERROR_FORBIDDEN);
    243             return null;
    244         }
    245 
    246         if (userFromForm != null) {
    247             username = userFromForm.getIdentifier();
    248         } else {
    249             username = authUser.getIdentifier();
    250         }
    251 
    252         // username should be a URI, if not it will set to the MPIWG namespace defined in
    253         // de.mpiwg.itgroup.annotationManager.Constants.NS
    254         String usernameOrig = username;
    255         if (!username.startsWith("http"))
    256             username = NS.MPIWG_PERSONS_URL + username;
    257 
    258         if (mode.equals("complexAnnotation")) {// Annotation mit text in externer ressource
    259 
    260             Context context = getContext();
    261             String drupalPath = context.getParameters().getFirstValue("de.mpiwg.itgroup.annotationManager.drupalServer");
    262 
    263             AnnotationHandler ah = new AnnotationHandler(drupalPath);
    264             JSONObject newAnnot;
    265             try {
    266                 newAnnot = ah.createAnnotation(title, text, usernameOrig, password);
    267             } catch (UnknowUserException e1) {
    268                 setStatus(Status.CLIENT_ERROR_FORBIDDEN);
    269                 e1.printStackTrace();
    270                 return null;
    271             }
    272             try {
    273                 annot = new Annotation(xpointer, username, null, text, type, newAnnot.getString("node_uri"));
    274             } catch (JSONException e) {
    275                 // TODO Auto-generated catch block
    276                 e.printStackTrace();
    277                 setStatus(Status.SERVER_ERROR_INTERNAL);
    278                 return null;
    279             }
    280         } else
    281             annot = new Annotation(xpointer, username, null, text, type, url);
    282         return annot;
    283     }
    284 
    285121
    286122    /**
     
    304140        if (!authenticated) {
    305141            setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Not Authorized!");
    306             return null;           
     142            return null;
    307143        }
    308144
    309145        Annotation annot = null;
     146        AnnotationStore store = getAnnotationStore();
    310147        try {
    311148            JsonRepresentation jrep = new JsonRepresentation(entity);
     
    315152                return null;
    316153            }
    317             RDFSearcher searcher = new RDFSearcher(NS.MPIWG_ANNOT_CTX); // TODO should ge into config file
    318154            // get stored Annotation
    319             List<Annotation> annots = searcher.searchById(id);
    320             if (annots.size() < 1) {
     155            Annotation storedAnnot = store.getAnnotationById(id);
     156            if (storedAnnot == null) {
    321157                setStatus(Status.CLIENT_ERROR_NOT_FOUND);
    322158                return null;
    323159            }
    324             Annotation storedAnnot = annots.get(0);
    325             // delete
    326             searcher.deleteById(id);
    327160            // update from posted JSON
    328161            annot = updateAnnotation(storedAnnot, jo, entity);
    329162            // store Annotation
    330             storedAnnot = new Convert(NS.MPIWG_ANNOT_CTX).storeAnnotation(annot);
    331             /* according to https://github.com/okfn/annotator/wiki/Storage
    332              * we should return 303: see other.
    333              * but the client doesn't like it
    334             setStatus(Status.REDIRECTION_SEE_OTHER);
    335             // go to same URL as this one
    336             Reference thisUrl = this.getReference();
    337             this.getResponse().setLocationRef(thisUrl); */
     163            storedAnnot = store.storeAnnotation(annot);
     164            /*
     165             * according to https://github.com/okfn/annotator/wiki/Storage we
     166             * should return 303: see other. but the client doesn't like it
     167             * setStatus(Status.REDIRECTION_SEE_OTHER); // go to same URL as
     168             * this one Reference thisUrl = this.getReference();
     169             * this.getResponse().setLocationRef(thisUrl);
     170            */
    338171            // return new annotation
    339172            jo = createAnnotatorJson(storedAnnot);
    340173            JsonRepresentation retRep = new JsonRepresentation(jo);
    341174            return retRep;
    342         } catch (TripleStoreHandlerException e) {
    343             e.printStackTrace();
    344             setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreHandler Error");
    345         } catch (TripleStoreSearchError e) {
    346             e.printStackTrace();
    347             setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreSearch Error");
    348175        } catch (JSONException e) {
    349176            e.printStackTrace();
     
    376203        if (!authenticated) {
    377204            setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Not Authorized!");
    378             return null;           
    379         }
    380        
    381         RDFSearcher searcher = new RDFSearcher(NS.MPIWG_ANNOT_CTX); // TODO should ge into config file
    382 
    383         try {
    384             // delete annotation
    385             searcher.deleteById(id);
    386             setStatus(Status.SUCCESS_NO_CONTENT);
    387         } catch (TripleStoreHandlerException e) {
    388             e.printStackTrace();
    389             setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreHandler Error");
    390         } catch (TripleStoreSearchError e) {
    391             e.printStackTrace();
    392             setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreSearch Error");
    393         }
     205            return null;
     206        }
     207
     208        // delete annotation
     209        getAnnotationStore().deleteById(id);
     210        setStatus(Status.SUCCESS_NO_CONTENT);
    394211        return null;
    395212    }
    396    
    397213
    398214}
  • src/main/java/de/mpiwg/itgroup/annotations/restlet/AnnotatorResourceImpl.java

    r3 r4  
    1414import java.util.regex.Pattern;
    1515
     16import javax.servlet.ServletContext;
     17
    1618import net.oauth.jsontoken.Checker;
    1719import net.oauth.jsontoken.JsonToken;
     
    2628import org.json.JSONException;
    2729import org.json.JSONObject;
    28 import org.restlet.data.ClientInfo;
    2930import org.restlet.data.Form;
    3031import org.restlet.data.Status;
     
    3233import org.restlet.resource.Options;
    3334import org.restlet.resource.ServerResource;
    34 import org.restlet.security.User;
    35 
    36 import de.mpiwg.itgroup.annotationManager.Constants.NS;
    37 import de.mpiwg.itgroup.annotationManager.RDFHandling.Annotation;
     35
     36import de.mpiwg.itgroup.annotations.Annotation;
     37import de.mpiwg.itgroup.annotations.Annotation.FragmentTypes;
     38import de.mpiwg.itgroup.annotations.neo4j.AnnotationStore;
     39import de.mpiwg.itgroup.annotations.old.NS;
    3840
    3941/**
     
    4547public abstract class AnnotatorResourceImpl extends ServerResource {
    4648
    47     protected Logger logger = Logger.getRootLogger();
     49    protected static Logger logger = Logger.getLogger(AnnotatorResourceImpl.class);
     50
     51    private AnnotationStore store;
    4852
    4953    protected String getAllowedMethodsForHeader() {
    5054        return "OPTIONS,GET,POST";
     55    }
     56
     57    protected AnnotationStore getAnnotationStore() {
     58        if (store == null) {
     59            ServletContext sc = (ServletContext) getContext().getServerDispatcher().getContext().getAttributes()
     60                    .get("org.restlet.ext.servlet.ServletContext");
     61            logger.debug("Getting AnnotationStore from Context");
     62            store = (AnnotationStore) sc.getAttribute(RestServer.ANNSTORE_KEY);
     63        }
     64        return store;
    5165    }
    5266
     
    115129
    116130    /**
    117      * checks Annotator Auth plugin authentication information from headers. returns userId if successful.
     131     * checks Annotator Auth plugin authentication information from headers.
     132     * returns userId if successful.
    118133     *
    119134     * @param entity
     
    166181        JSONObject jo = new JSONObject();
    167182        try {
    168             jo.put("text", annot.text);
    169             jo.put("uri", annot.url);
     183            jo.put("text", annot.getBodyText());
     184            jo.put("uri", annot.getTargetBaseUri());
    170185
    171186            if (makeUserObject) {
     
    173188                JSONObject userObject = new JSONObject();
    174189                // save creator as uri
    175                 userObject.put("uri", annot.creator);
     190                userObject.put("uri", annot.getCreatorUri());
    176191                // make short user id
    177                 String userID = annot.creator;
    178                 if (userID.startsWith(NS.MPIWG_PERSONS_URL)) {
    179                     userID = userID.replace(NS.MPIWG_PERSONS_URL, ""); // entferne
     192                String userId = annot.getCreatorUri();
     193                if (userId != null && userId.startsWith(NS.MPIWG_PERSONS_URL)) {
     194                    userId = userId.replace(NS.MPIWG_PERSONS_URL, ""); // entferne
    180195                                                                       // NAMESPACE
    181196                }
    182197                // save as id
    183                 userObject.put("id", userID);
     198                userObject.put("id", userId);
    184199                // get full name
    185200                RestServer restServer = (RestServer) getApplication();
    186                 String userName = restServer.getUserNameFromLdap(userID);
     201                String userName = restServer.getUserNameFromLdap(userId);
    187202                userObject.put("name", userName);
    188203                // save user object
     
    190205            } else {
    191206                // save user as string
    192                 jo.put("user", annot.creator);
    193             }
    194 
    195             List<String> xpointers = new ArrayList<String>();
    196             if (annot.xpointers == null || annot.xpointers.size() == 0)
    197                 xpointers.add(annot.xpointer);
    198             else {
    199                 for (String xpointerString : annot.xpointers) {
    200                     xpointers.add(xpointerString);
    201                 }
    202             }
    203             if (!xpointers.isEmpty()) {
     207                jo.put("user", annot.getCreatorUri());
     208            }
     209
     210            if (annot.getTargetFragment() != null) {
    204211                // we only look at the first xpointer
    205                 String xt = getXpointerType(xpointers.get(0));
    206                 if (xt == "range") {
    207                     jo.put("ranges", transformToRanges(xpointers));
    208                 } else if (xt == "area") {
    209                     jo.put("areas", transformToAreas(xpointers));
     212                List<String> fragments = new ArrayList<String>();
     213                fragments.add(annot.getTargetFragment());
     214                FragmentTypes xt = annot.getFragmentType();
     215                if (xt == FragmentTypes.XPOINTER) {
     216                    jo.put("ranges", transformToRanges(fragments));
     217                } else if (xt == FragmentTypes.AREA) {
     218                    jo.put("areas", transformToAreas(fragments));
    210219                }
    211220            }
    212221            // encode Annotation URL (=id) in base64
    213             String annotUrl = annot.getAnnotationUri();
     222            String annotUrl = annot.getUri();
    214223            String annotId = encodeJsonId(annotUrl);
    215224            jo.put("id", annotId);
     
    222231    }
    223232
    224     private String getXpointerType(String xpointer) {
    225         if (xpointer.contains("#xpointer")) {
    226             return "range";
    227         } else if (xpointer.contains("#xywh")) {
    228             return "area";
    229         }
    230         return null;
    231     }
    232 
    233233    private JSONArray transformToRanges(List<String> xpointers) {
    234234
     
    236236
    237237        Pattern rg = Pattern
    238                 .compile("#xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)/range-to\\(end-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)\\)");
    239         Pattern rg1 = Pattern.compile("#xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)");
     238                .compile("xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)/range-to\\(end-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)\\)");
     239        Pattern rg1 = Pattern.compile("xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)");
    240240
    241241        try {
     
    278278        JSONArray ja = new JSONArray();
    279279
    280         Pattern rg = Pattern.compile("#xywh=(\\w*:)([\\d\\.]+),([\\d\\.]+),([\\d\\.]+),([\\d\\.]+)");
     280        Pattern rg = Pattern.compile("xywh=(\\w*:)([\\d\\.]+),([\\d\\.]+),([\\d\\.]+),([\\d\\.]+)");
    281281
    282282        try {
     
    308308    }
    309309
     310    protected String parseArea(JSONObject area) throws JSONException, UnsupportedEncodingException {
     311        String x = area.getString("x");
     312        String y = area.getString("y");
     313        String width = "0";
     314        String height = "0";
     315        if (area.has("width")) {
     316            width = area.getString("width");
     317            height = area.getString("height");
     318        }
     319        String fragment = URLEncoder.encode(String.format("xywh=fraction:%s,%s,%s,%s", x, y, width, height), "utf-8");
     320        return fragment;
     321    }
     322
     323    protected String parseRange(JSONObject range) throws JSONException, UnsupportedEncodingException {
     324        String start = range.getString("start");
     325        String end = range.getString("end");
     326        String startOffset = range.getString("startOffset");
     327        String endOffset = range.getString("endOffset");
     328
     329        String fragment = URLEncoder.encode(String.format(
     330                "xpointer(start-point(string-range(\"%s\",%s,1))/range-to(end-point(string-range(\"%s\",%s,1))))", start,
     331                startOffset, end, endOffset), "utf-8");
     332        return fragment;
     333    }
     334
    310335    /**
    311336     * creates an Annotation object with data from JSON.
    312337     *
    313      * uses the specification from the annotator project: {@link https ://github.com/okfn/annotator/wiki/Annotation-format}
    314      *
    315      * The username will be transformed to an URI if not given already as URI, if not it will set to the MPIWG namespace defined in
     338     * uses the specification from the annotator project: {@link https
     339     * ://github.com/okfn/annotator/wiki/Annotation-format}
     340     *
     341     * The username will be transformed to an URI if not given already as URI,
     342     * if not it will set to the MPIWG namespace defined in
    316343     * de.mpiwg.itgroup.annotationManager.Constants.NS
    317344     *
     
    319346     * @return
    320347     * @throws JSONException
    321      */
    322     public Annotation createAnnotation(JSONObject jo, Representation entity) throws JSONException {
     348     * @throws UnsupportedEncodingException
     349     */
     350    public Annotation createAnnotation(JSONObject jo, Representation entity) throws JSONException, UnsupportedEncodingException {
    323351        return updateAnnotation(new Annotation(), jo, entity);
    324352    }
    325353
    326     public Annotation updateAnnotation(Annotation annot, JSONObject jo, Representation entity) throws JSONException {
     354    public Annotation updateAnnotation(Annotation annot, JSONObject jo, Representation entity) throws JSONException,
     355            UnsupportedEncodingException {
    327356        // annotated uri
    328         String url = annot.url;
    329357        if (jo.has("uri")) {
    330             url = jo.getString("uri");
     358            annot.setTargetBaseUri(jo.getString("uri"));
    331359        }
    332360        // annotation text
    333         String text = annot.text;
    334361        if (jo.has("text")) {
    335             text = jo.getString("text");
     362            annot.setBodyText(jo.getString("text"));
    336363        }
    337364        // check authentication
    338365        String authUser = checkAuthToken(entity);
    339366        if (authUser == null) {
    340             // try http auth
    341             User httpUser = getHttpAuthUser(entity);
    342             if (httpUser == null) {
    343                 setStatus(Status.CLIENT_ERROR_FORBIDDEN);
    344                 return null;
    345             }
    346             authUser = httpUser.getIdentifier();
     367            /*
     368             * // try http auth User httpUser = getHttpAuthUser(entity); if
     369             * (httpUser == null) {
     370             */
     371            setStatus(Status.CLIENT_ERROR_FORBIDDEN);
     372            return null;
     373            /*
     374             * } authUser = httpUser.getIdentifier();
     375             */
    347376        }
    348377        // username not required, if no username given authuser will be used
    349378        String username = null;
    350         String userUri = annot.creator;
     379        String userUri = annot.getCreatorUri();
    351380        if (jo.has("user")) {
    352381            if (jo.get("user") instanceof String) {
     
    381410
    382411        // create xpointer from the first range/area
    383         String xpointer = annot.xpointer;
    384412        if (jo.has("ranges")) {
    385413            JSONObject ranges = jo.getJSONArray("ranges").getJSONObject(0);
    386             String start = ranges.getString("start");
    387             String end = ranges.getString("end");
    388             String startOffset = ranges.getString("startOffset");
    389             String endOffset = ranges.getString("endOffset");
    390 
    391             try {
    392                 xpointer = url
    393                         + "#"
    394                         + URLEncoder.encode(String.format(
    395                                 "xpointer(start-point(string-range(\"%s\",%s,1))/range-to(end-point(string-range(\"%s\",%s,1))))",
    396                                 start, startOffset, end, endOffset), "utf-8");
    397             } catch (UnsupportedEncodingException e) {
    398                 e.printStackTrace();
    399                 setStatus(Status.SERVER_ERROR_INTERNAL);
    400                 return null;
    401             }
     414            annot.setFragmentType(FragmentTypes.XPOINTER);
     415            String fragment = parseRange(ranges);
     416            annot.setTargetFragment(fragment);
    402417        }
    403418        if (jo.has("areas")) {
    404419            JSONObject area = jo.getJSONArray("areas").getJSONObject(0);
    405             String x = area.getString("x");
    406             String y = area.getString("y");
    407             String width = "0";
    408             String height = "0";
    409             if (area.has("width")) {
    410                 width = area.getString("width");
    411                 height = area.getString("height");
    412             }
    413             try {
    414                 xpointer = url + "#" + URLEncoder.encode(String.format("xywh=fraction:%s,%s,%s,%s", x, y, width, height), "utf-8");
    415             } catch (UnsupportedEncodingException e) {
    416                 e.printStackTrace();
    417                 setStatus(Status.SERVER_ERROR_INTERNAL);
    418                 return null;
    419             }
    420         }
    421         return new Annotation(xpointer, userUri, annot.time, text, annot.type);
    422     }
    423 
    424     /**
    425      * returns the logged in User.
    426      *
    427      * @param entity
    428      * @return
    429      */
    430     protected User getHttpAuthUser(Representation entity) {
    431         RestServer restServer = (RestServer) getApplication();
    432         if (!restServer.authenticate(getRequest(), getResponse())) {
    433             // Not authenticated
    434             return null;
    435         }
    436 
    437         ClientInfo ci = getRequest().getClientInfo();
    438         logger.debug(ci);
    439         return getRequest().getClientInfo().getUser();
    440 
     420            annot.setFragmentType(FragmentTypes.AREA);
     421            String fragment = parseArea(area);
     422            annot.setTargetFragment(fragment);
     423        }
     424        return annot;
    441425    }
    442426
  • src/main/java/de/mpiwg/itgroup/annotations/restlet/RestServer.java

    r3 r4  
    2828import org.restlet.Restlet;
    2929import org.restlet.routing.Router;
    30 import org.restlet.security.ChallengeAuthenticator;
    31 
    32 import scala.sys.process.ProcessBuilderImpl.Dummy;
     30
     31import de.mpiwg.itgroup.annotations.neo4j.AnnotationStore;
    3332
    3433public class RestServer extends Application {
    3534
    36     public static Logger logger = Logger.getRootLogger();
    37 
    38     private ChallengeAuthenticator authenticator;
     35    public static Logger logger = Logger.getLogger(RestServer.class);
    3936
    4037    /**
     
    4744    public static final String GRAPHDB_KEY = "annotationmanager.graphdb";
    4845    public String DB_PATH = "WEB-INF/neo4j-annotation-db";
     46
     47    private WrappingNeoServerBootstrapper srv;
     48    public static final String GRAPHDBSRV_KEY = "annotationmanager.graphdb.srv";
     49   
     50    private AnnotationStore store;
     51    public static final String ANNSTORE_KEY = "annotationmanager.store";
    4952
    5053    /**
     
    7174                    logger.debug("opening DB " + dbFn);
    7275                    graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(dbFn);
     76                    registerShutdownHook(graphDb);
    7377                    // store in context
    7478                    sc.setAttribute(GRAPHDB_KEY, graphDb);
    75                     WrappingNeoServerBootstrapper srv = new WrappingNeoServerBootstrapper((AbstractGraphDatabase) graphDb);
     79                    // AnnotationStore
     80                    store = new AnnotationStore(graphDb);
     81                    sc.setAttribute(ANNSTORE_KEY, store);
     82                    // admin server
     83                    srv = new WrappingNeoServerBootstrapper((AbstractGraphDatabase) graphDb);
    7684                    logger.debug("Starting DB admin server...");
     85                    // store in context
     86                    sc.setAttribute(GRAPHDBSRV_KEY, srv);
    7787                    srv.start();
    7888                } else {
     
    127137        router.attach("/annotator/annotations", AnnotatorAnnotations.class);
    128138        router.attach("/annotator/annotations/{id}", AnnotatorAnnotations.class);
    129         // router.attach("/annotator/search", AnnotatorSearch.class);
     139        router.attach("/annotator/search", AnnotatorSearch.class);
    130140
    131141        // router.attach("",redirector); router.attach("/annotator",
     
    241251    }
    242252
     253    /* (non-Javadoc)
     254     * @see org.restlet.Application#stop()
     255     */
     256    @Override
     257    public synchronized void stop() throws Exception {
     258        /*
     259         * trying to clean up databases, nur sure if this is the right way...
     260         */
     261        if (srv != null) {
     262            logger.debug("Stopping DB admin server...");
     263            srv.stop();
     264            srv = null;
     265        }
     266        if (graphDb != null) {
     267            logger.debug("Stopping DB...");
     268            graphDb.shutdown();
     269            graphDb = null;
     270        }
     271        super.stop();
     272    }
     273
     274    private static void registerShutdownHook(final GraphDatabaseService graphDb) {
     275        // Registers a shutdown hook for the Neo4j instance so that it
     276        // shuts down nicely when the VM exits (even if you "Ctrl-C" the
     277        // running example before it's completed)
     278        Runtime.getRuntime().addShutdownHook(new Thread() {
     279            @Override
     280            public void run() {
     281                graphDb.shutdown();
     282            }
     283        });
     284    }
     285   
     286   
    243287}
Note: See TracChangeset for help on using the changeset viewer.