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.forgerock.openig.migrate.Main.java

void execute(OutputStream stream) throws Exception {

    // Pre-parse the original files with JSON-Simple parser (which is more lenient than Jackson's one)
    File source = new File(sources.get(0));
    JSONParser parser = new JSONParser();
    JSONObject object = (JSONObject) parser.parse(new FileReader(source));

    // Then serialize again the structure (should clean up the JSON)
    StringWriter writer = new StringWriter();
    object.writeJSONString(writer);//from   w  w w . ja  va2 s . c  om

    // Load migration actions to apply in order
    List<Action> actions = loadActions();

    // Parse the cleaned-up content with Jackson this time
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode node = (ObjectNode) mapper.readTree(writer.toString());

    // Apply migration actions
    for (Action action : actions) {
        node = action.migrate(node);
    }

    // Serialize the migrated content on the given stream (with pretty printer)
    DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
    prettyPrinter.indentArraysWith(DefaultPrettyPrinter.Lf2SpacesIndenter.instance);
    mapper.writeTree(factory.createGenerator(stream).setPrettyPrinter(prettyPrinter), node);
}

From source file:org.springframework.social.linkedin.api.impl.LinkedInErrorHandler.java

private Map<String, Object> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {
    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    try {//from  w  w w.  j  a v a 2  s.  c  o  m
        return mapper.<Map<String, Object>>readValue(response.getBody(),
                new TypeReference<Map<String, Object>>() {
                });
    } catch (JsonParseException e) {
        return Collections.emptyMap();
    }
}

From source file:org.eclipse.winery.repository.resources.servicetemplates.boundarydefinitions.interfaces.ExportedOperationResource.java

@GET
@Produces(MediaType.APPLICATION_JSON)// ww  w  .  java2  s . c o m
public Response getJSON() {
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jg = jsonFactory.createGenerator(sw);
        jg.writeStartObject();
        String type = this.getType();
        jg.writeStringField("type", type);
        jg.writeStringField("ref", this.getReference());
        if ((type != null) && (!type.equals("Plan"))) {
            jg.writeStringField("interfacename", this.getInterfaceName());
            jg.writeStringField("operationname", this.getOperationName());
        }
        jg.writeEndObject();
        jg.close();
    } catch (Exception e) {
        ExportedOperationResource.LOGGER.error(e.getMessage(), e);
        throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity(e).build());
    }
    return Response.ok(sw.toString()).build();
}

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

License:asdf

@Before
public void before() throws Exception {
    closeableHttpClient = HttpClientBuilder.create().build();

    String resourcePath = "internal/api/1.3/steering.json";
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);

    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }/*from  w  ww . j  a va  2  s .c  om*/

    ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
    JsonNode steeringNode = objectMapper.readTree(inputStream).get("response").get(0);

    steeringDeliveryServiceId = steeringNode.get("deliveryService").asText();
    Iterator<JsonNode> iterator = steeringNode.get("targets").iterator();
    while (iterator.hasNext()) {
        JsonNode target = iterator.next();
        steeredDeliveryServices.add(target.get("deliveryService").asText());
    }

    resourcePath = "publish/CrConfig.json";
    inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }

    JsonNode jsonNode = objectMapper.readTree(inputStream);

    deliveryServiceId = null;

    Iterator<String> deliveryServices = jsonNode.get("deliveryServices").fieldNames();
    while (deliveryServices.hasNext() && deliveryServiceId == null) {
        String dsId = deliveryServices.next();

        JsonNode deliveryServiceNode = jsonNode.get("deliveryServices").get(dsId);

        if (deliveryServiceNode.has("steeredDeliveryServices")) {
            continue;
        }

        JsonNode dispersionNode = deliveryServiceNode.get("dispersion");

        if (dispersionNode == null || dispersionNode.get("limit").asInt() != 1
                && dispersionNode.get("shuffled").asText().equals("true")) {
            continue;
        }

        Iterator<JsonNode> matchsets = deliveryServiceNode.get("matchsets").iterator();
        while (matchsets.hasNext() && deliveryServiceId == null) {
            if ("HTTP".equals(matchsets.next().get("protocol").asText())) {
                deliveryServiceId = dsId;
            }
        }

        if (deliveryServiceId == null) {
            System.out.println("Skipping " + deliveryServiceId + " no http protocol matchset");
        }
    }

    assertThat(deliveryServiceId, not(nullValue()));
    assertThat(steeringDeliveryServiceId, not(nullValue()));
    assertThat(steeredDeliveryServices.isEmpty(), equalTo(false));

    resourcePath = "czf.json";
    inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }

    jsonNode = objectMapper.readTree(inputStream);

    JsonNode network = jsonNode.get("coverageZones").get(jsonNode.get("coverageZones").fieldNames().next())
            .get("network");

    for (int i = 0; i < network.size(); i++) {
        String cidrString = network.get(i).asText();
        CidrAddress cidrAddress = CidrAddress.fromString(cidrString);
        if (cidrAddress.getNetmaskLength() == 24) {
            byte[] hostBytes = cidrAddress.getHostBytes();
            ipAddressInCoverageZone = String.format("%d.%d.%d.123", hostBytes[0], hostBytes[1], hostBytes[2]);
            break;
        }
    }

    assertThat(ipAddressInCoverageZone.length(), greaterThan(0));
}

From source file:de.odysseus.staxon.json.stream.jackson.JacksonStreamSourceTest.java

@Test
public void testArray1() throws IOException {
    StringReader reader = new StringReader("{\"alice\":[\"bob\"]}");
    JacksonStreamSource source = new JacksonStreamSource(new JsonFactory().createParser(reader));

    Assert.assertEquals(JsonStreamToken.START_OBJECT, source.peek());
    source.startObject();/*w w w  .  j a  va  2 s  . c o m*/

    Assert.assertEquals(JsonStreamToken.NAME, source.peek());
    Assert.assertEquals("alice", source.name());

    Assert.assertEquals(JsonStreamToken.START_ARRAY, source.peek());
    source.startArray();

    Assert.assertEquals(JsonStreamToken.VALUE, source.peek());
    Assert.assertEquals("bob", source.value().text);

    Assert.assertEquals(JsonStreamToken.END_ARRAY, source.peek());
    source.endArray();

    Assert.assertEquals(JsonStreamToken.END_OBJECT, source.peek());
    source.endObject();

    Assert.assertEquals(JsonStreamToken.NONE, source.peek());
    source.close();
}

From source file:com.quinsoft.zeidon.utils.WriteOisToJsonStreamNoIncrementals.java

@Override
public void writeToStream(SerializeOi options, Writer writer) {
    this.viewList = options.getViewList();
    if (options.getFlags() == null)
        flags = EnumSet.noneOf(WriteOiFlags.class);
    else//from   w ww  . j a  v a 2  s  .  co m
        flags = options.getFlags();
    if (flags.contains(WriteOiFlags.INCREMENTAL))
        throw new ZeidonException("This JSON stream writer not intended for writing incremental.");

    this.options = options;

    JsonFactory jsonF = new JsonFactory();
    try {
        jg = jsonF.createGenerator(writer);
        jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier
        jg.writeStartObject();

        jg.writeStringField("version", VERSION);

        for (View view : viewList)
            writeOi(view);

        jg.writeEndObject();
        jg.close();
    } catch (Exception e) {
        throw ZeidonException.wrapException(e);
    }
}

From source file:org.jberet.support.io.NoMappingJsonFactoryObjectFactory.java

/**
 * Gets an instance of {@code com.fasterxml.jackson.core.JsonFactory} based on the resource configuration in the
 * application server. The parameter {@code environment} contains JsonFactory configuration properties, and accepts
 * the following properties:/*from w  w  w.  j av a2 s.  c o m*/
 * <ul>
 * <li>jsonFactoryFeatures: JsonFactory features as defined in com.fasterxml.jackson.core.JsonFactory.Feature
 * <li>inputDecorator: fully-qualified name of a class that extends {@code com.fasterxml.jackson.core.io.InputDecorator}
 * <li>outputDecorator: fully-qualified name of a class that extends {@code com.fasterxml.jackson.core.io.OutputDecorator}
 * </ul>
 *
 * @param obj         the JNDI name of {@code com.fasterxml.jackson.core.JsonFactory} resource
 * @param name        always null
 * @param nameCtx     always null
 * @param environment a {@code Hashtable} of configuration properties
 * @return an instance of {@code com.fasterxml.jackson.core.JsonFactory}
 * @throws Exception any exception occurred
 */
@Override
public Object getObjectInstance(final Object obj, final Name name, final Context nameCtx,
        final Hashtable<?, ?> environment) throws Exception {
    JsonFactory jsonFactory = jsonFactoryCached;
    if (jsonFactory == null) {
        synchronized (this) {
            jsonFactory = jsonFactoryCached;
            if (jsonFactory == null) {
                jsonFactoryCached = jsonFactory = new JsonFactory();
            }

            final Object jsonFactoryFeatures = environment.get("jsonFactoryFeatures");
            if (jsonFactoryFeatures != null) {
                configureJsonFactoryFeatures(jsonFactory, (String) jsonFactoryFeatures);
            }
            configureInputDecoratorAndOutputDecorator(jsonFactory, environment);
        }
    }
    return jsonFactory;
}

From source file:monasca.log.api.app.validation.LogApplicationTypeValidationTest.java

private String getMessage(String json) throws JsonParseException, IOException {
    JsonFactory factory = new JsonFactory();
    JsonParser jp = factory.createParser(json);
    jp.nextToken();//w  ww  .j a va  2 s .c om
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldname = jp.getCurrentName();
        jp.nextToken();
        if ("message".equals(fieldname)) {

            return jp.getText();
        }
    }
    jp.close();
    return null;
}