Search in sources :

Example 1 with VertexFrame

use of com.tinkerpop.frames.VertexFrame 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 VertexFrame

use of com.tinkerpop.frames.VertexFrame in project org.openntf.domino by OpenNTF.

the class JsonSearchAdapter method getJsonProperty.

@SuppressWarnings("unlikely-arg-type")
@Override
public Object getJsonProperty(final String paramKey) {
    Object result = null;
    Object frame = getFrame();
    if (frame != null) {
        CaseInsensitiveString key = new CaseInsensitiveString(paramKey);
        if (key.equals("@id")) {
            if (frame instanceof VertexFrame) {
                result = ((VertexFrame) frame).asVertex().getId().toString();
            } else if (frame instanceof EdgeFrame) {
                result = ((EdgeFrame) frame).asEdge().getId().toString();
            }
        } else if (key.equals("@proxyid")) {
            if (frame instanceof VertexFrame) {
                Vertex v = ((VertexFrame) frame).asVertex();
                if (v instanceof DProxyVertex) {
                    result = ((DProxyVertex) v).getProperty(DProxyVertex.PROXY_ITEM, String.class);
                }
            }
        } else if (key.equals("@debug")) {
            Map<String, String> debugMap = new LinkedHashMap<String, String>();
            debugMap.put("frameIdentity", String.valueOf(System.identityHashCode(this)));
            if (frame instanceof VertexFrame) {
                Vertex v = ((VertexFrame) frame).asVertex();
                debugMap.put("vertexIdentity", String.valueOf(System.identityHashCode(v)));
            } else if (frame instanceof EdgeFrame) {
                Edge e = ((EdgeFrame) frame).asEdge();
                debugMap.put("edgeIdentity", String.valueOf(System.identityHashCode(e)));
            }
            result = debugMap;
        } else if (key.equals("@type")) {
            if (frame instanceof VertexFrame) {
                result = type_;
            } else if (frame instanceof EdgeFrame) {
                result = type_;
            }
        } else if (key.equals("@in") && frame instanceof EdgeFrame) {
            if (getInProperties() == null) {
                // why not just make a frame adapter with the vertex?
                // because that's another I/O operation. We already have the
                // information needed to
                DEdge dedge = (DEdge) ((EdgeFrame) frame).asEdge();
                Map<String, String> minProps = new LinkedHashMap<String, String>();
                minProps.put("@id", dedge.getVertexId(Direction.IN).toString());
                Class<?> inType = graph_.getTypeRegistry().getInType(type_);
                if (inType == null) {
                    minProps.put("@type", "Vertex");
                } else {
                    minProps.put("@type", inType.getName());
                }
                result = minProps;
            } else {
                ParamMap inMap = new ParamMap();
                inMap.put(Parameters.PROPS, CaseInsensitiveString.toStrings(getInProperties()));
                if (getIncludeEdges()) {
                    inMap.put(Parameters.EDGES, EMPTY_STRINGS);
                }
                if (getIncludeCounts()) {
                    inMap.put(Parameters.COUNTS, EMPTY_STRINGS);
                }
                Method inMethod = graph_.getTypeRegistry().getIn(type_);
                if (inMethod != null) {
                    try {
                        Object raw = inMethod.invoke(frame, (Object[]) null);
                        if (raw instanceof Term) {
                            result = new JsonSearchAdapter(graph_, (Term) raw, inMap, isCollectionRoute_);
                        } else if (raw instanceof Value) {
                            result = new JsonSearchAdapter(graph_, (Value) raw, inMap, isCollectionRoute_);
                        } else if (raw instanceof RichTextReference) {
                            result = new JsonSearchAdapter(graph_, (RichTextReference) raw, inMap, isCollectionRoute_);
                        } else if (raw instanceof VertexFrame) {
                            result = new JsonFrameAdapter(graph_, (VertexFrame) raw, inMap, isCollectionRoute_);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if (key.equals("@out") && frame instanceof EdgeFrame) {
            if (getOutProperties() == null) {
                // why not just make a frame adapter with the vertex?
                // because that's another I/O operation. We already have the
                // information needed to
                DEdge dedge = (DEdge) ((EdgeFrame) frame).asEdge();
                Map<String, String> minProps = new LinkedHashMap<String, String>();
                minProps.put("@id", dedge.getVertexId(Direction.OUT).toString());
                Class<?> outType = graph_.getTypeRegistry().getOutType(type_);
                if (outType == null) {
                    minProps.put("@type", "Vertex");
                } else {
                    minProps.put("@type", outType.getName());
                }
                result = minProps;
            } else {
                ParamMap outMap = new ParamMap();
                outMap.put(Parameters.PROPS, CaseInsensitiveString.toStrings(getOutProperties()));
                if (getIncludeEdges()) {
                    outMap.put(Parameters.EDGES, EMPTY_STRINGS);
                }
                if (getIncludeCounts()) {
                    outMap.put(Parameters.COUNTS, EMPTY_STRINGS);
                }
                Method outMethod = graph_.getTypeRegistry().getOut(type_);
                if (outMethod != null) {
                    try {
                        Object raw = outMethod.invoke(frame, (Object[]) null);
                        if (raw instanceof Term) {
                            result = new JsonSearchAdapter(graph_, (Term) raw, outMap, isCollectionRoute_);
                        } else if (raw instanceof Value) {
                            result = new JsonSearchAdapter(graph_, (Value) raw, outMap, isCollectionRoute_);
                        } else if (raw instanceof RichTextReference) {
                            result = new JsonSearchAdapter(graph_, (RichTextReference) raw, outMap, isCollectionRoute_);
                        } else if (raw instanceof VertexFrame) {
                            result = new JsonFrameAdapter(graph_, (VertexFrame) raw, outMap, isCollectionRoute_);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if (key.equals("@edges")) {
            Map<String, Integer> edgeCounts = new LinkedHashMap<String, Integer>();
            Set<CaseInsensitiveString> counterKeys = getCounters().keySet();
            for (CaseInsensitiveString label : counterKeys) {
                Method crystal = getCounters().get(label);
                if (crystal != null) {
                    try {
                        Object raw = crystal.invoke(getFrame(), (Object[]) null);
                        if (raw instanceof Integer) {
                            edgeCounts.put(label.toString(), (Integer) raw);
                        } else {
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                }
            }
            result = edgeCounts;
        } else if (key.equals("@actions")) {
            List<CaseInsensitiveString> actionList = new ArrayList<CaseInsensitiveString>();
            Set<CaseInsensitiveString> actionNames = getActions().keySet();
            for (CaseInsensitiveString name : actionNames) {
                actionList.add(name);
            }
            result = actionList;
        } else if (key.startsWith("@counts")) {
            String label = key.toString().substring("@counts".length());
            Method crystal = getCounters().get(new CaseInsensitiveString(label));
            if (crystal != null) {
                try {
                    Object raw = crystal.invoke(getFrame(), (Object[]) null);
                    if (raw instanceof Integer) {
                        result = raw;
                    } else {
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else {
            }
        } else if (key.equals("@columninfo")) {
            if (frame instanceof ViewVertex) {
                Map<String, String> columnInfo = new LinkedHashMap<String, String>();
                if (frame instanceof ViewVertex) {
                    View view = ((ViewVertex) frame).asView();
                    for (ViewColumn column : view.getColumns()) {
                        String progName = column.getItemName();
                        String title = column.getTitle();
                        columnInfo.put(progName, title);
                    }
                } else {
                    System.err.println("Frame is not a ViewVertex. It is " + DGraphUtils.findInterface(frame));
                }
                return columnInfo;
            }
        } else if (key.equals("@viewinfo")) {
            if (frame instanceof DbInfoVertex) {
                List viewInfo = ((DbInfoVertex) frame).getViewInfo();
                return viewInfo;
            }
        } else if (key.startsWith("#") && frame instanceof VertexFrame) {
            CharSequence label = key.subSequence(1, key.length());
            Method crystal = getIncidences().get(label);
            if (crystal != null) {
                try {
                    result = crystal.invoke(frame, (Object[]) null);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                if (result != null) {
                    if (!(result instanceof Iterable)) {
                        if (result instanceof EdgeFrame) {
                            Vertex v = ((VertexFrame) frame).asVertex();
                            List<Edge> edges = new org.openntf.domino.graph2.impl.DEdgeList((DVertex) v);
                            edges.add(((EdgeFrame) result).asEdge());
                            result = new FramedEdgeList(getGraph(), ((VertexFrame) frame).asVertex(), edges, crystal.getReturnType());
                        }
                    }
                    if (getIncludeVertices()) {
                        if (result instanceof DEdgeList) {
                            result = ((DEdgeList) result).toVertexList();
                        } else if (result instanceof FramedEdgeList) {
                            result = ((FramedEdgeList<?>) result).toVertexList();
                        } else {
                            System.err.println("TEMP DEBUG: Expected a DEdgeList but got a " + result.getClass().getName());
                        }
                    }
                    if (getFilterKeys() != null && !isCollectionRoute_) {
                        List<CharSequence> filterKeys = getFilterKeys();
                        List<CharSequence> filterValues = getFilterValues();
                        Map<CharSequence, Set<CharSequence>> filterMap = new HashMap<CharSequence, Set<CharSequence>>();
                        for (int i = 0; i < filterKeys.size(); i++) {
                            String curkey = filterKeys.get(i).toString();
                            String curvalue = filterValues.get(i).toString();
                            if (Value.REPLICA_KEY.equalsIgnoreCase(curkey)) {
                                Set<CharSequence> replicas = filterMap.get(Value.REPLICA_KEY);
                                if (replicas == null) {
                                    replicas = new HashSet<CharSequence>();
                                    filterMap.put(Value.REPLICA_KEY, replicas);
                                }
                                replicas.add(new CaseInsensitiveString(curvalue));
                            } else if (Value.FORM_KEY.equalsIgnoreCase(curkey)) {
                                Set<CharSequence> forms = filterMap.get(Value.FORM_KEY);
                                if (forms == null) {
                                    forms = new HashSet<CharSequence>();
                                    filterMap.put(Value.FORM_KEY, forms);
                                }
                                forms.add(new CaseInsensitiveString(curvalue));
                            } else if (Value.FIELD_KEY.equalsIgnoreCase(curkey)) {
                                Set<CharSequence> forms = filterMap.get(Value.FIELD_KEY);
                                if (forms == null) {
                                    forms = new HashSet<CharSequence>();
                                    filterMap.put(Value.FIELD_KEY, forms);
                                }
                                forms.add(new CaseInsensitiveString(curvalue));
                            }
                        }
                        if (result instanceof FramedVertexList) {
                            // this should always be the case
                            FramedVertexList fvl = (FramedVertexList) result;
                            List<Vertex> vertList = new ArrayList<Vertex>();
                            FramedVertexList filterList = new FramedVertexList<VertexFrame>(fvl.getGraph(), fvl.getSourceVertex(), vertList, null);
                            for (Object raw : fvl) {
                                if (raw instanceof Value) {
                                    Map hits = ((Value) raw).getHits(filterMap);
                                    if (hits.size() > 0) {
                                        filterList.add((Value) raw);
                                    }
                                } else if (raw instanceof RichTextReference) {
                                    if (((RichTextReference) raw).isFilterMatch(filterMap)) {
                                        filterList.add((RichTextReference) raw);
                                    }
                                }
                            }
                            result = filterList;
                        }
                    }
                    if (getStartsValues() != null) {
                        if (result instanceof DEdgeEntryList) {
                            ((DEdgeEntryList) result).initEntryList(getStartsValues());
                        } else if (result instanceof FramedEdgeList) {
                            ((FramedEdgeList) result).applyFilter("lookup", getStartsValues());
                        }
                    }
                    if (getFilterValues() != null && getFilterKeys() == null) {
                        if (result instanceof DEdgeEntryList) {
                            ((DEdgeEntryList) result).filterEntryList(getFilterValues());
                        } else if (result instanceof FramedEdgeList) {
                            ((FramedEdgeList) result).applyFilter("filter", getFilterValues());
                        }
                    }
                    if (getOrderBys() != null) {
                        if (result instanceof FramedEdgeList) {
                            result = ((FramedEdgeList<?>) result).sortBy(getOrderBys(), getDescending());
                        } else if (result instanceof FramedVertexList) {
                            result = ((FramedVertexList<?>) result).sortBy(getOrderBys(), getDescending());
                        }
                    }
                    if (getStart() >= 0) {
                        if (getCount() > 0) {
                            int end = getStart() + getCount();
                            if (result instanceof FramedEdgeList) {
                                // System.out.println("TEMP DEBUG Sublisting
                                // a FramedEdgeList...");
                                int size = ((FramedEdgeList<?>) result).size();
                                result = ((FramedEdgeList<?>) result).subList(getStart(), (end > size ? size : end));
                            } else if (result instanceof FramedVertexList) {
                                int size = ((FramedVertexList<?>) result).size();
                                result = ((FramedVertexList<?>) result).subList(getStart(), (end > size ? size : end));
                            } else if (result instanceof DEdgeEntryList) {
                                // System.out.println("TEMP DEBUG Sublisting
                                // a DEdgeEntryList...");
                                int size = ((DEdgeEntryList) result).size();
                                result = ((DEdgeEntryList) result).subList(getStart() + 1, (end > size ? size : end));
                            }
                        } else {
                            if (result instanceof FramedEdgeList) {
                                result = ((FramedEdgeList<?>) result).subList(getStart(), ((FramedEdgeList<?>) result).size());
                            } else if (result instanceof FramedVertexList) {
                                result = ((FramedVertexList<?>) result).subList(getStart(), ((FramedVertexList<?>) result).size());
                            } else if (result instanceof DEdgeEntryList) {
                                // System.out.println("TEMP DEBUG Sublisting
                                // a DEdgeEntryList...");
                                result = ((DEdgeEntryList) result).subList(getStart() + 1, ((DEdgeEntryList) result).size());
                            }
                        }
                    }
                    if (result instanceof FramedVertexList) {
                        ParamMap listMap = new ParamMap();
                        if (getIncludeEdges()) {
                            listMap.put(Parameters.EDGES, EMPTY_STRINGS);
                        }
                        if (getIncludeCounts()) {
                            listMap.put(Parameters.COUNTS, EMPTY_STRINGS);
                        }
                        listMap.put(Parameters.PROPS, CaseInsensitiveString.toStrings(this.getProperties()));
                        listMap.put(Parameters.HIDEPROPS, CaseInsensitiveString.toStrings(this.getHideProperties()));
                        result = new JsonFrameListAdapter(getGraph(), (FramedVertexList<?>) result, listMap, isCollectionRoute_);
                    }
                }
            } else {
            // NTF actually, this is a perfectly normal outcome.
            }
        } else {
            Method crystal = getGetters().get(key);
            if (crystal != null) {
                try {
                    result = crystal.invoke(frame, (Object[]) null);
                } catch (UserAccessException uae) {
                    throw uae;
                } catch (Throwable t) {
                    if (frame instanceof EdgeFrame) {
                        result = ((EdgeFrame) frame).asEdge().getProperty(paramKey);
                    } else if (frame instanceof VertexFrame) {
                        result = ((VertexFrame) frame).asVertex().getProperty(paramKey);
                    } else {
                        System.err.println("Trying to get property " + paramKey + " from an object " + frame.getClass().getName());
                    }
                }
            } else {
                if (frame instanceof ViewVertex.Contains) {
                    result = ((EdgeFrame) frame).asEdge().getProperty(paramKey);
                } else if (frame instanceof VertexFrame) {
                    result = ((VertexFrame) frame).asVertex().getProperty(paramKey);
                } else if (frame instanceof EdgeFrame) {
                    result = ((EdgeFrame) frame).asEdge().getProperty(paramKey);
                } else {
                    System.err.println("No method found for key " + paramKey);
                }
            }
        }
    } else {
        System.err.println("Unable to get property " + paramKey + " on a null object");
    }
    return result;
}
Also used : ParamMap(org.openntf.domino.rest.service.Parameters.ParamMap) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString) LinkedHashMap(java.util.LinkedHashMap) RichTextReference(org.openntf.domino.graph2.builtin.search.RichTextReference) DbInfoVertex(org.openntf.domino.graph2.builtin.DbInfoVertex) FramedEdgeList(org.openntf.domino.graph2.annotations.FramedEdgeList) ArrayList(java.util.ArrayList) DEdgeEntryList(org.openntf.domino.graph2.impl.DEdgeEntryList) DEdgeList(org.openntf.domino.graph2.DEdgeList) FramedVertexList(org.openntf.domino.graph2.annotations.FramedVertexList) List(java.util.List) DEdgeList(org.openntf.domino.graph2.DEdgeList) HashSet(java.util.HashSet) DProxyVertex(org.openntf.domino.graph2.impl.DProxyVertex) DVertex(org.openntf.domino.graph2.impl.DVertex) Method(java.lang.reflect.Method) Term(org.openntf.domino.graph2.builtin.search.Term) FramedEdgeList(org.openntf.domino.graph2.annotations.FramedEdgeList) UserAccessException(org.openntf.domino.exceptions.UserAccessException) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString) Value(org.openntf.domino.graph2.builtin.search.Value) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) JsonObject(com.ibm.commons.util.io.json.JsonObject) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ParamMap(org.openntf.domino.rest.service.Parameters.ParamMap) ViewVertex(org.openntf.domino.graph2.builtin.ViewVertex) DVertex(org.openntf.domino.graph2.impl.DVertex) Vertex(com.tinkerpop.blueprints.Vertex) DbInfoVertex(org.openntf.domino.graph2.builtin.DbInfoVertex) DProxyVertex(org.openntf.domino.graph2.impl.DProxyVertex) HashSet(java.util.HashSet) Set(java.util.Set) JsonFrameAdapter(org.openntf.domino.rest.resources.frames.JsonFrameAdapter) ViewColumn(org.openntf.domino.ViewColumn) FramedVertexList(org.openntf.domino.graph2.annotations.FramedVertexList) JsonFrameListAdapter(org.openntf.domino.rest.resources.frames.JsonFrameListAdapter) ViewVertex(org.openntf.domino.graph2.builtin.ViewVertex) EdgeFrame(com.tinkerpop.frames.EdgeFrame) DEdgeFrame(org.openntf.domino.graph2.builtin.DEdgeFrame) View(org.openntf.domino.View) UserAccessException(org.openntf.domino.exceptions.UserAccessException) DVertexFrame(org.openntf.domino.graph2.builtin.DVertexFrame) VertexFrame(com.tinkerpop.frames.VertexFrame) DEdgeEntryList(org.openntf.domino.graph2.impl.DEdgeEntryList) DEdge(org.openntf.domino.graph2.impl.DEdge) Edge(com.tinkerpop.blueprints.Edge) DEdge(org.openntf.domino.graph2.impl.DEdge)

Example 3 with VertexFrame

use of com.tinkerpop.frames.VertexFrame in project org.openntf.domino by OpenNTF.

the class FramedCollectionResource method processJsonUpdate.

@SuppressWarnings("unlikely-arg-type")
private void processJsonUpdate(final JsonJavaObject jsonItems, final DFramedTransactionalGraph graph, final JsonGraphWriter writer, final ParamMap pm, final String method) throws JsonException, IOException {
    boolean commit = true;
    boolean isPut = "put".equalsIgnoreCase(method);
    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 id = jsonItems.getAsString("@id");
    JsonFrameAdapter adapter = null;
    NoteCoordinate nc = NoteCoordinate.Utils.getNoteCoordinate(id.trim());
    Object element = graph.getElement(nc, null);
    if (element instanceof EdgeFrame) {
        adapter = new JsonFrameAdapter(graph, (EdgeFrame) element, null, true);
    } else if (element instanceof VertexFrame) {
        adapter = new JsonFrameAdapter(graph, (VertexFrame) element, null, true);
    } else if (element == null) {
        if ("post".equalsIgnoreCase(method)) {
            throw new RuntimeException("Cannot force a metaversalid through REST API: " + id);
        } else {
            throw new RuntimeException("Element id " + id + " was not found in the graph");
        }
    } else {
        // TODO
        throw new RuntimeException("TODO");
    }
    Iterator<String> frameProperties = adapter.getJsonProperties();
    CaseInsensitiveString actionName = null;
    CaseInsensitiveString preactionName = null;
    for (CaseInsensitiveString cis : cisMap.keySet()) {
        if (cis.equals("%preaction")) {
            preactionName = new CaseInsensitiveString(String.valueOf(cisMap.get(cis)));
        }
    }
    if (preactionName != null) {
        commit = adapter.runAction(preactionName);
    }
    if (commit) {
        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);
                } else if (isPut) {
                    adapter.putJsonProperty(key.toString(), value);
                }
            }
        }
        for (CaseInsensitiveString cis : cisMap.keySet()) {
            if (cis.equals("%action")) {
                actionName = new CaseInsensitiveString(String.valueOf(cisMap.get(cis)));
            } else if (!cis.startsWith("@")) {
                Object value = cisMap.get(cis);
                if (value != null) {
                    adapter.putJsonProperty(cis.toString(), value);
                }
            }
        }
        adapter.updateReadOnlyProperties();
        if (actionName != null) {
            commit = adapter.runAction(actionName);
        }
    }
    writer.outObject(element);
    if (commit) {
        graph.commit();
    } else {
        graph.rollback();
    }
}
Also used : NoteCoordinate(org.openntf.domino.big.NoteCoordinate) EdgeFrame(com.tinkerpop.frames.EdgeFrame) VertexFrame(com.tinkerpop.frames.VertexFrame) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString)

Example 4 with VertexFrame

use of com.tinkerpop.frames.VertexFrame 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)

Example 5 with VertexFrame

use of com.tinkerpop.frames.VertexFrame in project org.openntf.domino by OpenNTF.

the class FramedResource method deleteFramedObject.

@SuppressWarnings("resource")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public Response deleteFramedObject(final String requestEntity, @Context final UriInfo uriInfo, @PathParam(Routes.NAMESPACE) final String namespace, @Context final Request request) throws JsonException, IOException {
    DFramedTransactionalGraph graph = this.getGraph(namespace);
    String jsonEntity = null;
    ParamMap pm = Parameters.toParamMap(uriInfo);
    StringWriter sw = new StringWriter();
    JsonGraphWriter writer = new JsonGraphWriter(sw, graph, pm, false, true, false);
    @SuppressWarnings("unused") JsonGraphFactory factory = JsonGraphFactory.instance;
    Map<String, String> report = new HashMap<String, String>();
    List<String> ids = pm.get(Parameters.ID);
    if (ids.size() == 0) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse("No id specified for DELETE", Response.Status.INTERNAL_SERVER_ERROR));
    } else {
        for (String id : ids) {
            try {
                NoteCoordinate nc = NoteCoordinate.Utils.getNoteCoordinate(id.trim());
                Object element = graph.getElement(nc, null);
                if (element instanceof Element) {
                    ((Element) element).remove();
                } else if (element instanceof VertexFrame) {
                    graph.removeVertexFrame((VertexFrame) element);
                } else if (element instanceof EdgeFrame) {
                    graph.removeEdgeFrame((EdgeFrame) element);
                } else {
                    if (element != null) {
                        throw new WebApplicationException(ErrorHelper.createErrorResponse("Graph returned unexpected object type " + element.getClass().getName(), Response.Status.INTERNAL_SERVER_ERROR));
                    }
                }
                report.put(id, "deleted");
            } catch (Exception e) {
                throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
            }
        }
        graph.commit();
    }
    try {
        writer.outObject(report);
    } catch (JsonException e) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
    } catch (IOException e) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
    }
    jsonEntity = sw.toString();
    ResponseBuilder bob = getBuilder(jsonEntity, new Date(), false, null);
    Response response = bob.build();
    return response;
}
Also used : NoteCoordinate(org.openntf.domino.big.NoteCoordinate) JsonException(com.ibm.commons.util.io.json.JsonException) DEdgeFrame(org.openntf.domino.graph2.builtin.DEdgeFrame) EdgeFrame(com.tinkerpop.frames.EdgeFrame) ParamMap(org.openntf.domino.rest.service.Parameters.ParamMap) WebApplicationException(javax.ws.rs.WebApplicationException) JsonGraphWriter(org.openntf.domino.rest.json.JsonGraphWriter) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Element(com.tinkerpop.blueprints.Element) DFramedTransactionalGraph(org.openntf.domino.graph2.impl.DFramedTransactionalGraph) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString) IOException(java.io.IOException) KeyNotFoundException(org.openntf.domino.graph2.impl.DEdgeEntryList.KeyNotFoundException) 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) Response(javax.ws.rs.core.Response) DVertexFrame(org.openntf.domino.graph2.builtin.DVertexFrame) VertexFrame(com.tinkerpop.frames.VertexFrame) StringWriter(java.io.StringWriter) JsonGraphFactory(org.openntf.domino.rest.json.JsonGraphFactory) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces)

Aggregations

VertexFrame (com.tinkerpop.frames.VertexFrame)22 EdgeFrame (com.tinkerpop.frames.EdgeFrame)14 DVertexFrame (org.openntf.domino.graph2.builtin.DVertexFrame)13 JsonJavaObject (com.ibm.commons.util.io.json.JsonJavaObject)12 CaseInsensitiveString (org.openntf.domino.types.CaseInsensitiveString)12 Vertex (com.tinkerpop.blueprints.Vertex)11 UserAccessException (org.openntf.domino.exceptions.UserAccessException)9 DEdgeFrame (org.openntf.domino.graph2.builtin.DEdgeFrame)9 LinkedHashMap (java.util.LinkedHashMap)8 Edge (com.tinkerpop.blueprints.Edge)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 JsonObject (com.ibm.commons.util.io.json.JsonObject)6 Method (java.lang.reflect.Method)6 NoteCoordinate (org.openntf.domino.big.NoteCoordinate)6 DVertex (org.openntf.domino.graph2.impl.DVertex)6 List (java.util.List)5 DbInfoVertex (org.openntf.domino.graph2.builtin.DbInfoVertex)5 ViewVertex (org.openntf.domino.graph2.builtin.ViewVertex)5 DEdge (org.openntf.domino.graph2.impl.DEdge)5