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

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

Introduction

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

Prototype

public JsonNode get(String paramString) 

Source Link

Usage

From source file:scott.barleyrs.rest.CrudService.java

private Object getEntityKey(ObjectNode jsObject, EntityType entityType) {
    JsonNode keyNode = jsObject.get(entityType.getKeyNodeName());
    if (keyNode == null || keyNode.isNull()) {
        return null;
    }/*  ww  w  .ja  v a2  s . co  m*/
    String keyAsString = keyNode.asText();
    if (keyAsString == null || keyAsString.isEmpty()) {
        return null;
    }
    return convertForKey(entityType, keyAsString);
}

From source file:com.almende.pi5.lch.SimManager.java

@Override
protected void onReady() {
    final ObjectNode config = getConfig();
    if (config.has("timeCsv")) {
        try {//from   w  ww  .  ja v  a  2s.  c o  m
            final InputStream is = new FileInputStream(new File(config.get("timeCsv").asText()));
            if (is != null) {
                readTimeSpread(convertStreamToString(is));
            }
        } catch (FileNotFoundException e) {
            LOG.log(Level.WARNING, "Failed to read TimeSpread data.", e);
        }
    }
    if (config.has("flexCsv")) {
        try {
            final InputStream is = new FileInputStream(new File(config.get("flexCsv").asText()));
            if (is != null) {
                readFlexSpread(convertStreamToString(is));
            }
        } catch (FileNotFoundException e) {
            LOG.log(Level.WARNING, "Failed to read FlexSpread data.", e);
        }
    }
    if (config.has("dersCsv")) {
        try {
            final InputStream is = new FileInputStream(new File(config.get("dersCsv").asText()));
            if (is != null) {
                readDers(convertStreamToString(is));
            }
        } catch (FileNotFoundException e) {
            LOG.log(Level.WARNING, "Failed to read Ders data.", e);
        }
    }
}

From source file:org.jsonschema2pojo.SchemaGenerator.java

private ObjectNode mergeObjectNodes(ObjectNode targetNode, ObjectNode updateNode) {
    Iterator<String> fieldNames = updateNode.fieldNames();
    while (fieldNames.hasNext()) {

        String fieldName = fieldNames.next();
        JsonNode targetValue = targetNode.get(fieldName);
        JsonNode updateValue = updateNode.get(fieldName);

        if (targetValue == null) {
            // Target node doesn't have this field from update node: just add it
            targetNode.set(fieldName, updateValue);

        } else {//from   w  w  w  .  j a  v a  2s  . com
            // Both nodes have the same field: merge the values
            if (targetValue.isObject() && updateValue.isObject()) {
                // Both values are objects: recurse
                targetNode.set(fieldName, mergeObjectNodes((ObjectNode) targetValue, (ObjectNode) updateValue));
            } else if (targetValue.isArray() && updateValue.isArray()) {
                // Both values are arrays: concatenate them to be merged later
                ((ArrayNode) targetValue).addAll((ArrayNode) updateValue);
            } else {
                // Values have different types: use the one from the update node
                targetNode.set(fieldName, updateValue);
            }
        }
    }

    return targetNode;
}

From source file:com.collective.celos.OozieExternalService.java

Properties setupDefaultProperties(ObjectNode defaults, ScheduledTime t) {
    Properties props = new Properties();
    ScheduledTimeFormatter formatter = new ScheduledTimeFormatter();
    for (Iterator<String> names = defaults.fieldNames(); names.hasNext();) {
        String name = names.next();
        String value = defaults.get(name).textValue();
        props.setProperty(name, formatter.replaceTimeTokens(value, t));
    }/*from   ww w.  java2  s . c o  m*/
    return props;
}

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

/**
 * Given an RSS object, build and return the Provider object
 *
 * @param entry//from   w w  w  .  jav a 2s .  co m
 * @return
 */
private Provider buildProvider(ObjectNode entry) {
    Provider provider = new Provider();

    String link = null;
    String uri = null;
    String resourceLocation = null;

    if (entry.get("link") != null)
        link = entry.get("link").textValue();
    if (entry.get("uri") != null)
        uri = entry.get("uri").textValue();

    /**
     * Order of precedence for resourceLocation selection
     *
     * 1. Valid URI
     * 2. Valid Link
     * 3. Non-null URI
     * 4. Non-null Link
     */
    if (isValidResource(uri))
        resourceLocation = uri;
    else if (isValidResource(link))
        resourceLocation = link;
    else if (uri != null || link != null) {
        resourceLocation = (uri != null) ? uri : link;
    }

    provider.setId("id:providers:rss");
    provider.setUrl(resourceLocation);
    provider.setDisplayName("RSS");

    return provider;
}

From source file:org.lendingclub.mercator.ucs.UCSScanner.java

protected void recordServerServiceProfile(Element element) {
    ObjectNode n = toJson(element);

    String mercatorId = computeMercatorIdFromDn(n.get("dn").asText());

    String cypher = "merge (p:UCSServerServiceProfile {mercatorId:{mercatorId}}) set p+={props}, p.updateTs=timestamp()";

    getProjector().getNeoRxClient().execCypher(cypher, "mercatorId", mercatorId, "props", n);

    String orgDn = extractOrgDn(n.get("dn").asText());
    String orgMercatorId = computeMercatorIdFromDn(orgDn);

    cypher = "match (e:UCSServerServiceProfile {mercatorId:{mercatorId}}), (o:UCSOrg {mercatorId:{orgMercatorId}}) merge (o)-[r:CONTAINS]->(e) set r.updateTs=timestamp()";

    getProjector().getNeoRxClient().execCypher(cypher, "mercatorId", mercatorId, "orgMercatorId",
            orgMercatorId);//from  ww  w.j a  va  2  s. c o  m
}

From source file:org.lendingclub.mercator.ucs.UCSScanner.java

protected void recordOrg(Element element) {
    getUCSClient().logDebug("org", element);

    ObjectNode n = toJson(element);

    String mercatorId = computeMercatorIdFromDn(n.get("dn").asText());
    n.put("mercatorId", mercatorId);

    String cypher = "merge (c:UCSOrg {mercatorId:{mercatorId}}) set c+={props}, c.updateTs=timestamp()";

    getProjector().getNeoRxClient().execCypher(cypher, "mercatorId", mercatorId, "props", n);

    cypher = "match (m:UCSManager {mercatorId:{managerId}}), (c:UCSOrg {mercatorId:{orgId}}) merge (m)-[r:MANAGES]->(c)";

    getProjector().getNeoRxClient().execCypher(cypher, "managerId", getUCSClient().getUCSManagerId(), "orgId",
            mercatorId);//from w  w w. j a v a  2  s  .co  m

}

From source file:com.github.reinert.jjschema.HyperSchemaGeneratorV4.java

private <T> ObjectNode generateHyperSchemaFromResource(Class<T> type) throws TypeException {
    ObjectNode schema = null;//from  w  ww .  ja  va  2s.co  m

    Annotation[] ans = type.getAnnotations();
    boolean hasPath = false;
    for (Annotation a : ans) {
        if (a instanceof Path) {
            hasPath = true;
            Path p = (Path) a;
            if (schema == null) {
                schema = jsonSchemaGenerator.createInstance();
            }
            schema.put("pathStart", p.value());
        }
        if (a instanceof Produces) {
            Produces p = (Produces) a;
            if (schema == null) {
                schema = jsonSchemaGenerator.createInstance();
            }
            schema.put(MEDIA_TYPE, p.value()[0]);
        }
    }
    if (!hasPath) {
        throw new RuntimeException("Invalid Resource class. Must use Path annotation.");
    }

    ArrayNode links = schema.putArray("links");

    for (Method method : type.getDeclaredMethods()) {
        try {
            ObjectNode link = generateLink(method);
            if ("GET".equals(link.get("method").asText()) && "#".equals(link.get("href").asText())) {
                jsonSchemaGenerator.mergeSchema(schema, (ObjectNode) link.get("targetSchema"), true);
            } else {
                links.add(link);
            }
        } catch (InvalidLinkMethod e) {
            e.printStackTrace();
        }
    }

    return schema;
}

From source file:org.openmhealth.reference.request.DataWriteRequest.java

/**
 * Validates the data and, if valid, stores it.
 *///from   w ww. j a  v  a  2 s.co  m
@Override
public void service() throws OmhException {
    // First, short-circuit if this request has already been serviced.
    if (isServiced()) {
        return;
    } else {
        setServiced();
    }

    // Check to be sure the schema is known.
    MultiValueResult<? extends Schema> schemas = Registry.getInstance().getSchemas(schemaId, version, 0, 1);
    if (schemas.count() == 0) {
        throw new OmhException(
                "The schema ID, '" + schemaId + "', and version, '" + version + "', pair is unknown.");
    }
    Schema schema = schemas.iterator().next();

    // Get the user that owns this token.
    User requestingUser = authToken.getUser();

    // Parse the data.
    JsonNode dataNode;
    try {
        dataNode = JSON_FACTORY.createJsonParser(data).readValueAs(JsonNode.class);
    } catch (JsonParseException e) {
        throw new OmhException("The data was not well-formed JSON.", e);
    } catch (JsonProcessingException e) {
        throw new OmhException("The data was not well-formed JSON.", e);
    } catch (IOException e) {
        throw new OmhException("The data could not be read.", e);
    }

    // Make sure it is a JSON array.
    if (!(dataNode instanceof ArrayNode)) {
        throw new OmhException("The data was not a JSON array.");
    }
    ArrayNode dataArray = (ArrayNode) dataNode;

    // Get the number of data points.
    int numDataPoints = dataArray.size();

    // Create the result list of data points.
    List<Data> dataPoints = new ArrayList<Data>(numDataPoints);

    // Create a new ObjectMapper that will be used to convert the meta-data
    // node into a MetaData object.
    ObjectMapper mapper = new ObjectMapper();

    // For each element in the array, be sure it is a JSON object that
    // represents a valid data point for this schema.
    for (int i = 0; i < numDataPoints; i++) {
        // Get the current data point.
        JsonNode dataPoint = dataArray.get(i);

        // Validate that it is a JSON object.
        if (!(dataPoint instanceof ObjectNode)) {
            throw new OmhException("A data point was not a JSON object: " + i);
        }
        ObjectNode dataObject = (ObjectNode) dataPoint;

        // Attempt to get the meta-data;
        MetaData metaData = null;
        JsonNode metaDataNode = dataObject.get(Data.JSON_KEY_METADATA);
        if (metaDataNode != null) {
            metaData = mapper.convertValue(metaDataNode, MetaData.class);
        }

        // Attempt to get the schema data.
        JsonNode schemaData = dataObject.get(Data.JSON_KEY_DATA);

        // If the data is missing, fail the request.
        if (schemaData == null) {
            throw new OmhException("A data point's '" + Data.JSON_KEY_DATA + "' field is missing.");
        }

        // Create and add the point to the set of data.
        dataPoints.add(schema.validateData(requestingUser.getUsername(), metaData, schemaData));
    }

    // Store the data.
    DataSet.getInstance().storeData(dataPoints);
}

From source file:ws.wamp.jawampa.client.HandshakingState.java

void onMessage(WampMessage msg) {
    // We were not yet welcomed
    if (msg instanceof WelcomeMessage) {
        // Receive a welcome. Now the session is established!
        ObjectNode welcomeDetails = ((WelcomeMessage) msg).details;
        long sessionId = ((WelcomeMessage) msg).sessionId;

        // Extract the roles of the remote side
        JsonNode roleNode = welcomeDetails.get("roles");
        if (roleNode == null || !roleNode.isObject()) {
            handleProtocolError();//from w  w  w  .jav a2  s  .  c  o m
            return;
        }

        EnumSet<WampRoles> routerRoles = EnumSet.noneOf(WampRoles.class);
        Iterator<String> roleKeys = roleNode.fieldNames();
        while (roleKeys.hasNext()) {
            WampRoles role = WampRoles.fromString(roleKeys.next());
            if (role != null)
                routerRoles.add(role);
        }

        SessionEstablishedState newState = new SessionEstablishedState(stateController, connectionController,
                sessionId, welcomeDetails, routerRoles);
        stateController.setState(newState);
    } else if (msg instanceof ChallengeMessage) {
        if (!challengeMsgAllowed) {
            // Allow Challenge message only a single time
            handleProtocolError();
            return;
        }
        challengeMsgAllowed = false;

        ChallengeMessage challenge = (ChallengeMessage) msg;
        String authMethodString = challenge.authMethod;
        List<ClientSideAuthentication> authMethods = stateController.clientConfig().authMethods();

        for (ClientSideAuthentication authMethod : authMethods) {
            if (authMethod.getAuthMethod().equals(authMethodString)) {
                AuthenticateMessage reply = authMethod.handleChallenge(challenge,
                        stateController.clientConfig().objectMapper());
                if (reply == null) {
                    handleProtocolError();
                } else {
                    connectionController.sendMessage(reply, IWampConnectionPromise.Empty);
                }
                return;
            }
        }
        handleProtocolError();
    } else if (msg instanceof AbortMessage) {
        // The remote doesn't want us to connect :(
        AbortMessage abort = (AbortMessage) msg;
        handleSessionError(new ApplicationError(abort.reason), null);
    }
}