Search in sources :

Example 1 with JsonJavaObject

use of com.ibm.commons.util.io.json.JsonJavaObject in project org.openntf.nsfodp by OpenNTF.

the class StockComponentsServlet method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setBufferSize(0);
    // $NON-NLS-1$ //$NON-NLS-2$
    resp.setHeader("Content-Type", "text/json");
    ServletOutputStream os = resp.getOutputStream();
    try {
        if (componentInfo == null) {
            SharableRegistryImpl facesRegistry = new SharableRegistryImpl(getClass().getPackage().getName());
            // $NON-NLS-1$
            List<Object> libraries = ExtensionManager.findServices((List<Object>) null, LibraryServiceLoader.class, "com.ibm.xsp.Library");
            libraries.stream().filter(lib -> lib instanceof XspLibrary).map(XspLibrary.class::cast).map(lib -> new LibraryWrapper(lib.getLibraryId(), lib)).map(wrapper -> {
                SimpleRegistryProvider provider = new SimpleRegistryProvider();
                provider.init(wrapper);
                return provider;
            }).map(XspRegistryProvider::getRegistry).forEach(facesRegistry::addDepend);
            facesRegistry.refreshReferences();
            componentInfo = new JsonJavaObject();
            JsonArray defs = new JsonJavaArray();
            facesRegistry.findComponentDefs().stream().filter(FacesComponentDefinition::isTag).map(def -> {
                try {
                    JsonObject defObj = new JsonJavaObject();
                    // $NON-NLS-1$
                    defObj.putJsonProperty("namespaceUri", def.getNamespaceUri());
                    // $NON-NLS-1$
                    defObj.putJsonProperty("tagName", def.getTagName());
                    // $NON-NLS-1$
                    defObj.putJsonProperty("class", def.getJavaClass().getName());
                    // $NON-NLS-1$
                    defObj.putJsonProperty("since", def.getSince());
                    // $NON-NLS-1$
                    defObj.putJsonProperty("defaultPrefix", def.getFirstDefaultPrefix());
                    // $NON-NLS-1$
                    defObj.putJsonProperty("componentFamily", def.getComponentFamily());
                    // $NON-NLS-1$
                    defObj.putJsonProperty("componentType", def.getComponentType());
                    // $NON-NLS-1$
                    defObj.putJsonProperty("id", def.getId());
                    JsonArray facetNames = new JsonJavaArray();
                    for (String facetName : def.getFacetNames()) {
                        facetNames.add(facetName);
                    }
                    // $NON-NLS-1$
                    defObj.putJsonProperty("facetNames", facetNames);
                    FacesProperty defaultProp = def.getDefaultFacesProperty();
                    if (defaultProp != null) {
                        JsonObject defaultPropObj = new JsonJavaObject();
                        // $NON-NLS-1$
                        defaultPropObj.putJsonProperty("name", defaultProp.getName());
                        // $NON-NLS-1$
                        defaultPropObj.putJsonProperty("since", defaultProp.getSince());
                        // $NON-NLS-1$
                        defaultPropObj.putJsonProperty("class", defaultProp.getJavaClass().getName());
                        // $NON-NLS-1$
                        defaultPropObj.putJsonProperty("required", defaultProp.isRequired());
                        // $NON-NLS-1$
                        defaultPropObj.putJsonProperty("attribute", defaultProp.isAttribute());
                    }
                    JsonArray properties = new JsonJavaArray();
                    for (String propName : def.getPropertyNames()) {
                        FacesProperty prop = def.getProperty(propName);
                        JsonObject propObj = new JsonJavaObject();
                        // $NON-NLS-1$
                        propObj.putJsonProperty("name", propName);
                        // $NON-NLS-1$
                        propObj.putJsonProperty("class", prop.getJavaClass().getName());
                        // $NON-NLS-1$
                        propObj.putJsonProperty("since", prop.getSince());
                        // $NON-NLS-1$
                        propObj.putJsonProperty("required", prop.isRequired());
                        // $NON-NLS-1$
                        propObj.putJsonProperty("attribute", prop.isAttribute());
                        properties.add(propObj);
                    }
                    // $NON-NLS-1$
                    defObj.putJsonProperty("properties", properties);
                    return defObj;
                } catch (JsonException e) {
                    throw new RuntimeException(e);
                }
            }).forEach(defObj -> {
                try {
                    defs.add(defObj);
                } catch (JsonException e) {
                    throw new RuntimeException(e);
                }
            });
            // $NON-NLS-1$
            componentInfo.putJsonProperty("components", defs);
        }
        os.print(componentInfo.toString());
    } catch (Throwable e) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintWriter out = new PrintWriter(baos);
        e.printStackTrace(out);
        out.flush();
        os.println(LineDelimitedJsonProgressMonitor.message(// $NON-NLS-1$ //$NON-NLS-2$
        "type", // $NON-NLS-1$ //$NON-NLS-2$
        "error", // $NON-NLS-1$
        "stackTrace", // $NON-NLS-1$
        baos.toString()));
    }
}
Also used : PrintWriter(java.io.PrintWriter) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) SharableRegistryImpl(com.ibm.xsp.registry.SharableRegistryImpl) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpServlet(javax.servlet.http.HttpServlet) ServletException(javax.servlet.ServletException) JsonObject(com.ibm.commons.util.io.json.JsonObject) ExtensionManager(com.ibm.commons.extension.ExtensionManager) HttpServletResponse(javax.servlet.http.HttpServletResponse) SimpleRegistryProvider(com.ibm.xsp.registry.config.SimpleRegistryProvider) IOException(java.io.IOException) XspLibrary(com.ibm.xsp.library.XspLibrary) FacesProperty(com.ibm.xsp.registry.FacesProperty) LibraryServiceLoader(com.ibm.xsp.library.LibraryServiceLoader) List(java.util.List) HttpServletRequest(javax.servlet.http.HttpServletRequest) JsonJavaArray(com.ibm.commons.util.io.json.JsonJavaArray) JsonException(com.ibm.commons.util.io.json.JsonException) FacesComponentDefinition(com.ibm.xsp.registry.FacesComponentDefinition) ServletOutputStream(javax.servlet.ServletOutputStream) LineDelimitedJsonProgressMonitor(org.openntf.nsfodp.commons.LineDelimitedJsonProgressMonitor) JsonArray(com.ibm.commons.util.io.json.JsonArray) XspRegistryProvider(com.ibm.xsp.registry.config.XspRegistryProvider) LibraryWrapper(com.ibm.xsp.library.LibraryWrapper) JsonException(com.ibm.commons.util.io.json.JsonException) JsonJavaArray(com.ibm.commons.util.io.json.JsonJavaArray) LibraryWrapper(com.ibm.xsp.library.LibraryWrapper) ServletOutputStream(javax.servlet.ServletOutputStream) XspLibrary(com.ibm.xsp.library.XspLibrary) JsonObject(com.ibm.commons.util.io.json.JsonObject) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SharableRegistryImpl(com.ibm.xsp.registry.SharableRegistryImpl) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) JsonArray(com.ibm.commons.util.io.json.JsonArray) FacesComponentDefinition(com.ibm.xsp.registry.FacesComponentDefinition) SimpleRegistryProvider(com.ibm.xsp.registry.config.SimpleRegistryProvider) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) JsonObject(com.ibm.commons.util.io.json.JsonObject) FacesProperty(com.ibm.xsp.registry.FacesProperty) PrintWriter(java.io.PrintWriter)

Example 2 with JsonJavaObject

use of com.ibm.commons.util.io.json.JsonJavaObject 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 3 with JsonJavaObject

use of com.ibm.commons.util.io.json.JsonJavaObject 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 JsonJavaObject

use of com.ibm.commons.util.io.json.JsonJavaObject 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 JsonJavaObject

use of com.ibm.commons.util.io.json.JsonJavaObject in project org.openntf.domino by OpenNTF.

the class FramedResource method updateFrameByMetaid.

protected Response updateFrameByMetaid(final String requestEntity, final String namespace, final String ifUnmodifiedSince, final ParamMap pm, final boolean isPut, final Request request) throws JsonException, IOException {
    @SuppressWarnings("unused") Response result = null;
    DFramedTransactionalGraph<?> graph = this.getGraph(namespace);
    JsonJavaObject jsonItems = null;
    List<Object> jsonArray = null;
    // ResponseBuilder builder = null;
    JsonGraphFactory factory = JsonGraphFactory.instance;
    StringWriter sw = new StringWriter();
    JsonGraphWriter writer = new JsonGraphWriter(sw, graph, pm, false, true, false);
    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) jsonRaw;
            } else if (jsonRaw instanceof String) {
                // NTF reparse
                reader = new StringReader((String) jsonRaw);
                Object jsonRaw2 = JsonParser.fromJson(factory, reader);
                if (jsonRaw2 instanceof JsonJavaObject) {
                    jsonItems = (JsonJavaObject) jsonRaw2;
                } else if (jsonRaw2 instanceof List) {
                    jsonArray = (List) jsonRaw2;
                } else {
                    System.out.println("ALERT Got a jsonRaw2 of type " + (jsonRaw2 != null ? jsonRaw2.getClass().getName() : "null") + ".  Value is: " + String.valueOf(jsonRaw));
                }
            }
        } catch (UserAccessException uae) {
            throw new WebApplicationException(ErrorHelper.createErrorResponse("User " + Factory.getSession(SessionType.CURRENT).getEffectiveUserName() + " is not authorized to update this resource", Response.Status.UNAUTHORIZED));
        } 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));
    }
    if (jsonArray != null) {
        writer.startArray();
        for (Object raw : jsonArray) {
            if (raw instanceof JsonJavaObject) {
                writer.startArrayItem();
                processJsonUpdate((JsonJavaObject) raw, graph, writer, pm, isPut);
                writer.endArrayItem();
            }
        }
        writer.endArray();
    } else if (jsonItems != null) {
        processJsonUpdate(jsonItems, graph, writer, pm, isPut);
    } else {
        System.out.println("ALERT! Received a JSON object that was not expected!");
    }
    String jsonEntity = sw.toString();
    ResponseBuilder berg = getBuilder(jsonEntity, new Date(), false, request);
    Response response = berg.build();
    return response;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) JsonGraphWriter(org.openntf.domino.rest.json.JsonGraphWriter) CaseInsensitiveString(org.openntf.domino.types.CaseInsensitiveString) UserAccessException(org.openntf.domino.exceptions.UserAccessException) 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) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) JsonGraphFactory(org.openntf.domino.rest.json.JsonGraphFactory) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) JsonJavaObject(com.ibm.commons.util.io.json.JsonJavaObject) List(java.util.List) ArrayList(java.util.ArrayList) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Aggregations

JsonJavaObject (com.ibm.commons.util.io.json.JsonJavaObject)12 JsonException (com.ibm.commons.util.io.json.JsonException)8 IOException (java.io.IOException)8 List (java.util.List)8 CaseInsensitiveString (org.openntf.domino.types.CaseInsensitiveString)8 ArrayList (java.util.ArrayList)7 WebApplicationException (javax.ws.rs.WebApplicationException)6 UserAccessException (org.openntf.domino.exceptions.UserAccessException)6 Date (java.util.Date)5 HashMap (java.util.HashMap)5 LinkedHashMap (java.util.LinkedHashMap)5 VertexFrame (com.tinkerpop.frames.VertexFrame)4 StringReader (java.io.StringReader)4 StringWriter (java.io.StringWriter)4 Response (javax.ws.rs.core.Response)4 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)4 JsonGraphFactory (org.openntf.domino.rest.json.JsonGraphFactory)4 JsonGraphWriter (org.openntf.domino.rest.json.JsonGraphWriter)4 EdgeFrame (com.tinkerpop.frames.EdgeFrame)3 PrintWriter (java.io.PrintWriter)3