Example usage for com.fasterxml.jackson.databind ObjectMapper readTree

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper readTree.

Prototype

public JsonNode readTree(URL source) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content as tree expressed using set of JsonNode instances.

Usage

From source file:com.ikanow.aleph2.management_db.mongodb.services.TestIkanowV1SyncService_PurgeBuckets.java

@SuppressWarnings("deprecation")
@Test//from   w ww .  java2  s. c o m
public void test_SourceToBucketConversion_scripting()
        throws JsonProcessingException, IOException, ParseException {
    _logger.info("Starting test_SourceToBucketConversion_scripting");

    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    {
        final JsonNode v1_source = mapper
                .readTree(this.getClass().getResourceAsStream("test_scripting_1.json"));
        final DataBucketBean bucket = IkanowV1SyncService_Buckets.getBucketFromV1Source(v1_source);

        // (all the existing stuff)
        assertEquals("aleph...bucket.Template_V2_data_bucket.;", bucket._id());
        assertEquals("21 May 2015 02:37:23 GMT", bucket.created().toGMTString());
        assertEquals(null, bucket.data_locations());
        assertEquals("DESCRIPTION HERE.", bucket.description());
        assertEquals("Template V2 data bucket", bucket.display_name());
        assertEquals(1, bucket.harvest_configs().size());
        assertEquals(true, bucket.harvest_configs().get(0).enabled());
        assertEquals("/app/aleph2/library/import/harvest/tech/XXX", bucket.harvest_technology_name_or_id());
        assertEquals("none", bucket.master_enrichment_type().toString());
        assertEquals("25 May 2015 13:52:01 GMT", bucket.modified().toGMTString());
        assertEquals(null, bucket.multi_bucket_children());
        assertEquals(false, bucket.multi_node_enabled());
        assertEquals("506dc16dfbf042893dd6b8f2", bucket.owner_id());
        assertEquals(null, bucket.poll_frequency());
        assertEquals(null, bucket.streaming_enrichment_configs());
        assertEquals(null, bucket.streaming_enrichment_topology());
        assertEquals(Collections.unmodifiableSet(new HashSet<String>(Arrays.asList("test"))), bucket.tags());

        //Plus check on the subvariables:
        assertEquals(3, bucket.harvest_configs().get(0).config().size());
        assertEquals("test1:string1\n", bucket.harvest_configs().get(0).config().get("test1"));
        assertEquals("test2:\n\"string2\"\r:test2", bucket.harvest_configs().get(0).config().get("test2"));
        assertEquals("string1\n//ALEPH2_MODULE------------------\n\"string2\"\r:test_all",
                bucket.harvest_configs().get(0).config().get("test_all"));
    }

    {
        final JsonNode v1_source = mapper
                .readTree(this.getClass().getResourceAsStream("test_scripting_2.json"));
        final DataBucketBean bucket = IkanowV1SyncService_Buckets.getBucketFromV1Source(v1_source);

        // (all the existing stuff)
        assertEquals("aleph...bucket.Template_V2_data_bucket.;", bucket._id());
        assertEquals("21 May 2015 02:37:23 GMT", bucket.created().toGMTString());
        assertEquals(null, bucket.data_locations());
        assertEquals("DESCRIPTION HERE.", bucket.description());
        assertEquals("Template V2 data bucket", bucket.display_name());
        assertEquals(1, bucket.harvest_configs().size());
        assertEquals(true, bucket.harvest_configs().get(0).enabled());
        assertEquals("/app/aleph2/library/import/harvest/tech/a", bucket.harvest_technology_name_or_id());
        assertEquals("none", bucket.master_enrichment_type().toString());
        assertEquals("25 May 2015 13:52:01 GMT", bucket.modified().toGMTString());
        assertEquals(null, bucket.multi_bucket_children());
        assertEquals(false, bucket.multi_node_enabled());
        assertEquals("506dc16dfbf042893dd6b8f2", bucket.owner_id());
        assertEquals(null, bucket.poll_frequency());
        assertEquals(null, bucket.streaming_enrichment_configs());
        assertEquals(null, bucket.streaming_enrichment_topology());
        assertEquals(Collections.unmodifiableSet(new HashSet<String>(Arrays.asList("test"))), bucket.tags());

        //Plus check on the subvariables:
        assertEquals(1, bucket.harvest_configs().get(0).config().size());
        assertEquals("string1\n//ALEPH2_MODULE------------------\n\"string2\"",
                bucket.harvest_configs().get(0).config().get("test_all"));
    }
}

From source file:loadTest.loadTestLib.LUtil.java

public boolean startDockerSlave(LoadTestConfigModel ltModel) throws InterruptedException, IOException {

    String fileCount = String.valueOf(ltModel.getFileCount());

    if (runInDockerCluster) {
        HashMap<String, Integer> dockerNodes = getDockerNodes();

        Entry<String, Integer> entry = this.getLowestDockerHost();

        startedClusterContainer.put(entry.getKey(), entry.getValue() + 1);

        String dockerCommand = "{" + "\"Hostname\":\"\"," + "\"User\":\"\","
                + "\"Entrypoint\":[\"/bin/bash\",\"/pieShare/pieShareAppIntegrationTests/src/test/resources/docker/internal.sh\"],"
                + "\"Cmd\":[\"slave\",\"" + fileCount.toString() + "\"]," + "\"Memory\":0,"
                + "\"MemorySwap\":0," + "\"AttachStdin\":false," + "\"AttachStdout\":false,"
                + "\"AttachStderr\":false," + "\"PortSpecs\":null," + "\"Privileged\": false,"
                + "\"Tty\":false," + "\"OpenStdin\":false," + "\"StdinOnce\":false," + "\"Env\":null,"
                + "\"Dns\":null," + "\"Image\":\"vauvenal5/loadtest\"," + "\"Volumes\":{},"
                + "\"VolumesFrom\":\"\"," + "\"WorkingDir\":\"\"}";

        String url = entry.getKey() + "/containers/create";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/json");
        con.setDoOutput(true);//from ww w .  j  a  v  a  2  s  .co  m
        con.getOutputStream().write(dockerCommand.getBytes());
        con.getOutputStream().flush();
        con.getOutputStream().close();

        int responseCode = con.getResponseCode();

        if (responseCode != 201) {
            return false;
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line = null;
        String msg = "";

        while ((line = in.readLine()) != null) {
            msg += line;
        }

        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(msg);

        String containerId = node.get("Id").asText();
        con.disconnect();

        url = entry.getKey() + "/containers/" + containerId + "/start";
        obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/json");

        responseCode = con.getResponseCode();

        if (responseCode != 204) {
            return false;
        }

        if (!this.runningContainers.containsKey(entry.getKey())) {
            this.runningContainers.put(entry.getKey(), new ArrayList<>());
        }

        this.runningContainers.get(entry.getKey()).add(containerId);

        return true;
    }

    ProcessBuilder processBuilder = new ProcessBuilder("docker", "run", "vauvenal5/loadtest", "slave",
            fileCount);
    Process proc = processBuilder.start();
    this.slaves.add(proc);
    return true;
}

From source file:com.vaushell.superpipes.tools.scribe.linkedin.LinkedInClient.java

/**
 * Post message.//  w w w.j av a 2  s  . com
 *
 * @param message Status's message
 * @return Status ID
 * @throws IOException
 * @throws LinkedInException
 */
public String postMessage(final String message) throws IOException, LinkedInException {
    if (message == null || message.isEmpty()) {
        throw new IllegalArgumentException();
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getClass().getSimpleName() + "] updateStatus() : message=" + message);
    }

    final OAuthRequest request = new OAuthRequest(Verb.POST,
            "http://api.linkedin.com/v1/people/~/shares?format=json");

    final Element share = new Element("share");

    // Message
    share.addContent(new Element("comment").setText(message));

    // Visiblity
    final Element visiblity = new Element("visibility");
    visiblity.addContent(new Element("code").setText("anyone"));
    share.addContent(visiblity);

    final String xmlPayload = new XMLOutputter(Format.getPrettyFormat()).outputString(share);

    request.addHeader("Content-Type", "application/xml");
    request.addPayload(xmlPayload);

    final Response response = sendSignedRequest(request);

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode node = (JsonNode) mapper.readTree(response.getStream());

    checkErrors(response, node);

    return extractID(node.get("updateKey").asText());
}

From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java

@Override
public InputStream selectEntity(final InputStream src, final String[] propertyNames) throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode srcNode = (ObjectNode) mapper.readTree(src);

    final Set<String> retain = new HashSet<String>();
    retain.add(JSON_ID_NAME);//www .j  av  a  2 s  .c  o  m
    retain.add(JSON_TYPE_NAME);
    retain.add(JSON_EDITLINK_NAME);
    retain.add(JSON_NEXTLINK_NAME);
    retain.add(JSON_ODATAMETADATA_NAME);
    retain.add(JSON_VALUE_NAME);

    for (String name : propertyNames) {
        retain.add(name);
        retain.add(name + JSON_NAVIGATION_SUFFIX);
        retain.add(name + JSON_MEDIA_SUFFIX);
        retain.add(name + JSON_TYPE_SUFFIX);
    }

    srcNode.retain(retain);

    return IOUtils.toInputStream(srcNode.toString());
}

From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java

@Override
protected InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties)
        throws Exception {

    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode toBeChangedObject = (ObjectNode) mapper.readTree(toBeChanged);

    for (Map.Entry<String, InputStream> property : properties.entrySet()) {
        final JsonNode propertyNode = mapper.readTree(property.getValue());
        toBeChangedObject.set(property.getKey(), propertyNode);
    }//from ww  w  .  ja v  a  2  s  .c  o  m

    return IOUtils.toInputStream(toBeChangedObject.toString());
}

From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java

@Override
protected Set<String> retrieveAllLinkNames(InputStream is) throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode srcNode = (ObjectNode) mapper.readTree(is);
    IOUtils.closeQuietly(is);//  w w w  .j a v a  2 s . c  o m

    final Set<String> links = new HashSet<String>();

    final Iterator<String> fieldIter = srcNode.fieldNames();

    while (fieldIter.hasNext()) {
        final String field = fieldIter.next();

        if (field.endsWith(JSON_NAVIGATION_BIND_SUFFIX) || field.endsWith(JSON_NAVIGATION_SUFFIX)
                || field.endsWith(JSON_MEDIA_SUFFIX) || field.endsWith(JSON_EDITLINK_NAME)) {
            if (field.indexOf('@') > 0) {
                links.add(field.substring(0, field.indexOf('@')));
            } else {
                links.add(field);
            }
        }
    }

    return links;
}

From source file:com.baasbox.service.sociallogin.SocialLoginService.java

public boolean validationRequest(String token) throws BaasBoxSocialTokenValidationException {
    String url = getValidationURL(token);
    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
    HttpGet method = new HttpGet(url);

    BasicResponseHandler brh = new BasicResponseHandler();

    String body;// w  w  w. j  a v  a 2  s .  c  om
    try {
        body = client.execute(method, brh);

        if (StringUtils.isEmpty(body)) {
            return false;
        } else {
            ObjectMapper mapper = new ObjectMapper();
            JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead
            JsonParser jp = factory.createJsonParser(body);
            JsonNode jn = mapper.readTree(jp);
            return validate(jn);
        }
    } catch (IOException e) {
        throw new BaasBoxSocialTokenValidationException(
                "There was an error in the token validation process:" + ExceptionUtils.getMessage(e));
    }

}

From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java

@Override
protected InputStream replaceLink(final InputStream toBeChanged, final String linkName,
        final InputStream replacement) throws Exception {
    final ObjectMapper mapper = new ObjectMapper();

    final ObjectNode toBeChangedNode = (ObjectNode) mapper.readTree(toBeChanged);
    final ObjectNode replacementNode = (ObjectNode) mapper.readTree(replacement);

    if (toBeChangedNode.get(linkName + JSON_NAVIGATION_SUFFIX) == null) {
        throw new NotFoundException();
    }//  w ww.  j  a  va  2 s  .  co  m

    toBeChangedNode.set(linkName, replacementNode.get(JSON_VALUE_NAME));

    final JsonNode next = replacementNode.get(linkName + JSON_NEXTLINK_NAME);
    if (next != null) {
        toBeChangedNode.set(linkName + JSON_NEXTLINK_SUFFIX, next);
    }

    return IOUtils.toInputStream(toBeChangedNode.toString());
}

From source file:com.tango.elasticsearch.rest.action.unique.UniqueTermsAction.java

/**
 * Parse date request information and validates that request has expected format
 * <p/>//from  w  w  w  . ja  va2  s.  co  m
 * Example of input:
 * <code> {"facets": { "terms": { "terms": { "field": "@fields.uid", "size": 10000000, "order": "count", "exclude":
 * [] }, "facet_filter": { "fquery": { "query": { "filtered": { "query": { "bool": { "should": [ { "query_string": {
 * "query": "*" } } ] } }, "filter": { "bool": { "must": [ { "range": { "@timestamp": { "from": 1395275639569, "to":
 * "now" } } }, { "fquery": { "query": { "query_string": { "query": "@fields.tracer.service.name:(\"Like\")" } },
 * "_cache": true } }, { "terms": { "@fields.tracer.ip.country.name": ["UNITED STATES"] } } ] } } } } } } } },
 * "size": 0} }
 * </code>
 * 
 * @param requestSource source of request
 * @return parsed information
 * @throws IOException
 */
protected RequestParamsInfo getRequestInfo(String requestSource) throws IOException {
    RequestParamsInfo result = null;
    if (requestSource != null) {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(requestSource);
        JsonNode facets = jsonNode.findValue("facets");
        {
            if (facets.isMissingNode()) {
                throw new IllegalArgumentException("No facets found in requests");
            }
            Iterator<String> iterator = facets.fieldNames();
            while (iterator.hasNext()) {
                String facetName = iterator.next();
                if (!TARGET_FACET_NAME.equals(facetName)) {
                    throw new IllegalArgumentException("Unexpected facet name: " + facetName);
                }
            }
        }
        JsonNode terms = facets.path(TARGET_FACET_NAME);
        if (terms.isMissingNode()) {
            throw new IllegalArgumentException(
                    String.format("No facet with name '%s' found in requests", TARGET_FACET_NAME));
        }
        JsonNode range = jsonNode.findValue("@timestamp");
        if (range.isMissingNode()) {
            throw new IllegalArgumentException("No @timestamp found in requests");
        }
        String from = range.path("from").asText();
        String to = range.path("to").asText();
        if (from.length() > 0 && to.length() > 0) {
            long currentTime = System.currentTimeMillis();
            long fromLong = "now".equals(from) ? currentTime : Long.parseLong(from);
            long toLong = "now".equals(to) ? currentTime : Long.parseLong(to);
            Iterator<JsonNode> iterator = range.elements();
            while (iterator.hasNext()) {
                iterator.next();
                iterator.remove();
            }
            result = new RequestParamsInfo(fromLong, toLong, objectMapper.writeValueAsString(jsonNode));
        }
    }
    return result;
}

From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java

/**
 * {@inheritDoc }//from  w ww.ja  va2s  . c  o  m
 */
@Override
protected InputStream normalizeLinks(final String entitySetName, final String entityKey, final InputStream is,
        final NavigationLinks links) throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode srcNode = (ObjectNode) mapper.readTree(is);

    if (links != null) {
        for (String linkTitle : links.getLinkNames()) {
            // normalize link
            srcNode.remove(linkTitle + JSON_NAVIGATION_BIND_SUFFIX);
            srcNode.set(linkTitle + JSON_NAVIGATION_SUFFIX,
                    new TextNode(String.format("%s(%s)/%s", entitySetName, entityKey, linkTitle)));
        }

        for (String linkTitle : links.getInlineNames()) {
            // normalize link if exist; declare a new one if missing
            srcNode.remove(linkTitle + JSON_NAVIGATION_BIND_SUFFIX);
            srcNode.set(linkTitle + JSON_NAVIGATION_SUFFIX,
                    new TextNode(String.format("%s(%s)/%s", entitySetName, entityKey, linkTitle)));

            // remove inline
            srcNode.remove(linkTitle);

            // remove from links
            links.removeLink(linkTitle);
        }
    }

    srcNode.set(JSON_EDITLINK_NAME,
            new TextNode(Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")"));

    return IOUtils.toInputStream(srcNode.toString());
}