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:com.codealot.url2text.Response.java

/**
 * Renders this object as JSON.//from   www. j a v  a2  s . c  o  m
 * <p>
 * Beware. This method consumes the internal Reader, creating a buffer of
 * unlimited size.
 * 
 * @return
 * @throws Url2TextException
 */
public String toJson() throws Url2TextException {

    final JsonFactory jFactory = new JsonFactory();
    final ByteArrayOutputStream destination = new ByteArrayOutputStream();

    try (final JsonGenerator jsonGenerator = jFactory.createGenerator(destination);) {
        jsonGenerator.writeStartObject();

        // transaction metadata
        jsonGenerator.writeFieldName(HDR_TRANSACTION_METADATA);
        jsonGenerator.writeStartObject();

        jsonGenerator.writeStringField(HDR_REQUEST_PAGE, this.requestPage);
        jsonGenerator.writeStringField(HDR_LANDING_PAGE, this.landingPage);
        jsonGenerator.writeNumberField(HDR_STATUS, this.status);
        jsonGenerator.writeStringField(HDR_STATUS_MESSAGE, this.statusMessage);
        jsonGenerator.writeStringField(HDR_FETCH_DATE,
                DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(this.fetchDate));
        jsonGenerator.writeNumberField(HDR_FETCH_DURATION, this.fetchDuration);
        jsonGenerator.writeStringField(HDR_CONTENT_TYPE, this.contentType);
        jsonGenerator.writeStringField(HDR_CONTENT_CHARSET, this.contentCharset);
        jsonGenerator.writeNumberField(HDR_CONTENT_LENGTH, this.contentLength);
        jsonGenerator.writeStringField(HDR_ETAG, this.etag);
        jsonGenerator.writeStringField(HDR_LAST_MODIFIED, this.lastModified);
        jsonGenerator.writeNumberField(HDR_CONVERSION_DURATION, this.conversionDuration);

        jsonGenerator.writeEndObject();

        // response headers
        if (!this.responseHeaders.isEmpty()) {
            outputNameAndValueArray(jsonGenerator, HDR_RESPONSE_HEADERS, this.responseHeaders);
        }

        // content metadata
        if (!this.contentMetadata.isEmpty()) {
            outputNameAndValueArray(jsonGenerator, HDR_CONTENT_METADATA, this.contentMetadata);
        }

        // text
        jsonGenerator.writeStringField(HDR_CONVERTED_TEXT, this.getText());
        jsonGenerator.writeEndObject();
        jsonGenerator.close();

        String result = destination.toString(UTF_8);
        return result;
    } catch (IOException e) {
        throw new Url2TextException("Error emitting JSON", e);
    }
}

From source file:squash.booking.lambdas.core.BackupManager.java

@Override
public final ImmutablePair<List<Booking>, List<BookingRule>> backupAllBookingsAndBookingRules()
        throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The backup manager has not been initialised");
    }/*from  w  w w. j  av a2s.c  om*/

    // Encode bookings and booking rules as JSON
    JsonNodeFactory factory = new JsonNodeFactory(false);
    // Create a json factory to write the treenode as json.
    JsonFactory jsonFactory = new JsonFactory();
    ObjectNode rootNode = factory.objectNode();

    ArrayNode bookingsNode = rootNode.putArray("bookings");
    List<Booking> bookings = bookingManager.getAllBookings(false);
    for (Booking booking : bookings) {
        bookingsNode.add((JsonNode) (mapper.valueToTree(booking)));
    }

    ArrayNode bookingRulesNode = rootNode.putArray("bookingRules");
    List<BookingRule> bookingRules = ruleManager.getRules(false);
    for (BookingRule bookingRule : bookingRules) {
        bookingRulesNode.add((JsonNode) (mapper.valueToTree(bookingRule)));
    }

    // Add this, as will be needed for restore in most common case.
    rootNode.put("clearBeforeRestore", true);

    ByteArrayOutputStream backupDataStream = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(backupDataStream);
    try (JsonGenerator generator = jsonFactory.createGenerator(printStream)) {
        mapper.writeTree(generator, rootNode);
    }
    String backupString = backupDataStream.toString(StandardCharsets.UTF_8.name());

    logger.log("Backing up all bookings and booking rules to S3 bucket");
    IS3TransferManager transferManager = getS3TransferManager();
    byte[] backupAsBytes = backupString.getBytes(StandardCharsets.UTF_8);
    ByteArrayInputStream backupAsStream = new ByteArrayInputStream(backupAsBytes);
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(backupAsBytes.length);
    PutObjectRequest putObjectRequest = new PutObjectRequest(databaseBackupBucketName,
            "AllBookingsAndBookingRules", backupAsStream, metadata);
    TransferUtils.waitForS3Transfer(transferManager.upload(putObjectRequest), logger);
    logger.log("Backed up all bookings and booking rules to S3 bucket: " + backupString);

    // Backup to the SNS topic
    logger.log("Backing up all bookings and booking rules to SNS topic: " + adminSnsTopicArn);
    getSNSClient().publish(adminSnsTopicArn, backupString, "Sqawsh all-bookings and booking rules backup");

    return new ImmutablePair<>(bookings, bookingRules);
}

From source file:org.springframework.cloud.dataflow.shell.command.HttpCommands.java

private String prettyPrintIfJson(String maybeJson) {
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);
    TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
    };/*from  w  w  w . j a  va2s  .  c om*/
    try {
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readValue(maybeJson, typeRef));
    } catch (IOException e) {
        // Not JSON? Return unchanged
        return maybeJson;
    }
}

From source file:net.floodlightcontroller.configuration.ConfigurationManager.java

/**
 * Writes a configuration file based on information gathered from
 * the various configuration listeners.// ww  w  . j  a  v a2  s.  c  o  m
 * 
 * @param file An optional configuration file name.
 */
private void writeJsonToFile(String fileName) throws IOException {
    String configFile = (fileName != null) ? fileName : this.fileName;
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode rootNode = createJsonRootNode();
    JsonFactory f = new JsonFactory();
    JsonGenerator g = null;

    try {
        g = f.createJsonGenerator(new File(configFile), JsonEncoding.UTF8);
        g.useDefaultPrettyPrinter();
        mapper.writeTree(g, rootNode);
    } catch (IOException e) {
        if (logger.isErrorEnabled()) {
            logger.error("Could not write the JSON configuration file.");
        }
        throw new IOException("Could not write the JSON configuration file");
    }
}

From source file:org.kitesdk.apps.scheduled.Schedule.java

public String toString() {

    StringWriter writer = new StringWriter();

    try {//  w w w  .  j a  v a2  s. c  o  m

        JsonGenerator gen = new JsonFactory().createGenerator(writer);
        gen.setCodec(new ObjectMapper());
        gen.writeTree(toJson());

        gen.close();
    } catch (IOException e) {
        // An IOException should not be possible against a local buffer.
        throw new AssertionError(e);
    }

    return writer.toString();
}

From source file:org.graylog2.gelfclient.encoder.GelfMessageJsonEncoderTest.java

@Test
public void testNullLevel() throws Exception {
    final EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageJsonEncoder());
    final GelfMessage message = new GelfMessageBuilder("test").build();

    message.setLevel(null);//from w ww. j a v a2s. c o  m

    assertTrue(channel.writeOutbound(message));
    assertTrue(channel.finish());

    final ByteBuf byteBuf = (ByteBuf) channel.readOutbound();
    final byte[] bytes = new byte[byteBuf.readableBytes()];
    byteBuf.getBytes(0, bytes).release();
    final JsonFactory json = new JsonFactory();
    final JsonParser parser = json.createParser(bytes);

    String version = null;
    Number timestamp = null;
    String host = null;
    String short_message = null;
    String full_message = null;
    Number level = null;

    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String key = parser.getCurrentName();

        if (key == null) {
            continue;
        }

        parser.nextToken();

        switch (key) {
        case "version":
            version = parser.getText();
            break;
        case "timestamp":
            timestamp = parser.getNumberValue();
            break;
        case "host":
            host = parser.getText();
            break;
        case "short_message":
            short_message = parser.getText();
            break;
        case "full_message":
            full_message = parser.getText();
            break;
        case "level":
            level = parser.getNumberValue();
            break;
        default:
            throw new Exception("Found unexpected field in JSON payload: " + key);
        }
    }

    assertEquals(message.getVersion().toString(), version);
    assertEquals(message.getTimestamp(), timestamp);
    assertEquals(message.getHost(), host);
    assertEquals(message.getMessage(), short_message);
    assertNull(full_message);
    assertNull(level);
}

From source file:com.apteligent.ApteligentJavaClient.java

/**
 * @param appID appId (string, optional): The app to retrieve data about,
 * @param metricType The metric to retrieve
 * @param duration can only be 1440 (24 hours) or 43200 (1 month)
 * @param groupBy TODO FILL IN THIS COMMENT
 * @return//from  w ww  .  ja va  2s  .c  o  m
 */
public CrashSummary getErrorPie(String appID, CrashSummary.MetricType metricType, int duration,
        Pie.GroupBy groupBy) {

    String params = "{ \"params\": " + "{\"duration\": " + duration + "," + " \"graph\": \""
            + metricType.toString() + "\"," + " \"appId\": \"" + appID + "\"" + ",\"groupBy\": \""
            + groupBy.toString() + "\"}" + "}";

    CrashSummary crashSummary = null;
    try {
        HttpsURLConnection conn = sendPostRequest(API_ERROR_PIE, params);
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jp = jsonFactory.createParser(conn.getInputStream());
        ObjectMapper mapper = getObjectMapper();
        TreeNode node = mapper.readTree(jp);
        crashSummary = mapper.treeToValue(node.get("data"), CrashSummary.class);
        if (crashSummary != null) {
            crashSummary.setParams(appID, metricType, duration);
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
    return crashSummary;
}

From source file:com.palominolabs.crm.sf.rest.HttpApiClientTest.java

private static String reformatJson(@Nullable String input) throws IOException {
    checkNotNull(input);/*from  w ww  .j  a v  a2s  .  c  o  m*/

    JsonFactory jsonFactory = new JsonFactory();

    JsonParser parser = jsonFactory.createParser(input);
    StringWriter writer = new StringWriter();
    JsonGenerator generator = jsonFactory.createGenerator(writer);
    generator.useDefaultPrettyPrinter();

    while (parser.nextToken() != null) {
        generator.copyCurrentEvent(parser);
    }

    generator.close();

    return writer.toString();
}

From source file:com.teamlazerbeez.crm.sf.rest.HttpApiClientTest.java

private static String reformatJson(String input) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();

    JsonParser parser = jsonFactory.createJsonParser(input);
    StringWriter writer = new StringWriter();
    JsonGenerator generator = jsonFactory.createJsonGenerator(writer);
    generator.useDefaultPrettyPrinter();

    while (parser.nextToken() != null) {
        generator.copyCurrentEvent(parser);
    }/*from w  ww. j a  va 2  s  .  c  o  m*/

    generator.close();

    return writer.toString();
}

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

@Test
public void testLiteralValues() throws IOException {
    StringReader reader = new StringReader("[true,false,null]");
    JacksonStreamSource source = new JacksonStreamSource(new JsonFactory().createParser(reader));
    JsonStreamSource.Value value = null;

    Assert.assertEquals(JsonStreamToken.START_ARRAY, source.peek());
    source.startArray();//from   www. j av a 2s .  c om

    Assert.assertEquals(JsonStreamToken.VALUE, source.peek());
    value = source.value();
    Assert.assertEquals("true", value.text);
    Assert.assertEquals(Boolean.TRUE, value.data);

    Assert.assertEquals(JsonStreamToken.VALUE, source.peek());
    value = source.value();
    Assert.assertEquals("false", value.text);
    Assert.assertEquals(Boolean.FALSE, value.data);

    Assert.assertEquals(JsonStreamToken.VALUE, source.peek());
    value = source.value();
    Assert.assertNull(value.text);
    Assert.assertNull(value.data);

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

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