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 testEvaluateObjects() throws IOException {
    String json;//from  w w  w  . j a v  a2s.  com
    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 = "{ \"field\" : \"value\" }";
    root = mapper.readTree(json);
    assertThat(root, notNullValue());

    expression = JsonPath.compile("$.field");
    matches = expression.evaluate(root);
    assertThat(matches, notNullValue());
    assertThat(matches.size(), is(1));
    match = matches.get(0);
    assertThat(matches, notNullValue());
    seg = matches.get(0).getSegment();
    assertThat(seg, notNullValue());
    assertThat(seg.getType(), is(JsonPath.Segment.Type.FIELD));
    assertThat(seg.getField(), is("field"));
    node = match.getNode();
    assertThat(node, notNullValue());
    assertThat(node.getNodeType(), is(JsonNodeType.STRING));
    assertThat(node.asText(), is("value"));
    parent = match.getParent();
    assertThat(parent, notNullValue());
    assertThat(parent.getNode(), sameInstance(root));
    assertThat(parent.getParent(), nullValue());
    assertThat(parent.getSegment().getType(), is(JsonPath.Segment.Type.ROOT));

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

    expression = JsonPath.compile("$.outer.inner");
    matches = expression.evaluate(root);
    match = matches.get(0);
    assertThat(match, notNullValue());
    assertThat(match.getField(), is("inner"));
    seg = match.getSegment();
    assertThat(seg, notNullValue());
    assertThat(seg.getField(), is("inner"));
    assertThat(seg.getType(), is(JsonPath.Segment.Type.FIELD));

    node = match.getNode();
    assertThat(node, notNullValue());
    assertThat(node.asText(), is("value"));

    parent = match.getParent();
    assertThat(parent, notNullValue());
    assertThat(parent.getField(), is("outer"));
    assertThat(parent.getNode().getNodeType(), is(JsonNodeType.OBJECT));

    parent = parent.getParent();
    assertThat(parent.getSegment().getType(), is(JsonPath.Segment.Type.ROOT));
    assertThat(parent.getNode().getNodeType(), is(JsonNodeType.OBJECT));

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

    expression = JsonPath.compile("$.*.inner");
    matches = expression.evaluate(root);
    assertThat(matches.size(), is(1));
    match = matches.get(0);
    assertThat(match.getField(), is("inner"));
    assertThat(match.getNode().asText(), is("value"));
}

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

/**
 * Returns JSON-encoded booking data for a specified date.
 * //from   w  w w .  j a  v  a 2 s  . c  o m
 * <p>This is not private only so that it can be unit-tested.
 * 
 * @param date the date in YYYY-MM-DD format.
 * @param validDates the dates for which bookings can be made, in YYYY-MM-DD format.
 * @param bookings the bookings for the specified date.
 * @throws Exception 
 */
protected String createCachedBookingData(String date, List<String> validDates, List<Booking> bookings)
        throws Exception {

    ImmutablePair<LifecycleState, Optional<String>> lifecycleState = lifecycleManager.getLifecycleState();

    // N.B. we assume that the date is known to be a valid date
    logger.log("About to create cached booking data");
    logger.log("Lifecycle state is: " + lifecycleState.left.name());
    if (lifecycleState.left.equals(LifecycleState.RETIRED)) {
        logger.log("Lifecycle state forwarding url is: " + lifecycleState.right.get());
    }

    // Encode bookings as JSON
    // Create the node factory that gives us nodes.
    JsonNodeFactory factory = new JsonNodeFactory(false);
    // Create a json factory to write the treenode as json.
    JsonFactory jsonFactory = new JsonFactory();
    ObjectNode rootNode = factory.objectNode();

    rootNode.put("date", date);
    ArrayNode validDatesNode = rootNode.putArray("validdates");
    for (int i = 0; i < validDates.size(); i++) {
        validDatesNode.add(validDates.get(i));
    }
    ArrayNode bookingsNode = rootNode.putArray("bookings");
    for (int i = 0; i < bookings.size(); i++) {
        Booking booking = bookings.get(i);
        ObjectNode bookingNode = factory.objectNode();
        bookingNode.put("court", booking.getCourt());
        bookingNode.put("courtSpan", booking.getCourtSpan());
        bookingNode.put("slot", booking.getSlot());
        bookingNode.put("slotSpan", booking.getSlotSpan());
        bookingNode.put("name", booking.getName());
        bookingsNode.add(bookingNode);
    }
    // This gives the Angularjs app access to the lifecycle state.
    ObjectNode lifecycleStateNode = rootNode.putObject("lifecycleState");
    lifecycleStateNode.put("state", lifecycleState.left.name());
    lifecycleStateNode.put("url", lifecycleState.right.isPresent() ? lifecycleState.right.get() : "");

    ByteArrayOutputStream bookingDataStream = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(bookingDataStream);
    try (JsonGenerator generator = jsonFactory.createGenerator(printStream)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeTree(generator, rootNode);
    }
    String bookingData = bookingDataStream.toString(StandardCharsets.UTF_8.name());
    logger.log("Created cached booking data: " + bookingData);

    return bookingData;
}

From source file:com.tage.calcite.adapter.druid.DruidQuery.java

/** Generates a JSON string to query metadata about a data source. */
static String metadataQuery(String dataSourceName, List<String> intervals) {
    final StringWriter sw = new StringWriter();
    final JsonFactory factory = new JsonFactory();
    try {/*from   ww  w .  j a v a2  s.c om*/
        final JsonGenerator generator = factory.createGenerator(sw);
        generator.writeStartObject();
        generator.writeStringField("queryType", "segmentMetadata");
        generator.writeStringField("dataSource", dataSourceName);
        generator.writeBooleanField("merge", true);
        generator.writeArrayFieldStart("analysisTypes");
        generator.writeString("aggregators");
        generator.writeEndArray();
        writeFieldIf(generator, "intervals", intervals);
        generator.writeEndObject();
        generator.close();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    return sw.toString();
}

From source file:com.basho.riak.client.raw.http.ConversionUtil.java

/**
 * Converts a {@link BucketProperties} to a JSON string
 * @param bp//from  w  w  w.ja  v  a  2  s. c  o  m
 * @return a String of JSON that is acceptable to {@link RiakBucketInfo}
 * @throws IOException
 * TODO: move this to a custom serializer?
 */
private static String toJSON(BucketProperties bp) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JsonGenerator jg = new JsonFactory().createJsonGenerator(out, JsonEncoding.UTF8);

    jg.writeStartObject();
    writeIfNotNull(jg, bp.getAllowSiblings(), Constants.FL_SCHEMA_ALLOW_MULT);
    writeIfNotNull(jg, bp.getNVal(), Constants.FL_SCHEMA_NVAL);
    writeIfNotNull(jg, bp.getLastWriteWins(), Constants.FL_SCHEMA_LAST_WRITE_WINS);
    writeIfNotNull(jg, bp.getBackend(), Constants.FL_SCHEMA_BACKEND);
    writeIfNotNull(jg, bp.getSmallVClock(), Constants.FL_SCHEMA_SMALL_VCLOCK);
    writeIfNotNull(jg, bp.getBigVClock(), Constants.FL_SCHEMA_BIG_VCLOCK);
    writeIfNotNull(jg, bp.getYoungVClock(), Constants.FL_SCHEMA_YOUNG_VCLOCK);
    writeIfNotNull(jg, bp.getOldVClock(), Constants.FL_SCHEMA_OLD_VCLOCK);
    writeIfNotNull(jg, bp.getR(), Constants.FL_SCHEMA_R);
    writeIfNotNull(jg, bp.getRW(), Constants.FL_SCHEMA_RW);
    writeIfNotNull(jg, bp.getW(), Constants.FL_SCHEMA_W);
    writeIfNotNull(jg, bp.getDW(), Constants.FL_SCHEMA_DW);
    writeIfNotNull(jg, bp.getPR(), Constants.FL_SCHEMA_PR);
    writeIfNotNull(jg, bp.getPW(), Constants.FL_SCHEMA_PW);
    writeIfNotNull(jg, bp.getBasicQuorum(), Constants.FL_SCHEMA_BASIC_QUORUM);
    writeIfNotNull(jg, bp.getNotFoundOK(), Constants.FL_SCHEMA_NOT_FOUND_OK);
    writeIfNotNull(jg, bp.getChashKeyFunction(), Constants.FL_SCHEMA_CHASHFUN);
    writeIfNotNull(jg, bp.getLinkWalkFunction(), Constants.FL_SCHEMA_LINKFUN);
    writeIfNotNull(jg, bp.getPostcommitHooks(), Constants.FL_SCHEMA_POSTCOMMIT);
    writeIfNotNull(jg, bp.getPrecommitHooks(), Constants.FL_SCHEMA_PRECOMMIT);
    writeIfNotNull(jg, bp.getSearch(), Constants.FL_SCHEMA_SEARCH);

    jg.writeEndObject();

    jg.flush();
    return CharsetUtils.asUTF8String(out.toByteArray());
}

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

License:asdf

@Test
public void itUsesMultiLocationFormatResponse() throws Exception {
    final List<String> paths = new ArrayList<String>();
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=true");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=TRUE");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=TruE");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=T");

    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 ww  w. j a v  a 2  s .  c  o  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 302 for request " + httpGet.getFirstHeader("Host").getValue(),
                    response.getStatusLine().getStatusCode(), equalTo(302));
            assertThat(response.getFirstHeader("Location").getValue(), endsWith(location1));

            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(),
                    equalTo(response.getFirstHeader("Location").getValue()));
            assertThat(json.get("locations").get(1).asText(), endsWith(location2));
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
}

From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java

protected boolean Sync(String service, String scope, String params) {
    final Date start = new Date();
    boolean hasError = false;
    if (params == null)
        params = "";
    final SQLiteDatabase db = mDB.getWritableDatabase();
    final ArrayList<TableInfo> notifyTableInfo = new ArrayList<TableInfo>();

    final String download = String.format(contentHelper.DOWNLOAD_SERVICE_URI, service, scope, params);
    final String upload = String.format(contentHelper.UPLOAD_SERVICE_URI, service, scope, params);
    final String scopeServerBlob = String.format("%s.%s.%s", service, scope, _.serverBlob);
    String serverBlob = null;/*from  w w  w.j  a  v a  2  s.  c  o  m*/
    Cursor cur = db.query(BlobsTable.NAME, new String[] { BlobsTable.C_VALUE }, BlobsTable.C_NAME + "=?",
            new String[] { scopeServerBlob }, null, null, null);
    final String originalBlob;
    if (cur.moveToFirst()) {
        originalBlob = serverBlob = cur.getString(0);
    } else {
        originalBlob = null;
    }
    cur.close();
    db.beginTransaction();
    try {
        boolean nochanges = false;
        if (serverBlob != null) {
            nochanges = !contentHelper.hasDirtTable(db, scope);
        }
        boolean resolve = false;
        final Metadata meta = new Metadata();
        final HashMap<String, Object> vals = new HashMap<String, Object>();
        final ContentValues cv = new ContentValues(2);
        JsonFactory jsonFactory = new JsonFactory();
        JsonToken current = null;
        String name = null;
        boolean moreChanges = false;
        boolean forceMoreChanges = false;
        do {
            final int requestMethod;
            final String serviceRequestUrl;
            final ContentProducer contentProducer;

            if (serverBlob != null) {
                requestMethod = HTTP_POST;
                if (nochanges) {
                    serviceRequestUrl = download;
                } else {
                    serviceRequestUrl = upload;
                    forceMoreChanges = true;
                }
                contentProducer = new SyncContentProducer(jsonFactory, db, scope, serverBlob, !nochanges,
                        notifyTableInfo, contentHelper);
                nochanges = true;
            } else {
                requestMethod = HTTP_GET;
                serviceRequestUrl = download;
                contentProducer = null;

            }
            if (moreChanges) {
                db.beginTransaction();
            }

            Result result = executeRequest(requestMethod, serviceRequestUrl, contentProducer);
            if (result.getStatus() == HttpStatus.SC_OK) {
                final JsonParser jp = jsonFactory.createParser(result.getInputStream());

                jp.nextToken(); // skip ("START_OBJECT(d) expected");
                jp.nextToken(); // skip ("FIELD_NAME(d) expected");
                if (jp.nextToken() != JsonToken.START_OBJECT)
                    throw new Exception("START_OBJECT(d - object) expected");
                while (jp.nextToken() != JsonToken.END_OBJECT) {
                    name = jp.getCurrentName();
                    if (_.__sync.equals(name)) {
                        current = jp.nextToken();
                        while (jp.nextToken() != JsonToken.END_OBJECT) {
                            name = jp.getCurrentName();
                            current = jp.nextToken();
                            if (_.serverBlob.equals(name)) {
                                serverBlob = jp.getText();
                            } else if (_.moreChangesAvailable.equals(name)) {
                                moreChanges = jp.getBooleanValue() || forceMoreChanges;
                                forceMoreChanges = false;
                            } else if (_.resolveConflicts.equals(name)) {
                                resolve = jp.getBooleanValue();
                            }
                        }
                    } else if (_.results.equals(name)) {
                        if (jp.nextToken() != JsonToken.START_ARRAY)
                            throw new Exception("START_ARRAY(results) expected");
                        while (jp.nextToken() != JsonToken.END_ARRAY) {
                            meta.isDeleted = false;
                            meta.tempId = null;
                            vals.clear();
                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                name = jp.getCurrentName();
                                current = jp.nextToken();
                                if (current == JsonToken.VALUE_STRING) {
                                    vals.put(name, jp.getText());
                                } else if (current == JsonToken.VALUE_NUMBER_INT) {
                                    vals.put(name, jp.getLongValue());
                                } else if (current == JsonToken.VALUE_NUMBER_FLOAT) {
                                    vals.put(name, jp.getDoubleValue());
                                } else if (current == JsonToken.VALUE_FALSE) {
                                    vals.put(name, 0L);
                                } else if (current == JsonToken.VALUE_TRUE) {
                                    vals.put(name, 1L);
                                } else if (current == JsonToken.VALUE_NULL) {
                                    vals.put(name, null);
                                } else {
                                    if (current == JsonToken.START_OBJECT) {
                                        if (_.__metadata.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.uri.equals(name)) {
                                                    meta.uri = jp.getText();
                                                } else if (_.type.equals(name)) {
                                                    meta.type = jp.getText();
                                                } else if (_.isDeleted.equals(name)) {
                                                    meta.isDeleted = jp.getBooleanValue();
                                                } else if (_.tempId.equals(name)) {
                                                    meta.tempId = jp.getText();
                                                }
                                            }
                                        } else if (_.__syncConflict.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.isResolved.equals(name)) {
                                                } else if (_.conflictResolution.equals(name)) {
                                                } else if (_.conflictingChange.equals(name)) {
                                                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                        name = jp.getCurrentName();
                                                        current = jp.nextToken();
                                                        if (current == JsonToken.START_OBJECT) {
                                                            if (_.__metadata.equals(name)) {
                                                                while (jp.nextToken() != JsonToken.END_OBJECT) {

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            // resolve conf

                                        } else if (_.__syncError.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                            }
                                        }
                                    }
                                }
                            }
                            TableInfo tab = contentHelper.getTableFromType(meta.type);
                            if (meta.isDeleted) {
                                tab.DeleteWithUri(meta.uri, db);
                            } else {
                                tab.SyncJSON(vals, meta, db);
                            }
                            if (!notifyTableInfo.contains(tab))
                                notifyTableInfo.add(tab);
                        }
                    }
                }
                jp.close();
                if (!hasError) {
                    cv.clear();
                    cv.put(BlobsTable.C_NAME, scopeServerBlob);
                    cv.put(BlobsTable.C_VALUE, serverBlob);
                    cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
                    cv.put(BlobsTable.C_STATE, 0);
                    db.replace(BlobsTable.NAME, null, cv);
                    db.setTransactionSuccessful();
                    db.endTransaction();
                    if (DEBUG) {
                        Log.d(TAG, "CP-Sync: commit changes");
                    }
                    final ContentResolver cr = getContext().getContentResolver();
                    for (TableInfo t : notifyTableInfo) {
                        final Uri nu = contentHelper.getDirUri(t.name, false);
                        cr.notifyChange(nu, null, false);
                        // false - do not force sync cause we are in sync
                        if (DEBUG) {
                            Log.d(TAG, "CP-Sync: notifyChange table: " + t.name + ", uri: " + nu);
                        }

                        for (String n : t.notifyUris) {
                            cr.notifyChange(Uri.parse(n), null, false);
                            if (DEBUG) {
                                Log.d(TAG, "+uri: " + n);
                            }
                        }
                    }
                    notifyTableInfo.clear();
                }
            } else {
                if (DEBUG) {
                    Log.e(TAG, "Server error in fetching remote contacts: " + result.getStatus());
                }
                hasError = true;
                break;
            }
        } while (moreChanges);
    } catch (final ConnectTimeoutException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ConnectTimeoutException", e);
        }
    } catch (final IOException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    } catch (final ParseException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    } catch (final Exception e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    }
    if (hasError) {
        db.endTransaction();
        ContentValues cv = new ContentValues();
        cv.put(BlobsTable.C_NAME, scopeServerBlob);
        cv.put(BlobsTable.C_VALUE, originalBlob);
        cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
        cv.put(BlobsTable.C_STATE, -1);
        db.replace(BlobsTable.NAME, null, cv);
    }
    /*-if (!hasError) {
    final ContentValues cv = new ContentValues(2);
     cv.put(BlobsTable.C_NAME, scopeServerBlob);
     cv.put(BlobsTable.C_VALUE, serverBlob);
     db.replace(BlobsTable.NAME, null, cv);
     db.setTransactionSuccessful();
    }
    db.endTransaction();
    if (!hasError) {
     for (String t : notifyTableInfo) {
    getContext().getContentResolver().notifyChange(getDirUri(t),
          null);
     }
    }*/
    if (DEBUG) {
        Helpers.LogInfo(start);
    }
    return !hasError;
}

From source file:org.kie.workbench.common.stunner.bpmn.backend.legacy.Bpmn2JsonUnmarshaller.java

public Bpmn2Resource unmarshall(String json, String preProcessingData) throws IOException {
    return unmarshall(new JsonFactory().createJsonParser(json), preProcessingData);
}

From source file:org.elasticsearch.metrics.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
 *//*w ww. j a  v a 2  s. c  om*/
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");
            if (putTemplateConnection == null) {
                LOGGER.error("Error adding metrics template to elasticsearch");
                return;
            }

            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:squash.booking.lambdas.core.PageManager.java

/**
 * Returns JSON-encoded valid-dates data for a specified date.
 * /* w w  w.  ja va 2  s .  c o  m*/
 * <p>This is not private only so that it can be unit-tested.
 * 
 * @param validDates the dates for which bookings can be made, in YYYY-MM-DD format.
 * @throws IOException
 */
protected String createValidDatesData(List<String> validDates) throws IllegalArgumentException, IOException {

    // N.B. we assume that the date is known to be a valid date
    logger.log("About to create cached valid dates data");

    // Encode valid dates as JSON
    // Create the node factory that gives us nodes.
    JsonNodeFactory factory = new JsonNodeFactory(false);
    // Create a json factory to write the treenode as json.
    JsonFactory jsonFactory = new JsonFactory();
    ObjectNode rootNode = factory.objectNode();
    ArrayNode validDatesNode = rootNode.putArray("dates");
    for (int i = 0; i < validDates.size(); i++) {
        validDatesNode.add(validDates.get(i));
    }

    ByteArrayOutputStream validDatesStream = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(validDatesStream);
    try (JsonGenerator generator = jsonFactory.createGenerator(printStream)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeTree(generator, rootNode);
    }
    String validDatesString = validDatesStream.toString(StandardCharsets.UTF_8.name());
    logger.log("Created cached valid dates data : " + validDatesString);

    return validDatesString;
}