Example usage for com.fasterxml.jackson.core JsonFactory JsonFactory

List of usage examples for com.fasterxml.jackson.core JsonFactory JsonFactory

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonFactory JsonFactory.

Prototype

public JsonFactory() 

Source Link

Document

Default constructor used to create factory instances.

Usage

From source file:org.apache.hadoop.gateway.util.JsonPathTest.java

@Test
public void testEvaluateArrays() throws IOException {
    String json;//from w  ww .  jav  a2s .co m
    JsonPath.Segment seg;
    List<JsonPath.Match> matches;
    JsonPath.Match match;
    JsonPath.Match parent;
    JsonNode root;
    JsonNode node;
    JsonPath.Expression expression;

    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);

    json = "[ \"outer-array\", { \"nested-field\" : \"nested-object\" }, [ \"nested-array\" ] ]";
    root = mapper.readTree(json);
    assertThat(root, notNullValue());

    expression = JsonPath.compile("$[0]");
    matches = expression.evaluate(root);
    assertThat(matches.size(), is(1));
    match = matches.get(0);
    assertThat(match.getIndex(), is(0));
    assertThat(match.getSegment().getIndex(), is(0));
    assertThat(match.getNode().asText(), is("outer-array"));

    expression = JsonPath.compile("$[1][nested-field]");
    matches = expression.evaluate(root);
    assertThat(matches.size(), is(1));
    match = matches.get(0);
    assertThat(match.getField(), is("nested-field"));
    assertThat(match.getNode().asText(), is("nested-object"));

    expression = JsonPath.compile("$[*][nested-field]");
    matches = expression.evaluate(root);
    assertThat(matches.size(), is(1));
    match = matches.get(0);
    assertThat(match.getField(), is("nested-field"));
    assertThat(match.getNode().asText(), is("nested-object"));

    json = "{ \"array\" : [ { \"name\" : \"value-1\" }, { \"name\" : \"value-2 \"}, { \"name\" : \"value-3\" } ] }";
    root = mapper.readTree(json);
    expression = JsonPath.compile("$.array.*.name");
    matches = expression.evaluate(root);
    assertThat(matches.size(), is(3));
    expression = JsonPath.compile("$.array[*].name");
    matches = expression.evaluate(root);
    assertThat(matches.size(), is(3));
    expression = JsonPath.compile("$.array[*][name]");
    matches = expression.evaluate(root);
    assertThat(matches.size(), is(3));

    expression = JsonPath.compile("$.array");
    matches = expression.evaluate(root);
    match = matches.get(0);
    expression = JsonPath.compile("$.*.name");
    matches = expression.evaluate(match.getNode());
    Assert.assertThat(matches.size(), is(3));
}

From source file:com.oneops.metrics.es.ElasticsearchReporter.java

/**
 * This index template is automatically applied to all indices which start with the index name
 * The index template simply configures the name not to be analyzed
 *//*from  w  w w  .java 2  s  .  c  o  m*/
private void checkForIndexTemplate() {
    try {
        HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD");
        if (connection == null) {
            LOGGER.error("Could not connect to any configured elasticsearch instances: {}",
                    Arrays.asList(hosts));
            return;
        }
        connection.disconnect();

        boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND;

        // nothing there, lets create it
        if (isTemplateMissing) {
            LOGGER.debug("No metrics template found in elasticsearch. Adding...");
            HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT");
            JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream());
            json.writeStartObject();
            json.writeStringField("template", index + "*");
            json.writeObjectFieldStart("mappings");

            json.writeObjectFieldStart("_default_");
            json.writeObjectFieldStart("_all");
            json.writeBooleanField("enabled", false);
            json.writeEndObject();
            json.writeObjectFieldStart("properties");
            json.writeObjectFieldStart("name");
            json.writeObjectField("type", "string");
            json.writeObjectField("index", "not_analyzed");
            json.writeEndObject();
            json.writeEndObject();
            json.writeEndObject();

            json.writeEndObject();
            json.writeEndObject();
            json.flush();

            putTemplateConnection.disconnect();
            if (putTemplateConnection.getResponseCode() != 200) {
                LOGGER.error(
                        "Error adding metrics template to elasticsearch: {}/{}"
                                + putTemplateConnection.getResponseCode(),
                        putTemplateConnection.getResponseMessage());
            }
        }
        checkedForIndexTemplate = true;
    } catch (IOException e) {
        LOGGER.error("Error when checking/adding metrics template to elasticsearch", e);
    }
}

From source file:io.github.swagger2markup.internal.component.PathOperationComponent.java

/**
 * Parse a JSON array//from  w  ww .j  a v a 2  s .  co  m
 *
 * @param raw Object containing a JSON string
 * @return JsonNode[contentType, example]
 * @throws RuntimeException when the given JSON string cannot be parsed
 */
private JsonNode parseExample(Object raw) throws RuntimeException {
    try {
        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        return mapper.readTree(Json.pretty(raw));
    } catch (Exception ex) {
        throw new RuntimeException("Failed to read example", ex);
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.SteeringTest.java

License:asdf

@Test
public void itUsesMultiLocationFormatResponseWithout302() throws Exception {
    final List<String> paths = new ArrayList<String>();
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=false");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=FALSE");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=FalsE");

    for (final String path : paths) {
        HttpGet httpGet = new HttpGet("http://localhost:" + routerHttpPort + path);
        httpGet.addHeader("Host", "tr.client-steering-test-1.thecdn.example.com");

        CloseableHttpResponse response = null;

        try {//from  w ww .j a va 2  s  . co  m
            response = httpClient.execute(httpGet);
            String location1 = ".client-steering-target-2.thecdn.example.com:8090" + path;
            String location2 = ".client-steering-target-1.thecdn.example.com:8090" + path;

            assertThat("Failed getting 200 for request " + httpGet.getFirstHeader("Host").getValue(),
                    response.getStatusLine().getStatusCode(), equalTo(200));

            HttpEntity entity = response.getEntity();
            ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());

            assertThat(entity.getContent(), not(nullValue()));

            JsonNode json = objectMapper.readTree(entity.getContent());

            assertThat(json.has("locations"), equalTo(true));
            assertThat(json.get("locations").size(), equalTo(2));
            assertThat(json.get("locations").get(0).asText(), endsWith(location1));
            assertThat(json.get("locations").get(1).asText(), endsWith(location2));
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
}

From source file:com.marklogic.client.functionaltest.TestBulkReadWriteWithJacksonParserHandle.java

@Test
public void testWriteMultiJSONFilesDefaultMetadata() throws Exception {
    String docId[] = { "/original.json", "/updated.json", "/constraint1.json" };
    String jsonFilename1 = "json-original.json";
    String jsonFilename2 = "json-updated.json";
    String jsonFilename3 = "constraint1.json";

    File jsonFile1 = new File("src/test/java/com/marklogic/client/functionaltest/data/" + jsonFilename1);
    File jsonFile2 = new File("src/test/java/com/marklogic/client/functionaltest/data/" + jsonFilename2);
    File jsonFile3 = new File("src/test/java/com/marklogic/client/functionaltest/data/" + jsonFilename3);

    JSONDocumentManager docMgr = client.newJSONDocumentManager();
    docMgr.setMetadataCategories(Metadata.ALL);
    DocumentWriteSet writeset = docMgr.newWriteSet();
    // put meta-data
    DocumentMetadataHandle mh = setMetadata();
    DocumentMetadataHandle mhRead = new DocumentMetadataHandle();

    JsonFactory f = new JsonFactory();

    JacksonParserHandle jacksonParserHandle1 = new JacksonParserHandle();
    JacksonParserHandle jacksonParserHandle2 = new JacksonParserHandle();
    JacksonParserHandle jacksonParserHandle3 = new JacksonParserHandle();

    jacksonParserHandle1.set(f.createParser(jsonFile1));
    jacksonParserHandle2.set(f.createParser(jsonFile2));
    jacksonParserHandle3.set(f.createParser(jsonFile3));

    writeset.addDefault(mh);//from  w  w  w .j av  a2 s  .  co m
    writeset.add(docId[0], jacksonParserHandle1);
    writeset.add(docId[1], jacksonParserHandle2);
    writeset.add(docId[2], jacksonParserHandle3);

    docMgr.write(writeset);

    DocumentPage page = docMgr.read(docId);

    while (page.hasNext()) {
        DocumentRecord rec = page.next();
        docMgr.readMetadata(rec.getUri(), mhRead);
        System.out.println(rec.getUri());
        validateMetadata(mhRead);
    }
    validateMetadata(mhRead);
    mhRead = null;
    // Close handles.
    jacksonParserHandle1.close();
    jacksonParserHandle2.close();
    jacksonParserHandle3.close();
}

From source file:com.cedarsoft.serialization.test.performance.XmlParserPerformance.java

public void benchJackson() {
    runBenchmark(new Runnable() {
        @Override// www.j  a  va2 s  .  c o m
        public void run() {
            try {
                JsonFactory jsonFactory = new JsonFactory();
                benchParse(jsonFactory, CONTENT_SAMPLE_GSON);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }, 4);
}

From source file:com.castlemock.web.mock.rest.converter.swagger.SwaggerRestDefinitionConverter.java

/**
 * The method generates a body based on the provided {@link Response} and a map of {@link Model}.
 * @param response The response which the body will be based on.
 * @param definitions The map of definitions that might be required to generate the response.
 * @return A HTTP response body based on the provided {@link Response}.
 * @since 1.13/*from   w ww  . jav a 2s  .  c o  m*/
 * @see {@link #generateJsonBody(String, Property, Map, JsonGenerator)}
 */
private String generateJsonBody(final Response response, final Map<String, Model> definitions) {
    final StringWriter writer = new StringWriter();
    final Property schema = response.getSchema();
    if (schema == null) {
        return writer.toString();
    }

    final JsonFactory factory = new JsonFactory();
    JsonGenerator generator = null;
    try {
        generator = factory.createGenerator(writer);
        generateJsonBody(null, schema, definitions, generator);
    } catch (IOException e) {
        LOGGER.error("Unable to generate a response body", e);
    } finally {
        if (generator != null) {
            try {
                generator.close();
            } catch (IOException e) {
                LOGGER.error("Unable to close the JsonGenerator", e);
            }
        }
    }

    return writer.toString();
}

From source file:org.broadleafcommerce.common.web.BroadleafRequestContext.java

/**
 * Resurrect the BroadleafRequestContext state based on a JSON representation.
 *
 * @param Json//from   w ww .ja  va2  s.c om
 * @param em
 * @return
 */
public static BroadleafRequestContext createLightWeightCloneFromJson(String Json, EntityManager em) {
    BroadleafRequestContext context = new BroadleafRequestContext();
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);
    TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
    };
    HashMap<String, String> json;
    try {
        json = mapper.readValue(Json, typeRef);
    } catch (IOException e) {
        throw ExceptionHelper.refineException(e);
    }
    if (!json.get("ignoreSite").equals("null")) {
        context.setIgnoreSite(Boolean.valueOf(json.get("ignoreSite")));
    }
    if (!json.get("sandBox").equals("null")) {
        context.setSandBox(em.find(SandBoxImpl.class, Long.parseLong(json.get("sandBox"))));
    }
    if (!json.get("nonPersistentSite").equals("null")) {
        context.setNonPersistentSite(em.find(SiteImpl.class, Long.parseLong(json.get("nonPersistentSite"))));
    }
    if (!json.get("enforceEnterpriseCollectionBehaviorState").equals("null")) {
        context.setEnforceEnterpriseCollectionBehaviorState(EnforceEnterpriseCollectionBehaviorState
                .valueOf(json.get("enforceEnterpriseCollectionBehaviorState")));
    }
    if (!json.get("admin").equals("null")) {
        context.setAdmin(Boolean.valueOf(json.get("admin")));
    }
    if (!json.get("adminUserId").equals("null")) {
        context.setAdminUserId(Long.parseLong(json.get("ignoreSite")));
    }
    if (!json.get("broadleafCurrency").equals("null")) {
        context.setBroadleafCurrency(em.find(BroadleafCurrencyImpl.class, json.get("broadleafCurrency")));
    }
    if (!json.get("currentCatalog").equals("null")) {
        context.setCurrentCatalog(em.find(CatalogImpl.class, Long.parseLong(json.get("currentCatalog"))));
    }
    if (!json.get("currentProfile").equals("null")) {
        context.setCurrentProfile(em.find(SiteImpl.class, Long.parseLong(json.get("currentProfile"))));
    }
    if (!json.get("deployBehavior").equals("null")) {
        context.setDeployBehavior(DeployBehavior.valueOf(json.get("deployBehavior")));
    }
    if (!json.get("deployState").equals("null")) {
        context.setDeployState(DeployState.valueOf(json.get("deployState")));
    }
    if (!json.get("internalIgnoreFilters").equals("null")) {
        context.setInternalIgnoreFilters(Boolean.valueOf(json.get("internalIgnoreFilters")));
    }
    if (!json.get("locale").equals("null")) {
        context.setLocale(em.find(LocaleImpl.class, json.get("locale")));
    }
    if (!json.get("validateProductionChangesState").equals("null")) {
        context.setValidateProductionChangesState(
                ValidateProductionChangesState.valueOf(json.get("validateProductionChangesState")));
    }
    if (!json.get("timeZone").equals("null")) {
        context.setTimeZone(TimeZone.getTimeZone(json.get("timeZone")));
    }

    return context;
}

From source file:com.cedarsoft.serialization.test.performance.XmlParserPerformance.java

public void benchJacksonMapper() {
    runBenchmark(new Runnable() {
        @Override/*from w ww . jav  a  2s.co m*/
        public void run() {
            try {
                JsonFactory jsonFactory = new JsonFactory();
                benchParseMapper(jsonFactory, CONTENT_SAMPLE_JACKSON);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }, 4);
}

From source file:org.apache.hadoop.gateway.util.JsonPathTest.java

@Test
public void testGlobMatching() throws IOException {
    String json;// w  w w  . j  a  va  2s. co  m
    JsonPath.Segment seg;
    List<JsonPath.Match> matches;
    JsonPath.Match parent;
    JsonNode root;
    JsonNode node;
    JsonPath.Expression expression;
    Set<String> matchValues;

    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);

    json = "{ \"field\" : \"value\" }";
    root = mapper.readTree(json);
    assertThat(root, notNullValue());

    expression = JsonPath.compile("$..field");
    matches = expression.evaluate(root);
    matchValues = new HashSet<String>();
    assertThat(matches.size(), is(1));
    for (JsonPath.Match match : matches) {
        matchValues.add(match.getNode().asText());
    }
    assertThat(matchValues, hasItem("value"));

    json = "{ \"field-1\" : { \"field-1-1\" : { \"field-1-1-1\" : \"value-1-1-1\", \"field\" : \"value-A\" }, \"field\" : \"value-B\"}, \"field-2\" : { \"field-2-1\" : { \"field-2-1-1\" : \"value-2-1-1\", \"field\" : \"value-C\" }, \"field\" : \"value-D\" }, \"field\" : \"value-E\" }";
    root = mapper.readTree(json);
    assertThat(root, notNullValue());

    expression = JsonPath.compile("$..field");
    matches = expression.evaluate(root);
    assertThat(matches.size(), is(5));
    matchValues = new HashSet<String>();
    for (JsonPath.Match match : matches) {
        matchValues.add(match.getNode().asText());
    }
    assertThat(matchValues, hasItem("value-A"));
    assertThat(matchValues, hasItem("value-B"));
    assertThat(matchValues, hasItem("value-C"));
    assertThat(matchValues, hasItem("value-D"));
    assertThat(matchValues, hasItem("value-E"));

}