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

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

Introduction

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

Prototype

@Deprecated
public JsonParser createJsonParser(String content) throws IOException, JsonParseException 

Source Link

Document

Method for constructing parser for parsing contents of given String.

Usage

From source file:org.oscim.utils.overpass.OverpassAPIReader.java

public void parse(InputStream in) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    try {//from   ww  w.j  av  a 2  s.  c  om
        JsonParser jp = jsonFactory.createJsonParser(in);

        JsonToken t;
        while ((t = jp.nextToken()) != null) {
            if (t == JsonToken.START_OBJECT) {
                jp.nextToken();

                String name = jp.getCurrentName();
                jp.nextToken();

                if ("type".equals(name)) {
                    String type = jp.getText();

                    if ("node".equals(type))
                        parseNode(jp);

                    else if ("way".equals(type))
                        parseWay(jp);

                    else if ("relation".equals(type))
                        parseRelation(jp);
                }
            }
        }
    } catch (JsonParseException e) {
        e.printStackTrace();
    }
}

From source file:net.floodlightcontroller.cli.commands.ShowSwitchCmd.java

/**
 * Parses a JSON string and decomposes all JSON arrays and objects. Stores the
 * resulting strings in a nested Map of string objects.
 * //  www . j  a v a2s  . co m
 * @param jsonString
 */
@SuppressWarnings("unchecked")
private List<Map<String, Object>> parseJson(String jsonString) throws IOException {
    /* The Jackson JSON parser. */
    JsonParser jp;
    /* The Jackson JSON factory. */
    JsonFactory f = new JsonFactory();
    /* The Jackson object mapper. */
    ObjectMapper mapper = new ObjectMapper();
    /* A list of JSON data objects retrieved by using the REST API. */
    List<Map<String, Object>> jsonData = new ArrayList<Map<String, Object>>();

    try {
        jp = f.createJsonParser(jsonString);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }

    // Move to the first object in the array.
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_ARRAY) {
        throw new IOException("Expected START_ARRAY instead of " + jp.getCurrentToken());
    }

    // Retrieve the information from JSON
    while (jp.nextToken() == JsonToken.START_OBJECT) {
        jsonData.add(mapper.readValue(jp, Map.class));
    }

    // Close the JSON parser.
    jp.close();

    // Return.
    return jsonData;
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

@Override
protected Integer doInBackground(Void... params) {

    SharedPreferences prefs = dataService.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE);

    // Connectivity receiver.
    final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
    ComponentName receiver = new ComponentName(dataService, WifiReceiver.class);
    PackageManager pm = dataService.getPackageManager();
    if (activeNetwork == null || !activeNetwork.isConnected()) {
        // We've missed a scheduled update. Enable the receiver so it can launch an update when we reconnect.
        Log.d(LOG_TAG, "Missed library update: not connected. Enabling connectivity receiver.");
        pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
        return RESULT_CODE_FAILURE;
    } else {/*from w w  w  .j  ava 2 s.  co m*/
        // We are connected. Disable the receiver.
        Log.d(LOG_TAG, "Library updater connected. Disabling connectivity receiver.");
        pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }

    InputStream in = null;
    String etag = prefs.getString(SETTING_LIBRARY_ETAG, null);

    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        if (etag != null && !force) {
            conn.setRequestProperty("If-None-Match", etag);
        }

        int code = conn.getResponseCode();
        switch (code) {
        case HttpStatus.SC_NOT_MODIFIED:
            // If we got a 304, we're done.
            // Use failure code to indicate there is no temp db to copy over.
            Log.d(LOG_TAG, "304 in library response.");
            return RESULT_CODE_FAILURE;
        default:
            // Odd, but on 1/3/13 I received correct json responses with a -1 for responseCode. Fall through.
            Log.w(LOG_TAG, "Error code in library response: " + code);
        case HttpStatus.SC_OK:
            // Parse response.
            in = conn.getInputStream();
            JsonFactory factory = new JsonFactory();
            final JsonParser parser = factory.createJsonParser(in);

            SQLiteDatabase tempDb = tempDbHelper.getWritableDatabase();
            tempDb.beginTransaction();
            try {
                tempDb.execSQL("delete from topic");
                tempDb.execSQL("delete from topicvideo");
                tempDb.execSQL("delete from video");

                parseObject(parser, tempDb, null, 0);
                tempDb.setTransactionSuccessful();
            } catch (Exception e) {
                e.printStackTrace();
                return RESULT_CODE_FAILURE;
            } finally {
                tempDb.endTransaction();
                tempDb.close();
            }

            // Save etag once we've successfully parsed the response.
            etag = conn.getHeaderField("ETag");
            prefs.edit().putString(SETTING_LIBRARY_ETAG, etag).apply();

            // Move this new content from the temp db into the main one.
            mergeDbs();

            return RESULT_CODE_SUCCESS;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        tempDbHelper.close();
    }

    return RESULT_CODE_FAILURE;
}

From source file:org.apache.hadoop.hbase.rest.TestTableScan.java

@Test
public void testStreamingJSON() throws Exception {
    //Test with start row and end row.
    StringBuilder builder = new StringBuilder();
    builder.append("/*");
    builder.append("?");
    builder.append(Constants.SCAN_COLUMN + "=" + COLUMN_1);
    builder.append("&");
    builder.append(Constants.SCAN_START_ROW + "=aaa");
    builder.append("&");
    builder.append(Constants.SCAN_END_ROW + "=aay");
    Response response = client.get("/" + TABLE + builder.toString(), Constants.MIMETYPE_JSON);
    assertEquals(200, response.getCode());

    int count = 0;
    ObjectMapper mapper = new JacksonJaxbJsonProvider().locateMapper(CellSetModel.class,
            MediaType.APPLICATION_JSON_TYPE);
    JsonFactory jfactory = new JsonFactory(mapper);
    JsonParser jParser = jfactory.createJsonParser(response.getStream());
    boolean found = false;
    while (jParser.nextToken() != JsonToken.END_OBJECT) {
        if (jParser.getCurrentToken() == JsonToken.START_OBJECT && found) {
            RowModel row = jParser.readValueAs(RowModel.class);
            assertNotNull(row.getKey());
            for (int i = 0; i < row.getCells().size(); i++) {
                if (count == 0) {
                    assertEquals("aaa", Bytes.toString(row.getKey()));
                }/*from www .j  a  va  2  s. c o  m*/
                if (count == 23) {
                    assertEquals("aax", Bytes.toString(row.getKey()));
                }
                count++;
            }
            jParser.skipChildren();
        } else {
            found = jParser.getCurrentToken() == JsonToken.START_ARRAY;
        }
    }
    assertEquals(24, count);
}

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

/**
 * Loads the monomer store using the URL configured in
 * {@code MonomerStoreConfiguration} and the polymerType that was given to
 * constructor.// w w  w . j  a va2s. c  o m
 *
 * @param attachmentDB the attachments stored in Toolkit.
 *
 * @return Map containing monomers
 *
 * @throws IOException
 * @throws URISyntaxException
 * @throws EncoderException
 */
public Map<String, Monomer> loadMonomerStore(Map<String, Attachment> attachmentDB)
        throws IOException, URISyntaxException, EncoderException {
    Map<String, Monomer> monomers = new HashMap<String, Monomer>();

    CloseableHttpClient httpclient = HttpClients.createDefault();
    // There is no need to provide user credentials
    // HttpClient will attempt to access current user security context
    // through Windows platform specific methods via JNI.
    CloseableHttpResponse response = null;
    try {
        HttpGet httpget = new HttpGet(new URIBuilder(
                MonomerStoreConfiguration.getInstance().getWebserviceMonomersFullURL() + polymerType).build());

        LOG.debug("Executing request " + httpget.getRequestLine());
        response = httpclient.execute(httpget);
        LOG.debug(response.getStatusLine().toString());

        JsonFactory jsonf = new JsonFactory();
        InputStream instream = response.getEntity().getContent();
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new MonomerLoadingException("Response from the Webservice throws an error");
        }
        JsonParser jsonParser = jsonf.createJsonParser(instream);
        monomers = deserializeMonomerStore(jsonParser, attachmentDB);
        LOG.debug(monomers.size() + " " + polymerType + " monomers loaded");

        EntityUtils.consume(response.getEntity());

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

    return monomers;
}

From source file:to.sparks.mtgox.service.WebsocketClientService.java

@Override
public void onApplicationEvent(PacketEvent event) {
    JSONObject op = (JSONObject) event.getPayload();

    try {/*www .j ava  2 s  .c  om*/
        // logger.fine(aPacket.getUTF8());

        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper();

        //                    JsonParser jp = factory.createJsonParser(aPacket.getUTF8());
        //                    DynaBean op = mapper.readValue(jp, DynaBean.class);

        if (op.get("op") != null && op.get("op").equals("private")) {
            String messageType = op.get("private").toString();
            if (messageType.equalsIgnoreCase("ticker")) {
                OpPrivateTicker opPrivateTicker = mapper.readValue(factory.createJsonParser(op.toString()),
                        OpPrivateTicker.class);
                Ticker ticker = opPrivateTicker.getTicker();
                tickerEvent(ticker);
                logger.log(Level.FINE, "Ticker: last: {0}", new Object[] { ticker.getLast().toPlainString() });
            } else if (messageType.equalsIgnoreCase("depth")) {
                OpPrivateDepth opPrivateDepth = mapper.readValue(factory.createJsonParser(op.toString()),
                        OpPrivateDepth.class);
                Depth depth = opPrivateDepth.getDepth();
                depthEvent(depth);
                logger.log(Level.FINE, "Depth total volume: {0}",
                        new Object[] { depth.getTotalVolume().toPlainString() });
            } else if (messageType.equalsIgnoreCase("trade")) {
                OpPrivateTrade opPrivateTrade = mapper.readValue(factory.createJsonParser(op.toString()),
                        OpPrivateTrade.class);
                Trade trade = opPrivateTrade.getTrade();
                tradeEvent(trade);
                logger.log(Level.FINE, "Trade currency: {0}", new Object[] { trade.getPrice_currency() });
            } else {
                logger.log(Level.WARNING, "Unknown private operation: {0}", new Object[] { op.toString() });
            }

            // logger.log(Level.INFO, "messageType: {0}, payload: {1}", new Object[]{messageType, dataPayload});
        } else {
            logger.log(Level.WARNING, "Unknown operation: {0}, payload: {1}",
                    new Object[] { op.get("op"), op.toString() });
            // TODO:  Process the following types
            // subscribe
            // unsubscribe
            // remark
            // result
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, null, ex);
    }

}

From source file:org.wikimedia.analytics.kraken.schemas.JsonToClassConverter.java

/**
 * @param className refers to the name of the class that maps to the JSON file. Make sure that
 * all properties in the JSON file are defined in the Java class, else it will throw an error
 * @param file contains the name of the JSON file to be loaded. The default place to put this
 * file is in the src/main/resource folder
 * @param key name of the field from the JSON object that should be used as key to store the
 * JSON object in the HashMap. Suppose the field containing the key is called 'foo' then the
 * java Class should have a getter called getFoo.
 * @return//from w ww .jav a  2  s . co  m
 * @throws JsonMappingException
 * @throws JsonParseException
 */
public final HashMap<String, Schema> construct(final String className, final String file, final String key)
        throws JsonMappingException, JsonParseException {
    JsonFactory jfactory = new JsonFactory();
    HashMap<String, Schema> map = new HashMap<String, Schema>();
    List<Schema> schemas = null;
    InputStream input;
    JavaType type;
    ObjectMapper mapper = new ObjectMapper();

    try {
        Schema schema = (Schema) Schema.class.getClassLoader().loadClass(className).newInstance();

        input = schema.getClass().getClassLoader().getResourceAsStream(file);

        type = mapper.getTypeFactory().constructCollectionType(List.class, schema.getClass());
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    try {
        JsonParser jParser = jfactory.createJsonParser(input);
        schemas = mapper.readValue(jParser, type);
    } catch (IOException e) {
        System.err.println("Specified file could not be found.");
    } finally {
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException e) {
            System.err.println("Could not close filestream");
        }
    }
    if (schemas != null) {
        for (Schema schemaInstance : schemas) {
            try {
                Method getKey = schemaInstance.getClass().getMethod(key);
                map.put(getKey.invoke(schemaInstance).toString(), schemaInstance);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                System.err.println("Specified key is not a valid Getter for " + className);
            }
        }
    }
    return map;
}