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.basho.riak.client.api.commands.mapreduce.MapReduce.java

/**
 * Creates the JSON string of the M/R job for submitting to the client
 * <p/>//from   w  w  w.  j  a va2  s.co m
 * Uses Jackson to write out the JSON string. I'm not very happy with this method, it is a candidate for change.
 * <p/>
 * 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.
 */
String writeSpec() throws RiakException {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        JsonGenerator jg = new JsonFactory().createGenerator(out, JsonEncoding.UTF8);

        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule specModule = new SimpleModule("SpecModule", Version.unknownVersion());
        specModule.addSerializer(LinkPhase.class, new LinkPhaseSerializer());
        specModule.addSerializer(FunctionPhase.class, new FunctionPhaseSerializer());
        specModule.addSerializer(BucketInput.class, new BucketInputSerializer());
        specModule.addSerializer(SearchInput.class, new SearchInputSerializer());
        specModule.addSerializer(BucketKeyInput.class, new BucketKeyInputSerializer());
        specModule.addSerializer(IndexInput.class, new IndexInputSerializer());
        objectMapper.registerModule(specModule);

        jg.setCodec(objectMapper);

        List<MapReducePhase> phases = spec.getPhases();
        phases.get(phases.size() - 1).setKeep(true);
        jg.writeObject(spec);

        jg.flush();

        return out.toString("UTF8");

    } catch (IOException e) {
        throw new RiakException(e);
    }
}

From source file:uk.ac.cam.cl.dtg.isaac.quiz.IsaacSymbolicChemistryValidator.java

/**
 * Given two formulae, where one is student answer, and another is the target mhchem string,
 * this method generates a JSON object of them, and sends it to a back end chemistry checker
 * for comparison. Comparison results are sent back from server as a JSON string and returned here.
 *
 * @param submittedFormula Formula submitted by user.
 * @param formulaChoice Formula of one of the choice in content editor.
 * @param description A text description to show in the checker logs.
 * @return The JSON string returned from the ChemicalChecker server.
 * @throws IOException Trouble connecting to the ChemicalChecker server.
 *///from   www. ja  va2  s . c om
private String jsonPostAndGet(final String submittedFormula, final String formulaChoice,
        final String description) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    // Complicated: Put formulae into a JSON object
    HashMap<String, String> req = Maps.newHashMap();
    req.put("target", formulaChoice);
    req.put("test", submittedFormula);
    req.put("description", description);

    StringWriter sw = new StringWriter();
    JsonGenerator g = new JsonFactory().createGenerator(sw);
    mapper.writeValue(g, req);
    g.close();
    String requestString = sw.toString();

    // Do some real checking through HTTP
    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost("http://" + hostname + ":" + port + "/check");

    // Send JSON object across ChemistryChecker server.
    httpPost.setEntity(new StringEntity(requestString));
    httpPost.addHeader("Content-Type", "application/json");

    // Receive JSON response from server.
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity responseEntity = httpResponse.getEntity();

    return EntityUtils.toString(responseEntity);
}

From source file:org.talend.daikon.exception.TalendRuntimeException.java

/**
 * Describe this error in json into the given writer.
 * /*w w  w .j  a v  a2s .c  o m*/
 * @param writer where to write this error.
 */
public void writeTo(Writer writer) {
    try {
        JsonGenerator generator = (new JsonFactory()).createGenerator(writer);
        generator.writeStartObject();
        {
            generator.writeStringField("code", //$NON-NLS-1$
                    code.getProduct() + '_' + code.getGroup() + '_' + code.getCode());
            generator.writeStringField("message", code.getCode()); //$NON-NLS-1$
            if (cause != null) {
                generator.writeStringField("cause", cause.getMessage()); //$NON-NLS-1$
            }
            if (context != null) {
                generator.writeFieldName("context"); //$NON-NLS-1$
                generator.writeStartObject();
                for (Map.Entry<String, Object> entry : context.entries()) {
                    generator.writeStringField(entry.getKey(), entry.getValue().toString());
                }
                generator.writeEndObject();
            }
        }
        generator.writeEndObject();
        generator.flush();
    } catch (IOException e) {
        LOGGER.error("Unable to write exception to " + writer + ".", e);
    }
}

From source file:com.rockagen.commons.util.JsonUtil.java

/**
 * return a JsonFactory if exist,else new JsonFactory
 * //from w  w w . j  ava 2  s.c o m
 * @return JsonFactory
 */
public static JsonFactory getJsonFactory() {

    JsonFactory jsonFactory = threadJsonFactory.get();
    if (jsonFactory == null) {
        jsonFactory = new JsonFactory();
        // JsonParser.Feature for configuring parsing settings:
        // to allow C/C++ style comments in JSON (non-standard, disabled by
        // default)
        jsonFactory.enable(JsonParser.Feature.ALLOW_COMMENTS);
        // to allow (non-standard) unquoted field names in JSON:
        jsonFactory.disable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
        // to allow use of apostrophes (single quotes), non standard
        jsonFactory.disable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);

        // JsonGenerator.Feature for configuring low-level JSON generation:

        // no escaping of non-ASCII characters:
        jsonFactory.disable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
        threadJsonFactory.set(jsonFactory);

    }
    return jsonFactory;
}

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

@Test
public void itGetsCaches() throws Exception {
    HttpGet httpGet = new HttpGet(
            "http://localhost:3333/crs/coveragezone/caches?deliveryServiceId=steering-target-4&cacheLocationId=location-3");

    CloseableHttpResponse response = null;
    try {//from   w  ww .  ja v  a  2 s  .c o m
        response = closeableHttpClient.execute(httpGet);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode jsonNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));

        assertThat(jsonNode.isArray(), equalTo(true));
        JsonNode cacheNode = jsonNode.get(0);
        assertThat(cacheNode.get("id").asText(), not(nullValue()));
        assertThat(cacheNode.get("fqdn").asText(), not(nullValue()));
        assertThat(cacheNode.get("ip4").asText(), not(nullValue()));
        assertThat(cacheNode.get("ip6").asText(), not(nullValue()));
        // If the value is null or otherwise not an int we'll get back -123456, so any other value returned means success
        assertThat(cacheNode.get("port").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("deliveryServices").isArray(), equalTo(true));
        assertThat(cacheNode.get("hashValues").get(0).asDouble(-1024.1024), not(equalTo(-1024.1024)));
        assertThat(cacheNode.get("available").asText(), anyOf(equalTo("true"), equalTo("false")));
    } finally {
        if (response != null)
            response.close();
    }
}

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

@Test
public void testSimpleValue() throws IOException {
    StringWriter writer = new StringWriter();
    JacksonStreamTarget target = new JacksonStreamTarget(new JsonFactory().createGenerator(writer));

    target.startArray();/*from   w  w w  . jav  a 2  s.  co  m*/
    target.value("abc");
    target.value(1234);
    target.value(true);
    target.endArray();

    target.close();

    Assert.assertEquals("[\"abc\",1234,true]", writer.toString());
}

From source file:org.messic.server.api.musicinfo.youtube.MusicInfoYoutubePlugin.java

private String search(Locale locale, String search) throws IOException {

    // http://ctrlq.org/code/19608-youtube-search-api
    // Based con code writted by Amit Agarwal

    // YouTube Data API base URL (JSON response)
    String surl = "v=2&alt=jsonc";
    // set paid-content as false to hide movie rentals
    surl = surl + "&paid-content=false";
    // set duration as long to filter partial uploads
    // url = url + "&duration=long";
    // order search results by view count
    surl = surl + "&orderby=viewCount";
    // we can request a maximum of 50 search results in a batch
    surl = surl + "&max-results=50";
    surl = surl + "&q=" + search;

    URI uri = null;/*from  ww w.ja  va  2s  . co m*/
    try {
        uri = new URI("http", "gdata.youtube.com", "/feeds/api/videos", surl, null);
    } catch (URISyntaxException e) {
        log.error("failed!", e);
    }

    URL url = new URL(uri.toASCIIString());
    log.info(surl);
    Proxy proxy = getProxy();
    URLConnection connection = (proxy != null ? url.openConnection(proxy) : url.openConnection());
    InputStream is = connection.getInputStream();

    JsonFactory jsonFactory = new JsonFactory(); // or, for data binding,
                                                 // org.codehaus.jackson.mapper.MappingJsonFactory
    JsonParser jParser = jsonFactory.createParser(is);

    String htmlCode = "<script type=\"text/javascript\">";
    htmlCode = htmlCode + "  function musicInfoYoutubeDestroy(){";
    htmlCode = htmlCode + "       $('.messic-musicinfo-youtube-overlay').remove();";
    htmlCode = htmlCode + "       $('.messic-musicinfo-youtube-iframe').remove();";
    htmlCode = htmlCode + "  }";
    htmlCode = htmlCode + "  function musicInfoYoutubePlay(id){";
    htmlCode = htmlCode
            + "      var code='<div class=\"messic-musicinfo-youtube-overlay\" onclick=\"musicInfoYoutubeDestroy()\"></div>';";
    htmlCode = htmlCode
            + "      code=code+'<iframe class=\"messic-musicinfo-youtube-iframe\" src=\"http://www.youtube.com/embed/'+id+'\" frameborder=\"0\" allowfullscreen></iframe>';";
    htmlCode = htmlCode + "      $(code).hide().appendTo('body').fadeIn();";
    htmlCode = htmlCode + "  }";
    htmlCode = htmlCode + "</script>";

    // loop until token equal to "}"
    while (jParser.nextToken() != null) {
        String fieldname = jParser.getCurrentName();
        if ("items".equals(fieldname)) {
            jParser.nextToken();
            while (jParser.nextToken() != JsonToken.END_OBJECT) {
                YoutubeItem yi = new YoutubeItem();
                while (jParser.nextToken() != JsonToken.END_OBJECT) {
                    if (jParser.getCurrentToken() == JsonToken.START_OBJECT) {
                        jParser.skipChildren();
                    }
                    fieldname = jParser.getCurrentName();

                    if ("id".equals(fieldname)) {
                        jParser.nextToken();
                        yi.id = jParser.getText();
                    }
                    if ("category".equals(fieldname)) {
                        jParser.nextToken();
                        yi.category = jParser.getText();
                    }
                    if ("title".equals(fieldname)) {
                        jParser.nextToken();
                        yi.title = jParser.getText();
                    }
                    if ("description".equals(fieldname)) {
                        jParser.nextToken();
                        yi.description = jParser.getText();
                    }
                    if ("thumbnail".equals(fieldname)) {
                        jParser.nextToken();
                        jParser.nextToken();
                        jParser.nextToken();
                        jParser.nextToken();
                        fieldname = jParser.getCurrentName();
                        if ("hqDefault".equals(fieldname)) {
                            jParser.nextToken();
                            yi.thumbnail = jParser.getText();
                        }
                        jParser.nextToken();
                    }
                }

                if (yi.category != null && "MUSIC".equals(yi.category.toUpperCase()) || (yi.category == null)) {
                    if (yi.title != null) {
                        htmlCode = htmlCode + "<div class=\"messic-musicinfo-youtube-item\"><img src=\""
                                + yi.thumbnail
                                + "\"/><div class=\"messic-musicinfo-youtube-item-play\" onclick=\"musicInfoYoutubePlay('"
                                + yi.id + "')\"></div>" + "<div class=\"messic-musicinfo-youtube-description\">"
                                + "  <div class=\"messic-musicinfo-youtube-item-title\">" + yi.title + "</div>"
                                + "  <div class=\"messic-musicinfo-youtube-item-description\">" + yi.description
                                + "</div>" + "</div>" + "</div>";
                    }
                }
            }
        }

    }
    return htmlCode;
}

From source file:com.amazonaws.hal.client.HalJsonResourceUnmarshallerTest.java

private HalResource parseHalResourceFromClasspath(String classpathFile) throws Exception {
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(classpathFile);
    JsonParser jsonParser = new JsonFactory().createJsonParser(inputStream);
    JsonUnmarshallerContext jsonUnmarshallerContext = new JsonUnmarshallerContextImpl(jsonParser);

    return HalJsonResourceUnmarshaller.getInstance().unmarshall(jsonUnmarshallerContext);
}

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

@Test
public void testNested2() throws IOException {
    JsonParser p = new JsonFactory()
            .createParser("{\"a\":{\"c\":2, \"d\":2.1, \"$type\":\"y\"}, \"$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 w  ww.jav  a  2  s  . c om*/
    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());
}