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:org.openremote.server.inventory.DiscoveryService.java

protected String createDiscoveryEndpointUri(Adapter adapter) {
    ComponentConfiguration discoveryConfig = context.getComponent(adapter.getId())
            .createComponentConfiguration();
    discoveryConfig.setBaseUri(adapter.getDiscoveryEndpoint());
    try {//from ww  w  .j  av  a 2s .  c o m
        ObjectNode properties = JSON.readValue(adapter.getProperties(), ObjectNode.class);
        Iterator<String> it = properties.fieldNames();
        while (it.hasNext()) {
            String propertyName = it.next();
            JsonNode property = properties.get(propertyName);
            if (property.hasNonNull("value")) {
                discoveryConfig.setParameter(propertyName, property.get("value").asText());
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    LOG.debug("Using discovery URI: " + discoveryConfig.getUriString());
    return discoveryConfig.getUriString();
}

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

/**
 * Set access token and refresh token, used to authorize the calendar agent.
 * These tokens must be retrieved via Oauth 2.0 authorization.
 * //from  w  ww.  j a va2s. c om
 * @param access_token
 *            the access_token
 * @param token_type
 *            the token_type
 * @param expires_in
 *            the expires_in
 * @param refresh_token
 *            the refresh_token
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void setAuthorization(@Name("access_token") final String access_token,
        @Name("token_type") final String token_type, @Name("expires_in") final Integer expires_in,
        @Name("refresh_token") final String refresh_token) throws IOException {
    LOG.info("setAuthorization");

    final State state = getState();

    // retrieve user information
    final String url = "https://www.googleapis.com/oauth2/v1/userinfo";
    final Map<String, String> headers = new HashMap<String, String>();
    headers.put("Authorization", token_type + " " + access_token);
    final String resp = HttpUtil.get(url, headers);

    final ObjectNode info = JOM.getInstance().readValue(resp, ObjectNode.class);
    final String email = info.has("email") ? info.get("email").asText() : null;
    final String name = info.has("name") ? info.get("name").asText() : null;

    final DateTime expires_at = calculateExpiresAt(expires_in);
    final Authorization auth = new Authorization(access_token, token_type, expires_at, refresh_token);

    // store the tokens in the state
    state.put("auth", auth);
    state.put("email", email);
    state.put("name", name);
}

From source file:org.onosproject.dstreamon.rest.StackResource.java

/**
 * Registers the data of a new stack created through OpenStack Heat.
 *
 * @param stream the input stream//from w  w  w  . j a v a2s. c o  m
 * @return the result of the operation
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response registerStack(InputStream stream) {

    ObjectNode root = mapper().createObjectNode();
    DStreaMonStack stack = null;
    String stackUuid = null;
    JsonNode vm = null;
    String userUuid = null;
    String userIp = null;
    String userMac = null;
    String userPortUuid = null;
    String probeUuid = null;
    String probeIp = null;
    String probeMac = null;
    String probePortUuid = null;

    try {

        root = (ObjectNode) mapper().readTree(stream);
        stackUuid = root.get("stack_uuid").asText();
        vm = root.get("user");
        userUuid = vm.get("uuid").asText();
        userIp = vm.get("ip").asText();
        userMac = vm.get("mac").asText();
        userPortUuid = vm.get("port_uuid").asText();
        vm = root.get("probe");
        probeUuid = vm.get("uuid").asText();
        probeIp = vm.get("ip").asText();
        probeMac = vm.get("mac").asText();
        probePortUuid = vm.get("port_uuid").asText();

    } catch (IOException e) {
        e.printStackTrace();
        return Response.ok(INVALID_PARAMETER).build();
    }

    try {
        stack = DStreaMonStack.dStreaMonStack(stackUuid, userUuid, probeUuid, userIp, probeIp, userMac,
                probeMac, userPortUuid, probePortUuid);
        DStreaMonService service = get(DStreaMonService.class);
        service.registerStack(stack);

    } catch (Exception e) {
        log.info(e.getMessage());
        return Response.ok(FAILED).build();
    }

    return Response.ok(REGISTERED).build();

}

From source file:de.thomaskrille.dropwizard.environment_configuration.EnvironmentConfigurationFactory.java

private void addOverride(JsonNode root, String name, String value) {
    JsonNode node = root;/*from   w  w w.  java2  s.  co  m*/
    final Iterable<String> split = Splitter.on('.').trimResults().split(name);
    final String[] parts = Iterables.toArray(split, String.class);

    for (int i = 0; i < parts.length; i++) {
        String key = parts[i];

        if (!(node instanceof ObjectNode)) {
            throw new IllegalArgumentException("Unable to override " + name + "; it's not a valid path.");
        }
        final ObjectNode obj = (ObjectNode) node;

        final String remainingPath = Joiner.on('.').join(Arrays.copyOfRange(parts, i, parts.length));
        if (obj.has(remainingPath) && !remainingPath.equals(key)) {
            if (obj.get(remainingPath).isValueNode()) {
                obj.put(remainingPath, value);
                return;
            }
        }

        JsonNode child;
        final boolean moreParts = i < parts.length - 1;

        if (key.matches(".+\\[\\d+\\]$")) {
            final int s = key.indexOf('[');
            final int index = Integer.parseInt(key.substring(s + 1, key.length() - 1));
            key = key.substring(0, s);
            child = obj.get(key);
            if (child == null) {
                throw new IllegalArgumentException(
                        "Unable to override " + name + "; node with index not found.");
            }
            if (!child.isArray()) {
                throw new IllegalArgumentException(
                        "Unable to override " + name + "; node with index is not an array.");
            } else if (index >= child.size()) {
                throw new ArrayIndexOutOfBoundsException(
                        "Unable to override " + name + "; index is greater than size of array.");
            }
            if (moreParts) {
                child = child.get(index);
                node = child;
            } else {
                ArrayNode array = (ArrayNode) child;
                array.set(index, TextNode.valueOf(value));
                return;
            }
        } else if (moreParts) {
            child = obj.get(key);
            if (child == null) {
                child = obj.objectNode();
                obj.put(key, child);
            }
            if (child.isArray()) {
                throw new IllegalArgumentException(
                        "Unable to override " + name + "; target is an array but no index specified");
            }
            node = child;
        }

        if (!moreParts) {
            if (node.get(key) != null && node.get(key).isArray()) {
                ArrayNode arrayNode = (ArrayNode) obj.get(key);
                arrayNode.removeAll();
                Pattern escapedComma = Pattern.compile("\\\\,");
                for (String val : Splitter.on(Pattern.compile("(?<!\\\\),")).trimResults().split(value)) {
                    arrayNode.add(escapedComma.matcher(val).replaceAll(","));
                }
            } else {
                obj.put(key, value);
            }
        }
    }
}

From source file:com.marklogic.samplestack.database.DatabaseQnADocumentSearchIT.java

@Test
public void testAcceptedSearch() {
    JsonNode query;//from   ww w .  j av a  2 s .  c  o m
    ObjectNode results = null;
    try {
        query = mapper.readValue(
                "{\"query\":{\"value-constraint-query\":{\"constraint-name\":\"resolved\",\"boolean\":true}}}",
                JsonNode.class);
        results = operations.qnaSearch(ClientRole.SAMPLESTACK_CONTRIBUTOR, query, 1, QueryView.ALL);

        logger.debug("Query Results:" + mapper.writeValueAsString(results));

        logger.debug("Query Text:" + mapper.writeValueAsString(results.get("report")));
    } catch (IOException e) {
        throw new SamplestackIOException(e);
    }
    assertEquals("JSON has 1 result", 1, results.get("total").asInt());
}

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

protected void overwriteProperty(ObjectNode parent, ObjectNode child, String propertyName) {
    if (child.has(propertyName)) {
        parent.put(propertyName, child.get(propertyName));
    }/*from w  w  w  .  ja  v  a  2s.co m*/
}

From source file:com.mapr.synth.samplers.ZipSampler.java

@Override
public JsonNode sample() {
    while (true) {
        int i = rand.nextInt(zipCount);
        ObjectNode r = new ObjectNode(nodeFactory);
        for (String key : values.keySet()) {
            r.set(key, new TextNode(values.get(key).get(i)));
        }//from   w  ww .  ja v  a 2 s. co m

        if (latitudeFuzz > 0 || longitudeFuzz > 0) {
            r.set("longitude", new TextNode(
                    String.format("%.4f", r.get("longitude").asDouble() + rand.nextDouble() * longitudeFuzz)));
            r.set("latitude", new TextNode(
                    String.format("%.4f", r.get("latitude").asDouble() + rand.nextDouble() * latitudeFuzz)));
        }

        if (limits == null || limits.accept(r)) {
            if (verbose) {
                if (retainedFields != null) {
                    for (String key : values.keySet()) {
                        if (!retainedFields.contains(key)) {
                            r.remove(key);
                        }
                    }
                }
                return r;
            } else {
                return r.get("zip");
            }
        }
    }
}

From source file:org.gitana.platform.client.application.ApplicationImpl.java

@Override
public Settings createSettings(ObjectNode object) {
    if (object == null) {
        object = JsonUtil.createObject();
    }/*from www.j  a va  2s . co  m*/

    if (object.get(Settings.ROOT_KEY) == null) {
        object.putObject(Settings.ROOT_KEY);
    }

    Response response = getRemote().post(getResourceUri() + "/settings", object);

    String settingsId = response.getId();
    return readSettings(settingsId);
}

From source file:com.linkedin.drelephant.tuning.ParamGenerator.java

/**
 * Returns the tuning information for the jobs
 * @param tuningJobs Job List/*w  ww. jav  a  2 s. c o m*/
 * @return Tuning information list
 */
private List<JobTuningInfo> getJobsTuningInfo(List<TuningJobDefinition> tuningJobs) {

    List<JobTuningInfo> jobTuningInfoList = new ArrayList<JobTuningInfo>();
    for (TuningJobDefinition tuningJobDefinition : tuningJobs) {
        JobDefinition job = tuningJobDefinition.job;
        logger.info("Getting tuning information for job: " + job.jobDefId);
        List<TuningParameter> tuningParameterList = TuningParameter.find.where()
                .eq(TuningParameter.TABLE.tuningAlgorithm + "." + TuningAlgorithm.TABLE.id,
                        tuningJobDefinition.tuningAlgorithm.id)
                .eq(TuningParameter.TABLE.isDerived, 0).findList();

        try {
            logger.info("Fetching default parameter values for job " + tuningJobDefinition.job.jobDefId);
            TuningJobExecution defaultJobExecution = TuningJobExecution.find.where()
                    .eq(TuningJobExecution.TABLE.jobExecution + "." + JobExecution.TABLE.job + "."
                            + JobDefinition.TABLE.id, tuningJobDefinition.job.id)
                    .eq(TuningJobExecution.TABLE.isDefaultExecution, 1)
                    .orderBy(TuningJobExecution.TABLE.jobExecution + "." + JobExecution.TABLE.id + " desc")
                    .setMaxRows(1).findUnique();
            if (defaultJobExecution != null && defaultJobExecution.jobExecution != null) {
                List<JobSuggestedParamValue> jobSuggestedParamValueList = JobSuggestedParamValue.find.where()
                        .eq(JobSuggestedParamValue.TABLE.jobExecution + "." + JobExecution.TABLE.id,
                                defaultJobExecution.jobExecution.id)
                        .findList();

                if (jobSuggestedParamValueList.size() > 0) {
                    Map<Integer, Double> defaultExecutionParamMap = new HashMap<Integer, Double>();

                    for (JobSuggestedParamValue jobSuggestedParamValue : jobSuggestedParamValueList) {
                        defaultExecutionParamMap.put(jobSuggestedParamValue.tuningParameter.id,
                                jobSuggestedParamValue.paramValue);
                    }

                    for (TuningParameter tuningParameter : tuningParameterList) {
                        Integer paramId = tuningParameter.id;
                        if (defaultExecutionParamMap.containsKey(paramId)) {
                            logger.info("Updating value of param " + tuningParameter.paramName + " to "
                                    + defaultExecutionParamMap.get(paramId));
                            tuningParameter.defaultValue = defaultExecutionParamMap.get(paramId);
                        }
                    }
                }
            }
        } catch (NullPointerException e) {
            logger.error("Error extracting default value of params for job " + tuningJobDefinition.job.jobDefId,
                    e);
        }
        JobTuningInfo jobTuningInfo = new JobTuningInfo();
        jobTuningInfo.setTuningJob(job);
        jobTuningInfo.setParametersToTune(tuningParameterList);
        JobSavedState jobSavedState = JobSavedState.find.byId(job.id);

        boolean validSavedState = true;
        if (jobSavedState != null && jobSavedState.isValid()) {
            String savedState = new String(jobSavedState.savedState);
            ObjectNode jsonSavedState = (ObjectNode) Json.parse(savedState);
            JsonNode jsonCurrentPopulation = jsonSavedState.get(JSON_CURRENT_POPULATION_KEY);
            List<Particle> currentPopulation = jsonToParticleList(jsonCurrentPopulation);
            for (Particle particle : currentPopulation) {
                Long paramSetId = particle.getParamSetId();

                logger.info("Param set id: " + paramSetId.toString());
                TuningJobExecution tuningJobExecution = TuningJobExecution.find.select("*")
                        .fetch(TuningJobExecution.TABLE.jobExecution, "*").where()
                        .eq(TuningJobExecution.TABLE.jobExecution + "." + JobExecution.TABLE.id, paramSetId)
                        .findUnique();

                JobExecution jobExecution = tuningJobExecution.jobExecution;

                if (tuningJobExecution.fitness != null) {
                    particle.setFitness(tuningJobExecution.fitness);
                } else {
                    validSavedState = false;
                    logger.error("Invalid saved state: Fitness of previous execution not computed.");
                    break;
                }
            }

            if (validSavedState) {
                JsonNode updatedJsonCurrentPopulation = particleListToJson(currentPopulation);
                jsonSavedState.set(JSON_CURRENT_POPULATION_KEY, updatedJsonCurrentPopulation);
                savedState = Json.stringify(jsonSavedState);
                jobTuningInfo.setTunerState(savedState);
            }
        } else {
            logger.info("Saved state empty for job: " + job.jobDefId);
            validSavedState = false;
        }

        if (!validSavedState) {
            jobTuningInfo.setTunerState("{}");
        }

        logger.info("Adding JobTuningInfo " + Json.toJson(jobTuningInfo));
        jobTuningInfoList.add(jobTuningInfo);
    }
    return jobTuningInfoList;
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** More levels of utility for code reuse
 * @param mutable_o//from  w  ww.  j a  va 2 s  .  co  m
 * @param fielddata_info
 * @param mapper
 * @param index_type
 * @throws JsonProcessingException
 * @throws IOException
 */
protected static void setMapping(final ObjectNode mutable_o,
        final Optional<Tuple3<JsonNode, JsonNode, Boolean>> fielddata_info, final ObjectMapper mapper,
        final String index_type) throws JsonProcessingException, IOException {
    if (fielddata_info.isPresent()) {
        final JsonNode fielddata_not_analyzed = fielddata_info.get()._1();
        final JsonNode fielddata_analyzed = fielddata_info.get()._2();
        final boolean override_existing = fielddata_info.get()._3();

        final boolean is_analyzed = Optional.ofNullable(mutable_o.get("index"))
                .filter(jj -> !jj.isNull() && jj.isTextual())
                .map(jt -> jt.asText().equalsIgnoreCase("analyzed") || jt.asText().equalsIgnoreCase("yes"))
                .orElse(true);

        final JsonNode fielddata_settings = is_analyzed ? fielddata_analyzed : fielddata_not_analyzed;

        Optional.ofNullable(Optional.ofNullable(fielddata_settings.get(index_type)).filter(jj -> !jj.isNull())
                .orElse(fielddata_settings.get(DEFAULT_FIELDDATA_NAME))).ifPresent(jj -> {
                    if (override_existing || !mutable_o.has("fielddata"))
                        mutable_o.set("fielddata", jj);
                });
    } else { // This means it's a columnar exclude lookup
        //Previously did this, however I think it's preferable if columnar is disabled just to leave it alone
        mutable_o.set("fielddata", mapper.readTree(DISABLED_FIELDDATA));
    }
}