Search in sources :

Example 16 with NoteCoordinate

use of org.openntf.domino.big.NoteCoordinate 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 17 with NoteCoordinate

use of org.openntf.domino.big.NoteCoordinate 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 18 with NoteCoordinate

use of org.openntf.domino.big.NoteCoordinate 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)

Example 19 with NoteCoordinate

use of org.openntf.domino.big.NoteCoordinate in project org.openntf.domino by OpenNTF.

the class FramedResource method processJsonObject.

@SuppressWarnings({ "resource", "unlikely-arg-type" })
private void processJsonObject(final JsonJavaObject jsonItems, final DFramedTransactionalGraph graph, final JsonGraphWriter writer, final ParamMap pm) /* , Map<Object, Object> resultMap */
{
    Map<CaseInsensitiveString, Object> cisMap = new HashMap<CaseInsensitiveString, Object>();
    for (String jsonKey : jsonItems.keySet()) {
        CaseInsensitiveString cis = new CaseInsensitiveString(jsonKey);
        cisMap.put(cis, jsonItems.get(jsonKey));
    }
    List<String> ids = pm.get(Parameters.ID);
    boolean commit = true;
    if (ids == null) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("error", "Cannot POST to frame without an id parameter");
        try {
            writer.outObject(map);
        } 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));
        }
    } else {
        if (ids.size() == 0) {
            System.out.println("Cannot POST to frame without an id parameter");
            Map<String, String> map = new HashMap<String, String>();
            map.put("error", "Cannot POST to frame without an id parameter");
            try {
                writer.outObject(map);
            } 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));
            }
        } else {
            for (String id : ids) {
                // System.out.println("TEMP DEBUG POSTing to " + id);
                Class<?> type = null;
                if (pm.getTypes() != null) {
                    List<CharSequence> types = pm.getTypes();
                    String typename = types.get(0).toString();
                    type = graph.getTypeRegistry().findClassByName(typename);
                }
                NoteCoordinate nc = NoteCoordinate.Utils.getNoteCoordinate(id.trim());
                Object element = graph.getElement(nc, type);
                if (element instanceof VertexFrame) {
                    VertexFrame parVertex = (VertexFrame) element;
                    Map<CaseInsensitiveString, Method> adders = graph.getTypeRegistry().getAdders(parVertex.getClass());
                    CaseInsensitiveString rawLabel = new CaseInsensitiveString(jsonItems.getAsString("@label"));
                    Method method = adders.get(rawLabel);
                    if (method == null) {
                        method = adders.get(rawLabel + "In");
                    }
                    if (method != null) {
                        String rawId = jsonItems.getAsString("@id");
                        NoteCoordinate othernc = NoteCoordinate.Utils.getNoteCoordinate(rawId);
                        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, false);
                                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);
                                            }
                                        }
                                    }
                                    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(result);
                            } catch (Exception e) {
                                throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
                            }
                        } else {
                            throw new WebApplicationException(ErrorHelper.createErrorResponse("otherElement is not a VertexFrame. It's a " + (otherElement == null ? "null" : DGraphUtils.findInterface(otherElement).getName()), Response.Status.INTERNAL_SERVER_ERROR));
                        }
                    } 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() + ", ";
                        }
                        throw new WebApplicationException(ErrorHelper.createErrorResponse("No method found for " + rawLabel + " on element " + intList + ": " + ((VertexFrame) element).asVertex().getId() + " methods " + methList, Response.Status.INTERNAL_SERVER_ERROR));
                    }
                } else {
                    throw new WebApplicationException(ErrorHelper.createErrorResponse("Element is null", Response.Status.INTERNAL_SERVER_ERROR));
                }
            }
        }
        if (commit) {
            graph.commit();
        } else {
            graph.rollback();
        }
    }
}
Also used : JsonException(com.ibm.commons.util.io.json.JsonException) NoteCoordinate(org.openntf.domino.big.NoteCoordinate) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString) IOException(java.io.IOException) Method(java.lang.reflect.Method) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString) 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) DVertexFrame(org.openntf.domino.graph2.builtin.DVertexFrame) VertexFrame(com.tinkerpop.frames.VertexFrame) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject)

Example 20 with NoteCoordinate

use of org.openntf.domino.big.NoteCoordinate in project org.openntf.domino by OpenNTF.

the class FramedResource method getFramedObject.

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getFramedObject(@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);
    if (pm.getVersion() != null) {
        System.out.println("TEMP DEBUG Version number parameter detected " + pm.getVersion().get(0));
    }
    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;
                // System.out.println("TEMP DEBUG isIcon: " +
                // String.valueOf(nc.isIcon()));
                }
                if (nc == null) {
                // writer.outStringProperty("message", "NoteCoordinate
                // is null for id " + id);
                }
                if (graph == null) {
                // writer.outStringProperty("message", "Graph is null
                // for namespace " + namespace);
                }
                NoteCoordinate versionNC = null;
                if (pm.getVersion() != null) {
                    String versionString = pm.getVersion().get(0).toString();
                    System.out.println("Version parameter detected: " + versionString);
                    SimpleDateFormat sdf = TypeUtils.getDefaultDateFormat();
                    Date versionDate = sdf.parse(versionString);
                    try {
                        Session sess = Factory.getSession(SessionType.CURRENT);
                        Document doc = sess.getDocumentByMetaversalID(nc.toString());
                        Database db = doc.getAncestorDatabase();
                        List<DocumentBackupContributor> contributors = Factory.findApplicationServices(DocumentBackupContributor.class);
                        if (contributors != null) {
                            for (DocumentBackupContributor contributor : contributors) {
                                Optional<Document> versionDoc = contributor.createSidecarDocument(db, doc.getUniversalID(), versionDate);
                                if (versionDoc.isPresent()) {
                                    versionNC = versionDoc.get().getNoteCoordinate();
                                    break;
                                }
                            }
                        }
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
                Object elem = null;
                if (versionNC != null) {
                    elem = graph.getElement(versionNC, null);
                // System.out.println("Got an element from graph with id " + ((Element)elem).getId());
                } else {
                    elem = graph.getElement(nc, null);
                }
                if (elem == null) {
                    // builder = Response.status(Status.NOT_FOUND);
                    // writer.outStringProperty("currentUsername",
                    // Factory.getSession(SessionType.CURRENT).getEffectiveUserName());
                    // throw new IllegalStateException();
                    Response response = ErrorHelper.createErrorResponse("Graph element not found for id " + String.valueOf(id), Response.Status.NOT_FOUND);
                    throw new WebApplicationException(response);
                }
                try {
                    if (elem instanceof DVertexFrame && getLastMod) {
                        lastModified = ((DVertexFrame) elem).getModified();
                    }
                    if (elem instanceof DEdgeFrame && getLastMod) {
                        lastModified = ((DEdgeFrame) elem).getModified();
                    }
                } catch (UserAccessException uae) {
                    return ErrorHelper.createErrorResponse("User " + Factory.getSession(SessionType.CURRENT).getEffectiveUserName() + " is not authorized to access this resource", Response.Status.UNAUTHORIZED);
                } catch (Exception e) {
                    throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
                }
                writer.outObject(elem);
            } else {
                List<Object> maps = new ArrayList<Object>();
                for (String id : ids) {
                    NoteCoordinate nc = NoteCoordinate.Utils.getNoteCoordinate(id.trim());
                    maps.add(graph.getElement(nc, null));
                }
                writer.outArrayLiteral(maps);
            }
        } else if (pm.getKeys() != null) {
            Class<?> type = null;
            if (pm.getTypes() != null) {
                List<CharSequence> types = pm.getTypes();
                String typename = types.get(0).toString();
                type = graph.getTypeRegistry().findClassByName(typename);
            }
            DKeyResolver resolver = graph.getKeyResolver(type);
            List<CharSequence> keys = pm.getKeys();
            if (keys.size() == 0) {
                writer.outNull();
            } else if (keys.size() == 1) {
                CharSequence id = keys.get(0);
                NoteCoordinate nc = resolver.resolveKey(type, URLDecoder.decode(String.valueOf(id), "UTF-8"));
                Object elem = null;
                if (nc != null) {
                    // is null for id " + id);
                    try {
                        elem = graph.getElement(nc);
                    } catch (Exception e) {
                    // NOOP NTF - this is possible and not an error condition. That's why we have .handleMissingKey.
                    }
                }
                if (elem == null) {
                    elem = resolver.handleMissingKey(type, id);
                    if (elem == null) {
                        Response response = ErrorHelper.createErrorResponse("Graph element not found for key " + id, Response.Status.NOT_FOUND);
                        throw new WebApplicationException(response);
                    }
                }
                if (elem instanceof Vertex) {
                    // System.out.println("TEMP DEBUG Framing a vertex of
                    // type "
                    // + elem.getClass().getName());
                    VertexFrame vf = (VertexFrame) graph.frame((Vertex) elem, type);
                    if (vf instanceof DVertexFrame) {
                        lastModified = ((DVertexFrame) vf).getModified();
                    }
                    writer.outObject(vf);
                } else if (elem instanceof Edge) {
                    EdgeFrame ef = (EdgeFrame) graph.frame((Edge) elem, type);
                    if (ef instanceof DEdgeFrame) {
                        lastModified = ((DEdgeFrame) ef).getModified();
                    }
                    writer.outObject(ef);
                }
            } else {
                List<Object> maps = new ArrayList<Object>();
                for (CharSequence id : keys) {
                    NoteCoordinate nc = resolver.resolveKey(type, id);
                    maps.add(graph.getElement(nc, null));
                }
                writer.outArrayLiteral(maps);
            }
            graph.rollback();
        } else {
            MultivaluedMap<String, String> mvm = uriInfo.getQueryParameters();
            for (@SuppressWarnings("unused") String key : mvm.keySet()) {
            // System.out.println("TEMP DEBUG: " + key + ": " +
            // mvm.getFirst(key));
            }
            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 : Vertex(com.tinkerpop.blueprints.Vertex) 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) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString) Document(org.openntf.domino.Document) StringWriter(java.io.StringWriter) Database(org.openntf.domino.Database) List(java.util.List) ArrayList(java.util.ArrayList) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) NoteCoordinate(org.openntf.domino.big.NoteCoordinate) DEdgeFrame(org.openntf.domino.graph2.builtin.DEdgeFrame) EdgeFrame(com.tinkerpop.frames.EdgeFrame) Optional(java.util.Optional) DKeyResolver(org.openntf.domino.graph2.DKeyResolver) UserAccessException(org.openntf.domino.exceptions.UserAccessException) Date(java.util.Date) 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) DVertexFrame(org.openntf.domino.graph2.builtin.DVertexFrame) Response(javax.ws.rs.core.Response) DVertexFrame(org.openntf.domino.graph2.builtin.DVertexFrame) VertexFrame(com.tinkerpop.frames.VertexFrame) DEdgeFrame(org.openntf.domino.graph2.builtin.DEdgeFrame) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) DocumentBackupContributor(org.openntf.domino.contributor.DocumentBackupContributor) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) SimpleDateFormat(java.text.SimpleDateFormat) Edge(com.tinkerpop.blueprints.Edge) Map(java.util.Map) ParamMap(org.openntf.domino.rest.service.Parameters.ParamMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) KeyNotFoundException(org.openntf.domino.graph2.impl.DEdgeEntryList.KeyNotFoundException) Session(org.openntf.domino.Session) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

NoteCoordinate (org.openntf.domino.big.NoteCoordinate)31 CaseInsensitiveString (org.openntf.domino.types.CaseInsensitiveString)9 Database (org.openntf.domino.Database)8 ArrayList (java.util.ArrayList)7 LinkedHashMap (java.util.LinkedHashMap)7 UserAccessException (org.openntf.domino.exceptions.UserAccessException)7 JsonJavaObject (com.ibm.commons.util.io.json.JsonJavaObject)6 Element (com.tinkerpop.blueprints.Element)6 VertexFrame (com.tinkerpop.frames.VertexFrame)6 HashMap (java.util.HashMap)6 NoteCollection (org.openntf.domino.NoteCollection)6 JsonException (com.ibm.commons.util.io.json.JsonException)5 Edge (com.tinkerpop.blueprints.Edge)5 EdgeFrame (com.tinkerpop.frames.EdgeFrame)5 IOException (java.io.IOException)5 WebApplicationException (javax.ws.rs.WebApplicationException)5 DVertexFrame (org.openntf.domino.graph2.builtin.DVertexFrame)5 List (java.util.List)4 FastTable (javolution.util.FastTable)4 Document (org.openntf.domino.Document)4