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

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

Introduction

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

Prototype

public abstract String getCurrentName() throws IOException, JsonParseException;

Source Link

Document

Method that can be called to get the name associated with the current token: for JsonToken#FIELD_NAME s it will be the same as what #getText returns; for field values it will be preceding field name; and for others (array values, root-level values) null.

Usage

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

@Override
public Haplogroup parseHaplogroups(final InputStream inputStream) {
    checkNotNull(inputStream);//from  w  w w.j av a 2  s  .c om
    JsonParser parser = null;
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String maternal = null;
        String paternal = null;
        String rsid = null;
        String rcrsPosition = null;
        String snp = null;
        List<PaternalTerminalSnp> paternalTerminalSnps = new ArrayList<PaternalTerminalSnp>();
        List<MaternalTerminalSnp> maternalTerminalSnps = new ArrayList<MaternalTerminalSnp>();

        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();

            if ("id".equals(field)) {
                id = parser.getText();
            } else if ("maternal".equals(field)) {
                maternal = parser.getText();
            } else if ("paternal".equals(field)) {
                paternal = "null" == parser.getText() ? null : parser.getText();
            } else if ("maternal_terminal_snps".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    while (parser.nextToken() != JsonToken.END_OBJECT) {
                        String maternalTerminalSnpsField = parser.getCurrentName();
                        parser.nextToken();

                        if ("rsid".equals(maternalTerminalSnpsField)) {
                            rsid = parser.getText();
                        } else if ("rcrs_position".equals(maternalTerminalSnpsField)) {
                            rcrsPosition = parser.getText();
                        }
                    }
                    maternalTerminalSnps.add(new MaternalTerminalSnp(rsid, rcrsPosition));
                }
            } else if ("paternal_terminal_snps".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    while (parser.nextToken() != JsonToken.END_OBJECT) {
                        String paternalTerminalSnpsField = parser.getCurrentName();
                        parser.nextToken();

                        if ("rsid".equals(paternalTerminalSnpsField)) {
                            rsid = parser.getText();
                        } else if ("snp".equals(paternalTerminalSnpsField)) {
                            snp = parser.getText();
                        }
                    }
                    paternalTerminalSnps.add(new PaternalTerminalSnp(rsid, snp));
                }
            }
        }
        return new Haplogroup(id, paternal, maternal, paternalTerminalSnps, maternalTerminalSnps);
    } catch (IOException e) {
        logger.warn("could not parse haplogroups", e);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
    return null;
}

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

private void importMessages(final SlingHttpServletRequest request, final JsonParser jsonParser,
        final Map<String, Object> messageModifiers) throws ServletException {

    if (!jsonParser.getCurrentToken().equals(JsonToken.START_ARRAY)) {
        throw new ServletException("unexpected starting token " + jsonParser.getCurrentToken().asString());
    }// ww w .j  a  v  a  2 s .co  m

    try {
        jsonParser.nextToken(); //presumably, we will advance to a "start object" token
        while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) {
            final Map<String, Map<String, Boolean>> recipientModifiers = new HashMap<String, Map<String, Boolean>>();
            final Map<String, Object> props = new HashMap<String, Object>();
            final Map<String, Object> messageModifier = new HashMap<String, Object>();
            List<FileDataSource> attachments = new ArrayList<FileDataSource>();
            String sender = "";
            jsonParser.nextToken(); //field name
            while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
                final String fieldName = jsonParser.getCurrentName();
                jsonParser.nextToken(); //value
                if (fieldName.equals("senderId")) {
                    sender = URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8");
                } else if (fieldName.equals("added")) {
                    final Calendar calendar = new GregorianCalendar();
                    calendar.setTimeInMillis(jsonParser.getLongValue());
                    messageModifier.put("added", calendar);
                } else if (fieldName.equals("recipients")) {
                    // build the string for the "to" property and also create the modifiers we'll need later
                    final StringBuilder recipientString = new StringBuilder();
                    //iterate over each key (each being a recipient id)
                    if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
                        jsonParser.nextToken(); // should get first recipientId
                        while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
                            final String recipientId = jsonParser.getCurrentName();
                            jsonParser.nextToken(); //start object
                            jsonParser.nextToken(); //first label
                            final Map<String, Boolean> interactionModifiers = new HashMap<String, Boolean>();
                            while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
                                final String label = jsonParser.getCurrentName();
                                jsonParser.nextToken();
                                final Boolean labelValue = jsonParser.getBooleanValue();
                                interactionModifiers.put(label, labelValue);
                                jsonParser.nextToken(); //next label or end object
                            }
                            try {
                                final String userPath = userPropertiesService.getAuthorizablePath(recipientId);
                                recipientModifiers.put(userPath, interactionModifiers);
                                recipientString.append(recipientId);
                            } catch (final RepositoryException e) {
                                // log the fact that a recipient specified in the json file doesn't exist in this
                                // environment
                                throw new ServletException(
                                        "A recipient specified in the migration file couldn't "
                                                + "be found in this environment",
                                        e);
                            }
                            jsonParser.nextToken(); // next recipientId or end object
                            if (jsonParser.getCurrentToken().equals(JsonToken.FIELD_NAME)) {
                                recipientString.append(';');
                            }
                        }
                        props.put("to", recipientString);
                        messageModifier.put("recipientDetails", recipientModifiers);
                    }
                } else if (fieldName.equals(ContentTypeDefinitions.LABEL_ATTACHMENTS)) {
                    UGCImportHelper.getAttachments(jsonParser, attachments);
                } else {
                    props.put(fieldName, URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8"));
                }
                jsonParser.nextToken(); //either next field name or end object
            }
            final Random range = new Random();
            final String key = String.valueOf(range.nextInt(Integer.MAX_VALUE))
                    + String.valueOf(range.nextInt(Integer.MAX_VALUE));
            // we're going to temporarily overwrite the subject (to do a search) and need to track its initial value
            if (props.containsKey("subject")) {
                messageModifier.put("subject", props.get("subject"));
            } else {
                messageModifier.put("subject", "");
            }
            props.put("subject", key); //use subject as the search key
            messageModifiers.put(key, messageModifier);
            try {
                short result = messagingService.create(request.getResourceResolver(), request.getResource(),
                        sender, props, attachments,
                        clientUtilsFactory.getClientUtilities(xss, request, socialUtils));

                if (result != 200) {
                    throw new ServletException("Message sending failed. Return code was " + result);
                }
            } catch (final OperationException e) {
                throw new ServletException("Unable to create a message through the operation service", e);
            }
            jsonParser.nextToken(); //either END_ARRAY or START_OBJECT
        }

    } catch (final IOException e) {
        throw new ServletException("Encountered exception while parsing json content", e);
    }
}

From source file:com.netflix.hollow.jsonadapter.HollowJsonAdapter.java

private int addUnstructuredMap(JsonParser parser, String mapTypeName, HollowMapWriteRecord mapRec)
        throws IOException {
    mapRec.reset();//from   w  w  w.  j  a  v  a2  s  .  c  o  m

    HollowMapSchema schema = (HollowMapSchema) hollowSchemas.get(mapTypeName);
    ObjectFieldMapping valueRec = null;
    ObjectMappedFieldPath fieldMapping = null;

    JsonToken token = parser.nextToken();

    while (token != JsonToken.END_OBJECT) {
        if (token != JsonToken.FIELD_NAME) {
            HollowObjectWriteRecord mapKeyWriteRecord = (HollowObjectWriteRecord) getWriteRecord(
                    schema.getKeyType());
            String fieldName = mapKeyWriteRecord.getSchema().getFieldName(0);
            mapKeyWriteRecord.reset();

            switch (mapKeyWriteRecord.getSchema().getFieldType(0)) {
            case STRING:
                mapKeyWriteRecord.setString(fieldName, parser.getCurrentName());
                break;
            case BOOLEAN:
                mapKeyWriteRecord.setBoolean(fieldName, Boolean.valueOf(parser.getCurrentName()));
                break;
            case INT:
                mapKeyWriteRecord.setInt(fieldName, Integer.parseInt(parser.getCurrentName()));
                break;
            case LONG:
                mapKeyWriteRecord.setLong(fieldName, Long.parseLong(parser.getCurrentName()));
                break;
            case DOUBLE:
                mapKeyWriteRecord.setDouble(fieldName, Double.parseDouble(parser.getCurrentName()));
                break;
            case FLOAT:
                mapKeyWriteRecord.setFloat(fieldName, Float.parseFloat(parser.getCurrentName()));
                break;
            default:
                throw new IOException("Cannot parse type " + mapKeyWriteRecord.getSchema().getFieldType(0)
                        + " as key in map (" + mapKeyWriteRecord.getSchema().getName() + ")");
            }

            int keyOrdinal = stateEngine.add(schema.getKeyType(), mapKeyWriteRecord);

            int valueOrdinal;

            if (token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) {
                valueOrdinal = parseSubType(parser, token, schema.getValueType());
            } else {
                if (valueRec == null) {
                    valueRec = getObjectFieldMapping(schema.getValueType());
                    fieldMapping = valueRec.getSingleFieldMapping();
                }
                addObjectField(parser, token, fieldMapping);
                valueOrdinal = valueRec.build(-1);
            }

            mapRec.addEntry(keyOrdinal, valueOrdinal);
        }
        token = parser.nextToken();
    }

    return stateEngine.add(schema.getName(), mapRec);
}

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

/**
 * Method called when there are declared "unwrapped" properties
 * which need special handling/*from   w  ww  .java  2 s  . c om*/
 */
@SuppressWarnings("resource")
protected Object deserializeWithUnwrapped(JsonParser jp, DeserializationContext ctxt) throws IOException {
    if (_delegateDeserializer != null) {
        return _valueInstantiator.createUsingDelegate(ctxt, _delegateDeserializer.deserialize(jp, ctxt));
    }
    if (_propertyBasedCreator != null) {
        return deserializeUsingPropertyBasedWithUnwrapped(jp, ctxt);
    }
    TokenBuffer tokens = new TokenBuffer(jp);
    tokens.writeStartObject();
    final Object bean = _valueInstantiator.createUsingDefault(ctxt);

    if (_injectables != null) {
        injectValues(ctxt, bean);
    }
    final Class<?> activeView = _needViewProcesing ? ctxt.getActiveView() : null;
    beanDeserializerAdvice.before(bean, jp, ctxt);
    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        String propName = jp.getCurrentName();
        jp.nextToken();

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

        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) { // normal case
            if (activeView != null && !prop.visibleInView(activeView)) {
                jp.skipChildren();
                continue;
            }
            try {
                prop.deserializeAndSet(jp, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
        // ignorable things should be ignored
        if (_ignorableProps != null && _ignorableProps.contains(propName)) {
            handleIgnoredProperty(jp, ctxt, bean, propName);
            continue;
        }
        // but... others should be passed to unwrapped property deserializers
        tokens.writeFieldName(propName);
        tokens.copyCurrentStructure(jp);
        // how about any setter? We'll get copies but...
        if (_anySetter != null) {
            try {
                _anySetter.deserializeAndSet(jp, ctxt, bean, propName);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
    }
    tokens.writeEndObject();
    _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens);
    beanDeserializerAdvice.after(bean, jp, ctxt);
    return bean;
}

From source file:org.wso2.extension.siddhi.map.json.sourcemapper.JsonSourceMapper.java

private Event convertToSingleEventForDefaultMapping(Object eventObject) throws IOException {
    Event event = new Event(attributesSize);
    Object[] data = event.getData();
    JsonParser parser;
    int numberOfProvidedAttributes = 0;
    try {/*from w w  w.j  a v  a2 s  .  co  m*/
        parser = factory.createParser(eventObject.toString());
    } catch (IOException e) {
        throw new SiddhiAppRuntimeException(
                "Initializing a parser failed for the event string." + eventObject.toString());
    }
    int position;
    while (!parser.isClosed()) {
        JsonToken jsonToken = parser.nextToken();
        if (JsonToken.START_OBJECT.equals(jsonToken)) {
            parser.nextToken();
            if (DEFAULT_JSON_EVENT_IDENTIFIER.equalsIgnoreCase(parser.getText())) {
                parser.nextToken();
            } else {
                log.error("Default json message " + eventObject
                        + " contains an invalid event identifier. Required \"event\", " + "but found \""
                        + parser.getText() + "\". Hence dropping the message.");
                return null;
            }
        } else if (JsonToken.FIELD_NAME.equals(jsonToken)) {
            String key = parser.getCurrentName();
            numberOfProvidedAttributes++;
            position = findDefaultMappingPosition(key);
            if (position == -1) {
                log.error("Stream \"" + streamDefinition.getId() + "\" does not have an attribute named \""
                        + key + "\", but the received event " + eventObject.toString()
                        + " does. Hence dropping the message.");
                return null;
            }
            jsonToken = parser.nextToken();
            Attribute.Type type = streamAttributes.get(position).getType();

            if (JsonToken.VALUE_NULL.equals(jsonToken)) {
                data[position] = null;
            } else {
                switch (type) {
                case BOOL:
                    if (JsonToken.VALUE_TRUE.equals(jsonToken) || JsonToken.VALUE_FALSE.equals(jsonToken)) {
                        data[position] = parser.getValueAsBoolean();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type BOOL. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case INT:
                    if (JsonToken.VALUE_NUMBER_INT.equals(jsonToken)) {
                        data[position] = parser.getValueAsInt();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type INT. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case DOUBLE:
                    if (JsonToken.VALUE_NUMBER_FLOAT.equals(jsonToken)) {
                        data[position] = parser.getValueAsDouble();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type DOUBLE. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case STRING:
                    if (JsonToken.VALUE_STRING.equals(jsonToken)) {
                        data[position] = parser.getValueAsString();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type STRING. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case FLOAT:
                    if (JsonToken.VALUE_NUMBER_FLOAT.equals(jsonToken)
                            || JsonToken.VALUE_NUMBER_INT.equals(jsonToken)) {
                        data[position] = attributeConverter.getPropertyValue(parser.getValueAsString(),
                                Attribute.Type.FLOAT);
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type FLOAT. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case LONG:
                    if (JsonToken.VALUE_NUMBER_INT.equals(jsonToken)) {
                        data[position] = parser.getValueAsLong();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type LONG. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                default:
                    return null;
                }
            }
        }
    }

    if (failOnMissingAttribute && (numberOfProvidedAttributes != attributesSize)) {
        log.error("Json message " + eventObject.toString()
                + " contains missing attributes. Hence dropping the message.");
        return null;
    }
    return event;
}

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 2s . c  om*/
 *
 * <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

/**
 * Secondary deserialization method, called in cases where POJO
 * instance is created as part of deserialization, potentially
 * after collecting some or all of the properties to set.
 *//* w w  w  . ja  va2  s.  c o m*/
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt, Object bean) throws IOException {
    if (_injectables != null) {
        injectValues(ctxt, bean);
    }
    if (_unwrappedPropertyHandler != null) {
        return deserializeWithUnwrapped(jp, ctxt, bean);
    }
    if (_externalTypeIdHandler != null) {
        return deserializeWithExternalTypeId(jp, ctxt, bean);
    }
    JsonToken t = jp.getCurrentToken();
    // 23-Mar-2010, tatu: In some cases, we start with full JSON object too...
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    if (_needViewProcesing) {
        Class<?> view = ctxt.getActiveView();
        if (view != null) {
            return deserializeWithView(jp, ctxt, bean, view);
        }
    }
    beanDeserializerAdvice.before(bean, jp, ctxt);
    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) { // normal case
            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:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java

/**
 * General version used when handling needs more advanced
 * features.//from www.  j a va 2  s  . c  o  m
 */
@Override
public Object deserializeFromObject(JsonParser jp, DeserializationContext ctxt) throws IOException {
    if (_nonStandardCreation) {
        if (_unwrappedPropertyHandler != null) {
            return deserializeWithUnwrapped(jp, ctxt);
        }
        if (_externalTypeIdHandler != null) {
            return deserializeWithExternalTypeId(jp, ctxt);
        }
        return deserializeFromObjectUsingNonDefault(jp, ctxt);
    }
    final Object bean = _valueInstantiator.createUsingDefault(ctxt);
    if (jp.canReadObjectId()) {
        Object id = jp.getObjectId();
        if (id != null) {
            _handleTypedObjectId(jp, ctxt, bean, id);
        }
    }
    if (_injectables != null) {
        injectValues(ctxt, bean);
    }
    if (_needViewProcesing) {
        Class<?> view = ctxt.getActiveView();
        if (view != null) {
            return deserializeWithView(jp, ctxt, bean, view);
        }
    }
    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);
            }
            continue;
        }
        handleUnknownVanilla(jp, ctxt, bean, propName);
    }
    beanDeserializerAdvice.after(bean, jp, ctxt);
    return bean;
}

From source file:com.google.openrtb.json.AbstractOpenRtbJsonReader.java

/**
 * Read any extensions that may exist in a message.
 *
 * @param msg Builder of a message that may contain extensions
 * @param par The JSON parser, positioned at the "ext" field
 * @param <EB> Type of message builder being constructed
 * @throws IOException any parsing error
 *///w w w . j  ava 2 s.com
protected final <EB extends ExtendableBuilder<?, EB>> void readExtensions(EB msg, JsonParser par)
        throws IOException {
    @SuppressWarnings("unchecked")
    Set<OpenRtbJsonExtReader<EB>> extReaders = factory.getReaders((Class<EB>) msg.getClass());
    if (extReaders.isEmpty()) {
        par.skipChildren();
        return;
    }

    startObject(par);
    JsonToken tokLast = par.getCurrentToken();
    JsonLocation locLast = par.getCurrentLocation();

    while (true) {
        boolean extRead = false;
        for (OpenRtbJsonExtReader<EB> extReader : extReaders) {
            if (extReader.filter(par)) {
                extReader.read(msg, par);
                JsonToken tokNew = par.getCurrentToken();
                JsonLocation locNew = par.getCurrentLocation();
                boolean advanced = tokNew != tokLast || !locNew.equals(locLast);
                extRead |= advanced;

                if (!endObject(par)) {
                    return;
                } else if (advanced && par.getCurrentToken() != JsonToken.FIELD_NAME) {
                    tokLast = par.nextToken();
                    locLast = par.getCurrentLocation();
                } else {
                    tokLast = tokNew;
                    locLast = locNew;
                }
            }
        }

        if (!endObject(par)) {
            // Can't rely on this exit condition inside the for loop because no readers may filter.
            return;
        }

        if (!extRead) {
            // No field was consumed by any reader, so we need to skip the field to make progress.
            if (logger.isDebugEnabled()) {
                logger.debug("Extension field not consumed by any reader, skipping: {} @{}:{}",
                        par.getCurrentName(), locLast.getLineNr(), locLast.getCharOffset());
            }
            par.nextToken();
            par.skipChildren();
            tokLast = par.nextToken();
            locLast = par.getCurrentLocation();
        }
        // Else loop, try all readers again
    }
}