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.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java

@Override
public void storeChecksum(String tenantID, String checksum) throws IOException {

    //Write the contents to the file
    HashMap<String, String> map = new HashMap<>();
    map.put("tenantId", tenantID);
    map.put("checksum", checksum);
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);
    File to = new File(VOLUME + "/" + tenantID + "/" + CHECKSUM_FILE);

    mapper.writeValue(to, map);// ww w  . j a  va2s  .c  o  m

}

From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java

@Override
public String getChecksum(String tenantID) throws IOException {
    String fileName = VOLUME + "/" + tenantID + "/" + CHECKSUM_FILE;

    try {// ww w. jav  a 2 s  . co  m
        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);

        File from = new File(fileName);
        TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
        };

        HashMap<String, String> map = mapper.readValue(from, typeRef);

        return map.get("checksum");
    } catch (IOException ioe) {
        LOG.warn("IOException reading checksum (" + fileName + "), cause " + ioe.getMessage(), ioe);
        throw ioe;
    }
}

From source file:com.cinnober.msgcodec.json.JsonCodec.java

/**
 * Read a static group from the specified stream, when the JSON does not contain the '$type' field.
 *
 * @param groupName the expected group name, not null.
 * @param in the stream to read from, not null.
 * @return the decoded value./*from   w  w  w  .  jav  a 2s. c om*/
 * @throws IOException if the underlying stream throws an exception.
 * @throws DecodeException if the value could not be decoded, or if a required field is missing.
 */
public Object decodeStatic(String groupName, InputStream in) throws IOException {
    StaticGroupHandler groupHandler = lookupGroupByName(groupName);
    if (groupHandler == null) {
        throw new IllegalArgumentException("Unknown group name");
    }

    JsonFactory f = new JsonFactory();
    JsonParser p = f.createParser(in);
    JsonToken token = p.nextToken();
    if (token == JsonToken.VALUE_NULL) {
        return null;
    } else if (token != JsonToken.START_OBJECT) {
        throw new DecodeException("Expected {");
    }
    return groupHandler.readValue(p);
}

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

@Test
public void testWriteMultipleJSONDocsWithDefaultMetadata2() throws Exception {
    // Synthesize input content
    String doc1 = new String("{\"animal\": \"cat\", \"says\": \"meow\"}");
    String doc2 = new String("{\"animal\": \"dog\", \"says\": \"bark\"}");
    String doc3 = new String("{\"animal\": \"eagle\", \"says\": \"squeak\"}");
    String doc4 = new String("{\"animal\": \"lion\", \"says\": \"roar\"}");
    String doc5 = new String("{\"animal\": \"man\", \"says\": \"hello\"}");

    // Synthesize input meta-data
    DocumentMetadataHandle defaultMetadata1 = new DocumentMetadataHandle().withQuality(1);
    DocumentMetadataHandle defaultMetadata2 = new DocumentMetadataHandle().withQuality(2);
    DocumentMetadataHandle docSpecificMetadata = new DocumentMetadataHandle()
            .withCollections("mySpecificCollection");

    // Create and build up the batch
    JSONDocumentManager jdm = client.newJSONDocumentManager();
    jdm.setMetadataCategories(Metadata.ALL);

    DocumentWriteSet batch = jdm.newWriteSet();

    JsonFactory f = new JsonFactory();

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

    jacksonParserHandle1.set(f.createParser(doc1));
    jacksonParserHandle2.set(f.createParser(doc2));
    jacksonParserHandle3.set(f.createParser(doc3));
    jacksonParserHandle4.set(f.createParser(doc4));
    jacksonParserHandle5.set(f.createParser(doc5));

    // use system default meta-data
    batch.add("doc1.json", jacksonParserHandle1);

    // using batch default meta-data
    batch.addDefault(defaultMetadata1);/* w  ww.  j a va 2  s .c  o  m*/
    batch.add("doc2.json", jacksonParserHandle2); // batch default meta-data
    batch.add("doc3.json", docSpecificMetadata, jacksonParserHandle3);
    batch.add("doc4.json", jacksonParserHandle4); // batch default meta-data

    // replace batch default meta-data with new meta-data
    batch.addDefault(defaultMetadata2);
    batch.add("doc5.json", jacksonParserHandle5); // batch default

    // Execute the write operation
    jdm.write(batch);
    DocumentPage page;
    DocumentRecord rec;
    // Check the results
    // Doc1 should have the system default quality of 0
    page = jdm.read("doc1.json");
    DocumentMetadataHandle mh = new DocumentMetadataHandle();
    rec = page.next();
    jdm.readMetadata(rec.getUri(), mh);
    validateDefaultMetadata(mh);
    assertEquals("default quality", 0, mh.getQuality());

    // Doc2 should use the first batch default meta-data, with quality 1
    page = jdm.read("doc2.json");
    rec = page.next();
    jdm.readMetadata(rec.getUri(), mh);
    System.out.print(mh.getCollections().isEmpty());
    assertEquals("default quality", 1, mh.getQuality());
    assertTrue("default collections reset", mh.getCollections().isEmpty());

    // Doc3 should have the system default document quality (0) because
    // quality
    // was not included in the document-specific meta-data. It should be in
    // the
    // collection "mySpecificCollection", from the document-specific
    // meta-data.

    page = jdm.read("doc3.json");
    rec = page.next();
    jdm.readMetadata(rec.getUri(), mh);
    assertEquals("default quality", 0, mh.getQuality());
    assertEquals("default collection must change", "[mySpecificCollection]", mh.getCollections().toString());

    DocumentMetadataHandle doc3Metadata = jdm.readMetadata("doc3.json", new DocumentMetadataHandle());
    System.out.println("doc3 quality: Expected=0, Actual=" + doc3Metadata.getPermissions());
    System.out.print("doc3 collections: Expected: myCollection, Actual=");
    for (String collection : doc3Metadata.getCollections()) {
        System.out.print(collection + " ");
    }
    System.out.println();

    // Doc 4 should also use the 1st batch default meta-data, with quality 1
    page = jdm.read("doc4.json");
    rec = page.next();
    jdm.readMetadata(rec.getUri(), mh);
    assertEquals("default quality", 1, mh.getQuality());
    assertTrue("default collections reset", mh.getCollections().isEmpty());
    // Doc5 should use the 2nd batch default meta-data, with quality 2
    page = jdm.read("doc5.json");
    rec = page.next();
    jdm.readMetadata(rec.getUri(), mh);
    assertEquals("default quality", 2, mh.getQuality());
    // Close handles.
    jacksonParserHandle1.close();
    jacksonParserHandle2.close();
    jacksonParserHandle3.close();
    jacksonParserHandle4.close();
    jacksonParserHandle5.close();
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

@Override
public SerializerResult entity(final ServiceMetadata metadata, final EdmEntityType entityType,
        final Entity entity, final EntitySerializerOptions options) throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;
    try {//from   w  ww.  j  a  va  2  s . c om
        final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL());
        CircleStreamBuffer buffer = new CircleStreamBuffer();
        outputStream = buffer.getOutputStream();
        JsonGenerator json = new JsonFactory().createGenerator(outputStream);
        String name = contextURL == null ? null : contextURL.getEntitySetOrSingletonOrType();
        writeEntity(metadata, entityType, entity, contextURL, options == null ? null : options.getExpand(),
                null, options == null ? null : options.getSelect(),
                options == null ? false : options.getWriteOnlyReferences(), null, name, json);

        json.close();
        outputStream.close();
        return SerializerResultImpl.with().content(buffer.getInputStream()).build();
    } catch (final IOException e) {
        cachedException = new SerializerException(IO_EXCEPTION_TEXT, e,
                SerializerException.MessageKeys.IO_EXCEPTION);
        throw cachedException;
    } catch (DecoderException e) {
        cachedException = new SerializerException(IO_EXCEPTION_TEXT, e,
                SerializerException.MessageKeys.IO_EXCEPTION);
        throw cachedException;
    } finally {
        closeCircleStreamBufferOutput(outputStream, cachedException);
    }
}

From source file:portal.api.osm.client.OSMClient.java

public List<Nsd> getNSDs() {

    String response = getOSMResponse(BASE_SERVICE_URL + "/nsd-catalog/nsd");

    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    try {/*from   w ww . j ava 2s . co m*/

        JsonNode tr = mapper.readTree(response).findValue("nsd:nsd");
        if (tr == null) {
            tr = mapper.readTree(response).findValue("nsd");
        }
        ArrayList<Nsd> nsds = new ArrayList<>();

        for (JsonNode jsonNode : tr) {
            Nsd nsd = mapper.readValue(jsonNode.toString(), Nsd.class);
            nsds.add(nsd);
        }

        return nsds;

    } catch (IllegalStateException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Creates the JsonFactory.// ww w  .  jav a  2s.c  o m
 */
private void init() {
    jsFactory = new JsonFactory();
    jsFactory.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    jsFactory.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    jsFactory.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
}

From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonUnmarshaller.java

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

From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonUnmarshaller.java

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

From source file:com.couchbase.lite.replicator.ChangeTracker.java

protected void runLoop() {
    paused = false;/*from   w w  w  .ja  va 2 s . c o m*/

    if (client == null) {
        // This is a race condition that can be reproduced by calling cbpuller.start() and cbpuller.stop()
        // directly afterwards.  What happens is that by the time the Changetracker thread fires up,
        // the cbpuller has already set this.client to null.  See issue #109
        Log.w(Log.TAG_CHANGE_TRACKER, "%s: ChangeTracker run() loop aborting because client == null", this);
        return;
    }

    if (mode == ChangeTrackerMode.Continuous) {
        // there is a failing unit test for this, and from looking at the code the Replication
        // object will never use Continuous mode anyway.  Explicitly prevent its use until
        // it is demonstrated to actually work.
        throw new RuntimeException("ChangeTracker does not correctly support continuous mode");
    }

    OkHttpClient httpClient = client.getOkHttpClient();

    backoff = new ChangeTrackerBackoff();

    while (running) {
        startTime = System.currentTimeMillis();

        Request.Builder builder = new Request.Builder();
        URL url = getChangesFeedURL();
        builder.url(url);
        if (usePOST) {
            builder.header("Content-Type", "application/json").addHeader("User-Agent", Manager.getUserAgent())
                    .addHeader("Accept-Encoding", "gzip").post(RequestBody.create(JSON, changesFeedPOSTBody()));
        }
        addRequestHeaders(builder);

        // Perform BASIC Authentication if needed
        builder = RequestUtils.preemptivelySetAuthCredentials(builder, url, authenticator);
        request = builder.build();

        try {
            String maskedRemoteWithoutCredentials = getChangesFeedURL().toString();
            maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.replaceAll("://.*:.*@",
                    "://---:---@");
            Log.v(Log.TAG_CHANGE_TRACKER, "%s: Making request to %s", this, maskedRemoteWithoutCredentials);
            call = httpClient.newCall(request);
            Response response = call.execute();
            try {
                // In case response status is Error, ChangeTracker stops here
                if (isResponseFailed(response)) {
                    RequestUtils.closeResponseBody(response);
                    if (retryIfFailedPost(response))
                        continue;
                    break;
                }

                // Parse response body
                ResponseBody responseBody = response.body();

                Log.v(Log.TAG_CHANGE_TRACKER, "%s: got response. status: %s mode: %s", this, response.message(),
                        mode);
                if (responseBody != null) {
                    try {
                        Log.v(Log.TAG_CHANGE_TRACKER, "%s: /entity.getContent().  mode: %s", this, mode);
                        //inputStream = entity.getContent();
                        inputStream = responseBody.byteStream();
                        // decompress if contentEncoding is gzip
                        if (Utils.isGzip(response))
                            inputStream = new GZIPInputStream(inputStream);

                        if (mode == ChangeTrackerMode.LongPoll) { // continuous replications
                            // NOTE: 1. check content length, ObjectMapper().readValue() throws Exception if size is 0.
                            // NOTE: 2. HttpEntity.getContentLength() returns the number of bytes of the content, or a negative number if unknown.
                            // NOTE: 3. If Http Status is error, not parse response body
                            boolean responseOK = false; // default value
                            if (responseBody.contentLength() != 0 && response.code() < 300) {
                                try {
                                    Log.v(Log.TAG_CHANGE_TRACKER, "%s: readValue", this);
                                    Map<String, Object> fullBody = Manager.getObjectMapper()
                                            .readValue(inputStream, Map.class);
                                    Log.v(Log.TAG_CHANGE_TRACKER, "%s: /readValue.  fullBody: %s", this,
                                            fullBody);
                                    responseOK = receivedPollResponse(fullBody);
                                } catch (JsonParseException jpe) {
                                    Log.w(Log.TAG_CHANGE_TRACKER, "%s: json parsing error; %s", this,
                                            jpe.toString());
                                } catch (JsonMappingException jme) {
                                    Log.w(Log.TAG_CHANGE_TRACKER, "%s: json mapping error; %s", this,
                                            jme.toString());
                                }
                            }
                            Log.v(Log.TAG_CHANGE_TRACKER, "%s: responseOK: %s", this, responseOK);

                            if (responseOK) {
                                // TODO: this logic is questionable, there's lots
                                // TODO: of differences in the iOS changetracker code,
                                if (!caughtUp) {
                                    caughtUp = true;
                                    client.changeTrackerCaughtUp();
                                }
                                Log.v(Log.TAG_CHANGE_TRACKER, "%s: Starting new longpoll", this);
                                backoff.resetBackoff();
                                continue;
                            } else {
                                long elapsed = (System.currentTimeMillis() - startTime) / 1000;
                                Log.w(Log.TAG_CHANGE_TRACKER,
                                        "%s: Longpoll connection closed (by proxy?) after %d sec", this,
                                        elapsed);
                                if (elapsed >= 30) {
                                    // Looks like the connection got closed by a proxy (like AWS' load balancer) while the
                                    // server was waiting for a change to send, due to lack of activity.
                                    // Lower the heartbeat time to work around this, and reconnect:
                                    this.heartBeatSeconds = Math.min(this.heartBeatSeconds,
                                            (int) (elapsed * 0.75));
                                    Log.v(Log.TAG_CHANGE_TRACKER, "%s: Starting new longpoll", this);
                                    backoff.resetBackoff();
                                    continue;
                                } else {
                                    Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling stop (LongPoll)",
                                            this);
                                    client.changeTrackerFinished(this);
                                    break;
                                }
                            }
                        } else { // one-shot replications
                            Log.v(Log.TAG_CHANGE_TRACKER, "%s: readValue (oneshot)", this);
                            JsonFactory factory = new JsonFactory();
                            JsonParser jp = factory.createParser(inputStream);
                            JsonToken token;
                            // nextToken() is null => no more token
                            while (((token = jp.nextToken()) != JsonToken.START_ARRAY) && (token != null)) {
                                // ignore these tokens
                            }
                            while (jp.nextToken() == JsonToken.START_OBJECT) {
                                Map<String, Object> change = (Map) Manager.getObjectMapper().readValue(jp,
                                        Map.class);
                                if (!receivedChange(change)) {
                                    Log.w(Log.TAG_CHANGE_TRACKER,
                                            "Received unparseable change line from server: %s", change);
                                }
                                // if not running state anymore, exit from loop.
                                if (!running)
                                    break;
                            }
                            if (jp != null)
                                jp.close();

                            Log.v(Log.TAG_CHANGE_TRACKER, "%s: /readValue (oneshot)", this);
                            client.changeTrackerCaughtUp();
                            if (isContinuous()) { // if enclosing replication is continuous
                                mode = ChangeTrackerMode.LongPoll;
                            } else {
                                Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling stop (OneShot)",
                                        this);
                                client.changeTrackerFinished(this);
                                break;
                            }
                        }
                        backoff.resetBackoff();
                    } finally {
                        try {
                            if (inputStream != null) {
                                inputStream.close();
                                inputStream = null;
                            }
                        } catch (IOException e) {
                        }
                    }
                }
            } finally {
                RequestUtils.closeResponseBody(response);
            }
        } catch (Exception e) {
            if (!running && e instanceof IOException) {
                // in this case, just silently absorb the exception because it
                // frequently happens when we're shutting down and have to
                // close the socket underneath our read.
            } else {
                Log.w(Log.TAG_CHANGE_TRACKER, this + ": Exception in change tracker", e);
                this.error = e;
            }
            backoff.sleepAppropriateAmountOfTime();
        }
    }
    Log.v(Log.TAG_CHANGE_TRACKER, "%s: Change tracker run loop exiting", this);
}