List of usage examples for com.fasterxml.jackson.core JsonParser getValueAsString
public String getValueAsString() throws IOException, JsonParseException
From source file:com.microsoft.azure.storage.table.CEKReturn.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. * //from ww w . j av a 2s .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 options * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout * settings for the operation. * @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 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, StorageException, InstantiationException, IllegalAccessException { final TableResult res = new TableResult(); HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>(); if (!parser.hasCurrentToken()) { parser.nextToken(); } JsonUtilities.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); newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility()); 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) { tempProp.setDateBackwardCompatibility(false); timestamp = tempProp.getValueAsDate(); if (res.getEtag() == null) { etag = getETagFromTimestamp(tempProp.getValueAsString()); res.setEtag(etag); } } // Deserialize the metadata property value to get the names of encrypted properties so that they can be parsed correctly below. Key cek = null; Boolean isJavaV1 = true; EncryptionData encryptionData = new EncryptionData(); HashSet<String> encryptedPropertyDetailsSet = null; if (options.getEncryptionPolicy() != null) { EntityProperty propertyDetailsProperty = properties .get(Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS); EntityProperty keyProperty = properties.get(Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS); if (propertyDetailsProperty != null && !propertyDetailsProperty.getIsNull() && keyProperty != null && !keyProperty.getIsNull()) { // Decrypt the metadata property value to get the names of encrypted properties. CEKReturn cekReturn = options.getEncryptionPolicy().decryptMetadataAndReturnCEK(partitionKey, rowKey, keyProperty, propertyDetailsProperty, encryptionData); cek = cekReturn.key; isJavaV1 = cekReturn.isJavaV1; properties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS, propertyDetailsProperty); encryptedPropertyDetailsSet = parsePropertyDetails(propertyDetailsProperty); } else { if (options.requireEncryption() != null && options.requireEncryption()) { throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.ENCRYPTION_DATA_NOT_PRESENT_ERROR, null); } } } // 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)) { for (final Entry<String, EntityProperty> property : properties.entrySet()) { if (Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS.equals(property.getKey())) { // This and the following check are required because in JSON no-metadata, the type information for // the properties are not returned and users are not expected to provide a type for them. So based // on how the user defined property resolvers treat unknown properties, we might get unexpected results. final EntityProperty newProp = new EntityProperty(property.getValue().getValueAsString(), EdmType.STRING); properties.put(property.getKey(), newProp); } else if (Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS .equals(property.getKey())) { if (options.getEncryptionPolicy() == null) { final EntityProperty newProp = new EntityProperty(property.getValue().getValueAsString(), EdmType.BINARY); properties.put(property.getKey(), newProp); } } else if (options.getPropertyResolver() != null) { final String key = property.getKey(); final String value = property.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, isEncrypted(encryptedPropertyDetailsSet, key) ? EdmType.BINARY : edmType); newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility()); properties.put(property.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); } PropertyPair propPair = classProperties.get(property.getKey()); if (propPair != null) { EntityProperty newProp; if (isEncrypted(encryptedPropertyDetailsSet, property.getKey())) { newProp = new EntityProperty(property.getValue().getValueAsString(), EdmType.BINARY); } else { newProp = new EntityProperty(property.getValue().getValueAsString(), propPair.type); } newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility()); properties.put(property.getKey(), newProp); } } } } // set the result properties, now that they are appropriately parsed if (options.getEncryptionPolicy() != null && cek != null) { // decrypt properties, if necessary properties = options.getEncryptionPolicy().decryptEntity(properties, encryptedPropertyDetailsSet, partitionKey, rowKey, cek, encryptionData, isJavaV1); } res.setProperties(properties); // use resolver if provided, else create entity based on clazz type if (resolver != null) { res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, properties, 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(properties, opContext); res.setResult(entity); } return res; }
From source file:io.pdef.json.JsonJacksonFormat.java
private Object read(final JsonParser parser) throws IOException { JsonToken current = parser.getCurrentToken(); if (current == null || current == JsonToken.VALUE_NULL) { return null; }/*from ww w . jav a2s. co m*/ switch (current) { case VALUE_NULL: return null; case VALUE_TRUE: return true; case VALUE_FALSE: return false; case VALUE_STRING: return parser.getValueAsString(); case VALUE_NUMBER_INT: case VALUE_NUMBER_FLOAT: return parser.getNumberValue(); case START_ARRAY: return readArray(parser); case START_OBJECT: return readMap(parser); default: throw new JsonFormatException("Bad JSON string"); } }
From source file:com.netflix.hollow.jsonadapter.util.JsonUtil.java
private static void print(JsonParser parser, JsonToken token, int index, PrintStream out) throws Exception { if (index == 0) System.out.println("\n\n -----"); try {// ww w.j a v a 2s. co m while (token != null && token != JsonToken.END_OBJECT) { switch (token) { case START_ARRAY: print(index, String.format("fieldname=%s, token=%s", parser.getCurrentName(), token), out); print(parser, parser.nextToken(), index + 1, out); break; case START_OBJECT: print(index, String.format("fieldname=%s, token=%s", parser.getCurrentName(), token), out); print(parser, parser.nextToken(), index + 1, out); break; case VALUE_NUMBER_INT: print(index, String.format("fieldname=%s, token=%s, value=%s", parser.getCurrentName(), token, parser.getLongValue()), out); break; case VALUE_NUMBER_FLOAT: print(index, String.format("fieldname=%s, token=%s, value=%s", parser.getCurrentName(), token, parser.getDoubleValue()), out); break; case VALUE_NULL: print(index, String.format("fieldname=%s, token=%s, value=NULL", parser.getCurrentName(), token), out); break; case VALUE_STRING: print(index, String.format("fieldname=%s, token=%s, value=%s", parser.getCurrentName(), token, parser.getValueAsString()), out); break; case VALUE_FALSE: case VALUE_TRUE: print(index, String.format("fieldname=%s, token=%s, value=%s", parser.getCurrentName(), token, parser.getBooleanValue()), out); break; case FIELD_NAME: //print(index, String.format("fieldname=%s, token=%s", parser.getCurrentName(), token)); break; case END_ARRAY: case END_OBJECT: index--; break; default: } token = parser.nextToken(); } } catch (Exception ex) { ex.printStackTrace(); throw ex; } }
From source file:org.debezium.core.doc.JacksonReader.java
private Array parseArray(JsonParser parser) throws IOException { // Iterate over the fields in the top-level document ... BasicArray array = new BasicArray(); JsonToken token = parser.nextToken(); while (token != JsonToken.END_ARRAY) { switch (token) { case START_OBJECT: array.add(parseDocument(parser, true)); break; case START_ARRAY: array.add(parseArray(parser)); break; case VALUE_STRING: array.add(parser.getValueAsString()); break; case VALUE_TRUE: array.add(true);/*ww w . j a v a 2 s . c om*/ break; case VALUE_FALSE: array.add(false); break; case VALUE_NULL: array.addNull(); break; case VALUE_NUMBER_FLOAT: case VALUE_NUMBER_INT: switch (parser.getNumberType()) { case FLOAT: array.add(parser.getFloatValue()); break; case DOUBLE: array.add(parser.getDoubleValue()); break; case BIG_DECIMAL: array.add(parser.getDecimalValue()); break; case INT: array.add(parser.getIntValue()); break; case LONG: array.add(parser.getLongValue()); break; case BIG_INTEGER: array.add(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 FIELD_NAME: throw new JsonParseException("Not expecting a FIELD_NAME token", 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 array; }
From source file:com.ntsync.shared.RawContact.java
private static RawOrganizationData readOrg(String rowId, JsonParser jp) throws IOException { String orgname = null;/*from ww w . j a va 2 s . c om*/ OrganizationType orgtype = null; String orgLabel = null; String department = null; String jobTitle = null; String title = null; boolean isSuperPrimary = false; boolean isPrimary = false; while (jp.nextToken() != JsonToken.END_OBJECT) { String namefield = jp.getCurrentName(); // move to value if (jp.nextToken() == null) { throw new JsonParseException("Invalid JSON-Structure. End of Object missing.", jp.getCurrentLocation()); } if (ContactConstants.DATA.equals(namefield)) { orgname = jp.getValueAsString(); } else if (ContactConstants.TYPE.equals(namefield)) { orgtype = OrganizationType.fromVal(jp.getValueAsInt()); } else if (ContactConstants.PRIMARY.equals(namefield)) { isPrimary = jp.getValueAsBoolean(); } else if (ContactConstants.SUPERPRIMARY.equals(namefield)) { isSuperPrimary = jp.getValueAsBoolean(); } else if (ContactConstants.LABEL.equals(namefield)) { orgLabel = jp.getValueAsString(); } else if (ContactConstants.ORGANIZATION_DEPARTMENT.equals(namefield)) { department = jp.getValueAsString(); } else if (ContactConstants.ORGANIZATION_TITLE.equals(namefield)) { title = jp.getValueAsString(); } else if (ContactConstants.ORGANIZATION_JOB.equals(namefield)) { jobTitle = jp.getValueAsString(); } else { LOG.error("Unrecognized Organization-field for row with Id:" + rowId + " Fieldname:" + namefield); } } if (orgtype == null) { orgtype = OrganizationType.TYPE_OTHER; } return new RawOrganizationData(orgname, orgtype, orgLabel, isPrimary, isSuperPrimary, title, department, jobTitle); }
From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java
private void parseDownloadUrls(JsonParser parser, ContentValues result) throws JsonParseException, IOException { // parser points at begin object token right now if (parser.getCurrentToken() == JsonToken.START_OBJECT) { while (parser.nextValue() != JsonToken.END_OBJECT) { String fieldName = parser.getCurrentName(); if (downloadUrlFields.contains(fieldName)) { result.put(fieldName + "url", parser.getValueAsString()); }// ww w . j a va2 s .c om } } // else we must not have any download urls (null, '', something like that.) }
From source file:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java
public static Map<String, Object> extractSubmap(final JsonParser jsonParser) throws IOException { jsonParser.nextToken(); // skip the START_OBJECT token final Map<String, Object> subMap = new HashMap<String, Object>(); while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) { final String label = jsonParser.getCurrentName(); // get the current label final JsonToken token = jsonParser.nextToken(); // get the current value if (!token.isScalarValue()) { if (token.equals(JsonToken.START_OBJECT)) { // if the next token starts a new object, recurse into it subMap.put(label, extractSubmap(jsonParser)); } else if (token.equals(JsonToken.START_ARRAY)) { final List<String> subArray = new ArrayList<String>(); jsonParser.nextToken(); // skip the START_ARRAY token while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) { subArray.add(jsonParser.getValueAsString()); jsonParser.nextToken(); }//from w w w .j a va 2s .c om subMap.put(label, subArray); jsonParser.nextToken(); // skip the END_ARRAY token } } else { // either a string, boolean, or long value if (token.isNumeric()) { subMap.put(label, jsonParser.getValueAsLong()); } else { final String value = jsonParser.getValueAsString(); if (value.equals("true") || value.equals("false")) { subMap.put(label, jsonParser.getValueAsBoolean()); } else { subMap.put(label, value); } } } jsonParser.nextToken(); // next token will either be an "END_OBJECT" or a new label } jsonParser.nextToken(); // skip the END_OBJECT token return subMap; }
From source file:com.adobe.communities.ugc.migration.importer.GenericUGCImporter.java
/** * Handle each of the importable types of ugc content * @param jsonParser - the parsing stream * @param resource - the parent resource of whatever it is we're importing (must already exist) * @throws ServletException//from ww w . j av a 2 s . com * @throws IOException */ protected void importFile(final JsonParser jsonParser, final Resource resource, final ResourceResolver resolver) throws ServletException, IOException { final UGCImportHelper importHelper = new UGCImportHelper(); JsonToken token1 = jsonParser.getCurrentToken(); importHelper.setSocialUtils(socialUtils); if (token1.equals(JsonToken.START_OBJECT)) { jsonParser.nextToken(); if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT_TYPE)) { jsonParser.nextToken(); final String contentType = jsonParser.getValueAsString(); if (contentType.equals(ContentTypeDefinitions.LABEL_QNA_FORUM)) { importHelper.setQnaForumOperations(qnaForumOperations); } else if (contentType.equals(ContentTypeDefinitions.LABEL_FORUM)) { importHelper.setForumOperations(forumOperations); } else if (contentType.equals(ContentTypeDefinitions.LABEL_CALENDAR)) { importHelper.setCalendarOperations(calendarOperations); } else if (contentType.equals(ContentTypeDefinitions.LABEL_JOURNAL)) { importHelper.setJournalOperations(journalOperations); } else if (contentType.equals(ContentTypeDefinitions.LABEL_FILELIBRARY)) { importHelper.setFileLibraryOperations(fileLibraryOperations); } importHelper.setTallyService(tallyOperationsService); // (everything potentially needs tally) importHelper.setCommentOperations(commentOperations); // nearly anything can have comments on it jsonParser.nextToken(); // content if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT)) { jsonParser.nextToken(); token1 = jsonParser.getCurrentToken(); if (token1.equals(JsonToken.START_OBJECT) || token1.equals(JsonToken.START_ARRAY)) { if (!resolver.isLive()) { throw new ServletException("Resolver is already closed"); } } else { throw new ServletException("Start object token not found for content"); } if (token1.equals(JsonToken.START_OBJECT)) { try { if (contentType.equals(ContentTypeDefinitions.LABEL_QNA_FORUM)) { importHelper.importQnaContent(jsonParser, resource, resolver); } else if (contentType.equals(ContentTypeDefinitions.LABEL_FORUM)) { importHelper.importForumContent(jsonParser, resource, resolver); } else if (contentType.equals(ContentTypeDefinitions.LABEL_COMMENTS)) { importHelper.importCommentsContent(jsonParser, resource, resolver); } else if (contentType.equals(ContentTypeDefinitions.LABEL_JOURNAL)) { importHelper.importJournalContent(jsonParser, resource, resolver); } else if (contentType.equals(ContentTypeDefinitions.LABEL_FILELIBRARY)) { importHelper.importFileLibrary(jsonParser, resource, resolver); } else { LOG.info("Unsupported content type: {}", contentType); jsonParser.skipChildren(); } jsonParser.nextToken(); } catch (final IOException e) { throw new ServletException(e); } jsonParser.nextToken(); // skip over END_OBJECT } else { try { if (contentType.equals(ContentTypeDefinitions.LABEL_CALENDAR)) { importHelper.importCalendarContent(jsonParser, resource, resolver); } else if (contentType.equals(ContentTypeDefinitions.LABEL_TALLY)) { importHelper.importTallyContent(jsonParser, resource, resolver); } else { LOG.info("Unsupported content type: {}", contentType); jsonParser.skipChildren(); } jsonParser.nextToken(); } catch (final IOException e) { throw new ServletException(e); } jsonParser.nextToken(); // skip over END_ARRAY } } else { throw new ServletException("Content not found"); } } else { throw new ServletException("No content type specified"); } } else { throw new ServletException("Invalid Json format"); } }
From source file:com.ntsync.shared.RawContact.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static <T extends ListType> List<ListRawData<T>> readJsonList(String rowId, List<ListRawData<T>> listData, JsonParser jp, String fieldname, ListType defaultType, Class<T> typeClass) throws IOException { List<ListRawData<T>> newListData = listData; while (jp.nextToken() != JsonToken.END_ARRAY) { String number = null;// w w w .j a va2s. c o m ListType type = defaultType; String label = null; boolean isSuperPrimary = false; boolean isPrimary = false; while (jp.nextToken() != JsonToken.END_OBJECT) { String namefield = jp.getCurrentName(); // move to value if (jp.nextToken() == null) { throw new JsonParseException("Invalid JSON-Structure. End of Array missing.", jp.getCurrentLocation()); } if (ContactConstants.DATA.equals(namefield)) { number = jp.getValueAsString(); } else if (ContactConstants.TYPE.equals(namefield)) { type = ContactConstants.fromVal(typeClass, jp.getValueAsInt()); if (type == null) { type = defaultType; } } else if (ContactConstants.SUPERPRIMARY.equals(namefield)) { isSuperPrimary = jp.getValueAsBoolean(); } else if (ContactConstants.PRIMARY.equals(namefield)) { isPrimary = jp.getValueAsBoolean(); } else if (ContactConstants.LABEL.equals(namefield)) { label = jp.getValueAsString(); } else { LOG.error(JSON_FIELDNOTRECOGNIZED + rowId + " Fieldname:" + fieldname + " Unrecognized: " + namefield); break; } } if (number != null) { if (newListData == null) { newListData = new ArrayList(); } newListData.add(new ListRawData(number, type, label, isPrimary, isSuperPrimary)); } } return newListData; }
From source file:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java
public static void extractTally(final Resource post, final JsonParser jsonParser, final ModifyingResourceProvider srp, final TallyOperationsService tallyOperationsService) throws IOException { jsonParser.nextToken(); // should be start object, but would be end array if no objects were present while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) { Long timestamp = null;//from ww w. j a va2 s .c o m String userIdentifier = null; String response = null; String tallyType = null; jsonParser.nextToken(); // should make current token by "FIELD_NAME" but could be END_OBJECT if this were // an empty object while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) { final String label = jsonParser.getCurrentName(); jsonParser.nextToken(); // should be FIELD_VALUE if (label.equals(TallyConstants.TIMESTAMP_PROPERTY)) { timestamp = jsonParser.getValueAsLong(); } else { final String responseValue = jsonParser.getValueAsString(); if (label.equals("response")) { response = URLDecoder.decode(responseValue, "UTF-8"); } else if (label.equals("userIdentifier")) { userIdentifier = URLDecoder.decode(responseValue, "UTF-8"); } else if (label.equals("tallyType")) { tallyType = responseValue; } } jsonParser.nextToken(); // should make current token be "FIELD_NAME" unless we're at the end of our // loop and it's now "END_OBJECT" instead } if (timestamp != null && userIdentifier != null && response != null && tallyType != null) { createTally(srp, post, tallyType, userIdentifier, timestamp, response, tallyOperationsService); } jsonParser.nextToken(); // may advance to "START_OBJECT" if we're not finished yet, but might be // "END_ARRAY" now } }