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:eu.project.ttc.readers.TermSuiteJsonCasDeserializer.java

public static void deserialize(InputStream inputStream, CAS cas, String encoding) {
    Preconditions.checkNotNull(inputStream, "Paramater input stream is null");
    Preconditions.checkNotNull(inputStream, "Paramater CAS is null");

    try {/*from  www . j  av  a 2s  .  co  m*/

        JsonFactory factory = new JsonFactory();
        parser = factory.createParser(inputStream);

        SourceDocumentInformation sdi = (SourceDocumentInformation) cas
                .createAnnotation(cas.getJCas().getCasType(SourceDocumentInformation.type), 0, 0);
        WordAnnotation wa = (WordAnnotation) cas.createAnnotation(cas.getJCas().getCasType(WordAnnotation.type),
                0, 0);
        TermOccAnnotation toa = (TermOccAnnotation) cas
                .createAnnotation(cas.getJCas().getCasType(TermOccAnnotation.type), 0, 0);
        FixedExpression fe = (FixedExpression) cas
                .createAnnotation(cas.getJCas().getCasType(FixedExpression.type), 0, 0);
        boolean inSdi = false;
        boolean inWa = false;
        boolean inToa = false;
        boolean inFe = false;
        boolean inCoveredText = false;

        while ((token = parser.nextToken()) != null) {

            if (inSdi) {

                if (token == JsonToken.END_OBJECT) {
                    inSdi = false;
                } else {
                    fillSdi(parser, token, sdi);
                }
            }

            else if (inWa) {
                if (token == JsonToken.END_ARRAY) {
                    inWa = false;
                } else if (token == JsonToken.END_OBJECT) {
                    wa.addToIndexes();
                    wa = (WordAnnotation) cas.createAnnotation(cas.getJCas().getCasType(WordAnnotation.type), 0,
                            0);
                }
                fillWordAnnotations(parser, token, wa);
            }

            else if (inToa) {
                if (token == JsonToken.END_ARRAY && Objects.equals(parser.getParsingContext().getCurrentName(),
                        "term_occ_annotations")) {
                    inToa = false;
                } else if (token == JsonToken.END_OBJECT) {
                    toa.addToIndexes();
                    toa = (TermOccAnnotation) cas
                            .createAnnotation(cas.getJCas().getCasType(TermOccAnnotation.type), 0, 0);
                }
                FillTermOccAnnotations(parser, token, toa, cas);
            }

            else if (inFe) {
                if (token == JsonToken.END_ARRAY
                        && Objects.equals(parser.getParsingContext().getCurrentName(), "fixed_expressions")) {
                    inFe = false;
                } else if (token == JsonToken.END_OBJECT) {
                    fe.addToIndexes();
                    fe = (FixedExpression) cas.createAnnotation(cas.getJCas().getCasType(FixedExpression.type),
                            0, 0);
                }
                FillFixedExpressions(parser, token, fe, cas);
            }

            else if (inCoveredText) {
                if (token == JsonToken.VALUE_STRING) {
                    String text = parser.getText();
                    cas.setDocumentText(text);
                }
            }

            else if ("sdi".equals(parser.getParsingContext().getCurrentName())) {
                inSdi = true;
            }

            else if ("word_annotations".equals(parser.getParsingContext().getCurrentName())) {
                inWa = true;
            }

            else if ("term_occ_annotations".equals(parser.getParsingContext().getCurrentName())) {
                inToa = true;
            }

            else if ("fixed_expressions".equals(parser.getParsingContext().getCurrentName())) {
                inFe = true;
            }

            else if ("covered_text".equals(parser.getParsingContext().getCurrentName())) {
                inCoveredText = true;
            }
        }
        sdi.addToIndexes();
    } catch (IOException | CASException e) {
        logger.error("An error occurred during TermSuite Json Cas parsing", e);
    }
}

From source file:com.ryan.ryanreader.jsonwrap.JsonValue.java

/**
 * Begins parsing a JSON stream into a tree structure. The JsonValue object
 * created contains the value at the root of the tree.
 * //from  ww  w.  j a va  2s  . c  o  m
 * This constructor will block until the first JSON token is received. To
 * continue building the tree, the "build" method (inherited from
 * JsonBuffered) must be called in another thread.
 * 
 * @param source
 *         The source of incoming JSON data.
 * @throws java.io.IOException
 */
public JsonValue(final URL source) throws IOException {
    this(new JsonFactory().createParser(source));
}

From source file:com.asprise.imaging.core.Request.java

public static Request fromJson(String spec) throws IOException {
    JsonParser parser = new JsonFactory().enable(JsonParser.Feature.ALLOW_COMMENTS).createParser(spec);
    Map<Object, Object> json = JSON.std.mapFrom(parser);

    Request request = new Request();
    request.id = JsonUtils.attrValue(json, "request_id", null);
    request.processImagesAfterAllScans = "after-all-scans"
            .equals(JsonUtils.attrValue(json, "processing_strategy", null));
    request.promptScanMore = JsonUtils.attrValueAsBoolean(json, "prompt_scan_more", false);
    request.discardBlankPages = JsonUtils.attrValueAsBoolean(json, "discard_blank_pages", false);
    request.blankPageThreshold = JsonUtils.attrValueAsDouble(json, "blank_page_threshold",
            DEFAULT_BLANK_PAGE_THRESHOLD);
    request.blankPageMarginPercent = JsonUtils.attrValueAsInt(json, "blank_page_margin_percent",
            DEFAULT_BLANK_PAGE_MARGIN_PERCENT);
    request.recognizeBarcodes = JsonUtils.attrValueAsBoolean(json, "recognize_barcodes", false);

    request.useAspriseDialog = JsonUtils.attrValueAsBoolean(json, "use_asprise_dialog", null);
    request.showScannerUI = JsonUtils.attrValueAsBoolean(json, "show_scanner_ui", null);
    request.modalScannerUI = JsonUtils.attrValueAsBoolean(json, "modal_scanner_ui", null);
    request.dialogWidth = JsonUtils.attrValueAsInt(json, "dialog_width", -1);
    request.dialogHeight = JsonUtils.attrValueAsInt(json, "dialog_height", -1);
    request.sourceName = JsonUtils.attrValue(json, "source_name", null);

    Map caps = (Map) json.get("twain_cap_setting");
    if (caps != null) {
        request.twainCapSetting.putAll(caps);
    }/*from   w w w  .j  av  a2 s.  co m*/

    List outputs = (List) json.get("output_settings");
    for (int i = 0; outputs != null && i < outputs.size(); i++) {
        request.outputItems.add(RequestOutputItem.fromJsonMap((Map) outputs.get(i)));
    }

    if (json.get("retrieve_caps") instanceof Collection) {
        request.retrieveCaps.addAll((Collection<? extends String>) json.get("retrieve_caps"));
    }

    if (json.get("retrieve_extended_image_attrs") instanceof Collection) {
        request.retrieveExtendedImageAttributes
                .addAll((Collection<? extends String>) json.get("retrieve_extended_image_attrs"));
    }

    List imgFiles = (List) json.get("image_files");
    for (int i = 0; imgFiles != null && i < imgFiles.size(); i++) {
        request.imageFiles.add(new File((String) imgFiles.get(i)));
    }

    request.sourceJson = json;
    return request;
}

From source file:com.adobe.communities.ugc.migration.importer.ForumImportServlet.java

protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    final ResourceResolver resolver = request.getResourceResolver();

    UGCImportHelper.checkUserPrivileges(resolver, rrf);

    final UGCImportHelper importHelper = new UGCImportHelper();
    importHelper.setForumOperations(forumOperations);
    importHelper.setTallyService(tallyOperationsService);
    // get the forum we'll be adding new topics to
    final String path = request.getRequestParameter("path").getString();
    final Resource resource = request.getResourceResolver().getResource(path);
    if (resource == null) {
        throw new ServletException("Could not find a valid resource for import");
    }/*  w w  w. ja  v a2s .c o  m*/

    // finally get the uploaded file
    final RequestParameter[] fileRequestParameters = request.getRequestParameters("file");
    if (fileRequestParameters != null && fileRequestParameters.length > 0
            && !fileRequestParameters[0].isFormField()) {

        InputStream inputStream = fileRequestParameters[0].getInputStream();
        JsonParser jsonParser = new JsonFactory().createParser(inputStream);
        jsonParser.nextToken(); // get the first token

        if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
            jsonParser.nextToken();
            if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT_TYPE)) {
                jsonParser.nextToken();
                final String contentType = jsonParser.getValueAsString();
                if (contentType.equals(getContentType())) {
                    jsonParser.nextToken(); // content
                    if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT)) {
                        jsonParser.nextToken(); // startObject
                        if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
                            JsonToken token = jsonParser.nextToken(); // social:key
                            try {
                                while (!token.equals(JsonToken.END_OBJECT)) {
                                    importHelper.extractTopic(jsonParser, resource,
                                            resource.getResourceResolver(), getOperationsService());
                                    token = jsonParser.nextToken();
                                }
                            } catch (final IOException e) {
                                throw new ServletException("Encountered an IOException", e);
                            }
                        } else {
                            throw new ServletException("Start object token not found for content");
                        }
                    } else {
                        throw new ServletException("Content not found");
                    }
                } else {
                    throw new ServletException("Expected forum data");
                }
            } else {
                throw new ServletException("Content Type not specified");
            }
        } else {
            throw new ServletException("Invalid Json format");
        }
    }
}

From source file:com.ntsync.shared.ContactGroup.java

/**
 * Serialize this ContactGroup for transporting to a server
 * /*from ww w . j a  v  a2  s .  co m*/
 * @param secret
 * @param pwdSaltBase64
 * @return null if serializing failed.
 */
public byte[] toDTO(Key secret, String pwdSaltBase64) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream(DEFAULT_BYTEARRAY_SIZE);

        AEADBlockCipher ecipher = CryptoHelper.getCipher();

        byte[] iv = new byte[CryptoHelper.IV_LEN];
        SecureRandom random = new SecureRandom();

        StringBuilder hashValue = new StringBuilder();
        hashValue.append(pwdSaltBase64);
        hashValue.append(title);

        out.write(GroupConstants.ROWID);

        byte[] rowId = String.valueOf(rawId).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME);

        SyncDataHelper.writeInt(out, rowId.length);
        out.write(rowId);

        JsonFactory json = new JsonFactory();
        StringWriter writer = new StringWriter();
        JsonGenerator g = json.createGenerator(writer);
        g.writeStartObject();

        writeField(g, GroupConstants.TITLE, title);
        writeField(g, GroupConstants.NOTES, notes);

        g.writeEndObject();
        g.close();

        String textData = writer.toString();

        CryptoHelper.writeValue(secret, out, ecipher, iv, random, GroupConstants.TEXTDATA, textData);

        if (lastModified != null) {
            writeRawValue(out, GroupConstants.MODIFIED,
                    String.valueOf(lastModified.getTime()).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME));
        }

        if (deleted) {
            writeRawValue(out, GroupConstants.DELETED, "1".getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME));
        }
        if (sourceId != null) {
            writeRawValue(out, GroupConstants.SERVERROW_ID,
                    sourceId.getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME));
        }

        MessageDigest md = MessageDigest.getInstance("SHA-256");

        md.update(hashValue.toString().getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME));
        byte[] hash = md.digest();
        writeRawValue(out, GroupConstants.HASH, hash);

        return out.toByteArray();
    } catch (final Exception ex) {
        LOG.error("Error converting ContactGroup to ByteStream: " + ex.toString(), ex);
    }
    return null;
}

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

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

    Assert.assertEquals(JsonStreamToken.START_OBJECT, source.peek());
    source.startObject();//from w  w  w  .java  2  s  .  com

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

    Assert.assertEquals(JsonStreamToken.START_OBJECT, source.peek());
    source.startObject();

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

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

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

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

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

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

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

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

From source file:com.basho.riak.client.query.MapReduce.java

/**
 * Creates the JSON string of the M/R job for submitting to the
 * {@link RawClient}// w w w  .  j  a v  a 2s .  c  o m
 * 
 * Uses Jackson to write out the JSON string. I'm not very happy with this
 * method, it is a candidate for change.
 * 
 * TODO re-evaluate this method, look for something smaller and more elegant.
 * 
 * @return a String of JSON
 * @throws RiakException
 *             if, for some reason, we can't create a JSON string.
 */
private String writeSpec() throws RiakException {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        JsonGenerator jg = new JsonFactory().createJsonGenerator(out, JsonEncoding.UTF8);
        jg.setCodec(new ObjectMapper());

        jg.writeStartObject();

        jg.writeFieldName("inputs");
        writeInput(jg);

        jg.writeFieldName("query");
        jg.writeStartArray();

        writePhases(jg);

        jg.writeEndArray();
        if (timeout != null) {
            jg.writeNumberField("timeout", timeout);
        }

        jg.writeEndObject();
        jg.flush();

        return out.toString("UTF8");
    } catch (IOException e) {
        throw new RiakException(e);
    }
}

From source file:com.googlecode.jmxtrans.model.output.LibratoWriterFactory.java

@Override
public ResultTransformerOutputWriter<HttpOutputWriter<LibratoWriter2>> create() {
    return ResultTransformerOutputWriter.booleanToNumber(booleanAsNumber,
            new HttpOutputWriter<LibratoWriter2>(new LibratoWriter2(new JsonFactory(), typeNames), url, proxy,
                    new HttpUrlConnectionConfigurer("POST", readTimeoutInMillis, authorization,
                            "application/json; charset=utf-8"),
                    UTF_8));/*  w  ww .  ja  va 2  s.c  om*/
}

From source file:com.heisenberg.api.WorkflowEngineConfiguration.java

protected void initializeJsonFactory() {
    registerService(new JsonFactory());
}