Example usage for com.fasterxml.jackson.databind.node ObjectNode ObjectNode

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode ObjectNode

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ObjectNode ObjectNode.

Prototype

public ObjectNode(JsonNodeFactory paramJsonNodeFactory) 

Source Link

Usage

From source file:com.redhat.lightblue.metadata.parser.JSONMetadataParserTest.java

License:asdf

@Test
public void newArrayField() {
    ObjectNode parent = new ObjectNode(factory);
    String name = "foo";
    Object array = parser.newArrayField(parent, name);

    Assert.assertNotNull(array);//from   ww w. j  a v a 2 s .  c  o m
    Assert.assertEquals(array, parent.get(name));
}

From source file:org.jetbrains.webdemo.database.MySqlConnector.java

public String addProject(UserInfo userInfo, String name, String type) throws DatabaseOperationException {
    try {//from   w  w w  .  jav a2 s. c o m
        String projectId = addProject(userInfo, new Project(name, "", "java"), type, null);
        String fileId = addFileToProject(userInfo, projectId, name, "fun main(args: Array<String>) {\n\n}");

        ObjectNode response = new ObjectNode(JsonNodeFactory.instance);
        response.put("projectId", projectId);
        response.put("fileId", fileId);
        return objectMapper.writeValueAsString(response);
    } catch (IOException e) {
        throw new DatabaseOperationException("IO exception");
    }
}

From source file:org.walkmod.conf.providers.YAMLConfigurationProvider.java

public JsonNode getRootNode() {
    File cfg = new File(fileName);
    JsonNode node = null;//from  w ww  .j  a v a2s  .  c  o  m
    try {
        node = mapper.readTree(cfg);
    } catch (Exception e) {

    }
    if (node == null) {
        node = new ObjectNode(mapper.getNodeFactory());
    }
    return node;
}

From source file:org.jetbrains.webdemo.database.MySqlConnector.java

public String addAdventOfCodeProject(UserInfo userInfo, String name, String inputFileContent)
        throws DatabaseOperationException {
    try {// w ww.  j a  va 2  s .  c  o  m
        String projectId = addProject(userInfo, new Project(name, "", "java"), "ADVENT_OF_CODE_PROJECT", null);
        String fileId = addFileToProject(userInfo, projectId, name,
                "fun main(args: Array<String>) {\n//your input stored in the `input` variable\n}");
        String inputFileId = addFileToProject(userInfo, projectId, "Input.kt", inputFileContent);

        ObjectNode response = new ObjectNode(JsonNodeFactory.instance);
        response.put("projectId", projectId);
        response.put("fileId", fileId);
        response.put("inputFileId", inputFileId);
        return objectMapper.writeValueAsString(response);
    } catch (IOException e) {
        throw new DatabaseOperationException("IO exception");
    }
}

From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java

/**
 * Get all busy event timeslots in given interval.
 * //w w w.  ja  v  a  2s .  c  o  m
 * @param timeMin
 *            start of the interval
 * @param timeMax
 *            end of the interval
 * @param calendarId
 *            optional calendar id. If not provided, the default calendar is
 *            used
 * @param timeZone
 *            Time zone used in the response. Optional. The default is UTC.
 * @return the busy
 * @throws Exception
 *             the exception
 */
@Override
public ArrayNode getBusy(@Name("timeMin") final String timeMin, @Name("timeMax") final String timeMax,
        @Optional @Name("calendarId") String calendarId, @Optional @Name("timeZone") final String timeZone)
        throws Exception {
    // initialize optional parameters
    if (calendarId == null) {
        calendarId = getState().get("email", String.class);
    }

    // build request body
    final ObjectNode request = new ObjectNode(JsonNodeFactory.instance);
    request.put("timeMin", new DateTime(timeMin).toString());
    request.put("timeMax", new DateTime(timeMax).toString());

    if (timeZone != null) {
        request.put("timeZone", timeZone);
    }

    final ArrayNode node = request.putArray("items");
    node.addObject().put("id", calendarId);

    final String url = "https://www.googleapis.com/calendar/v3/freeBusy";

    // perform POST request
    final ObjectMapper mapper = JOM.getInstance();
    final String body = mapper.writeValueAsString(request);
    final Map<String, String> headers = getAuthorizationHeaders();
    headers.put("Content-Type", "application/json");
    final String resp = HttpUtil.post(url, body, headers);
    final ObjectNode response = mapper.readValue(resp, ObjectNode.class);

    // check for errors
    if (response.has("error")) {
        final ObjectNode error = (ObjectNode) response.get("error");
        throw new JSONRPCException(error);
    }

    // get items from the response
    ArrayNode items = null;
    if (response.has("calendars")) {
        final JsonNode calendars = response.get("calendars");
        if (calendars.has(calendarId)) {
            final JsonNode calendar = calendars.get(calendarId);
            if (calendar.has("busy")) {
                items = (ArrayNode) calendar.get("busy");
            }
        }
    }

    if (items == null) {
        items = JOM.createArrayNode();
    }

    return items;
}

From source file:org.jetbrains.webdemo.database.MySqlConnector.java

public ArrayNode getProjectHeaders(UserInfo userInfo, String projectType) throws DatabaseOperationException {
    PreparedStatement st = null;//ww  w  .j  av  a 2s .c om
    ResultSet rs = null;
    try (Connection connection = dataSource.getConnection()) {
        st = connection.prepareStatement("SELECT projects.public_id, projects.name FROM projects JOIN "
                + "users ON projects.owner_id = users.id WHERE "
                + "(users.client_id = ? AND users.provider = ? AND projects.type = ?)");
        st.setString(1, userInfo.getId());
        st.setString(2, userInfo.getType());
        st.setString(3, projectType);

        rs = st.executeQuery();

        ArrayNode projects = new ArrayNode(JsonNodeFactory.instance);
        while (rs.next()) {
            ObjectNode object = new ObjectNode(JsonNodeFactory.instance);
            object.put("name", unEscape(rs.getString("name")));
            object.put("publicId", rs.getString("public_id"));
            object.put("modified", false);
            projects.add(object);
        }

        return projects;
    } catch (Throwable e) {
        ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e,
                SessionInfo.TypeOfRequest.WORK_WITH_DATABASE.name(), "unknown",
                userInfo.getId() + " " + userInfo.getType() + " " + userInfo.getName());
        throw new DatabaseOperationException("Unknown error while loading list of your programs");
    } finally {
        closeStatementAndResultSet(st, rs);
    }
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManager.java

/**
 * Creates the JSON request body used to commit all of the parts of a multipart
 * upload request./*from   www .  j  a  v  a2s  .  com*/
 *
 * @param parts stream of tuples - this is a terminal operation that will close the stream
 * @return byte array containing JSON data
 */
static ImmutablePair<byte[], Integer> createCommitRequestBody(
        final Stream<? extends MantaMultipartUploadTuple> parts) {
    final JsonNodeFactory nodeFactory = MantaObjectMapper.NODE_FACTORY_INSTANCE;
    final ObjectNode objectNode = new ObjectNode(nodeFactory);

    final ArrayNode partsArrayNode = new ArrayNode(nodeFactory);
    objectNode.set("parts", partsArrayNode);

    try (Stream<? extends MantaMultipartUploadTuple> sorted = parts.sorted()) {
        sorted.forEach(tuple -> partsArrayNode.add(tuple.getEtag()));
    }

    Validate.isTrue(partsArrayNode.size() > 0, "Can't commit multipart upload with no parts");

    try {
        return ImmutablePair.of(MantaObjectMapper.INSTANCE.writeValueAsBytes(objectNode),
                partsArrayNode.size());
    } catch (IOException e) {
        String msg = "Error serializing JSON for commit MPU request body";
        throw new MantaMultipartException(msg, e);
    }
}

From source file:com.redhat.lightblue.metadata.mongo.MongoMetadata.java

@Override
public Response getAccess(String entityName, String version) {
    List<String> entityNames = new ArrayList<>();
    // accessMap: <role, <operation, List<path>>>
    Map<String, Map<String, List<String>>> accessMap = new HashMap<>();

    if (null != entityName && !entityName.isEmpty()) {
        entityNames.add(entityName);/*from  w ww .  j a v a  2s. c  o  m*/
    } else {
        // force version to be null
        version = null;
        entityNames.addAll(Arrays.asList(getEntityNames()));
    }

    // initialize response, assume will be completely successful
    Response response = new Response(JsonNodeFactory.instance);
    response.setStatus(OperationStatus.COMPLETE);

    // for each name get metadata
    for (String name : entityNames) {
        EntityMetadata metadata;
        try {
            metadata = getEntityMetadata(name, version);
        } catch (Exception e) {
            response.setStatus(OperationStatus.PARTIAL);
            // construct error data
            ObjectNode obj = new ObjectNode(JsonNodeFactory.instance);
            obj.put(LITERAL_NAME, name);
            if (null != version) {
                obj.put("version", version);
            }
            List<Error> errors = new ArrayList<>();
            errors.add(Error.get("ERR_NO_METADATA",
                    "Could not get metadata for given input. Error message: " + e.getMessage()));
            DataError error = new DataError(obj, errors);
            response.getDataErrors().add(error);
            // skip to next entity name
            continue;
        }

        EntityAccess ea = metadata.getAccess();
        Map<FieldAccess, Path> fa = new HashMap<>();
        FieldCursor fc = metadata.getFieldCursor();
        // collect field access
        while (fc.next()) {
            FieldTreeNode ftn = fc.getCurrentNode();
            if (ftn instanceof Field) {
                // add access if there is anything to extract later
                Field f = (Field) ftn;
                if (!f.getAccess().getFind().isEmpty() || !f.getAccess().getInsert().isEmpty()
                        || !f.getAccess().getUpdate().isEmpty()) {
                    fa.put(f.getAccess(), f.getFullPath());
                }
            }
        }

        // key is role, value is all associated paths.
        // accessMap: <role, <operation, List<path>>>
        // collect entity access
        helperAddRoles(ea.getDelete().getRoles(), "delete", name, accessMap);
        helperAddRoles(ea.getFind().getRoles(), "find", name, accessMap);
        helperAddRoles(ea.getInsert().getRoles(), "insert", name, accessMap);
        helperAddRoles(ea.getUpdate().getRoles(), "update", name, accessMap);

        // collect field access
        for (Map.Entry<FieldAccess, Path> entry : fa.entrySet()) {
            FieldAccess access = entry.getKey();
            String pathString = name + "." + entry.getValue().toString();
            helperAddRoles(access.getFind().getRoles(), "find", pathString, accessMap);
            helperAddRoles(access.getInsert().getRoles(), "insert", pathString, accessMap);
            helperAddRoles(access.getUpdate().getRoles(), "update", pathString, accessMap);
        }
    }

    // finally, populate response with valid output
    if (!accessMap.isEmpty()) {
        ArrayNode root = new ArrayNode(JsonNodeFactory.instance);
        response.setEntityData(root);
        for (Map.Entry<String, Map<String, List<String>>> entry : accessMap.entrySet()) {
            String role = entry.getKey();
            Map<String, List<String>> opPathMap = entry.getValue();

            ObjectNode roleJson = new ObjectNode(JsonNodeFactory.instance);
            root.add(roleJson);

            roleJson.put("role", role);

            for (Map.Entry<String, List<String>> operationMap : opPathMap.entrySet()) {
                String operation = operationMap.getKey();
                List<String> paths = opPathMap.get(operation);
                ArrayNode pathNode = new ArrayNode(JsonNodeFactory.instance);
                for (String path : paths) {
                    pathNode.add(path);
                }
                roleJson.put(operation, pathNode);
            }
        }
    } else {
        // nothing successful! set status to error
        response.setStatus(OperationStatus.ERROR);
    }

    return response;
}