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.helm.notation2.wsadapter.NucleotideWSLoader.java

/**
 * Loads the nucleotide store using the URL configured in {@code MonomerStoreConfiguration}.
 * /*  ww w  .j  a  v  a  2 s.c o  m*/
 * @return Map containing nucleotides
 * 
 * @throws IOException
 * @throws URISyntaxException
 */
public Map<String, String> loadNucleotideStore() throws IOException, URISyntaxException {

    Map<String, String> nucleotides = new HashMap<String, String>();
    LOG.debug("Loading nucleotide store by Webservice Loader");
    LOG.debug(MonomerStoreConfiguration.getInstance().toString());
    CloseableHttpResponse response = null;
    try {
        response = WSAdapterUtils
                .getResource(MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesFullURL());
        LOG.debug(response.getStatusLine().toString());

        JsonFactory jsonf = new JsonFactory();
        InputStream instream = response.getEntity().getContent();

        JsonParser jsonParser = jsonf.createJsonParser(instream);
        nucleotides = deserializeNucleotideStore(jsonParser);
        LOG.debug(nucleotides.size() + " nucleotides loaded");

        EntityUtils.consume(response.getEntity());

    } catch (ClientProtocolException e) {

        /* read file */
        JsonFactory jsonf = new JsonFactory();
        InputStream instream = new FileInputStream(
                new File(MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesFullURL()));

        JsonParser jsonParser = jsonf.createJsonParser(instream);
        nucleotides = deserializeNucleotideStore(jsonParser);
        LOG.debug(nucleotides.size() + " nucleotides loaded");

    } finally {

        if (response != null) {
            response.close();
        }
    }

    return nucleotides;
}

From source file:com.googlecode.jmxtrans.model.output.kafka.DefaultResultSerializer.java

@JsonCreator
public DefaultResultSerializer(@JsonProperty("typeNames") List<String> typeNames,
        @JsonProperty("booleanAsNumber") boolean booleanAsNumber, @JsonProperty("rootPrefix") String rootPrefix,
        @JsonProperty("tags") Map<String, String> tags, @JsonProperty("resultTags") List<String> resultTags) {
    this.jsonFactory = new JsonFactory();
    this.typeNames = typeNames == null ? ImmutableList.<String>of() : ImmutableList.copyOf(typeNames);
    this.booleanAsNumber = booleanAsNumber;
    this.rootPrefix = rootPrefix;
    this.tags = tags == null ? ImmutableMap.<String, String>of() : ImmutableMap.copyOf(tags);
    this.resultAttributesToWriteAsTags = resultTags == null ? ImmutableSet.<ResultAttribute>of()
            : ResultAttributes.forNames(resultTags);
}

From source file:uk.ac.manchester.cs.owl.semspreadsheets.repository.bioportal.BioPortalRepositoryAccessor.java

public String fetchOntologyFormat(String ontologyAcronym) {
    logger.debug("Fetching format for " + ontologyAcronym);
    BioPortalCache cache = BioPortalCache.getInstance();
    String format = cache.getFormat(ontologyAcronym);
    if (format != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("The ontology format for " + ontologyAcronym + " was found in the cache as " + format);
        }/*from  www . j  a  v  a2 s . c  om*/
    } else {
        logger.info("The format for " + ontologyAcronym + " not found in cache, fetching");
        try {
            URL url = new URL(BioPortalRepository.ONTOLOGY_LIST + "/" + ontologyAcronym + "/"
                    + BioPortalRepository.LATEST_SUBMISSION + "?format=json&apikey="
                    + BioPortalRepository.readAPIKey());
            logger.info("About to fetch more ontology information from " + url.toExternalForm());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(CONNECT_TIMEOUT);
            int responseCode = connection.getResponseCode();
            logger.info("BioPortal http response: " + responseCode);

            if (responseCode == 400 || responseCode == 403) {
                throw new BioPortalAccessDeniedException();
            }

            JsonParser parser = new JsonFactory().createParser(connection.getInputStream());
            while (format == null && parser.nextToken() != null) {
                String name = parser.getCurrentName();
                if ("hasOntologyLanguage".equals(name)) {
                    parser.nextToken();
                    format = parser.getText();
                }
            }
            if (format == null) {
                format = "unknown";
            }
            cache.storeFormat(ontologyAcronym, format);
        } catch (UnknownHostException e) {
            ErrorHandler.getErrorHandler().handleError(e);
        } catch (MalformedURLException e) {
            logger.error("Error with URL for BioPortal rest API", e);
        } catch (SocketTimeoutException e) {
            logger.error("Timeout connecting to BioPortal", e);
            ErrorHandler.getErrorHandler().handleError(e);
        } catch (IOException e) {
            logger.error("Error communiciating with BioPortal rest API", e);
        } catch (BioPortalAccessDeniedException e) {
            ErrorHandler.getErrorHandler().handleError(e);
        }
    }

    return format;
}

From source file:me.tfeng.toolbox.dust.NodeEngine.java

private JsonNode evaluate(Process process, String template, String data) throws IOException {
    PrintWriter writer = new PrintWriter(process.getOutputStream());
    writer.println("[");
    printRenderScript(writer, template, data);
    writer.println("]");
    writer.println("1");
    writer.flush();//from   w w  w. java  2  s  . c om

    String result = readInput(process, "1");
    JsonParser parser = new JsonFactory().createParser(result).configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES,
            true);
    ArrayNode arrayNode = OBJECT_MAPPER.readValue(parser, ArrayNode.class);
    return arrayNode.get(0);
}

From source file:ru.histone.HistoneOptimizeAstMojo.java

public void execute() throws MojoExecutionException {
    try {//from   ww  w .j av  a 2  s  .  com

        getLog().info(MessageFormat.format("Running DirectoryScanner with params: baseDir={0}, includes=[{1}]",
                baseDir, StringUtils.join(includes, ", ")));
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(baseDir);
        scanner.setIncludes(includes);
        scanner.scan();

        List<OptimizationTypes> optimizationTypeses = new ArrayList<OptimizationTypes>();
        for (String optimizationType : optimizationTypes) {
            optimizationTypeses.add(OptimizationTypes.valueOf(optimizationType));
        }
        OptimizationTypes[] array = optimizationTypeses
                .toArray(new OptimizationTypes[optimizationTypeses.size()]);
        getLog().info(MessageFormat.format("Optimizations to be run: [{0}]",
                "" + StringUtils.join(optimizationTypes, ", ")));

        String[] includedFiles = scanner.getIncludedFiles();
        getLog().info(MessageFormat.format("Files found:\n{0}", StringUtils.join(includedFiles, "\n")));

        HistoneBuilder builder = new HistoneBuilder();
        Histone histone = builder.build();
        ObjectMapper jackson = new ObjectMapper();
        JsonFactory jsonFactory = new JsonFactory();

        for (String includedFile : includedFiles) {
            ArrayNode ast = histone.parseTemplateToAST(new FileReader(new File(baseDir, includedFile)));

            ObjectNode context = builder.getNodeFactory().jsonObject();

            int astCount1 = ASTTreeElementsCounter.count(ast);
            ArrayNode optimizedAst = histone.optimizeAST(ast, context, array);
            int astCount2 = ASTTreeElementsCounter.count(ast);

            getLog().info(MessageFormat.format("Processing {0}, before: {1}, after: {2}", includedFile,
                    astCount1, astCount2));

            JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(baseDir, includedFile + ".ast"),
                    JsonEncoding.UTF8);
            jackson.writeTree(jsonGenerator, optimizedAst);
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Error parsing templates to AST", e);
    }

}

From source file:com.netflix.hollow.jsonadapter.AbstractHollowJsonAdaptorTask.java

protected void processFile(Reader r, int maxSample) throws Exception {
    JsonArrayChunker chunker = new JsonArrayChunker(r, executor);
    chunker.initialize();//from ww  w .j a  va  2s.c  o m

    int counter = 0;

    Reader jsonObj = chunker.nextChunk();
    while (jsonObj != null && counter < maxSample) {

        final Reader currentObject = jsonObj;

        executor.execute(new Runnable() {
            public void run() {
                try {
                    JsonFactory factory = new JsonFactory();
                    JsonParser parser = factory.createParser(currentObject);
                    processRecord(parser);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        while (executor.getQueue().size() > maxWorkQueue) {
            Thread.sleep(5);
        }

        counter++;

        jsonObj.close();
        jsonObj = chunker.nextChunk();
    }

    executor.awaitSuccessfulCompletion();
}

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

@Test
public void testNested1() throws IOException {
    JsonParser p = new JsonFactory()
            .createParser("{\"a\":{\"c\":2, \"$type\":\"y\", \"d\":2.1}, \"$type\":\"x\", \"b\":1.1}");
    p.nextToken(); // START_OBJECT
    p.nextToken(); // FIELD_NAME
    TypeScannerJsonParser p2 = new TypeScannerJsonParser(p);
    assertEquals("x", p2.findType());

    assertNextField("a", p2);
    assertEquals(JsonToken.START_OBJECT, p2.nextToken());
    // start nested object
    p2.nextToken(); // FIELD_NAME
    assertEquals("y", p2.findType());
    assertNextField("c", p2);
    assertNextIntValue(2, p2);/*from ww w .  j  a  v  a  2 s  .  c o  m*/
    assertNextField("d", p2);
    assertNextFloatValue(2.1, p2);
    assertEquals(JsonToken.END_OBJECT, p2.nextToken());
    // end nested object

    assertNextField("b", p2);
    assertNextFloatValue(1.1, p2);

    assertEquals(JsonToken.END_OBJECT, p2.nextToken());
    assertNull(p2.nextToken());
}

From source file:io.cslinmiso.line.utils.Utility.java

public static String bean2Json(Object obj) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    StringWriter sw = new StringWriter();
    JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
    mapper.writeValue(gen, obj);//from  ww  w . j a  va  2  s . c o m
    gen.close();
    return sw.toString();
}

From source file:com.viridiansoftware.metrics.elasticsearch.ElasticsearchReporter.java

protected ElasticsearchReporter(MetricRegistry registry, Clock clock, String elasticsearchIndexPrefix,
        String timestampFieldName, String metricPrefix, TimeUnit rateUnit, TimeUnit durationUnit,
        MetricFilter filter) {//  ww w .j  a  v a  2s . c  o m
    super(registry, "elasticsearch-reporter", filter, rateUnit, durationUnit);
    this.clock = clock;
    this.metricPrefix = metricPrefix;
    this.timestampFieldName = timestampFieldName;

    if (elasticsearchIndexPrefix.endsWith("-")) {
        this.elasticsearchIndexPrefix = elasticsearchIndexPrefix;
    } else {
        this.elasticsearchIndexPrefix = elasticsearchIndexPrefix + "-";
    }
    jsonFactory = new JsonFactory();
}

From source file:org.zapto.samhippiemiddlepoolchecker.Values.java

PoolError update(String address, URL... urls) {
    //error is returned at the end
    PoolError error = PoolError.NONE;/*from w  w  w  .j  av a 2  s . c  o m*/

    //Aborting the http to save data throws an error. This says if we should cover it up.
    boolean actualNetworkError = true;

    //reset the values. If they are never changed, then 0 is the most accurate number
    accepted = 0;
    rejected = 0;
    immature = 0;
    unexchanged = 0;
    balance = 0;
    paid = 0;

    try {
        //streaming the json
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(urls[0].toString());
        HttpResponse response = client.execute(request);
        InputStream in = response.getEntity().getContent();

        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(in);
        boolean addressFound = false;//see if we need to return and address not found error
        mainParse: //label for breaking when address is found
        while (parser.nextToken() != JsonToken.END_OBJECT)//finding "report"
        {
            if ("report".equals(parser.getCurrentName()))//beginning of report
            {
                boolean firstRun = true;
                while (parser.nextToken() == JsonToken.START_ARRAY)//each address has its own array
                {
                    if (firstRun)//this jumps over some junk at the begining
                    {
                        parser.nextToken();
                        firstRun = false;
                    }
                    parser.nextToken();//have to skip some junk each time
                    if (address.equals(parser.getText()))//we have found our address
                    {
                        addressFound = true;//this prevents an address not found error from being returned
                        while (parser.nextToken() != JsonToken.END_ARRAY) {
                            //getting each of our values from the array.
                            //having -420 as a default lets us see if the value is there while not using up 0

                            if ("megahashesPerSecond".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    accepted = value;
                                }
                            }

                            if ("rejectedMegahashesPerSecond".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    rejected = value;
                                }
                            }

                            if ("immatureBalance".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    immature = value;
                                }
                            }

                            if ("unexchangedBalance".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    unexchanged = value;
                                }
                            }

                            if ("bitcoinBalance".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    balance = value;
                                }
                            }

                            if ("paidOut".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    paid = value;
                                }
                            }
                        }
                        break mainParse;//no need to download any more addresses
                    } else {
                        while (parser.nextToken() != JsonToken.END_ARRAY) {
                        } //skipping over an unwanted address
                    }
                }
            }
        }
        if (!addressFound)//we never found an address
        {
            error = PoolError.ADDRESS;
        }
        actualNetworkError = false;
        request.abort();//should stop any extra data usage, also forces ioexception (which is ignored)
        parser.close();
        in.close();
    } catch (MalformedURLException e) {
        if (actualNetworkError) {
            error = PoolError.NETWORK;
        }
    } catch (IOException e) {
        if (actualNetworkError) {
            error = PoolError.NETWORK;
        }
    }
    return error;
}