Example usage for com.fasterxml.jackson.core JsonFactory createParser

List of usage examples for com.fasterxml.jackson.core JsonFactory createParser

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonFactory createParser.

Prototype

public JsonParser createParser(String content) throws IOException, JsonParseException 

Source Link

Document

Method for constructing parser for parsing contents of given String.

Usage

From source file:name.gumartinm.weather.information.parser.JPOSForecastParser.java

public Forecast retrieveForecastFromJPOS(final String jsonData) throws JsonParseException, IOException {
    final JsonFactory f = new JsonFactory();

    final Forecast forecastWeatherData = new Forecast();
    forecastWeatherData.setList(new ArrayList<List>(15));
    final City city = new City();
    city.setCoord(new Coord());
    forecastWeatherData.setCity(city);/* w  w  w  .ja  va 2  s .  c  om*/
    final JsonParser jParser = f.createParser(jsonData);

    this.getForecastWeatherData(forecastWeatherData, jParser);

    return forecastWeatherData;
}

From source file:org.ojai.json.impl.JsonDocumentStream.java

public JsonDocumentStream(InputStream in, Map<FieldPath, Type> fieldPathTypeMap,
        Events.Delegate eventDelegate) {
    inputStream = in;//from w  w  w .ja  v a2 s .  co m
    readStarted = false;
    iteratorOpened = false;
    this.eventDelegate = eventDelegate;
    this.fieldPathTypeMap = fieldPathTypeMap;
    try {
        JsonFactory jFactory = new JsonFactory();
        /* setting explicitly AUTO_CLOSE_SOURCE = false to ensure that
         * jsonParser.close() do not close the underlying inputstream.
         * It has to be closed by the owner of the stream.
         */
        jFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
        jsonParser = jFactory.createParser(inputStream);
    } catch (IOException e) {
        throw new DecodingException(e);
    }
}

From source file:kr.ac.postech.lispconfig.LispConfigManager.java

public boolean registerDevice(String address, String port) {
    log.info("{} {}", address, port);
    InputStream is = null;//ww  w . java  2s  . c  om
    try {
        is = context.getBundleContext().getBundle().getEntry(DEVICE_CFG_JSON).openStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jsonFactory = mapper.getFactory();
    JsonParser jsonParser = null;
    try {
        jsonParser = jsonFactory.createParser(is);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JsonNode jsonNode = null;
    try {
        jsonNode = mapper.readTree(jsonParser);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JsonNode deviceRoot = jsonNode.get(DEVICE_SUBJECT_CLASS_KEY);

    String deviceName = deviceRoot.fieldNames().next();
    JsonNode removed = ((ObjectNode) deviceRoot).remove(deviceName);

    String newDeviceName = "netconf:" + address + ":" + port;
    ((ObjectNode) deviceRoot).set(newDeviceName, removed);

    DeviceId deviceId = DeviceId.deviceId(newDeviceName);

    JsonNode subjectNode = deviceRoot.path(newDeviceName);

    Object result = cfgService.applyConfig(DEVICE_SUBJECT_CLASS_KEY, deviceId, DEVICE_CONFIG_KEY,
            subjectNode.get(DEVICE_CONFIG_KEY));
    return result != null ? true : false;
}

From source file:kr.ac.postech.lispconfig.LispConfigManager.java

public boolean configureDevice(String name, String password, String address, String port) {
    ApplicationId netConfAppId = coreService.getAppId(NETCONF_APP_NAME);

    InputStream is = null;/*from w  w w  .j  av a2 s .  c  o  m*/
    try {
        is = context.getBundleContext().getBundle().getEntry(DEVICE_CFG_JSON).openStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jsonFactory = mapper.getFactory();
    JsonParser jsonParser = null;
    try {
        jsonParser = jsonFactory.createParser(is);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JsonNode jsonNode = null;
    try {
        jsonNode = mapper.readTree(jsonParser);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JsonNode appRoot = jsonNode.get(APP_SUBJECT_CLASS_KEY);
    appRoot = appRoot.get(NETCONF_APP_NAME);

    jsonNode = appRoot.get(APP_CONFIG_KEY).get(0);

    ((ObjectNode) jsonNode).put("name", name);
    ((ObjectNode) jsonNode).put("password", password);
    ((ObjectNode) jsonNode).put("ip", address);
    ((ObjectNode) jsonNode).put("port", port);

    log.info(appRoot.toString());

    Object result = cfgService.applyConfig(APP_SUBJECT_CLASS_KEY, netConfAppId, APP_CONFIG_KEY,
            appRoot.path(APP_CONFIG_KEY));

    return result != null ? true : false;
}

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;//w ww .j av  a  2  s.c  o 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.netflix.hollow.jsonadapter.HollowJsonAdapter.java

public int processRecord(String singleRecord) throws IOException {
    JsonFactory factory = new JsonFactory();
    JsonParser parser = factory.createParser(new StringReader(singleRecord));
    return processRecord(parser);
}

From source file:com.github.jonpeterson.jackson.module.versioning.VersionedModelSerializer.java

private void doSerialize(T value, JsonGenerator generator, SerializerProvider provider,
        TypeSerializer typeSerializer) throws IOException {
    // serialize the value into a byte array buffer then parse it back out into a JsonNode tree
    // TODO: find a better way to convert the value into a tree
    JsonFactory factory = generator.getCodec().getFactory();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096);
    JsonGenerator bufferGenerator = factory.createGenerator(buffer);
    try {/*from   w  w  w  . j a v  a 2 s  . c om*/
        if (typeSerializer != null)
            delegate.serializeWithType(value, bufferGenerator, provider, typeSerializer);
        else
            delegate.serialize(value, bufferGenerator, provider);
    } finally {
        bufferGenerator.close();
    }

    ObjectNode modelData = factory.createParser(buffer.toByteArray()).readValueAsTree();

    // set target version to @SerializeToVersion's value, @JsonVersionModel's defaultSerializeToVersion, or
    //   @JsonVersionModel's currentVersion in that order
    String targetVersion = null;
    if (serializeToVersionProperty != null) {
        targetVersion = (String) serializeToVersionProperty.getAccessor().getValue(value);
        modelData.remove(serializeToVersionProperty.getName());
    }
    if (targetVersion == null)
        targetVersion = jsonVersionedModel.defaultSerializeToVersion();
    if (targetVersion.isEmpty())
        targetVersion = jsonVersionedModel.currentVersion();

    // convert model data if there is a converter and targetVersion is different than the currentVersion or if
    //   alwaysConvert is true
    if (converter != null && (jsonVersionedModel.alwaysConvert()
            || !targetVersion.equals(jsonVersionedModel.currentVersion())))
        modelData = converter.convert(modelData, jsonVersionedModel.currentVersion(), targetVersion,
                JsonNodeFactory.instance);

    // add target version to model data if it wasn't the version to suppress
    if (!targetVersion.equals(jsonVersionedModel.versionToSuppressPropertySerialization()))
        modelData.put(jsonVersionedModel.propertyName(), targetVersion);

    // write node
    generator.writeTree(modelData);
}

From source file:name.gumartinm.weather.information.parser.JPOSCurrentParser.java

public Current retrieveCurrenFromJPOS(final String jsonData) throws JsonParseException, IOException {
    final JsonFactory f = new JsonFactory();

    final Current currentWeatherData = new Current();
    currentWeatherData.setClouds(new Clouds());
    currentWeatherData.setCoord(new Coord());
    currentWeatherData.setMain(new Main());
    currentWeatherData.setRain(new Rain());
    currentWeatherData.setSys(new Sys());
    currentWeatherData.setSnow(new Snow());
    currentWeatherData.setWeather(new ArrayList<Weather>());
    currentWeatherData.setWind(new Wind());
    final JsonParser jParser = f.createParser(jsonData);

    this.getCurrentWeatherData(currentWeatherData, jParser);

    return currentWeatherData;
}

From source file:com.quinsoft.zeidon.standardoe.ActivateOisFromJsonStream.java

public List<View> read() {
    try {// w w  w  . java  2 s  .  c  o  m
        JsonFactory jsonFactory = new JsonFactory();
        jp = jsonFactory.createParser(stream);
        jp.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);

        // Read the START_OBJECT
        JsonToken token = jp.nextToken();
        if (token != JsonToken.START_OBJECT)
            throw new ZeidonException("OI JSON stream doesn't start with object.");

        token = jp.nextToken();
        if (token != JsonToken.FIELD_NAME)
            throw new ZeidonException("OI JSON missing OI field name.");

        String fieldName = jp.getCurrentName();
        if (fieldName.equals(".meta")) {
            readFileMeta();

            JsonReader reader = getReaderForVersion();
            reader.process();
        } else {
            if (StringUtils.equalsIgnoreCase(fieldName, "version")) {
                token = jp.nextToken(); // Move to value.
                version = jp.getValueAsString();
                token = jp.nextToken(); // Move to next field name.
                assert token == JsonToken.FIELD_NAME;
                fieldName = jp.getCurrentName();
            } else if (StringUtils.isBlank(options.getVersion())) {
                throw new ZeidonException("First field must be version");
            }

            totalRootCount = null;
            if (StringUtils.equalsIgnoreCase(fieldName, "totalRootCount")) {
                token = jp.nextToken(); // Move to value.
                totalRootCount = jp.getValueAsInt();
                token = jp.nextToken(); // Move to next field name.
                assert token == JsonToken.FIELD_NAME;
                fieldName = jp.getCurrentName();
            }

            if (lodDef == null)
                throw new ZeidonException("JSON stream appears to start with the root entity name (%s)"
                        + " but the LodDef has not been specified.", fieldName);

            String rootName = lodDef.getRoot().getName();
            if (!fieldName.equalsIgnoreCase(rootName))
                throw new ZeidonException("The first field in the JSON stream must be the root entity name"
                        + " (%s) or '.meta' but was %s.", rootName, fieldName);

            view = task.activateEmptyObjectInstance(lodDef);
            returnList.add(view);
            if (totalRootCount != null)
                view.setTotalRootCount(totalRootCount);

            JsonReader reader = getSimpleReaderForVersion();
            reader.process();
        }

        jp.close();
    } catch (Exception e) {
        ZeidonException ze = ZeidonException.wrapException(e);
        JsonLocation loc = jp.getCurrentLocation();
        JsonToken token = jp.getCurrentToken();
        ze.appendMessage("Position line=%d col=%d, token=%s", loc.getLineNr(), loc.getColumnNr(),
                token == null ? "No Token" : token.name());
        throw ze;
    }

    return returnList;
}