Search in sources :

Example 1 with DFramedTransactionalGraph

use of org.openntf.domino.graph2.impl.DFramedTransactionalGraph in project org.openntf.domino by OpenNTF.

the class AbstractIncidenceHandler method processVertexAdjacency.

@SuppressWarnings({ "rawtypes", "unchecked" })
public Object processVertexAdjacency(final Annotation annotation, final Method method, final Object[] arguments, final FramedGraph framedGraph, final Vertex vertex) {
    Edge resultEdge = null;
    Class<?> returnType = method.getReturnType();
    Direction dir = Direction.BOTH;
    String label = "";
    boolean unique = false;
    if (annotation instanceof Adjacency) {
        dir = ((Adjacency) annotation).direction();
        label = ((Adjacency) annotation).label();
    } else if (annotation instanceof AdjacencyUnique) {
        dir = ((AdjacencyUnique) annotation).direction();
        label = ((AdjacencyUnique) annotation).label();
        unique = true;
    } else if (annotation instanceof Incidence) {
        dir = ((Incidence) annotation).direction();
        label = ((Incidence) annotation).label();
    } else if (annotation instanceof IncidenceUnique) {
        dir = ((IncidenceUnique) annotation).direction();
        label = ((IncidenceUnique) annotation).label();
        unique = true;
    }
    if (ClassUtilities.isGetMethod(method)) {
        final FramedVertexList r = new FramedVertexList(framedGraph, vertex, vertex.getVertices(dir, label), ClassUtilities.getGenericClass(method));
        if (ClassUtilities.returnsIterable(method)) {
            return r;
        } else {
            return r.iterator().hasNext() ? r.iterator().next() : null;
        }
    } else if (ClassUtilities.isAddMethod(method)) {
        Vertex newVertex;
        Object returnValue = null;
        if (arguments == null) {
            // Use this method to get the vertex so that the vertex
            // initializer is called.
            returnValue = framedGraph.addVertex(null, returnType);
            newVertex = ((VertexFrame) returnValue).asVertex();
        } else {
            newVertex = ((VertexFrame) arguments[0]).asVertex();
        }
        if (unique) {
            resultEdge = findEdge(annotation, framedGraph, vertex, newVertex);
        }
        if (resultEdge == null) {
            String replicaid = null;
            if (framedGraph instanceof DFramedTransactionalGraph) {
                DElementStore store = ((DFramedTransactionalGraph) framedGraph).getElementStore(returnType);
                long rawkey = store.getStoreKey();
                replicaid = NoteCoordinate.Utils.getReplidFromLong(rawkey);
            }
            resultEdge = addEdge(annotation, framedGraph, vertex, newVertex, replicaid);
        }
        if (returnType.isPrimitive()) {
            return null;
        } else if (Edge.class.isAssignableFrom(returnType)) {
            return resultEdge;
        } else if (EdgeFrame.class.isAssignableFrom(returnType)) {
            // System.out.println("TEMP DEBUG about to wrap edge with id " + resultEdge.getId());
            Object result = framedGraph.frame(resultEdge, returnType);
            return result;
        } else {
            return returnValue;
        }
    } else if (ClassUtilities.isRemoveMethod(method)) {
        removeEdges(dir, label, vertex, ((VertexFrame) arguments[0]).asVertex(), framedGraph);
        return null;
    } else if (AnnotationUtilities.isCountMethod(method)) {
        return countEdges(annotation, vertex);
    } else if (ClassUtilities.isSetMethod(method)) {
        removeEdges(dir, label, vertex, null, framedGraph);
        if (ClassUtilities.acceptsIterable(method)) {
            for (Object o : (Iterable) arguments[0]) {
                Vertex v = ((VertexFrame) o).asVertex();
                addEdge(annotation, framedGraph, vertex, v, null);
            }
            return null;
        } else {
            if (null != arguments[0]) {
                Vertex newVertex = ((VertexFrame) arguments[0]).asVertex();
                addEdge(annotation, framedGraph, vertex, newVertex, null);
            }
            return null;
        }
    }
    return null;
}
Also used : DVertex(org.openntf.domino.graph2.DVertex) Vertex(com.tinkerpop.blueprints.Vertex) EdgeFrame(com.tinkerpop.frames.EdgeFrame) DFramedTransactionalGraph(org.openntf.domino.graph2.impl.DFramedTransactionalGraph) DElementStore(org.openntf.domino.graph2.DElementStore) Direction(com.tinkerpop.blueprints.Direction) Incidence(com.tinkerpop.frames.Incidence) VertexFrame(com.tinkerpop.frames.VertexFrame) Adjacency(com.tinkerpop.frames.Adjacency) Edge(com.tinkerpop.blueprints.Edge)

Example 2 with DFramedTransactionalGraph

use of org.openntf.domino.graph2.impl.DFramedTransactionalGraph in project org.openntf.domino by OpenNTF.

the class SearchResource method getSearchObject.

@SuppressWarnings("unchecked")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getSearchObject(@Context final UriInfo uriInfo, @PathParam(Routes.NAMESPACE) final String namespace, @Context final Request request) throws JsonException, IOException {
    @SuppressWarnings("rawtypes") DFramedTransactionalGraph graph = this.getGraph(namespace);
    ParamMap pm = Parameters.toParamMap(uriInfo);
    StringWriter sw = new StringWriter();
    JsonGraphWriter writer = new JsonGraphWriter(sw, graph, pm, false, true, false);
    Date lastModified = new Date();
    boolean getLastMod = false;
    try {
        if (pm.get(Parameters.ID) != null) {
            List<String> ids = pm.get(Parameters.ID);
            if (ids.size() == 0) {
                writer.outNull();
            } else if (ids.size() == 1) {
                String id = ids.get(0).trim();
                NoteCoordinate nc = null;
                if (id.startsWith("E")) {
                    nc = ViewEntryCoordinate.Utils.getViewEntryCoordinate(id);
                } else if (id.startsWith("V")) {
                    nc = ViewEntryCoordinate.Utils.getViewEntryCoordinate(id);
                } else {
                    nc = NoteCoordinate.Utils.getNoteCoordinate(id);
                    getLastMod = true;
                }
                Object elem = graph.getElement(nc, null);
                if (elem == null) {
                    throw new WebApplicationException(ErrorHelper.createErrorResponse("Graph element not found for id " + id, Response.Status.NOT_FOUND));
                }
                if (elem instanceof DVertexFrame && getLastMod) {
                    lastModified = ((DVertexFrame) elem).getModified();
                }
                if (elem instanceof DEdgeFrame && getLastMod) {
                    lastModified = ((DEdgeFrame) elem).getModified();
                }
                writer.outObject(elem);
            } else {
                List<Value> valueResults = null;
                List<RichTextReference> rtRefResults = null;
                for (String id : ids) {
                    NoteCoordinate nc = NoteCoordinate.Utils.getNoteCoordinate(id.trim());
                    Object rawterm = graph.getElement(nc, null);
                    // System.out.println("TEMP DEBUG got a " + DGraphUtils.getInterfaceList(rawterm) + " from id " + nc);
                    Term term = null;
                    if (rawterm instanceof Term) {
                        term = (Term) rawterm;
                    } else {
                    // System.out.println("TEMP DEBUG didn't get a Term!");
                    }
                    List<Value> values = term.getValues();
                    // System.out.println("TEMP DEBUG found " + values.size()  + " values for term " + term.getValue() + " in a " + values.getClass().getName());
                    List<RichTextReference> rtRefs = term.getRichTextReferences();
                    // System.out.println("TEMP DEBUG found " + rtRefs.size()  + " rtrefs for term " + term.getValue() + " in a " + rtRefs.getClass().getName());
                    if (valueResults == null) {
                        valueResults = values;
                    } else {
                        valueResults.retainAll(values);
                    // System.out.println("TEMP DEBUG retained " + valueResults.size()  + " values for term " + term.getValue());
                    }
                    if (rtRefResults == null) {
                        rtRefResults = rtRefs;
                    } else {
                        rtRefResults.retainAll(rtRefs);
                    // System.out.println("TEMP DEBUG retained " + rtRefResults.size()  + " rtrefs for term " + term.getValue());
                    }
                }
                List<Object> combinedResults = new ArrayList<Object>();
                combinedResults.addAll(valueResults);
                combinedResults.addAll(rtRefResults);
                writer.outArrayLiteral(combinedResults);
            }
        } else if (pm.getKeys() != null) {
            Class<?> type = Term.class;
            DKeyResolver resolver = graph.getKeyResolver(type);
            List<CharSequence> keys = pm.getKeys();
            if (keys.size() == 0) {
                writer.outNull();
            } else {
                List<Value> valueResults = null;
                List<RichTextReference> rtRefResults = null;
                String key = URLDecoder.decode(String.valueOf(keys.get(0)), "UTF-8");
                String[] array = key.split(" ");
                for (String cur : array) {
                    NoteCoordinate nc = resolver.resolveKey(type, cur);
                    Object rawterm = graph.getElement(nc, null);
                    Term term = null;
                    if (rawterm instanceof Term) {
                        term = (Term) rawterm;
                    } else {
                    }
                    List<Value> values = term.getValues();
                    List<RichTextReference> rtRefs = term.getRichTextReferences();
                    if (valueResults == null) {
                        valueResults = values;
                    } else {
                        valueResults.retainAll(values);
                    }
                    if (rtRefResults == null) {
                        rtRefResults = rtRefs;
                    } else {
                        rtRefResults.retainAll(rtRefs);
                    }
                }
                List<Object> combinedResults = new ArrayList<Object>();
                combinedResults.addAll(valueResults);
                combinedResults.addAll(rtRefResults);
                writer.outArrayLiteral(combinedResults);
            }
            graph.rollback();
        } else {
            // MultivaluedMap<String, String> mvm = uriInfo.getQueryParameters();
            Map<String, Object> jsonMap = new LinkedHashMap<String, Object>();
            jsonMap.put("namespace", namespace);
            jsonMap.put("status", "active");
            writer.outObject(jsonMap);
        }
    } catch (UserAccessException uae) {
        return ErrorHelper.createErrorResponse("User " + Factory.getSession(SessionType.CURRENT).getEffectiveUserName() + " is not authorized to access this resource", Response.Status.UNAUTHORIZED);
    } catch (KeyNotFoundException knfe) {
        ResponseBuilder rb = Response.noContent();
        return rb.build();
    } catch (Exception e) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
    }
    String jsonEntity = sw.toString();
    ResponseBuilder berg = getBuilder(jsonEntity, lastModified, true, request);
    Response response = berg.build();
    return response;
}
Also used : ParamMap(org.openntf.domino.rest.service.Parameters.ParamMap) WebApplicationException(javax.ws.rs.WebApplicationException) JsonGraphWriter(org.openntf.domino.rest.json.JsonGraphWriter) DFramedTransactionalGraph(org.openntf.domino.graph2.impl.DFramedTransactionalGraph) StringWriter(java.io.StringWriter) ArrayList(java.util.ArrayList) List(java.util.List) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) NoteCoordinate(org.openntf.domino.big.NoteCoordinate) DKeyResolver(org.openntf.domino.graph2.DKeyResolver) Term(org.openntf.domino.graph2.builtin.search.Term) UserAccessException(org.openntf.domino.exceptions.UserAccessException) Date(java.util.Date) UserAccessException(org.openntf.domino.exceptions.UserAccessException) KeyNotFoundException(org.openntf.domino.graph2.impl.DEdgeEntryList.KeyNotFoundException) IOException(java.io.IOException) JsonException(com.ibm.commons.util.io.json.JsonException) WebApplicationException(javax.ws.rs.WebApplicationException) DVertexFrame(org.openntf.domino.graph2.builtin.DVertexFrame) Response(javax.ws.rs.core.Response) DEdgeFrame(org.openntf.domino.graph2.builtin.DEdgeFrame) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ParamMap(org.openntf.domino.rest.service.Parameters.ParamMap) KeyNotFoundException(org.openntf.domino.graph2.impl.DEdgeEntryList.KeyNotFoundException) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 3 with DFramedTransactionalGraph

use of org.openntf.domino.graph2.impl.DFramedTransactionalGraph in project org.openntf.domino by OpenNTF.

the class TermsResource method getTermsObject.

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getTermsObject(@Context final UriInfo uriInfo, @PathParam(Routes.NAMESPACE) final String namespace, @Context final Request request) throws JsonException, IOException {
    DFramedTransactionalGraph graph = this.getGraph(namespace);
    ParamMap pm = Parameters.toParamMap(uriInfo);
    StringWriter sw = new StringWriter();
    JsonGraphWriter writer = new JsonGraphWriter(sw, graph, pm, false, true, true);
    try {
        List<CharSequence> types = new ArrayList<CharSequence>();
        types.add("org.openntf.domino.graph2.builtin.search.Term");
        List<CharSequence> filterkeys = pm.getFilterKeys();
        List<CharSequence> filtervalues = pm.getFilterValues();
        List<CharSequence> partialkeys = pm.getPartialKeys();
        List<CharSequence> partialvalues = pm.getPartialValues();
        List<CharSequence> startskeys = pm.getStartsKeys();
        List<CharSequence> startsvalues = pm.getStartsValues();
        if (types.size() == 0) {
            writer.outNull();
        } else if (types.size() == 1) {
            CharSequence typename = types.get(0);
            Iterable<?> elements = null;
            if (filterkeys != null) {
                elements = graph.getFilteredElements(typename.toString(), filterkeys, filtervalues);
            } else if (partialkeys != null) {
                elements = graph.getFilteredElementsPartial(typename.toString(), partialkeys, partialvalues);
            } else if (startskeys != null) {
                elements = graph.getFilteredElementsStarts(typename.toString(), startskeys, startsvalues);
            } else {
                elements = graph.getElements(typename.toString());
            }
            if (elements instanceof FramedEdgeList) {
                List<?> result = sortAndLimitList((List<?>) elements, pm);
                writer.outArrayLiteral(result);
            } else if (elements instanceof FramedVertexList) {
                List<?> result = sortAndLimitList((List<?>) elements, pm);
                writer.outArrayLiteral(result);
            } else {
                List<Object> maps = new ArrayList<Object>();
                for (Object element : elements) {
                    maps.add(element);
                }
                writer.outArrayLiteral(maps);
            }
        } else {
            MixedFramedVertexList vresult = null;
            FramedEdgeList eresult = null;
            for (CharSequence typename : types) {
                Iterable<?> elements = null;
                if (filterkeys != null) {
                    elements = graph.getFilteredElements(typename.toString(), filterkeys, filtervalues);
                } else if (partialkeys != null) {
                    elements = graph.getFilteredElementsPartial(typename.toString(), partialkeys, partialvalues);
                } else if (startskeys != null) {
                    elements = graph.getFilteredElementsStarts(typename.toString(), startskeys, startsvalues);
                } else {
                    elements = graph.getElements(typename.toString());
                }
                if (elements instanceof FramedVertexList) {
                    if (vresult == null) {
                        vresult = new MixedFramedVertexList(graph, null, (FramedVertexList) elements);
                    } else {
                        vresult.addAll((List<?>) elements);
                    }
                } else if (elements instanceof FramedEdgeList) {
                    if (eresult == null) {
                        eresult = (FramedEdgeList) elements;
                    } else {
                        eresult.addAll((FramedEdgeList) elements);
                    }
                }
            }
            if (vresult != null) {
                List<?> result = sortAndLimitList(vresult, pm);
                writer.outArrayLiteral(result);
            }
            if (eresult != null) {
                List<?> result = sortAndLimitList(eresult, pm);
                writer.outArrayLiteral(result);
            }
        }
    } catch (UserAccessException uae) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse(uae, Response.Status.UNAUTHORIZED));
    } catch (Exception e) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
    }
    String jsonEntity = sw.toString();
    ResponseBuilder berg = getBuilder(jsonEntity, new Date(), true, request);
    Response response = berg.build();
    return response;
}
Also used : ParamMap(org.openntf.domino.rest.service.Parameters.ParamMap) WebApplicationException(javax.ws.rs.WebApplicationException) JsonGraphWriter(org.openntf.domino.rest.json.JsonGraphWriter) ArrayList(java.util.ArrayList) DFramedTransactionalGraph(org.openntf.domino.graph2.impl.DFramedTransactionalGraph) MixedFramedVertexList(org.openntf.domino.graph2.annotations.MixedFramedVertexList) FramedEdgeList(org.openntf.domino.graph2.annotations.FramedEdgeList) FramedVertexList(org.openntf.domino.graph2.annotations.FramedVertexList) MixedFramedVertexList(org.openntf.domino.graph2.annotations.MixedFramedVertexList) UserAccessException(org.openntf.domino.exceptions.UserAccessException) UserAccessException(org.openntf.domino.exceptions.UserAccessException) IOException(java.io.IOException) JsonException(com.ibm.commons.util.io.json.JsonException) WebApplicationException(javax.ws.rs.WebApplicationException) Date(java.util.Date) Response(javax.ws.rs.core.Response) StringWriter(java.io.StringWriter) FramedEdgeList(org.openntf.domino.graph2.annotations.FramedEdgeList) ArrayList(java.util.ArrayList) FramedVertexList(org.openntf.domino.graph2.annotations.FramedVertexList) MixedFramedVertexList(org.openntf.domino.graph2.annotations.MixedFramedVertexList) List(java.util.List) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 4 with DFramedTransactionalGraph

use of org.openntf.domino.graph2.impl.DFramedTransactionalGraph in project org.openntf.domino by OpenNTF.

the class FramedCollectionResource method createFramedObject.

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createFramedObject(final String requestEntity, @Context final UriInfo uriInfo, @PathParam(Routes.NAMESPACE) final String namespace, @Context final Request request) throws JsonException, IOException {
    // org.apache.wink.common.internal.registry.metadata.ResourceMetadataCollector
    // rc;
    DFramedTransactionalGraph graph = this.getGraph(namespace);
    ParamMap pm = Parameters.toParamMap(uriInfo);
    StringWriter sw = new StringWriter();
    JsonGraphWriter writer = new JsonGraphWriter(sw, graph, pm, false, true, true);
    // System.out.println("TEMP DEBUG Starting new POST...");
    JsonJavaObject jsonItems = null;
    List<Object> jsonArray = null;
    JsonGraphFactory factory = JsonGraphFactory.instance;
    try {
        StringReader reader = new StringReader(requestEntity);
        try {
            Object jsonRaw = JsonParser.fromJson(factory, reader);
            if (jsonRaw instanceof JsonJavaObject) {
                jsonItems = (JsonJavaObject) jsonRaw;
            } else if (jsonRaw instanceof List) {
                jsonArray = (List<Object>) jsonRaw;
            // System.out.println("TEMP DEBUG processing a POST with an
            // array of size " + jsonArray.size());
            } else {
            // System.out.println("TEMP DEBUG Got an unexpected object
            // from parser "
            // + (jsonRaw == null ? "null" :
            // jsonRaw.getClass().getName()));
            }
        } catch (Exception e) {
            throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
        } finally {
            reader.close();
        }
    } catch (Exception ex) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse(ex, Response.Status.INTERNAL_SERVER_ERROR));
    }
    boolean committed = true;
    Map<Object, Object> results = new LinkedHashMap<Object, Object>();
    if (jsonArray != null) {
        writer.startArray();
        for (Object raw : jsonArray) {
            if (raw instanceof JsonJavaObject) {
                writer.startArrayItem();
                committed = processJsonObject((JsonJavaObject) raw, graph, writer, results);
                writer.endArrayItem();
            } else {
                System.err.println("Raw array member isn't a JsonJavaObject. It's a " + (raw == null ? "null" : raw.getClass().getName()));
            }
        }
        writer.endArray();
    } else if (jsonItems != null) {
        committed = processJsonObject(jsonItems, graph, writer, results);
    } else {
    // System.out.println("TEMP DEBUG Nothing to POST. No JSON items
    // found.");
    }
    String jsonEntity = sw.toString();
    ResponseBuilder berg = getBuilder(jsonEntity, new Date(), false, request);
    Response response = berg.build();
    if (!committed) {
        graph.rollback();
    }
    return response;
}
Also used : ParamMap(org.openntf.domino.rest.service.Parameters.ParamMap) WebApplicationException(javax.ws.rs.WebApplicationException) JsonGraphWriter(org.openntf.domino.rest.json.JsonGraphWriter) DFramedTransactionalGraph(org.openntf.domino.graph2.impl.DFramedTransactionalGraph) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString) JsonException(com.ibm.commons.util.io.json.JsonException) WebApplicationException(javax.ws.rs.WebApplicationException) UserAccessException(org.openntf.domino.exceptions.UserAccessException) IOException(java.io.IOException) Date(java.util.Date) LinkedHashMap(java.util.LinkedHashMap) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) Response(javax.ws.rs.core.Response) StringWriter(java.io.StringWriter) JsonGraphFactory(org.openntf.domino.rest.json.JsonGraphFactory) StringReader(java.io.StringReader) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) FramedEdgeList(org.openntf.domino.graph2.annotations.FramedEdgeList) List(java.util.List) ArrayList(java.util.ArrayList) FramedVertexList(org.openntf.domino.graph2.annotations.FramedVertexList) MixedFramedVertexList(org.openntf.domino.graph2.annotations.MixedFramedVertexList) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 5 with DFramedTransactionalGraph

use of org.openntf.domino.graph2.impl.DFramedTransactionalGraph in project org.openntf.domino by OpenNTF.

the class FramedCollectionResource method processJsonObject.

@SuppressWarnings("unlikely-arg-type")
private boolean processJsonObject(final JsonJavaObject jsonItems, final DFramedTransactionalGraph graph, final JsonGraphWriter writer, final Map<Object, Object> results) {
    Map<CaseInsensitiveString, Object> cisMap = new HashMap<CaseInsensitiveString, Object>();
    for (String jsonKey : jsonItems.keySet()) {
        CaseInsensitiveString cis = new CaseInsensitiveString(jsonKey);
        cisMap.put(cis, jsonItems.get(jsonKey));
    }
    String rawType = jsonItems.getAsString("@type");
    String label = jsonItems.getAsString("@label");
    Object rawId = jsonItems.get("@id");
    boolean commit = true;
    if (rawType != null && rawType.length() > 0) {
        try {
            rawType = rawType.trim();
            Class<?> type = graph.getTypeRegistry().findClassByName(rawType);
            if (VertexFrame.class.isAssignableFrom(type)) {
                VertexFrame parVertex = (VertexFrame) graph.addVertex(null, type);
                String resultId = parVertex.asVertex().getId().toString();
                results.put(rawId, resultId);
                try {
                    JsonFrameAdapter adapter = new JsonFrameAdapter(graph, parVertex, null, true);
                    Iterator<String> frameProperties = adapter.getJsonProperties();
                    CaseInsensitiveString actionName = null;
                    CaseInsensitiveString preactionName = null;
                    List<Object> actionArguments = null;
                    for (CaseInsensitiveString cis : cisMap.keySet()) {
                        if (cis.equals("%preaction")) {
                            preactionName = new CaseInsensitiveString(String.valueOf(cisMap.get(cis)));
                        }
                        if (cis.equals("%args")) {
                            Object result = cisMap.get(cis);
                            if (result instanceof List) {
                                actionArguments = (List) result;
                            }
                        }
                    }
                    if (preactionName != null) {
                        if (actionArguments != null) {
                            commit = adapter.runAction(preactionName, actionArguments);
                        } else {
                            commit = adapter.runAction(preactionName);
                        }
                    }
                    if (commit) {
                        while (frameProperties.hasNext()) {
                            CaseInsensitiveString key = new CaseInsensitiveString(frameProperties.next());
                            if (!key.startsWith("@") && !key.startsWith("%")) {
                                Object value = cisMap.get(key);
                                if (value != null) {
                                    adapter.putJsonProperty(key.toString(), value);
                                    cisMap.remove(key);
                                }
                            }
                        }
                        if (!cisMap.isEmpty()) {
                            for (CaseInsensitiveString cis : cisMap.keySet()) {
                                if (cis.equals("%action")) {
                                    actionName = new CaseInsensitiveString(String.valueOf(cisMap.get(cis)));
                                } else if (!cis.startsWith("@") && !cis.startsWith("%")) {
                                    Object value = cisMap.get(cis);
                                    if (value != null) {
                                        adapter.putJsonProperty(cis.toString(), value);
                                    }
                                }
                            }
                            adapter.updateReadOnlyProperties();
                            if (actionName != null) {
                                if (actionArguments != null) {
                                    commit = adapter.runAction(actionName, actionArguments);
                                } else {
                                    commit = adapter.runAction(actionName);
                                }
                            }
                        }
                    }
                    writer.outObject(parVertex);
                } catch (Exception e) {
                    throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
                }
            }
        } catch (IllegalArgumentException iae) {
            throw new RuntimeException(iae);
        }
    } else if (label != null && label.length() > 0) {
        // System.out.println("TEMP DEBUG adding an inline edge...");
        String inid = null;
        String outid = null;
        JsonJavaObject in = jsonItems.getAsObject("@in");
        if (in != null) {
            Object rawinid = in.get("@id");
            if (rawinid instanceof Double) {
                inid = String.valueOf(results.get(rawinid)).trim();
                // System.out.println("in id is an integer. It resolves to "
                // + inid);
                in.put("@id", inid);
            } else {
                inid = String.valueOf(rawinid).trim();
            // System.out.println("in id is not an integer. It's a " +
            // rawinid.getClass().getName() + ": "
            // + String.valueOf(rawinid));
            }
        }
        JsonJavaObject out = jsonItems.getAsObject("@out");
        if (out != null) {
            Object rawoutid = out.get("@id");
            if (rawoutid instanceof Double) {
                outid = String.valueOf(results.get(rawoutid));
                // System.out.println("out id is an integer. It resolves to
                // " + outid);
                out.put("@id", outid);
            } else {
                outid = String.valueOf(rawoutid).trim();
            // System.out.println("out id is not an integer. It's a " +
            // rawoutid.getClass().getName() + ": "
            // + String.valueOf(rawoutid));
            }
        }
        NoteCoordinate nc = NoteCoordinate.Utils.getNoteCoordinate(inid);
        Object element = graph.getElement(nc, null);
        if (element instanceof VertexFrame) {
            VertexFrame parVertex = (VertexFrame) element;
            Map<CaseInsensitiveString, Method> adders = graph.getTypeRegistry().getAdders(parVertex.getClass());
            CaseInsensitiveString rawLabel = new CaseInsensitiveString(label);
            Method method = adders.get(rawLabel);
            if (method == null) {
                rawLabel = new CaseInsensitiveString(label + "In");
                method = adders.get(rawLabel);
            }
            if (method != null) {
                NoteCoordinate othernc = NoteCoordinate.Utils.getNoteCoordinate(outid);
                Object otherElement = graph.getElement(othernc, null);
                if (otherElement instanceof VertexFrame) {
                    VertexFrame otherVertex = (VertexFrame) otherElement;
                    try {
                        Object result = method.invoke(parVertex, otherVertex);
                        if (result == null) {
                            System.out.println("Invokation of method " + method.getName() + " on a vertex of type " + DGraphUtils.findInterface(parVertex) + " with an argument of type " + DGraphUtils.findInterface(otherVertex) + " resulted in null when we expected an Edge");
                        }
                        JsonFrameAdapter adapter = new JsonFrameAdapter(graph, (EdgeFrame) result, null, true);
                        Iterator<String> frameProperties = adapter.getJsonProperties();
                        while (frameProperties.hasNext()) {
                            CaseInsensitiveString key = new CaseInsensitiveString(frameProperties.next());
                            if (!key.startsWith("@")) {
                                Object value = cisMap.get(key);
                                if (value != null) {
                                    adapter.putJsonProperty(key.toString(), value);
                                    cisMap.remove(key);
                                }
                            }
                        }
                        for (CaseInsensitiveString cis : cisMap.keySet()) {
                            if (!cis.startsWith("@")) {
                                Object value = cisMap.get(cis);
                                if (value != null) {
                                    adapter.putJsonProperty(cis.toString(), value);
                                }
                            }
                        }
                        writer.outObject(result);
                    } catch (IllegalArgumentException iae) {
                        Exception e = new RuntimeException("Invokation of method " + method.getName() + " on a vertex of type " + DGraphUtils.findInterface(parVertex) + " with an argument of type " + DGraphUtils.findInterface(otherVertex) + " resulted in an exception", iae);
                        throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
                    } catch (Exception e) {
                        throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
                    }
                } else {
                    Factory.println("otherElement is not a VertexFrame. It's a " + (otherElement == null ? "null" : DGraphUtils.findInterface(otherElement).getName()));
                }
            } else {
                Class<?>[] interfaces = element.getClass().getInterfaces();
                String intList = "";
                for (Class<?> inter : interfaces) {
                    intList = intList + inter.getName() + ", ";
                }
                String methList = "";
                for (CaseInsensitiveString key : adders.keySet()) {
                    methList = methList + key.toString() + ", ";
                }
                Factory.println("No method found for " + rawLabel + " on element " + intList + ": " + ((VertexFrame) element).asVertex().getId() + " methods " + methList);
            }
        } else {
            org.openntf.domino.utils.Factory.println("element is not a VertexFrame. It's a " + element.getClass().getName());
        }
    } else {
        System.err.println("Cannot POST without an @type in the JSON");
    }
    if (commit) {
        graph.commit();
    }
    return commit;
}
Also used : NoteCoordinate(org.openntf.domino.big.NoteCoordinate) EdgeFrame(com.tinkerpop.frames.EdgeFrame) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString) Method(java.lang.reflect.Method) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString) JsonException(com.ibm.commons.util.io.json.JsonException) WebApplicationException(javax.ws.rs.WebApplicationException) UserAccessException(org.openntf.domino.exceptions.UserAccessException) IOException(java.io.IOException) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) VertexFrame(com.tinkerpop.frames.VertexFrame) Iterator(java.util.Iterator) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) FramedEdgeList(org.openntf.domino.graph2.annotations.FramedEdgeList) List(java.util.List) ArrayList(java.util.ArrayList) FramedVertexList(org.openntf.domino.graph2.annotations.FramedVertexList) MixedFramedVertexList(org.openntf.domino.graph2.annotations.MixedFramedVertexList) Map(java.util.Map) ParamMap(org.openntf.domino.rest.service.Parameters.ParamMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

DFramedTransactionalGraph (org.openntf.domino.graph2.impl.DFramedTransactionalGraph)13 JsonException (com.ibm.commons.util.io.json.JsonException)11 IOException (java.io.IOException)11 WebApplicationException (javax.ws.rs.WebApplicationException)11 UserAccessException (org.openntf.domino.exceptions.UserAccessException)11 JsonJavaObject (com.ibm.commons.util.io.json.JsonJavaObject)10 VertexFrame (com.tinkerpop.frames.VertexFrame)10 StringWriter (java.io.StringWriter)10 ArrayList (java.util.ArrayList)10 List (java.util.List)10 Response (javax.ws.rs.core.Response)10 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)10 JsonGraphWriter (org.openntf.domino.rest.json.JsonGraphWriter)10 CaseInsensitiveString (org.openntf.domino.types.CaseInsensitiveString)10 Date (java.util.Date)9 ParamMap (org.openntf.domino.rest.service.Parameters.ParamMap)9 LinkedHashMap (java.util.LinkedHashMap)8 Produces (javax.ws.rs.Produces)8 DVertexFrame (org.openntf.domino.graph2.builtin.DVertexFrame)8 Vertex (com.tinkerpop.blueprints.Vertex)6