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.hbz.oerworldmap.JsonDecoder.java

@Override
public void process(final Reader reader) {
    STARTED = false;// w  w  w.  j  av a 2 s . c  o m
    JsonDecoder.LOG.debug("############################ New");
    // necessary if it is JSONP
    String text;
    try {
        text = CharStreams.toString(reader);
        this.jsonParser = new JsonFactory().createParser(text);
        // find start
        JsonToken currentToken = null;
        try {
            currentToken = this.jsonParser.nextToken();
        } catch (final JsonParseException e) {
            // assuming JSONP :
            final String callbackString = text.substring(0, text.indexOf(JsonDecoder.JSON_START_CHAR) - 1);
            text = text.substring(text.indexOf(JsonDecoder.JSON_START_CHAR), text.length() - 1);
            this.jsonParser = new JsonFactory().createParser(text);
            JsonDecoder.LOG.debug("key=" + JsonDecoder.JSON_CALLBACK + " value=" + callbackString);
            getReceiver().startRecord("");
            STARTED = true;
            JSONP = true;
            getReceiver().literal(JsonDecoder.JSON_CALLBACK, callbackString);
            JsonDecoder.LOG.debug("Text=" + text);
            currentToken = this.jsonParser.nextToken();
        }
        while (JsonToken.START_OBJECT != currentToken) {
            this.jsonParser.nextToken();
        }

        String key = null;
        while (currentToken != null) {
            if (JsonToken.START_OBJECT == currentToken) {
                if (!STARTED) {
                    getReceiver().startRecord("");
                    STARTED = true;
                }
                currentToken = this.jsonParser.nextToken();
                while (currentToken != null) {
                    if (JsonToken.FIELD_NAME == currentToken) {
                        key = this.jsonParser.getCurrentName();
                    }
                    if (JsonToken.START_ARRAY == currentToken) {
                        if (this.JSONP) {
                            currentToken = this.jsonParser.nextToken();
                            currentToken = this.jsonParser.nextToken();
                        } else {
                            currentToken = this.jsonParser.nextToken();
                            // treat objects in arrays as new objects
                            if (JsonToken.START_OBJECT == currentToken) {
                                break;
                            }
                            // values of arrays are submitted with an index
                            // so
                            // you can handle
                            // semantics in the morph
                            int i = 0;
                            while (JsonToken.END_ARRAY != currentToken) {
                                final String value = this.jsonParser.getText();
                                JsonDecoder.LOG.debug("key=" + key + i + " valueArray=" + value);
                                getReceiver().literal(key + i, value);
                                currentToken = this.jsonParser.nextToken();
                                i++;
                            }
                        }
                    }
                    if (JsonToken.START_OBJECT == currentToken) {
                        if (this.jsonParser.getCurrentName() == null) {
                            break;
                        }
                    } else {
                        handleValue(currentToken, key);
                    }
                    try {
                        currentToken = this.jsonParser.nextToken();
                    } catch (JsonParseException jpe) {
                        LOG.info(
                                "JsonParseException happens at the end of an non JSON object, e.g. if it is JSONP",
                                jpe.getMessage());
                        currentToken = null;
                        break;
                    }
                }
            }
            JsonDecoder.LOG.debug("############################ End");
            if (STARTED) {
                getReceiver().endRecord();
                STARTED = false;

            }
        }
    } catch (final IOException e) {
        throw new MetafactureException(e);

    }
}

From source file:com.krobothsoftware.commons.parse.ParserJson.java

/**
 * Parses Json Inputstream for handler. Stream is passed to Jackson parser
 * and should close after use./*  ww w.j a  va2  s  . c  o m*/
 * 
 * @param inputStream
 * @param handler
 * @throws ParseException
 * @since SNC-EXT-JSON 1.0
 */
@SuppressWarnings("resource")
public void parse(InputStream inputStream, HandlerJson handler) throws ParseException {
    if (factory == null)
        factory = new JsonFactory();
    JsonParser parser = null;
    try {
        parser = factory.createParser(inputStream);
        handler.setLogger(log);
        handler.setJsonParser(parser);
        handler.parse();
    } catch (JsonParseException e) {
        throw new ParseException(e);
    } catch (IOException e) {
        throw new ParseException(e);
    } finally {
        CommonUtils.closeQuietly(parser);
    }
}

From source file:name.osipov.alexey.server.ServerHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
            return;
        }/* w  ww. j a  v a2 s.c  o m*/

        //String passkey = req.headers().get("passkey");

        // in case of large output this buffer will demand memory
        // writing directly to channel maybe more efficient...
        ByteBufOutputStream bufstream = new ByteBufOutputStream(Unpooled.buffer());
        JsonGenerator json = new JsonFactory().createGenerator(bufstream);
        json.writeStartObject();

        HttpResponseStatus status = HttpResponseStatus.INTERNAL_SERVER_ERROR;

        switch (req.getUri()) {
        case "/register": {
            User u = users.Register();
            json.writeNumberField("id", u.getId());
            json.writeBinaryField("key", u.getKey().asBinary());
            status = HttpResponseStatus.OK;
        }
            break;

        case "/statistics": {
            String hashed_key_base64 = req.headers().get("key");
            byte[] hashed_key = Base64.decodeBase64(hashed_key_base64);
            long salt = System.currentTimeMillis() / 1000 / 30;
            User u = users.getBySaltedHash(hashed_key, salt);
            if (u != null) {
                u.requestHappen();
                json.writeNumberField("id", u.getId());
                json.writeNumberField("requests", u.getRequests());
                status = HttpResponseStatus.OK;
            } else
                status = HttpResponseStatus.UNAUTHORIZED;
        }
            break;
        }

        json.writeEndObject();
        json.close();

        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
                bufstream.buffer());
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());

        if (!HttpHeaders.isKeepAlive(req)) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

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

@Test
public void itGetsCacheLocation() throws Exception {
    HttpGet httpGet = new HttpGet(
            "http://localhost:3333/crs/coveragezone/cachelocation?ip=100.3.3.123&deliveryServiceId=steering-target-1");

    CloseableHttpResponse response = null;
    try {/* w  ww.ja v  a2s .co m*/
        response = closeableHttpClient.execute(httpGet);
        String jsonString = EntityUtils.toString(response.getEntity());
        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode jsonNode = objectMapper.readTree(jsonString);

        assertThat(jsonNode.get("id").asText(), equalTo("location-3"));
        assertThat(jsonNode.get("geolocation"), not(nullValue()));
        assertThat(jsonNode.get("caches").get(0).get("id").asText(), startsWith("edge-cache-03"));
        assertThat(jsonNode.get("caches").get(0).get("fqdn").asText(), startsWith("edge-cache-03"));
        assertThat(jsonNode.get("caches").get(0).get("fqdn").asText(), endsWith("thecdn.example.com"));
        assertThat(jsonNode.get("caches").get(0).get("port").asInt(), greaterThan(1024));
        assertThat(jsonNode.get("caches").get(0).get("hashValues").get(0).asDouble(), greaterThan(1.0));
        assertThat(isValidIpV4String(jsonNode.get("caches").get(0).get("ip4").asText()), equalTo(true));
        assertThat(jsonNode.get("caches").get(0).get("ip6").asText(), not(equalTo("")));
        assertThat(jsonNode.get("caches").get(0).has("available"), equalTo(true));
        assertThat(jsonNode.has("properties"), equalTo(true));
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:com.joliciel.jochre.search.highlight.Snippet.java

public Snippet(String json) {
    try {//from  ww  w. j a  v  a 2  s  .c o  m
        Reader reader = new StringReader(json);
        JsonFactory jsonFactory = new JsonFactory(); // or, for data binding, org.codehaus.jackson.mapper.MappingJsonFactory 
        JsonParser jsonParser = jsonFactory.createJsonParser(reader);
        jsonParser.nextToken();
        this.read(jsonParser);
    } catch (IOException e) {
        LOG.error(e);
        throw new RuntimeException(e);
    }
}

From source file:org.helm.notation2.wsadapter.MonomerWSSaver.java

/**
 * Adds or updates a single monomer to the monomer store using the URL configured in {@code MonomerStoreConfiguration}
 * .//from w  w  w  . ja v a 2  s  .c om
 * 
 * @param monomer to save
 */
public String saveMonomerToStore(Monomer monomer) {
    String res = "";
    CloseableHttpResponse response = null;

    try {
        response = WSAdapterUtils.putResource(monomer.toJSON(),
                MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesPutFullURL());
        LOG.debug(response.getStatusLine().toString());

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

        JsonParser jsonParser = jsonf.createParser(instream);

        while (!jsonParser.isClosed()) {
            JsonToken jsonToken = jsonParser.nextToken();
            if (JsonToken.FIELD_NAME.equals(jsonToken)) {
                String fieldName = jsonParser.getCurrentName();
                LOG.debug("Field name: " + fieldName);
                jsonParser.nextToken();
                if (fieldName.equals("monomerShortName")) {
                    res = jsonParser.getValueAsString();
                    break;
                }
            }
        }

        EntityUtils.consume(response.getEntity());

    } catch (Exception e) {
        LOG.error("Saving monomer failed!", e);
        return "";
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            LOG.debug("Closing resources failed.", e);
            return res;
        }
    }

    return res;
}

From source file:com.sdl.odata.unmarshaller.json.JsonLinkUnmarshaller.java

@Override
protected String getToEntityId(ODataRequestContext requestContext) throws ODataUnmarshallingException {
    // The body is expected to contain a single entity reference
    // See OData JSON specification chapter 13

    String bodyText;// w  w  w  .java 2  s .  c  om
    try {
        bodyText = requestContext.getRequest().getBodyText(StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        throw new ODataSystemException("UTF-8 is not supported", e);
    }

    String idValue = null;
    try {
        JsonParser parser = new JsonFactory().createParser(bodyText);
        while (idValue == null && !parser.isClosed()) {
            JsonToken token = parser.nextToken();
            if (token == null) {
                break;
            }

            if (token.equals(JsonToken.FIELD_NAME) && parser.getCurrentName().equals(JsonConstants.ID)) {
                token = parser.nextToken();
                if (token.equals(JsonToken.VALUE_STRING)) {
                    idValue = parser.getText();
                }
            }
        }
    } catch (IOException e) {
        throw new ODataUnmarshallingException("Error while parsing JSON data", e);
    }

    if (isNullOrEmpty(idValue)) {
        throw new ODataUnmarshallingException("The JSON object in the body has no '@odata.id' value,"
                + " or the value is empty. The JSON object in the body must have an '@odata.id' value"
                + " that refers to the entity to link to.");
    }

    return idValue;
}

From source file:org.apache.orc.bench.convert.json.JsonWriter.java

public JsonWriter(Path path, TypeDescription schema, Configuration conf, CompressionKind compression)
        throws IOException {
    OutputStream file = path.getFileSystem(conf).create(path, true);
    outStream = new OutputStreamWriter(compression.create(file), StandardCharsets.UTF_8);
    JsonFactory factory = new JsonFactory();
    factory.setRootValueSeparator("\n");
    writer = factory.createGenerator(outStream);
    this.schema = schema;
}

From source file:msearch.io.MSFilmlisteSchreiben.java

public void filmlisteSchreibenJson(String datei, ListeFilme listeFilme) {
    MSLog.systemMeldung("Filme Schreiben (" + listeFilme.size() + " Filme) :");
    File file = new File(datei);
    File dir = new File(file.getParent());
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            MSLog.fehlerMeldung(915236478, MSLog.FEHLER_ART_PROG,
                    "MSearchIoXmlFilmlisteSchreiben.xmlSchreibenStart",
                    "Kann den Pfad nicht anlegen: " + dir.toString());
        }/*  www . j a v a2 s.  c o  m*/
    }
    MSLog.systemMeldung("   --> Start Schreiben nach: " + datei);
    try {
        String sender = "", thema = "";
        JsonFactory jsonF = new JsonFactory();
        JsonGenerator jg;
        if (datei.endsWith(MSConst.FORMAT_XZ)) {
            LZMA2Options options = new LZMA2Options();
            XZOutputStream out = new XZOutputStream(new FileOutputStream(file), options);
            jg = jsonF.createGenerator(out);
        } else if (datei.endsWith(MSConst.FORMAT_BZ2)) {
            bZip2CompressorOutputStream = new BZip2CompressorOutputStream(new FileOutputStream(file),
                    9 /*Blocksize: 1 - 9*/);
            jg = jsonF.createGenerator(bZip2CompressorOutputStream, JsonEncoding.UTF8);
        } else if (datei.endsWith(MSConst.FORMAT_ZIP)) {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
            ZipEntry entry = new ZipEntry(MSConst.XML_DATEI_FILME);
            zipOutputStream.putNextEntry(entry);
            jg = jsonF.createGenerator(zipOutputStream, JsonEncoding.UTF8);
        } else {
            jg = jsonF.createGenerator(new File(datei), JsonEncoding.UTF8);
        }
        jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier
        jg.writeStartObject();
        // Infos zur Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < ListeFilme.MAX_ELEM; ++i) {
            jg.writeString(listeFilme.metaDaten[i]);
        }
        jg.writeEndArray();
        // Infos der Felder in der Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
            jg.writeString(DatenFilm.COLUMN_NAMES[DatenFilm.COLUMN_NAMES_JSON[i]]);
        }
        jg.writeEndArray();
        //Filme schreiben
        ListIterator<DatenFilm> iterator;
        DatenFilm datenFilm;
        iterator = listeFilme.listIterator();
        while (iterator.hasNext()) {
            datenFilm = iterator.next();
            jg.writeArrayFieldStart(DatenFilm.FILME_);
            for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
                int m = DatenFilm.COLUMN_NAMES_JSON[i];
                if (m == DatenFilm.FILM_SENDER_NR) {
                    if (datenFilm.arr[m].equals(sender)) {
                        jg.writeString("");
                    } else {
                        sender = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else if (m == DatenFilm.FILM_THEMA_NR) {
                    if (datenFilm.arr[m].equals(thema)) {
                        jg.writeString("");
                    } else {
                        thema = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else {
                    jg.writeString(datenFilm.arr[m]);
                }
            }
            jg.writeEndArray();
        }
        jg.writeEndObject();
        jg.close();
        MSLog.systemMeldung("   --> geschrieben!");
    } catch (Exception ex) {
        MSLog.fehlerMeldung(846930145, MSLog.FEHLER_ART_PROG, "IoXmlSchreiben.FilmeSchreiben", ex,
                "nach: " + datei);
    }
}

From source file:msearch.filmlisten.MSFilmlisteSchreiben.java

public void filmlisteSchreibenJson(String datei, ListeFilme listeFilme) {
    MSLog.systemMeldung("Filme schreiben (" + listeFilme.size() + " Filme) :");
    File file = new File(datei);
    File dir = new File(file.getParent());
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            MSLog.fehlerMeldung(915236478, MSLog.FEHLER_ART_PROG,
                    "MSearchIoXmlFilmlisteSchreiben.xmlSchreibenStart",
                    "Kann den Pfad nicht anlegen: " + dir.toString());
        }/*from w w w  .  j a  va  2s  .  c  o m*/
    }
    MSLog.systemMeldung("   --> Start Schreiben nach: " + datei);
    try {
        String sender = "", thema = "";
        JsonFactory jsonF = new JsonFactory();
        JsonGenerator jg;
        if (datei.endsWith(MSConst.FORMAT_XZ)) {
            LZMA2Options options = new LZMA2Options();
            XZOutputStream out = new XZOutputStream(new FileOutputStream(file), options);
            jg = jsonF.createGenerator(out);
        } else if (datei.endsWith(MSConst.FORMAT_BZ2)) {
            bZip2CompressorOutputStream = new BZip2CompressorOutputStream(new FileOutputStream(file),
                    9 /*Blocksize: 1 - 9*/);
            jg = jsonF.createGenerator(bZip2CompressorOutputStream, JsonEncoding.UTF8);
        } else if (datei.endsWith(MSConst.FORMAT_ZIP)) {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
            ZipEntry entry = new ZipEntry(MSConst.XML_DATEI_FILME);
            zipOutputStream.putNextEntry(entry);
            jg = jsonF.createGenerator(zipOutputStream, JsonEncoding.UTF8);
        } else {
            jg = jsonF.createGenerator(new File(datei), JsonEncoding.UTF8);
        }
        jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier
        jg.writeStartObject();
        // Infos zur Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < ListeFilme.MAX_ELEM; ++i) {
            jg.writeString(listeFilme.metaDaten[i]);
        }
        jg.writeEndArray();
        // Infos der Felder in der Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
            jg.writeString(DatenFilm.COLUMN_NAMES[DatenFilm.COLUMN_NAMES_JSON[i]]);
        }
        jg.writeEndArray();
        //Filme schreiben
        ListIterator<DatenFilm> iterator;
        DatenFilm datenFilm;
        iterator = listeFilme.listIterator();
        while (iterator.hasNext()) {
            datenFilm = iterator.next();
            jg.writeArrayFieldStart(DatenFilm.FILME_);
            for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
                int m = DatenFilm.COLUMN_NAMES_JSON[i];
                if (m == DatenFilm.FILM_SENDER_NR) {
                    if (datenFilm.arr[m].equals(sender)) {
                        jg.writeString("");
                    } else {
                        sender = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else if (m == DatenFilm.FILM_THEMA_NR) {
                    if (datenFilm.arr[m].equals(thema)) {
                        jg.writeString("");
                    } else {
                        thema = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else {
                    jg.writeString(datenFilm.arr[m]);
                }
            }
            jg.writeEndArray();
        }
        jg.writeEndObject();
        jg.close();
        MSLog.systemMeldung("   --> geschrieben!");
    } catch (Exception ex) {
        MSLog.fehlerMeldung(846930145, MSLog.FEHLER_ART_PROG, "IoXmlSchreiben.FilmeSchreiben", ex,
                "nach: " + datei);
    }
}