List of usage examples for com.fasterxml.jackson.core JsonParser nextValue
public abstract JsonToken nextValue() throws IOException, JsonParseException;
From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java
private ChildArrayResults parseChildArray(JsonParser parser, SQLiteDatabase tempDb, String parentTopic_id) throws JsonParseException, IOException { ChildArrayResults result = new ChildArrayResults(); int seq = 0;//w w w .j a v a 2 s . com JsonToken currentToken = parser.getCurrentToken(); if (currentToken == JsonToken.START_ARRAY) { while (parser.nextValue() == JsonToken.START_OBJECT) { // Otherwise, we will be at END_ARRAY here. ContentValues values = parseObject(parser, tempDb, parentTopic_id, seq++); if (values != null && values.containsKey("kind")) { String kind = values.getAsString("kind"); if ("Topic".equals(kind) && values.containsKey("_id")) { result.childKind = kind; result.childIds.add(values.getAsString("_id")); result.videoCount += values.getAsInteger("video_count"); if (result.thumbId == null && values.containsKey("thumb_id")) { // Return the first available thumb id as this topic's thumb id. result.thumbId = values.getAsString("thumb_id"); } } else if ("Video".equals(kind) && values.containsKey("readable_id")) { result.childKind = kind; result.childIds.add(values.getAsString("readable_id")); result.videoCount += 1; if (result.thumbId == null && values.containsKey("pngurl")) { // Return youtube_id of first video with a thumbnail as this topic's thumbnail id. result.thumbId = values.getAsString("youtube_id"); } } } } } return result; }
From source file:no.ssb.jsonstat.v2.deser.DatasetDeserializer.java
@Override public DatasetBuildable deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { if (p.getCurrentToken() == JsonToken.START_OBJECT) { p.nextToken();//from w w w.ja va2s .c o m } Set<String> ids = Collections.emptySet(); List<Integer> sizes = Collections.emptyList(); Multimap<String, String> roles = ArrayListMultimap.create(); Map<String, Dimension.Builder> dims = Collections.emptyMap(); List<Number> values = Collections.emptyList(); DatasetBuilder builder = Dataset.create(); Optional<String> version = Optional.empty(); Optional<String> clazz = Optional.empty(); Optional<ObjectNode> extension = Optional.empty(); while (p.nextValue() != JsonToken.END_OBJECT) { switch (p.getCurrentName()) { case "label": builder.withLabel(_parseString(p, ctxt)); break; case "source": builder.withSource(_parseString(p, ctxt)); break; case "href": break; case "updated": Instant updated = parseEcmaDate(_parseString(p, ctxt)); builder.updatedAt(updated); break; case "value": values = parseValues(p, ctxt); break; case "dimension": if (!version.orElse("1.x").equals("2.0")) { dims = Maps.newHashMap(); // Deal with the id, size and role inside dimension. while (p.nextValue() != JsonToken.END_OBJECT) { switch (p.getCurrentName()) { case "id": ids = p.readValueAs(ID_SET); break; case "size": sizes = p.readValueAs(SIZE_LIST); break; case "role": roles = p.readValueAs(ROLE_MULTIMAP); break; default: dims.put(p.getCurrentName(), ctxt.readValue(p, Dimension.Builder.class)); } } } else { dims = p.readValueAs(DIMENSION_MAP); } break; case "id": ids = p.readValueAs(ID_SET); break; case "size": sizes = p.readValueAs(SIZE_LIST); break; case "role": roles = p.readValueAs(ROLE_MULTIMAP); break; case "extension": extension = Optional.of(ctxt.readValue(p, ObjectNode.class)); break; case "link": case "status": // TODO p.skipChildren(); break; case "version": version = Optional.of(_parseString(p, ctxt)); break; case "class": // TODO clazz = Optional.of(_parseString(p, ctxt)); break; default: boolean handled = ctxt.handleUnknownProperty(p, this, Dimension.Builder.class, p.getCurrentName()); if (!handled) p.skipChildren(); break; } } // Setup roles for (Map.Entry<String, String> dimRole : roles.entries()) { Dimension.Roles role = Dimension.Roles.valueOf(dimRole.getKey().toUpperCase()); Dimension.Builder dimension = checkNotNull(dims.get(dimRole.getValue()), "could not assign the role {} to the dimension {}. The dimension did not exist", role, dimRole.getValue() ); dimension.withRole(role); } List<Dimension.Builder> orderedDimensions = Lists.newArrayList(); for (String dimensionName : ids) { orderedDimensions.add(dims.get(dimensionName)); } // TODO: Check size? // Check ids and add to the data set. checkArgument(ids.size() == dims.size(), "dimension and size did not match"); if (extension.isPresent()) { builder.withExtension(extension.get()); } return builder.withDimensions(orderedDimensions).withValues(values); }
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); }/*from w w w. j a v a 2 s . co m*/ } } 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.joliciel.jochre.search.highlight.Snippet.java
private void read(JsonParser jsonParser) { try {//from ww w . j av a 2 s.co m if (jsonParser.getCurrentToken() != JsonToken.START_OBJECT) throw new RuntimeException("Expected START_OBJECT, but was " + jsonParser.getCurrentToken() + " at " + jsonParser.getCurrentLocation()); while (jsonParser.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonParser.getCurrentName(); if (fieldName.equals("docId")) { this.docId = jsonParser.nextIntValue(0); } else if (fieldName.equals("field")) { this.field = jsonParser.nextTextValue(); } else if (fieldName.equals("start")) { this.startOffset = jsonParser.nextIntValue(0); } else if (fieldName.equals("end")) { this.endOffset = jsonParser.nextIntValue(0); } else if (fieldName.equals("score")) { jsonParser.nextValue(); this.score = jsonParser.getDoubleValue(); this.scoreCalculated = true; } else if (fieldName.equals("terms")) { if (jsonParser.nextToken() != JsonToken.START_ARRAY) throw new RuntimeException("Expected START_ARRAY, but was " + jsonParser.getCurrentToken() + " at " + jsonParser.getCurrentLocation()); while (jsonParser.nextToken() != JsonToken.END_ARRAY) { if (jsonParser.getCurrentToken() != JsonToken.START_OBJECT) throw new RuntimeException("Expected START_OBJECT, but was " + jsonParser.getCurrentToken() + " at " + jsonParser.getCurrentLocation()); int termDocId = docId; String termField = field; int termStart = 0; int termEnd = 0; int pageIndex = 0; int imageIndex = 0; double weight = 0.0; while (jsonParser.nextToken() != JsonToken.END_OBJECT) { String termFieldName = jsonParser.getCurrentName(); if (termFieldName.equals("docId")) { termDocId = jsonParser.nextIntValue(0); } else if (termFieldName.equals("field")) { termField = jsonParser.nextTextValue(); } else if (termFieldName.equals("start")) { termStart = jsonParser.nextIntValue(0); } else if (termFieldName.equals("end")) { termEnd = jsonParser.nextIntValue(0); } else if (termFieldName.equals("pageIndex")) { pageIndex = jsonParser.nextIntValue(0); } else if (termFieldName.equals("imageIndex")) { imageIndex = jsonParser.nextIntValue(0); } else if (termFieldName.equals("weight")) { jsonParser.nextValue(); weight = jsonParser.getDoubleValue(); } else { throw new RuntimeException("Unexpected term field name: " + termFieldName + " at " + jsonParser.getCurrentLocation()); } } HighlightTerm highlightTerm = new HighlightTerm(termDocId, termField, termStart, termEnd, imageIndex, pageIndex); highlightTerm.setWeight(weight); this.highlightTerms.add(highlightTerm); } } else { throw new RuntimeException( "Unexpected field name: " + fieldName + " at " + jsonParser.getCurrentLocation()); } } } catch (JsonParseException e) { LOG.error(e); throw new RuntimeException(e); } catch (IOException e) { LOG.error(e); throw new RuntimeException(e); } }
From source file:com.opentable.jaxrs.StreamedJsonResponseConverter.java
private <T> void doRead(Callback<T> callback, TypeReference<T> type, final JsonParser jp) throws IOException { expect(jp, jp.nextToken(), JsonToken.START_OBJECT); expect(jp, jp.nextToken(), JsonToken.FIELD_NAME); if (!"results".equals(jp.getCurrentName())) { throw new JsonParseException("expecting results field", jp.getCurrentLocation()); }/*from w ww . j a v a 2 s.c om*/ expect(jp, jp.nextToken(), JsonToken.START_ARRAY); // As noted in a well-hidden comment in the MappingIterator constructor, // readValuesAs requires the parser to be positioned after the START_ARRAY // token with an empty current token jp.clearCurrentToken(); Iterator<T> iter = jp.readValuesAs(type); while (iter.hasNext()) { try { callback.call(iter.next()); } catch (CallbackRefusedException e) { LOG.debug("callback refused execution, finishing.", e); return; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Callback interrupted", e); } catch (Exception e) { Throwables.propagateIfPossible(e, IOException.class); throw new IOException("Callback failure", e); } } if (jp.nextValue() != JsonToken.VALUE_TRUE || !jp.getCurrentName().equals("success")) { throw new IOException("Streamed receive did not terminate normally; inspect server logs for cause."); } }
From source file:org.mongojack.internal.DBRefDeserializer.java
@Override public DBRef deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // First of all, make sure that we can get a copy of the DBCollection if (jp instanceof JacksonDBCollectionProvider) { K id = null;//from w w w. j a va 2 s.com String collectionName = null; JsonToken token = jp.getCurrentToken(); if (token == JsonToken.VALUE_NULL) { return null; } if (token == JsonToken.VALUE_EMBEDDED_OBJECT) { // Someones already kindly decoded it for us Object object = jp.getEmbeddedObject(); if (object instanceof com.mongodb.DBRef) { if (keyDeserializer != null) { id = keyDeserializer.deserialize(jp, ctxt); } else { id = (K) ((com.mongodb.DBRef) object).getId(); } collectionName = ((com.mongodb.DBRef) object).getRef(); } else { throw ctxt.instantiationException(DBRef.class, "Don't know what to do with embedded object: " + object); } } else if (token == JsonToken.START_OBJECT) { token = jp.nextValue(); while (token != JsonToken.END_OBJECT) { if (jp.getCurrentName().equals("$id")) { if (keyDeserializer != null) { id = keyDeserializer.deserialize(jp, ctxt); } else { id = (K) jp.getEmbeddedObject(); } } else if (jp.getCurrentName().equals("$ref")) { collectionName = jp.getText(); } else { // Ignore the rest } token = jp.nextValue(); } } if (id == null) { return null; } if (collectionName == null) { throw ctxt.instantiationException(DBRef.class, "DBRef contains no collection name"); } JacksonDBCollection coll = ((JacksonDBCollectionProvider) jp).getDBCollection(); JacksonDBCollection<T, K> refColl = coll.getReferenceCollection(collectionName, type, keyType); return new FetchableDBRef<T, K>(id, refColl); } else { throw ctxt.instantiationException(DBRef.class, "DBRef can only be deserialised by this deserializer if parser implements " + JacksonDBCollectionProvider.class.getName() + " parser is actually " + jp.getClass().getName()); } }
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. * // w w w . java 2s. com * @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:org.instagram4j.DefaultInstagramClient.java
private <T> Result<T> requestEntity(HttpRequestBase method, Class<T> type, boolean signableRequest) throws InstagramException { method.getParams().setParameter("http.useragent", "Instagram4j/1.0"); JsonParser jp = null; HttpResponse response = null;// ww w . j a v a2 s. c o m ResultMeta meta = null; try { method.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); if (signableRequest) setEnforceHeader(method); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 15000); client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 30000); if (LOG.isDebugEnabled()) LOG.debug(String.format("Requesting entity entry point %s, method %s", method.getURI().toString(), method.getMethod())); autoThrottle(); response = client.execute(method); jp = createParser(response, method); JsonToken tok = jp.nextToken(); if (tok != JsonToken.START_OBJECT) { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw createInstagramException("Instagram request failed", method.getURI().toString(), response, null, null); throw createInstagramException("Invalid response format from Instagram API", method.getURI().toString(), response, null, null); } T data = null; while (true) { tok = jp.nextValue(); if (tok == JsonToken.START_ARRAY) { throw createInstagramException("Unexpected array in entity response " + jp.getCurrentName(), method.getURI().toString(), response, meta, null); } else if (tok == JsonToken.START_OBJECT) { // Should be "data" or "meta" String name = jp.getCurrentName(); if ("meta".equals(name)) meta = jp.readValueAs(ResultMeta.class); else if ("data".equals(name)) { if (type != null) data = jp.readValueAs(type); else jp.readValueAs(Map.class); // Consume & ignore } else throw createInstagramException("Unexpected field name " + name, method.getURI().toString(), response, meta, null); } else break; } if (data == null && meta == null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw createInstagramException("Instagram request failed", method.getURI().toString(), response, null, null); Result<T> result = new Result<T>(null, meta, data); setRateLimits(response, result); return result; } catch (JsonParseException e) { throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } catch (JsonProcessingException e) { throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } catch (IOException e) { throw createInstagramException("Error communicating with Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } finally { if (jp != null) try { jp.close(); } catch (IOException e) { } method.releaseConnection(); } }
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 ava 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:org.instagram4j.DefaultInstagramClient.java
@SuppressWarnings("unchecked") private <T> Result<T[]> requestEntities(HttpRequestBase method, Class<T> type) throws InstagramException { method.getParams().setParameter("http.useragent", "Instagram4j/1.0"); JsonParser jp = null; HttpResponse response = null;//from w ww . ja va 2 s.c o m ResultMeta meta = null; try { method.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); setEnforceHeader(method); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 15000); client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 30000); if (LOG.isDebugEnabled()) LOG.debug(String.format("Requesting entities entry point %s, method %s", method.getURI().toString(), method.getMethod())); autoThrottle(); response = client.execute(method); jp = createParser(response, method); JsonToken tok = jp.nextToken(); if (tok != JsonToken.START_OBJECT) { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw createInstagramException("Instagram request failed", method.getURI().toString(), response, null, null); throw createInstagramException("Invalid response format from Instagram API", method.getURI().toString(), response, null, null); } Pagination pagination = null; T[] data = null; while (true) { tok = jp.nextValue(); if (tok == JsonToken.START_ARRAY) { // Should be "data" String name = jp.getCurrentName(); if (!"data".equals(name)) throw createInstagramException("Unexpected field name " + name, method.getURI().toString(), response, meta, null); List<T> items = new ArrayList<T>(); tok = jp.nextToken(); if (tok == JsonToken.START_OBJECT) { if (type != null) { T item; while ((item = jp.readValueAs(type)) != null) items.add(item); } else jp.readValueAs(Map.class); // Consume & ignore } data = (T[]) Array.newInstance(type, items.size()); System.arraycopy(items.toArray(), 0, data, 0, items.size()); } else if (tok == JsonToken.START_OBJECT) { // Should be "pagination" or "meta" String name = jp.getCurrentName(); if ("pagination".equals(name)) pagination = jp.readValueAs(Pagination.class); else if ("meta".equals(name)) meta = jp.readValueAs(ResultMeta.class); else throw createInstagramException("Unexpected field name " + name, method.getURI().toString(), response, meta, null); } else break; } if (data == null && meta == null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw createInstagramException("Instagram request failed", method.getURI().toString(), response, null, null); Result<T[]> result = new Result<T[]>(pagination, meta, data); setRateLimits(response, result); return result; } catch (JsonParseException e) { throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } catch (JsonProcessingException e) { throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } catch (IOException e) { throw createInstagramException("Error communicating with Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } finally { if (jp != null) try { jp.close(); } catch (IOException e) { } method.releaseConnection(); } }