Example usage for com.fasterxml.jackson.databind.node JsonNodeFactory objectNode

List of usage examples for com.fasterxml.jackson.databind.node JsonNodeFactory objectNode

Introduction

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

Prototype

public ObjectNode objectNode() 

Source Link

Usage

From source file:org.kitesdk.apps.scheduled.Schedule.java

private TreeNode toJson() {

    JsonNodeFactory js = JsonNodeFactory.instance;

    ObjectNode root = js.objectNode();

    root.put(NAME, getName());/* w  w  w  .j a v a 2 s.c o  m*/
    root.put(JOBCLASS, getJobClass().getName());
    root.put(START_TIME, formatter.print(getStartTime()));
    root.put(FREQUENCY, getFrequency());

    ArrayNode views = js.arrayNode();

    for (ViewTemplate template : getViewTemplates().values()) {

        ObjectNode viewNode = views.addObject();

        viewNode.put(NAME, template.getName());
        viewNode.put(URI, template.getUriTemplate());
        viewNode.put(FREQUENCY, template.getFrequency());
        viewNode.put(TYPE, template.getInputType().getName());
        viewNode.put(IS_INPUT, template.isInput);
    }

    root.put(VIEWS, views);

    return root;
}

From source file:com.netflix.genie.web.controllers.JobRestController.java

/**
 * Get the status of the given job if it exists.
 *
 * @param id The id of the job to get status for
 * @return The status of the job as one of: {@link JobStatus}
 * @throws GenieException on error//from   w  ww .  ja v a 2s. c o  m
 */
@RequestMapping(value = "/{id}/status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public JsonNode getJobStatus(@PathVariable("id") final String id) throws GenieException {
    log.debug("[getJobStatus] Called for job with id: {}", id);
    final JsonNodeFactory factory = JsonNodeFactory.instance;
    return factory.objectNode().set("status",
            factory.textNode(this.jobSearchService.getJobStatus(id).toString()));
}

From source file:org.apache.streams.rss.serializer.SyndEntrySerializer.java

private void serializeLinks(ObjectNode root, JsonNodeFactory factory, List links) {
    if (links == null || links.size() == 0) {
        return;//from   w ww  .java2s .c o  m
    } else if (links.get(0) instanceof String) {
        serializeListOfStrings(links, "links", root, factory);
    } else if (links.get(0) instanceof SyndLinkImpl) {
        ArrayNode linksArray = factory.arrayNode();
        SyndLinkImpl syndLink;
        ObjectNode linkNode;
        for (Object obj : links) {
            linkNode = factory.objectNode();
            syndLink = (SyndLinkImpl) obj;
            linkNode.put("rel", syndLink.getRel());
            linkNode.put("href", syndLink.getHref());
            linkNode.put("type", syndLink.getType());
            linkNode.put("length", syndLink.getLength());
            linkNode.put("hrefLang", syndLink.getHreflang());
            linkNode.put("title", syndLink.getTitle());
            linksArray.add(linkNode);
        }
        root.put("links", linksArray);
    } else {
        LOGGER.error("No implementation for handling links of class : {}", links.get(0).getClass().toString());
    }
}

From source file:io.fabric8.maven.plugin.mojo.build.HelmMojo.java

private void createTemplateParameters(File outputDir, Template template, File templatesDir)
        throws MojoExecutionException {
    JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
    ObjectNode values = nodeFactory.objectNode();
    List<io.fabric8.openshift.api.model.Parameter> parameters = template.getParameters();
    if (parameters == null || parameters.isEmpty()) {
        return;//from w  w w.  j  av  a 2 s .co m
    }
    List<HelmParameter> helmParameters = new ArrayList<>();
    for (io.fabric8.openshift.api.model.Parameter parameter : parameters) {
        HelmParameter helmParameter = new HelmParameter(parameter);
        helmParameter.addToValue(values);
        helmParameters.add(helmParameter);
    }
    File outputChartFile = new File(outputDir, "values.yaml");
    try {
        ResourceUtil.save(outputChartFile, values, ResourceFileType.yaml);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to save chart values " + outputChartFile + ": " + e, e);
    }

    // now lets replace all the parameter expressions in each template
    File[] files = templatesDir.listFiles();
    if (files != null) {
        for (File file : files) {
            if (file.isFile()) {
                String extension = Files.getFileExtension(file.getName()).toLowerCase();
                if (extension.equals("yaml") || extension.equals("yml")) {
                    convertTemplateParameterExpressionsWithHelmExpressions(file, helmParameters);
                }
            }
        }
    }
}

From source file:com.redhat.lightblue.metadata.rdbms.converter.RDBMSContext.java

@Override
public String toString() {
    JsonNodeFactory jsonNodeFactory1 = jsonNodeFactory;
    if (jsonNodeFactory == null) {
        jsonNodeFactory1 = JsonNodeFactory.withExactBigDecimals(true);
    }/*ww  w.  j a v  a  2s . c  om*/
    ObjectNode objectNode = jsonNodeFactory1.objectNode();
    NullNode nullNode = jsonNodeFactory1.nullNode();
    String nullNodeString = JsonUtils.prettyPrint(nullNode);
    String s = null;
    JsonNode j = null;
    try {

        s = fromToQueryRange == null ? nullNodeString : fromToQueryRange.toString();
        objectNode.set("fromToQueryRange", JsonUtils.json(s));

        j = dataSource == null ? nullNode : jsonNodeFactory1.textNode(dataSource.toString());
        objectNode.set("dataSource", j);

        j = dataSourceName == null ? nullNode : jsonNodeFactory1.textNode(dataSourceName.toString());
        objectNode.set("dataSourceName", j);

        j = connection == null ? nullNode : jsonNodeFactory1.textNode(connection.toString());
        objectNode.set("connection", j);

        j = preparedStatement == null ? nullNode : jsonNodeFactory1.textNode(preparedStatement.toString());
        objectNode.set("preparedStatement", j);

        j = resultBoolean == null ? nullNode : jsonNodeFactory1.booleanNode(resultBoolean);
        objectNode.set("resultBoolean", j);

        j = resultInteger == null ? nullNode : jsonNodeFactory1.numberNode(resultInteger);
        objectNode.set("resultInteger", j);

        j = rowMapper == null ? nullNode : jsonNodeFactory1.textNode(rowMapper.toString());
        objectNode.set("rowMapper", j);

        if (resultList != null) {
            ArrayNode jsonNodes = jsonNodeFactory1.arrayNode();
            for (T a : resultList) {
                jsonNodes.add(a.toString());
            }
            objectNode.set("resultList", jsonNodes);
        } else {
            objectNode.set("resultList", nullNode);
        }

        s = rdbms == null ? nullNodeString : rdbms.toString();
        objectNode.set("rdbms", JsonUtils.json(s));

        j = sql == null ? nullNode : jsonNodeFactory1.textNode(sql.toString());
        objectNode.set("sql", j);

        j = type == null ? nullNode : jsonNodeFactory1.textNode(type.toString());
        objectNode.set("type", j);

        j = entityMetadata == null ? nullNode : jsonNodeFactory1.textNode(entityMetadata.toString());
        objectNode.set("entityMetadata", j);

        j = queryExpression == null ? nullNode : jsonNodeFactory1.textNode(queryExpression.toString());
        objectNode.set("queryExpression", j);

        j = projection == null ? nullNode : jsonNodeFactory1.textNode(projection.toString());
        objectNode.set("projection", j);

        j = sort == null ? nullNode : jsonNodeFactory1.textNode(sort.toString());
        objectNode.set("sort", j);

        if (temporaryVariable != null) {
            ObjectNode jsonNodes = jsonNodeFactory1.objectNode();
            for (Map.Entry<String, Object> a : temporaryVariable.entrySet()) {
                jsonNodes.set(a.getKey(), jsonNodeFactory1.textNode(a.getValue().toString()));
            }
            objectNode.set("temporaryVariable", jsonNodes);
        } else {
            objectNode.set("temporaryVariable", nullNode);
        }

        if (in != null) {
            ArrayNode jsonNodes = jsonNodeFactory1.arrayNode();
            for (InOut a : in) {
                jsonNodes.add(a.toString());
            }
            objectNode.set("in", jsonNodes);
        } else {
            objectNode.set("in", nullNode);
        }

        s = out == null ? nullNodeString : out.toString();
        if (out != null) {
            ArrayNode jsonNodes = jsonNodeFactory1.arrayNode();
            for (InOut a : out) {
                jsonNodes.add(a.toString());
            }
            objectNode.set("out", jsonNodes);
        } else {
            objectNode.set("out", nullNode);
        }

        s = inVar == null ? nullNodeString : inVar.toString();
        objectNode.set("inVar", JsonUtils.json(s));

        s = outVar == null ? nullNodeString : outVar.toString();
        objectNode.set("outVar", JsonUtils.json(s));

        objectNode.set("initialInput", JsonUtils.json(Boolean.toString(initialInput)));

        if (inputMappedByField != null) {
            ObjectNode jsonNodes = jsonNodeFactory1.objectNode();
            for (Map.Entry<String, Object> a : inputMappedByField.entrySet()) {
                jsonNodes.set(a.getKey(), jsonNodeFactory1.textNode(a.getValue().toString()));
            }
            objectNode.set("inputMappedByField", jsonNodes);
        } else {
            objectNode.set("inputMappedByField", nullNode);
        }

        if (inputMappedByColumn != null) {
            ObjectNode jsonNodes = jsonNodeFactory1.objectNode();
            for (Map.Entry<String, Object> a : inputMappedByColumn.entrySet()) {
                jsonNodes.set(a.getKey(), jsonNodeFactory1.textNode(a.getValue().toString()));
            }
            objectNode.set("inputMappedByColumn", jsonNodes);
        } else {
            objectNode.set("inputMappedByColumn", nullNode);
        }

        s = jsonNodeFactory == null ? nullNodeString : jsonNodeFactory.toString();
        objectNode.set("jsonNodeFactory", jsonNodeFactory1.textNode(s));

        s = RDBMSDataSourceResolver == null ? nullNodeString : RDBMSDataSourceResolver.toString();
        objectNode.set("RDBMSDataSourceResolver", JsonUtils.json(s));

        s = fieldAccessRoleEvaluator == null ? nullNodeString : fieldAccessRoleEvaluator.toString();
        objectNode.set("fieldAccessRoleEvaluator", jsonNodeFactory1.textNode(s));

        s = CRUDOperationName == null ? nullNodeString : CRUDOperationName.toString();
        objectNode.set("CRUDOperationName", jsonNodeFactory1.textNode(s));

        s = crudOperationContext == null ? nullNodeString : crudOperationContext.toString();
        objectNode.set("crudOperationContext", jsonNodeFactory1.textNode(s));

        s = currentLoopOperator == null ? nullNodeString : currentLoopOperator.toString();
        objectNode.set("currentLoopOperator", jsonNodeFactory1.textNode(s));

        s = updateExpression == null ? nullNodeString : updateExpression.toString();
        objectNode.set("updateExpression", jsonNodeFactory1.textNode(s));

    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

    return JsonUtils.prettyPrint(objectNode);
}

From source file:squash.booking.lambdas.core.PageManager.java

/**
 * Returns JSON-encoded valid-dates data for a specified date.
 * //  w  w  w.j  a  v a 2  s  . c o  m
 * <p>This is not private only so that it can be unit-tested.
 * 
 * @param validDates the dates for which bookings can be made, in YYYY-MM-DD format.
 * @throws IOException
 */
protected String createValidDatesData(List<String> validDates) throws IllegalArgumentException, IOException {

    // N.B. we assume that the date is known to be a valid date
    logger.log("About to create cached valid dates data");

    // Encode valid dates as JSON
    // Create the node factory that gives us nodes.
    JsonNodeFactory factory = new JsonNodeFactory(false);
    // Create a json factory to write the treenode as json.
    JsonFactory jsonFactory = new JsonFactory();
    ObjectNode rootNode = factory.objectNode();
    ArrayNode validDatesNode = rootNode.putArray("dates");
    for (int i = 0; i < validDates.size(); i++) {
        validDatesNode.add(validDates.get(i));
    }

    ByteArrayOutputStream validDatesStream = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(validDatesStream);
    try (JsonGenerator generator = jsonFactory.createGenerator(printStream)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeTree(generator, rootNode);
    }
    String validDatesString = validDatesStream.toString(StandardCharsets.UTF_8.name());
    logger.log("Created cached valid dates data : " + validDatesString);

    return validDatesString;
}

From source file:squash.booking.lambdas.core.PageManager.java

/**
 * Returns JSON-encoded booking data for a specified date.
 * // w  w w  .j  a  v  a 2 s .com
 * <p>This is not private only so that it can be unit-tested.
 * 
 * @param date the date in YYYY-MM-DD format.
 * @param validDates the dates for which bookings can be made, in YYYY-MM-DD format.
 * @param bookings the bookings for the specified date.
 * @throws Exception 
 */
protected String createCachedBookingData(String date, List<String> validDates, List<Booking> bookings)
        throws Exception {

    ImmutablePair<LifecycleState, Optional<String>> lifecycleState = lifecycleManager.getLifecycleState();

    // N.B. we assume that the date is known to be a valid date
    logger.log("About to create cached booking data");
    logger.log("Lifecycle state is: " + lifecycleState.left.name());
    if (lifecycleState.left.equals(LifecycleState.RETIRED)) {
        logger.log("Lifecycle state forwarding url is: " + lifecycleState.right.get());
    }

    // Encode bookings as JSON
    // Create the node factory that gives us nodes.
    JsonNodeFactory factory = new JsonNodeFactory(false);
    // Create a json factory to write the treenode as json.
    JsonFactory jsonFactory = new JsonFactory();
    ObjectNode rootNode = factory.objectNode();

    rootNode.put("date", date);
    ArrayNode validDatesNode = rootNode.putArray("validdates");
    for (int i = 0; i < validDates.size(); i++) {
        validDatesNode.add(validDates.get(i));
    }
    ArrayNode bookingsNode = rootNode.putArray("bookings");
    for (int i = 0; i < bookings.size(); i++) {
        Booking booking = bookings.get(i);
        ObjectNode bookingNode = factory.objectNode();
        bookingNode.put("court", booking.getCourt());
        bookingNode.put("courtSpan", booking.getCourtSpan());
        bookingNode.put("slot", booking.getSlot());
        bookingNode.put("slotSpan", booking.getSlotSpan());
        bookingNode.put("name", booking.getName());
        bookingsNode.add(bookingNode);
    }
    // This gives the Angularjs app access to the lifecycle state.
    ObjectNode lifecycleStateNode = rootNode.putObject("lifecycleState");
    lifecycleStateNode.put("state", lifecycleState.left.name());
    lifecycleStateNode.put("url", lifecycleState.right.isPresent() ? lifecycleState.right.get() : "");

    ByteArrayOutputStream bookingDataStream = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(bookingDataStream);
    try (JsonGenerator generator = jsonFactory.createGenerator(printStream)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeTree(generator, rootNode);
    }
    String bookingData = bookingDataStream.toString(StandardCharsets.UTF_8.name());
    logger.log("Created cached booking data: " + bookingData);

    return bookingData;
}

From source file:com.spotify.docker.client.DefaultDockerClient.java

@Override
public InputStream copyContainer(String containerId, String path) throws DockerException, InterruptedException {
    final WebTarget resource = resource().path("containers").path(containerId).path("copy");

    // Internal JSON object; not worth it to create class for this
    JsonNodeFactory nf = JsonNodeFactory.instance;
    final JsonNode params = nf.objectNode().set("Resource", nf.textNode(path));

    return request(POST, InputStream.class, resource, resource.request(APPLICATION_OCTET_STREAM_TYPE),
            Entity.json(params));
}

From source file:com.redhat.lightblue.crud.ldap.LdapCRUDController.java

/**
 * For Insert and Save (and possibly Update), this method will project the results back
 * onto the documents./*from  w w w .j  av  a 2  s . c  o  m*/
 * @param projection - {@link Projection} If null, then nothing will happen.
 * @param ctx - {@link CRUDOperationContext}
 * @param documentToDnMap - Map linking {@link DocCtx} to the DN that represents it.
 */
private void projectChanges(Projection projection, CRUDOperationContext ctx,
        Map<DocCtx, String> documentToDnMap) {
    if (projection == null) {
        return;
    }

    EntityMetadata md = ctx.getEntityMetadata(ctx.getEntityName());
    JsonNodeFactory factory = ctx.getFactory().getNodeFactory();
    LdapFieldNameTranslator fieldNameTranslator = LdapCrudUtil.getLdapFieldNameTranslator(md);

    Set<String> requiredAttributeNames = translateFieldNames(fieldNameTranslator,
            gatherRequiredFields(md, projection, null, null));
    Projector projector = Projector
            .getInstance(Projection.add(projection, new FieldAccessRoleEvaluator(md, ctx.getCallerRoles())
                    .getExcludedFields(FieldAccessRoleEvaluator.Operation.insert)), md);

    Path dnFieldPath = fieldNameTranslator.translateAttributeName(LdapConstant.ATTRIBUTE_DN);

    for (Entry<DocCtx, String> insertedDn : documentToDnMap.entrySet()) {
        DocCtx document = insertedDn.getKey();
        String dn = insertedDn.getValue();
        DocCtx projectionResponseJson = null;

        // If only dn is in the projection, then no need to query LDAP.
        if ((requiredAttributeNames.size() == 1)
                && requiredAttributeNames.contains(LdapConstant.ATTRIBUTE_DN)) {
            JsonDoc jdoc = new JsonDoc(factory.objectNode());
            jdoc.modify(dnFieldPath, StringType.TYPE.toJson(factory, dn), true);
            projectionResponseJson = new DocCtx(jdoc);
        }
        //TODO: else fetch entity from LDAP and project results.
        //TODO: Probably want to batch fetch as opposed to individual fetches.

        document.setOutputDocument(projector.project(projectionResponseJson, factory));
    }
}