Example usage for com.fasterxml.jackson.core JsonParser nextToken

List of usage examples for com.fasterxml.jackson.core JsonParser nextToken

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonParser nextToken.

Prototype

public abstract JsonToken nextToken() throws IOException, JsonParseException;

Source Link

Document

Main iteration method, which will advance stream enough to determine type of the next token, if any.

Usage

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Parses one position//from w w  w  .  jav a 2  s.c  o  m
 *
 * Syntax:
 *
 * { "type": "Point", "coordinates": [100.0, 0.0] }
 *
 * @param jsParser
 * @throws IOException
 * @return Point
 */
private Point parsePoint(JsonParser jp) throws IOException, SQLException {
    jp.nextToken(); // FIELD_NAME coordinates        
    String coordinatesField = jp.getText();
    if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
        jp.nextToken(); // START_ARRAY [ to parse the coordinate
        Point point = GF.createPoint(parseCoordinate(jp));
        return point;
    } else {
        throw new SQLException(
                "Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
    }
}

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Parses an array of positions//from  w  w w. j av  a2 s.c o  m
 *
 * Syntax:
 *
 * { "type": "MultiPoint", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] }
 *
 * @param jsParser
 * @throws IOException
 * @return MultiPoint
 */
private MultiPoint parseMultiPoint(JsonParser jp) throws IOException, SQLException {
    jp.nextToken(); // FIELD_NAME coordinates        
    String coordinatesField = jp.getText();
    if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
        jp.nextToken(); // START_ARRAY [ coordinates
        MultiPoint mPoint = GF.createMultiPoint(parseCoordinates(jp));
        jp.nextToken();//END_OBJECT } geometry
        return mPoint;
    } else {
        throw new SQLException(
                "Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
    }
}

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 *
 * Parse the array of positions./*from  www .j ava  2 s  .co m*/
 *
 * Syntax:
 *
 * { "type": "LineString", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] }
 *
 * @param jsParser
 */
private LineString parseLinestring(JsonParser jp) throws IOException, SQLException {
    jp.nextToken(); // FIELD_NAME coordinates        
    String coordinatesField = jp.getText();
    if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
        jp.nextToken(); // START_ARRAY [ coordinates
        LineString line = GF.createLineString(parseCoordinates(jp));
        jp.nextToken();//END_OBJECT } geometry
        return line;
    } else {
        throw new SQLException(
                "Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
    }
}

From source file:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java

public void importCalendarContent(final JsonParser jsonParser, final Resource resource) throws IOException {
    if (jsonParser.getCurrentToken().equals(JsonToken.START_ARRAY)) {
        jsonParser.nextToken(); // skip START_ARRAY here
    } else {//w w  w  .  j ava 2  s  .  c  om
        throw new IOException("Improperly formed JSON - expected an START_ARRAY token, but got "
                + jsonParser.getCurrentToken().toString());
    }
    if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
        while (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
            extractEvent(jsonParser, resource);
            jsonParser.nextToken(); // get the next token - either a start object token or an end array token
        }
    } else {
        throw new IOException("Improperly formed JSON - expected an OBJECT_START token, but got "
                + jsonParser.getCurrentToken().toString());
    }
}

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Each element in the geometries array of a GeometryCollection is one of
 * the geometry objects described above:
 *
 * { "type": "GeometryCollection", "geometries": [ { "type": "Point",
 * "coordinates": [100.0, 0.0] }, { "type": "LineString", "coordinates": [
 * [101.0, 0.0], [102.0, 1.0] ] } ]/*from w ww .ja  v a  2 s.co  m*/
 *
 * @param jp
 *
 * @throws IOException
 * @throws SQLException
 * @return GeometryCollection
 */
private GeometryCollection parseGeometryCollection(JsonParser jp) throws IOException, SQLException {
    jp.nextToken(); // FIELD_NAME geometries        
    String coordinatesField = jp.getText();
    if (coordinatesField.equalsIgnoreCase(GeoJsonField.GEOMETRIES)) {
        jp.nextToken();//START array
        jp.nextToken();//START object
        ArrayList<Geometry> geometries = new ArrayList<Geometry>();
        while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
            geometries.add(parseGeometry(jp));
            jp.nextToken();
        }
        jp.nextToken();//END_OBJECT } geometry
        return GF.createGeometryCollection(geometries.toArray(new Geometry[geometries.size()]));
    } else {
        throw new SQLException(
                "Malformed GeoJSON file. Expected 'geometries', found '" + coordinatesField + "'");
    }

}

From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java

protected Object deserializeWithView(JsonParser jp, DeserializationContext ctxt, Object bean,
        Class<?> activeView) throws IOException {
    beanDeserializerAdvice.before(bean, jp, ctxt);
    JsonToken t = jp.getCurrentToken();//from w  w w .  j av  a 2 s. c  o m
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        String propName = jp.getCurrentName();
        // Skip field name:
        jp.nextToken();

        if (beanDeserializerAdvice.intercept(bean, propName, jp, ctxt)) {
            continue;
        }

        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) {
            if (!prop.visibleInView(activeView)) {
                jp.skipChildren();
                continue;
            }
            try {
                prop.deserializeAndSet(jp, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
        handleUnknownVanilla(jp, ctxt, bean, propName);
    }
    beanDeserializerAdvice.after(bean, jp, ctxt);
    return bean;
}

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Parses an array of positions defined as:
 *
 * { "type": "MultiLineString", "coordinates": [ [ [100.0, 0.0], [101.0,
 * 1.0] ], [ [102.0, 2.0], [103.0, 3.0] ] ] }
 *
 * @param jsParser/*from   ww w .j  av a  2  s. com*/
 * @return MultiLineString
 */
private MultiLineString parseMultiLinestring(JsonParser jp) throws IOException, SQLException {
    jp.nextToken(); // FIELD_NAME coordinates        
    String coordinatesField = jp.getText();
    if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
        ArrayList<LineString> lineStrings = new ArrayList<LineString>();
        jp.nextToken();//START_ARRAY [ coordinates
        jp.nextToken(); // START_ARRAY [ coordinates line
        while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
            lineStrings.add(GF.createLineString(parseCoordinates(jp)));
            jp.nextToken();
        }
        MultiLineString line = GF
                .createMultiLineString(lineStrings.toArray(new LineString[lineStrings.size()]));
        jp.nextToken();//END_OBJECT } geometry
        return line;
    } else {
        throw new SQLException(
                "Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
    }

}

From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java

/**
 * Main deserialization method for bean-based objects (POJOs).
 * <p/>/*from   ww w. ja  va2  s  . c om*/
 * NOTE: was declared 'final' in 2.2; should NOT be to let extensions
 * like Afterburner change definition.
 */
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken t = jp.getCurrentToken();
    // common case first:
    if (t == JsonToken.START_OBJECT) {
        if (_vanillaProcessing) {
            return vanillaDeserialize(jp, ctxt, jp.nextToken());
        }
        jp.nextToken();
        if (_objectIdReader != null) {
            return deserializeWithObjectId(jp, ctxt);
        }
        return deserializeFromObject(jp, ctxt);
    }
    return _deserializeOther(jp, ctxt, t);
}

From source file:mobile.tiis.appv2.LoginActivity.java

/**
 * This method will take the url built to use the webservice
 * and will try to parse JSON from the webservice stream to get
 * the user and password if they are correct or not. In case correct, fills
 * the Android Account Manager./*from  w ww.j a va  2  s .com*/
 *
 * <p>This method will throw a Toast message when user and password
 * are not valid
 *
 */

protected void startWebService(final CharSequence loginURL, final String username, final String password) {
    client.setBasicAuth(username, password, true);

    //new handler in case of login error in the thread
    handler = new Handler();

    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                int balanceCounter = 0;
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(loginURL.toString());
                Utils.writeNetworkLogFileOnSD(
                        Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + loginURL.toString());
                httpGet.setHeader("Authorization", "Basic "
                        + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
                HttpResponse httpResponse = httpClient.execute(httpGet);
                InputStream inputStream = httpResponse.getEntity().getContent();
                Log.d("", loginURL.toString());

                ByteArrayInputStream bais = Utils.getMultiReadInputStream(inputStream);
                Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext())
                        + Utils.getStringFromInputStreamAndLeaveStreamOpen(bais));
                bais.reset();
                JsonFactory factory = new JsonFactory();
                JsonParser jsonParser = factory.createJsonParser(bais);
                JsonToken token = jsonParser.nextToken();

                if (token == JsonToken.START_OBJECT) {
                    balanceCounter++;
                    boolean idNextToHfId = false;
                    while (!(balanceCounter == 0)) {
                        token = jsonParser.nextToken();

                        if (token == JsonToken.START_OBJECT) {
                            balanceCounter++;
                        } else if (token == JsonToken.END_OBJECT) {
                            balanceCounter--;
                        } else if (token == JsonToken.FIELD_NAME) {
                            String object = jsonParser.getCurrentName();
                            switch (object) {
                            case "HealthFacilityId":
                                token = jsonParser.nextToken();
                                app.setLoggedInUserHealthFacilityId(jsonParser.getText());
                                Log.d("", "healthFacilityId is: " + jsonParser.getText());
                                idNextToHfId = true;
                                break;
                            case "Firstname":
                                token = jsonParser.nextToken();
                                app.setLoggedInFirstname(jsonParser.getText());
                                Log.d("", "firstname is: " + jsonParser.getText());
                                break;
                            case "Lastname":
                                token = jsonParser.nextToken();
                                app.setLoggedInLastname(jsonParser.getText());
                                Log.d("", "lastname is: " + jsonParser.getText());
                                break;
                            case "Username":
                                token = jsonParser.nextToken();
                                app.setLoggedInUsername(jsonParser.getText());
                                Log.d("", "username is: " + jsonParser.getText());
                                break;
                            case "Lastlogin":
                                token = jsonParser.nextToken();
                                Log.d("", "lastlogin is: " + jsonParser.getText());
                                break;
                            case "Id":
                                if (idNextToHfId) {
                                    token = jsonParser.nextToken();
                                    app.setLoggedInUserId(jsonParser.getText());
                                    Log.d("", "Id is: " + jsonParser.getText());
                                }
                                break;
                            default:
                                break;
                            }
                        }
                    }

                    Account account = new Account(username, ACCOUNT_TYPE);
                    AccountManager accountManager = AccountManager.get(LoginActivity.this);
                    //                        boolean accountCreated = accountManager.addAccountExplicitly(account, LoginActivity.this.password, null);
                    boolean accountCreated = accountManager.addAccountExplicitly(account, password, null);

                    Bundle extras = LoginActivity.this.getIntent().getExtras();
                    if (extras != null) {
                        if (accountCreated) { //Pass the new account back to the account manager
                            AccountAuthenticatorResponse response = extras
                                    .getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
                            Bundle res = new Bundle();
                            res.putString(AccountManager.KEY_ACCOUNT_NAME, username);
                            res.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
                            res.putString(AccountManager.KEY_PASSWORD, password);
                            response.onResult(res);
                        }
                    }

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putBoolean("secondSyncNeeded", true);
                    editor.commit();

                    ContentValues values = new ContentValues();
                    values.put(SQLHandler.SyncColumns.UPDATED, 1);
                    values.put(SQLHandler.UserColumns.FIRSTNAME, app.getLOGGED_IN_FIRSTNAME());
                    values.put(SQLHandler.UserColumns.LASTNAME, app.getLOGGED_IN_LASTNAME());
                    values.put(SQLHandler.UserColumns.HEALTH_FACILITY_ID, app.getLOGGED_IN_USER_HF_ID());
                    values.put(SQLHandler.UserColumns.ID, app.getLOGGED_IN_USER_ID());
                    values.put(SQLHandler.UserColumns.USERNAME, app.getLOGGED_IN_USERNAME());
                    values.put(SQLHandler.UserColumns.PASSWORD, password);
                    databaseHandler.addUser(values);

                    Log.d(TAG, "initiating offline for " + username + " password = " + password);
                    app.initializeOffline(username, password);

                    Intent intent;
                    if (prefs.getBoolean("synchronization_needed", true)) {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                    } else {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        evaluateIfFirstLogin(app.getLOGGED_IN_USER_ID());
                    }
                    app.setUsername(username);

                    startActivity(intent);
                }
                //if login failed show error
                else {
                    handler.post(new Runnable() {
                        public void run() {
                            progressDialog.show();
                            progressDialog.dismiss();
                            toastMessage("Login failed.\nPlease check your details!");
                            loginButton.setEnabled(true);
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    public void run() {
                        progressDialog.show();
                        progressDialog.dismiss();
                        toastMessage("Login failed Login failed.\n"
                                + "Please check your details or your web connectivity");
                        loginButton.setEnabled(true);

                    }
                });
                e.printStackTrace();
            }
        }
    });
    thread.start();

}

From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java

/**
 * Streamlined version that is only used when no "special"
 * features are enabled./* www .j a  va 2 s.c  om*/
 */
private Object vanillaDeserialize(JsonParser jp, DeserializationContext ctxt, JsonToken t) throws IOException {
    final Object bean = _valueInstantiator.createUsingDefault(ctxt);
    beanDeserializerAdvice.before(bean, jp, ctxt);
    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        String propName = jp.getCurrentName();
        // Skip field name:
        jp.nextToken();

        if (beanDeserializerAdvice.intercept(bean, propName, jp, ctxt)) {
            continue;
        }

        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) { // normal case
            try {
                prop.deserializeAndSet(jp, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
        } else {
            handleUnknownVanilla(jp, ctxt, bean, propName);
        }
    }
    beanDeserializerAdvice.after(bean, jp, ctxt);
    return bean;
}