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

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

Introduction

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

Prototype

public String getValueAsString() throws IOException, JsonParseException 

Source Link

Document

Method that will try to convert value of current token to a java.lang.String .

Usage

From source file:com.ntsync.shared.RequestGenerator.java

/**
 * //from   ww w  .  j  a  v  a 2  s.  c  o  m
 * @param key
 * @param clientId
 * @param response
 * @return
 * @throws HeaderParseException
 */
public static SyncResponse processServerResponse(SecretKey key, String clientId, final byte[] response)
        throws HeaderParseException {
    short version = SyncDataHelper.readShort(response, 0);
    SyncState syncState = null;

    Map<Long, String> newGroupIdMap = null;
    Map<Long, String> newContactIdMap = null;
    SyncAnchor newSyncAnchor = new SyncAnchor();
    int skippedRows = 0;
    List<RawContact> serverContactList = new ArrayList<RawContact>();
    List<ContactGroup> serverGroupList = new ArrayList<ContactGroup>();

    String newClientId = clientId;
    Restrictions restr = null;
    if (version == RequestGenerator.PROT_VERSION) {
        int headerLength = SyncDataHelper.readInt(response, 2);

        JsonParser jp = null;
        try {
            jp = getJsonFactory().createParser(response, HEADER_POS, headerLength);
            jp.nextToken();
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String fieldname = jp.getCurrentName();
                // move to value, or START_OBJECT/START_ARRAY
                if (jp.nextToken() == null) {
                    break;
                }
                if (CLIENT_FIELD_NAME.equals(fieldname)) {
                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                        String clientField = jp.getCurrentName();
                        if (jp.nextToken() == null) {
                            break;
                        }
                        if (PARAM_SYNC_ANCHOR.equals(clientField)) {
                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                String anchorType = jp.getCurrentName();
                                if (jp.nextToken() == null) {
                                    break;
                                }
                                long syncAnchor = jp.getLongValue();
                                if (anchorType != null && anchorType.length() > 0) {
                                    newSyncAnchor.setAnchor((byte) anchorType.charAt(0), syncAnchor);
                                }
                            }
                        } else if (PARAM_CLIENTID.equals(clientField)) {
                            newClientId = jp.getValueAsString();
                        } else if (TAG_GROUPIDS.equals(clientField)) {
                            newGroupIdMap = extractNewIdList(jp);
                        } else if (TAG_CONTACTIDS.equals(clientField)) {
                            newContactIdMap = extractNewIdList(jp);
                        } else {
                            LOG.warn("Unsupported Client-Header-Field: {}", clientField);
                        }
                    }
                } else if (SERVER_FIELD_NAME.equals(fieldname)) {
                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                        String serverField = jp.getCurrentName();
                        if (jp.nextToken() == null) {
                            break;
                        }
                        if (RequestGenerator.SYNCSTATE_FIELD_NAME.equals(serverField)) {
                            String syncStateStr = jp.getValueAsString();
                            if (syncStateStr != null && syncStateStr.length() > 0) {
                                syncState = SyncState.fromErrorVal(syncStateStr);
                            }
                        } else if (RequestGenerator.TAG_SERVER_CONFIG.equals(serverField)) {
                            restr = parseRestr(jp);
                        }
                    }

                }
            }

            final int respLen = response.length;

            if (respLen > headerLength + HEADER_POS) {
                skippedRows = getUpdatedRows(key, serverContactList, serverGroupList, response, headerLength,
                        respLen);
            }
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        } catch (JsonParseException ex) {
            throw new HeaderParseException(ex);
        } catch (IOException e) {
            throw new HeaderParseException(e);
        } finally {
            if (jp != null) {
                try {
                    jp.close();
                } catch (IOException ex) {
                    LOG.warn("Could not close JSONParser", ex);
                }
            }
        }
    }

    return new SyncResponse(syncState, serverContactList, serverGroupList, newSyncAnchor, newClientId,
            newGroupIdMap, newContactIdMap, skippedRows, restr);
}

From source file:io.debezium.document.JacksonReader.java

private Document parseDocument(JsonParser parser, boolean nested) throws IOException {
    // Iterate over the fields in the top-level document ...
    BasicDocument doc = new BasicDocument();
    JsonToken token = null;/*w w w.ja  va2 s.co  m*/
    if (!nested) {
        // We expect the START_OBJECT token ...
        token = parser.nextToken();
        if (!nested && token != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object, but was " + token);
        }
    }
    String fieldName = null;
    token = parser.nextToken();
    while (token != JsonToken.END_OBJECT) {
        switch (token) {
        case FIELD_NAME:
            fieldName = parser.getCurrentName();
            break;
        case START_OBJECT:
            doc.setDocument(fieldName, parseDocument(parser, true));
            break;
        case START_ARRAY:
            doc.setArray(fieldName, parseArray(parser, true));
            break;
        case VALUE_STRING:
            doc.setString(fieldName, parser.getValueAsString());
            break;
        case VALUE_TRUE:
            doc.setBoolean(fieldName, true);
            break;
        case VALUE_FALSE:
            doc.setBoolean(fieldName, false);
            break;
        case VALUE_NULL:
            doc.setNull(fieldName);
            break;
        case VALUE_NUMBER_FLOAT:
        case VALUE_NUMBER_INT:
            switch (parser.getNumberType()) {
            case FLOAT:
                doc.setNumber(fieldName, parser.getFloatValue());
                break;
            case DOUBLE:
                doc.setNumber(fieldName, parser.getDoubleValue());
                break;
            case BIG_DECIMAL:
                doc.setNumber(fieldName, parser.getDecimalValue());
                break;
            case INT:
                doc.setNumber(fieldName, parser.getIntValue());
                break;
            case LONG:
                doc.setNumber(fieldName, parser.getLongValue());
                break;
            case BIG_INTEGER:
                doc.setNumber(fieldName, parser.getBigIntegerValue());
                break;
            }
            break;
        case VALUE_EMBEDDED_OBJECT:
            // disregard this, since it's an extension ...
            break;
        case NOT_AVAILABLE:
            throw new JsonParseException("Non-blocking parsers are not supported", parser.getCurrentLocation());
        case END_ARRAY:
            throw new JsonParseException("Not expecting an END_ARRAY token", parser.getCurrentLocation());
        case END_OBJECT:
            throw new JsonParseException("Not expecting an END_OBJECT token", parser.getCurrentLocation());
        }
        token = parser.nextToken();
    }
    return doc;
}

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

private void getCurrentWeatherDataObjects(final Current currentWeatherData, final JsonParser jParser,
        final String fieldname) throws JsonParseException, IOException {
    if ("coord".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("lon".equals(namefield)) {
                currentWeatherData.getCoord().setLon(jParser.getDoubleValue());
            }//from  w w  w  . java 2s  .c  o  m
            if ("lat".equals(namefield)) {
                currentWeatherData.getCoord().setLat(jParser.getDoubleValue());
            }
        }
    }
    if ("sys".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("message".equals(namefield)) {
                currentWeatherData.getSys().setMessage(jParser.getDoubleValue());
            }
            if ("country".equals(namefield)) {
                currentWeatherData.getSys().setCountry(jParser.getValueAsString());
            }
            if ("sunrise".equals(namefield)) {
                currentWeatherData.getSys().setSunrise(jParser.getValueAsLong());
            }
            if ("sunset".equals(namefield)) {
                currentWeatherData.getSys().setSunset(jParser.getValueAsLong());
            }
        }
    }
    if ("weather".equals(fieldname)) {
        final Weather weather = new Weather();
        currentWeatherData.getWeather().add(weather);
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("id".equals(namefield)) {
                weather.setId(jParser.getIntValue());
            }
            if ("main".equals(namefield)) {
                weather.setMain(jParser.getText());
            }
            if ("description".equals(namefield)) {
                weather.setDescription(jParser.getText());
            }
            if ("icon".equals(namefield)) {
                weather.setIcon(jParser.getText());
            }

        }
    }
    if ("base".equals(fieldname)) {
        currentWeatherData.setBase(jParser.getText());
    }
    if ("main".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("temp".equals(namefield)) {
                currentWeatherData.getMain().setTemp(jParser.getDoubleValue());
            }
            if ("temp_min".equals(namefield)) {
                currentWeatherData.getMain().setTemp_min(jParser.getDoubleValue());
            }
            if ("temp_max".equals(namefield)) {
                currentWeatherData.getMain().setTemp_max(jParser.getDoubleValue());
            }
            if ("pressure".equals(namefield)) {
                currentWeatherData.getMain().setPressure(jParser.getDoubleValue());
            }
            if ("sea_level".equals(namefield)) {
                currentWeatherData.getMain().setSea_level(jParser.getDoubleValue());
            }
            if ("grnd_level".equals(namefield)) {
                currentWeatherData.getMain().setGrnd_level(jParser.getDoubleValue());
            }
            if ("humidity".equals(namefield)) {
                currentWeatherData.getMain().setHumidity(jParser.getDoubleValue());
            }
        }
    }
    if ("wind".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("speed".equals(namefield)) {
                currentWeatherData.getWind().setSpeed(jParser.getDoubleValue());
            }
            if ("deg".equals(namefield)) {
                currentWeatherData.getWind().setDeg(jParser.getDoubleValue());
            }
        }
    }
    if ("clouds".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("all".equals(namefield)) {
                currentWeatherData.getClouds().setAll(jParser.getDoubleValue());
            }
        }
    }
    if ("dt".equals(fieldname)) {
        currentWeatherData.setDt(jParser.getLongValue());
    }
    if ("rain".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("3h".equals(namefield)) {
                currentWeatherData.getRain().set3h(jParser.getDoubleValue());
            }
        }
    }
    if ("snow".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("3h".equals(namefield)) {
                currentWeatherData.getSnow().set3h(jParser.getDoubleValue());
            }
        }
    }
    if ("id".equals(fieldname)) {
        currentWeatherData.setId(jParser.getLongValue());
    }
    if ("name".equals(fieldname)) {
        currentWeatherData.setName(jParser.getText());
    }
    if ("cod".equals(fieldname)) {
        currentWeatherData.setCod(jParser.getIntValue());
    }
}

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

private void addPassthroughField(JsonParser parser, JsonToken token, String fieldName,
        PassthroughWriteRecords rec) throws IOException {
    rec.passthroughMapKeyWriteRecord.reset();
    rec.passthroughMapKeyWriteRecord.setString("value", fieldName);
    int keyOrdinal = stateEngine.add("MapKey", rec.passthroughMapKeyWriteRecord);

    switch (token) {
    case START_ARRAY:
        rec.multiValuePassthroughListRec.reset();

        while (token != JsonToken.END_ARRAY) {
            switch (token) {
            case VALUE_FALSE:
            case VALUE_TRUE:
            case VALUE_NUMBER_INT:
            case VALUE_NUMBER_FLOAT:
            case VALUE_STRING:
                rec.passthroughMapValueWriteRecord.reset();
                rec.passthroughMapValueWriteRecord.setString("value", parser.getValueAsString());
                int elementOrdinal = stateEngine.add("String", rec.passthroughMapValueWriteRecord);
                rec.multiValuePassthroughListRec.addElement(elementOrdinal);
                break;
            default:
                break;
            }//from  w w  w . j  a  v a2 s .co  m

            token = parser.nextToken();
        }

        int valueListOrdinal = stateEngine.add("ListOfString", rec.multiValuePassthroughListRec);
        rec.multiValuePassthroughMapRec.addEntry(keyOrdinal, valueListOrdinal);
        break;
    case VALUE_FALSE:
    case VALUE_TRUE:
    case VALUE_NUMBER_INT:
    case VALUE_NUMBER_FLOAT:
    case VALUE_STRING:
        rec.passthroughMapValueWriteRecord.reset();
        rec.passthroughMapValueWriteRecord.setString("value", parser.getValueAsString());
        int valueOrdinal = stateEngine.add("String", rec.passthroughMapValueWriteRecord);
        rec.singleValuePassthroughMapRec.addEntry(keyOrdinal, valueOrdinal);
        break;
    case VALUE_NULL:
        break;
    case START_OBJECT:
        skipObject(parser);
        break;
    default:
        break;
    }
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the
 * specified stream in JSON format into a {@link TableResult} containing an entity of the specified class type
 * projected using the specified resolver.
 * //w w  w  .j a  v a  2 s  . c  o m
 * @param parser
 *            The <code>JsonParser</code> to read the data to parse from.
 * @param clazzType
 *            The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to
 *            <code>null</code> to ignore the returned entity and copy only response properties into the
 *            {@link TableResult} object.
 * @param resolver
 *            An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set
 *            to <code>null</code> to return the entity as an instance of the class type <code>T</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         A {@link TableResult} containing the parsed entity result of the operation.
 * @throws IOException
 *             if an error occurs while accessing the stream.
 * @throws ParseException
 *             if an error occurs while parsing the stream.
 * @throws InstantiationException
 *             if an error occurs while constructing the result.
 * @throws IllegalAccessException
 *             if an error occurs in reflection while parsing the result.
 * @throws StorageException
 *             if a storage service error occurs.
 * @throws IOException
 *             if an error occurs while accessing the stream.
 * @throws JsonParseException
 *             if an error occurs while parsing the stream.
 */
private static <T extends TableEntity, R> TableResult parseJsonEntity(final JsonParser parser,
        final Class<T> clazzType, HashMap<String, PropertyPair> classProperties,
        final EntityResolver<R> resolver, final TableRequestOptions options, final OperationContext opContext)
        throws JsonParseException, IOException, ParseException, StorageException, InstantiationException,
        IllegalAccessException {
    final TableResult res = new TableResult();

    final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>();

    if (!parser.hasCurrentToken()) {
        parser.nextToken();
    }

    ODataUtilities.assertIsStartObjectJsonToken(parser);

    parser.nextToken();

    // get all metadata, if present
    while (parser.getCurrentName().startsWith(ODataConstants.ODATA_PREFIX)) {
        final String name = parser.getCurrentName().substring(ODataConstants.ODATA_PREFIX.length());

        // get the value token
        parser.nextToken();

        if (name.equals(ODataConstants.ETAG)) {
            String etag = parser.getValueAsString();
            res.setEtag(etag);
        }

        // get the key token
        parser.nextToken();
    }

    if (resolver == null && clazzType == null) {
        return res;
    }

    // get object properties
    while (parser.getCurrentToken() != JsonToken.END_OBJECT) {
        String key = Constants.EMPTY_STRING;
        String val = Constants.EMPTY_STRING;
        EdmType edmType = null;

        // checks if this property is preceded by an OData property type annotation
        if (options.getTablePayloadFormat() != TablePayloadFormat.JsonNoMetadata
                && parser.getCurrentName().endsWith(ODataConstants.ODATA_TYPE_SUFFIX)) {
            parser.nextToken();
            edmType = EdmType.parse(parser.getValueAsString());

            parser.nextValue();
            key = parser.getCurrentName();
            val = parser.getValueAsString();
        } else {
            key = parser.getCurrentName();

            parser.nextToken();
            val = parser.getValueAsString();
            edmType = evaluateEdmType(parser.getCurrentToken(), parser.getValueAsString());
        }

        final EntityProperty newProp = new EntityProperty(val, edmType);
        properties.put(key, newProp);

        parser.nextToken();
    }

    String partitionKey = null;
    String rowKey = null;
    Date timestamp = null;
    String etag = null;

    // Remove core properties from map and set individually
    EntityProperty tempProp = properties.remove(TableConstants.PARTITION_KEY);
    if (tempProp != null) {
        partitionKey = tempProp.getValueAsString();
    }

    tempProp = properties.remove(TableConstants.ROW_KEY);
    if (tempProp != null) {
        rowKey = tempProp.getValueAsString();
    }

    tempProp = properties.remove(TableConstants.TIMESTAMP);
    if (tempProp != null) {
        timestamp = tempProp.getValueAsDate();

        if (res.getEtag() == null) {
            etag = getETagFromTimestamp(tempProp.getValueAsString());
            res.setEtag(etag);
        }
    }

    // do further processing for type if JsonNoMetdata by inferring type information via resolver or clazzType
    if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata
            && (options.getPropertyResolver() != null || clazzType != null)) {
        if (options.getPropertyResolver() != null) {
            for (final Entry<String, EntityProperty> p : properties.entrySet()) {
                final String key = p.getKey();
                final String value = p.getValue().getValueAsString();
                EdmType edmType;

                // try to use the property resolver to get the type
                try {
                    edmType = options.getPropertyResolver().propertyResolver(partitionKey, rowKey, key, value);
                } catch (Exception e) {
                    throw new StorageException(StorageErrorCodeStrings.INTERNAL_ERROR, SR.CUSTOM_RESOLVER_THREW,
                            Constants.HeaderConstants.HTTP_UNUSED_306, null, e);
                }

                // try to create a new entity property using the returned type
                try {
                    final EntityProperty newProp = new EntityProperty(value, edmType);
                    properties.put(p.getKey(), newProp);
                } catch (IllegalArgumentException e) {
                    throw new StorageException(StorageErrorCodeStrings.INVALID_TYPE,
                            String.format(SR.FAILED_TO_PARSE_PROPERTY, key, value, edmType),
                            Constants.HeaderConstants.HTTP_UNUSED_306, null, e);
                }
            }
        } else if (clazzType != null) {
            if (classProperties == null) {
                classProperties = PropertyPair.generatePropertyPairs(clazzType);
            }
            for (final Entry<String, EntityProperty> p : properties.entrySet()) {
                PropertyPair propPair = classProperties.get(p.getKey());
                if (propPair != null) {
                    final EntityProperty newProp = new EntityProperty(p.getValue().getValueAsString(),
                            propPair.type);
                    properties.put(p.getKey(), newProp);
                }
            }
        }
    }

    // set the result properties, now that they are appropriately parsed
    res.setProperties(properties);

    // use resolver if provided, else create entity based on clazz type
    if (resolver != null) {
        res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag()));
    } else if (clazzType != null) {
        // Generate new entity and return
        final T entity = clazzType.newInstance();
        entity.setEtag(res.getEtag());

        entity.setPartitionKey(partitionKey);
        entity.setRowKey(rowKey);
        entity.setTimestamp(timestamp);

        entity.readEntity(res.getProperties(), opContext);

        res.setResult(entity);
    }

    return res;
}

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

private ContentValues parseObject(JsonParser parser, SQLiteDatabase tempDb, String parentId, int seq)
        throws JsonParseException, IOException {
    // TODO : Grab id of root topic here, and store it in shared prefs, in case it ever
    //        changes. Currently we assume "root" and a change would be catastrophic.
    ContentValues result = new ContentValues();
    ChildArrayResults childResults = null;
    boolean badKind = false;

    result.put("parentTopic_id", parentId);
    result.put("seq", seq);

    while (parser.nextValue() != JsonToken.END_OBJECT) {

        // Allows us to burn through the rest of the object once we discover it's an exercise or something else we don't care about.
        if (badKind)
            continue;

        String fieldName = parser.getCurrentName();

        // Keys present will determine object type.
        if (stringFields.contains(fieldName)) {
            // Use getValueAsString over getText; getText returns "null" while getValueAsString returns null.
            String value = parser.getValueAsString();
            result.put(fieldName, value);

            if ("id".equals(fieldName)) {
                if (childResults != null) {
                    addParentIdToChildren(tempDb, childResults, value);
                }//www  .  jav  a2  s. c  om
            }
        } else if (intFields.contains(fieldName)) {
            result.put(fieldName, parser.getIntValue());
        } else if (booleanFields.contains(fieldName)) {
            result.put(fieldName, parser.getBooleanValue());
        } else if ("children".equals(fieldName)) {
            childResults = parseChildArray(parser, tempDb,
                    result.containsKey("id") ? result.getAsString("id") : null);
            result.put("video_count", childResults.videoCount);
            result.put("child_kind", childResults.childKind);
            result.put("thumb_id", childResults.thumbId);
        } else if ("download_urls".equals(fieldName)) {
            parseDownloadUrls(parser, result);
        } else if (null == fieldName) {
            // Noop. Just in case.
        } else {
            JsonToken next = parser.getCurrentToken();
            if (next == JsonToken.START_OBJECT || next == JsonToken.START_ARRAY) {
                // Skip this object or array, leaving us pointing at the matching end_object / end_array token.
                parser.skipChildren();
            }
        }
    }

    // Ignore types we don't need.
    if (badKind) {
        return null;
    }

    // Having parsed this whole object, we can insert it.
    if (result.containsKey("kind")) {
        String kind = result.getAsString("kind");
        if ("Topic".equals(kind)) {
            if (result.containsKey("id")) {
                result.put("_id", result.getAsString("id"));
                result.remove("id");
            }
            if (result.containsKey("child_kind")) {
                String child_kind = result.getAsString("child_kind");
                if ("Topic".equals(child_kind) || "Video".equals(child_kind)) {
                    insertTopic(tempDb, result);
                }
            }
        } else if ("Video".equals(kind)) {
            if (result.containsKey("id")) {
                result.put("video_id", result.getAsString("id"));
                result.remove("id");
            }
            insertTopicVideo(tempDb, result);
            insertVideo(tempDb, result);
        }
    }

    return result;
}

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());
    }/*from ww w . jav  a2  s  .  c o 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:invar.lib.data.DataParserJson.java

private void parse(JsonParser parser, DataNode root) throws IOException {
    String fieldName = null;/*from  www. j av a 2  s . c o m*/
    DataNode parent = root;
    while (!parser.isClosed()) {
        JsonToken token = parser.nextToken();
        if (token == null) {
            continue;
        }
        switch (token) {
        case START_ARRAY:
            parent.addChild(parent = DataNode.createArray().setFieldName(fieldName));
            fieldName = null;
            break;
        case END_ARRAY:
            parent = parent.getParent();
            fieldName = null;
            break;
        case START_OBJECT:
            parent.addChild(parent = DataNode.createObject().setFieldName(fieldName));
            fieldName = null;
            break;
        case END_OBJECT:
            parent = parent.getParent();
            fieldName = null;
            break;
        case VALUE_TRUE:
            parent.addChild(DataNode.createBoolean().setValue(true).setFieldName(fieldName));
            fieldName = null;
            break;
        case VALUE_FALSE:
            parent.addChild(DataNode.createBoolean().setValue(false).setFieldName(fieldName));
            fieldName = null;
            break;
        case VALUE_NULL:
            parent.addChild(DataNode.createNull().setValue(null).setFieldName(fieldName));
            fieldName = null;
            break;
        case VALUE_STRING:
            parent.addChild(
                    DataNode.createString().setFieldName(fieldName).setValue(parser.getValueAsString()));
            fieldName = null;
            break;
        case VALUE_NUMBER_INT:
            try {
                Long v = parser.getValueAsLong();
                parent.addChild(DataNode.createLong().setFieldName(fieldName).setValue(v));
            } catch (JsonParseException e) {
                BigInteger v = parser.getBigIntegerValue();
                parent.addChild(DataNode.createBigInt().setFieldName(fieldName).setValue(v));
            }
            fieldName = null;
            break;
        case VALUE_NUMBER_FLOAT:
            parent.addChild(
                    DataNode.createDouble().setFieldName(fieldName).setValue(parser.getValueAsDouble()));
            fieldName = null;
            break;
        case FIELD_NAME:
            fieldName = parser.getValueAsString();
            break;
        default:
            fieldName = null;
            break;
        }
    }
}

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

protected void extractTopic(final JsonParser jsonParser, final Resource resource,
        final ResourceResolver resolver, final CommentOperations operations)
        throws IOException, ServletException {
    if (jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
        return; // replies could just be an empty object (i.e. "ugc:replies":{} ) in which case, do nothing
    }/*  w  w  w. j  a v  a 2 s  . c  o m*/
    final Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("social:key", jsonParser.getCurrentName());
    Resource post = null;
    jsonParser.nextToken();
    if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
        jsonParser.nextToken();
        String author = null;
        List<DataSource> attachments = new ArrayList<DataSource>();
        while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
            final String label = jsonParser.getCurrentName();
            JsonToken token = jsonParser.nextToken();
            if (jsonParser.getCurrentToken().isScalarValue()) {

                // either a string, boolean, or long value
                if (token.isNumeric()) {
                    properties.put(label, jsonParser.getValueAsLong());
                } else {
                    final String value = jsonParser.getValueAsString();
                    if (value.equals("true") || value.equals("false")) {
                        properties.put(label, jsonParser.getValueAsBoolean());
                    } else {
                        final String decodedValue = URLDecoder.decode(value, "UTF-8");
                        if (label.equals("language")) {
                            properties.put("mtlanguage", decodedValue);
                        } else {
                            properties.put(label, decodedValue);
                            if (label.equals("userIdentifier")) {
                                author = decodedValue;
                            } else if (label.equals("jcr:description")) {
                                properties.put("message", decodedValue);
                            }
                        }
                    }
                }
            } else if (label.equals(ContentTypeDefinitions.LABEL_ATTACHMENTS)) {
                attachments = getAttachments(jsonParser);
            } else if (label.equals(ContentTypeDefinitions.LABEL_REPLIES)
                    || label.equals(ContentTypeDefinitions.LABEL_TALLY)
                    || label.equals(ContentTypeDefinitions.LABEL_TRANSLATION)
                    || label.equals(ContentTypeDefinitions.LABEL_SUBNODES)) {
                // replies and sub-nodes ALWAYS come after all other properties and attachments have been listed,
                // so we can create the post now if we haven't already, and then dive in
                if (post == null) {
                    try {
                        post = createPost(resource, author, properties, attachments,
                                resolver.adaptTo(Session.class), operations);
                        resProvider = SocialResourceUtils.getSocialResource(post).getResourceProvider();
                    } catch (Exception e) {
                        throw new ServletException(e.getMessage(), e);
                    }
                }
                if (label.equals(ContentTypeDefinitions.LABEL_REPLIES)) {
                    if (token.equals(JsonToken.START_OBJECT)) {
                        jsonParser.nextToken();
                        while (!token.equals(JsonToken.END_OBJECT)) {
                            extractTopic(jsonParser, post, resolver, operations);
                            token = jsonParser.nextToken();
                        }
                    } else {
                        throw new IOException("Expected an object for the subnodes");
                    }
                } else if (label.equals(ContentTypeDefinitions.LABEL_SUBNODES)) {
                    if (token.equals(JsonToken.START_OBJECT)) {
                        token = jsonParser.nextToken();
                        try {
                            while (!token.equals(JsonToken.END_OBJECT)) {
                                final String subnodeType = jsonParser.getCurrentName();
                                token = jsonParser.nextToken();
                                if (token.equals(JsonToken.START_OBJECT)) {
                                    jsonParser.skipChildren();
                                    token = jsonParser.nextToken();
                                }
                            }
                        } catch (final IOException e) {
                            throw new IOException("unable to skip child of sub-nodes", e);
                        }
                    } else {
                        final String field = jsonParser.getValueAsString();
                        throw new IOException("Expected an object for the subnodes. Instead: " + field);
                    }
                } else if (label.equals(ContentTypeDefinitions.LABEL_TALLY)) {
                    UGCImportHelper.extractTally(post, jsonParser, resProvider, tallyOperationsService);
                } else if (label.equals(ContentTypeDefinitions.LABEL_TRANSLATION)) {
                    importTranslation(jsonParser, post);
                    resProvider.commit(post.getResourceResolver());
                }

            } else if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
                properties.put(label, UGCImportHelper.extractSubmap(jsonParser));
            } else if (jsonParser.getCurrentToken().equals(JsonToken.START_ARRAY)) {
                jsonParser.nextToken(); // skip the START_ARRAY token
                if (label.equals(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS)) {
                    while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) {
                        final String timestampLabel = jsonParser.getValueAsString();
                        if (properties.containsKey(timestampLabel)
                                && properties.get(timestampLabel) instanceof Long) {
                            final Calendar calendar = new GregorianCalendar();
                            calendar.setTimeInMillis((Long) properties.get(timestampLabel));
                            properties.put(timestampLabel, calendar.getTime());
                        }
                        jsonParser.nextToken();
                    }
                } else {
                    final List<String> subArray = new ArrayList<String>();
                    while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) {
                        subArray.add(jsonParser.getValueAsString());
                        jsonParser.nextToken();
                    }
                    String[] strings = new String[subArray.size()];
                    for (int i = 0; i < subArray.size(); i++) {
                        strings[i] = subArray.get(i);
                    }
                    properties.put(label, strings);
                }
            }
            jsonParser.nextToken();
        }
        if (post == null) {
            try {
                post = createPost(resource, author, properties, attachments, resolver.adaptTo(Session.class),
                        operations);
                if (null == resProvider) {
                    resProvider = SocialResourceUtils.getSocialResource(post).getResourceProvider();
                }
                // resProvider.commit(resolver);
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        }
    } else {
        throw new IOException("Improperly formed JSON - expected an OBJECT_START token, but got "
                + jsonParser.getCurrentToken().toString());
    }
}