List of usage examples for com.fasterxml.jackson.core JsonParser nextToken
public abstract JsonToken nextToken() throws IOException, JsonParseException;
From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
@Override public Genotype parseGenotypes(final InputStream inputStream) { checkNotNull(inputStream);/*from w w w .ja v a 2s. c om*/ JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String location = null; String interpretation = null; Map<String, String> values = new HashMap<String, String>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else { location = field; interpretation = parser.getText(); values.put(location, interpretation); } } return new Genotype(id, values); } catch (IOException e) { logger.warn("could not parse genotypes"); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return null; }
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. * // ww w . j a va 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 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.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
@Override public PersonalGenomeClientException parseException(final InputStream inputStream) { checkNotNull(inputStream);//from w ww . j ava2 s. com JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String error = null; String errorDescription = null; while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("error".equals(field)) { error = parser.getText(); } else if ("error_description".equals(field)) { errorDescription = parser.getText(); } } if ("access_denied".equals(error)) { return new AccessDeniedException(errorDescription); } else if ("invalid_client".equals(error)) { return new InvalidClientException(errorDescription); } else if ("invalid_request".equals(error)) { return new InvalidRequestException(errorDescription); } else if ("invalid_scope".equals(error)) { return new InvalidScopeException(errorDescription); } return new PersonalGenomeClientException(errorDescription); } catch (IOException e) { logger.warn("could not parse exception", e); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return new PersonalGenomeClientException("unknown error"); }
From source file:com.netflix.hollow.jsonadapter.HollowJsonAdapter.java
private int addUnstructuredMap(JsonParser parser, String mapTypeName, HollowMapWriteRecord mapRec) throws IOException { mapRec.reset();/*w w w . j a v a2 s .c o m*/ HollowMapSchema schema = (HollowMapSchema) hollowSchemas.get(mapTypeName); ObjectFieldMapping valueRec = null; ObjectMappedFieldPath fieldMapping = null; JsonToken token = parser.nextToken(); while (token != JsonToken.END_OBJECT) { if (token != JsonToken.FIELD_NAME) { HollowObjectWriteRecord mapKeyWriteRecord = (HollowObjectWriteRecord) getWriteRecord( schema.getKeyType()); String fieldName = mapKeyWriteRecord.getSchema().getFieldName(0); mapKeyWriteRecord.reset(); switch (mapKeyWriteRecord.getSchema().getFieldType(0)) { case STRING: mapKeyWriteRecord.setString(fieldName, parser.getCurrentName()); break; case BOOLEAN: mapKeyWriteRecord.setBoolean(fieldName, Boolean.valueOf(parser.getCurrentName())); break; case INT: mapKeyWriteRecord.setInt(fieldName, Integer.parseInt(parser.getCurrentName())); break; case LONG: mapKeyWriteRecord.setLong(fieldName, Long.parseLong(parser.getCurrentName())); break; case DOUBLE: mapKeyWriteRecord.setDouble(fieldName, Double.parseDouble(parser.getCurrentName())); break; case FLOAT: mapKeyWriteRecord.setFloat(fieldName, Float.parseFloat(parser.getCurrentName())); break; default: throw new IOException("Cannot parse type " + mapKeyWriteRecord.getSchema().getFieldType(0) + " as key in map (" + mapKeyWriteRecord.getSchema().getName() + ")"); } int keyOrdinal = stateEngine.add(schema.getKeyType(), mapKeyWriteRecord); int valueOrdinal; if (token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) { valueOrdinal = parseSubType(parser, token, schema.getValueType()); } else { if (valueRec == null) { valueRec = getObjectFieldMapping(schema.getValueType()); fieldMapping = valueRec.getSingleFieldMapping(); } addObjectField(parser, token, fieldMapping); valueOrdinal = valueRec.build(-1); } mapRec.addEntry(keyOrdinal, valueOrdinal); } token = parser.nextToken(); } return stateEngine.add(schema.getName(), mapRec); }
From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
/** * Parse the specified input stream and return a user. * * @param inputStream input stream// w w w . jav a2s. co m * @return the specified input stream parsed into a user */ @Override public User parseUser(final InputStream inputStream) { checkNotNull(inputStream); JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String profileId = null; boolean genotyped = false; List<Profile> profiles = new ArrayList<Profile>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else if ("profiles".equals(field)) { while (parser.nextToken() != JsonToken.END_ARRAY) { while (parser.nextToken() != JsonToken.END_OBJECT) { String profileField = parser.getCurrentName(); parser.nextToken(); if ("id".equals(profileField)) { profileId = parser.getText(); } else if ("genotyped".equals(profileField)) { genotyped = parser.getBooleanValue(); } } profiles.add(new Profile(profileId, genotyped)); } } } return new User(id, profiles); } catch (IOException e) { logger.warn("could not parse user", e); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return null; }
From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
@Override public Ancestry parseAncestry(final InputStream inputStream) { checkNotNull(inputStream);//w w w .j a v a 2 s . co m JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String label = null; double proportion = 0.0d; double unassigned = 0.0d; List<Ancestry> subPopulations = new ArrayList<Ancestry>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else if ("ancestry".equals(field)) { while (parser.nextToken() != JsonToken.END_OBJECT) { String ancestryField = parser.getCurrentName(); parser.nextToken(); if ("label".equals(ancestryField)) { label = parser.getText(); } else if ("proportion".equals(ancestryField)) { proportion = Double.parseDouble(parser.getText()); } else if ("unassigned".equals(ancestryField)) { unassigned = Double.parseDouble(parser.getText()); } else if ("sub_populations".equals(ancestryField)) { subPopulations = parseSubPopulation(id, subPopulations, parser); } } } } return new Ancestry(id, label, proportion, unassigned, subPopulations); } catch (IOException e) { logger.warn("could not parse ancestry", e); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return null; }
From source file:com.cedarsoft.serialization.test.performance.XmlParserPerformance.java
private void benchParse(@Nonnull JsonFactory factory, @Nonnull byte[] contentSample) throws XMLStreamException, IOException { for (int i = 0; i < BIG; i++) { JsonParser parser = factory.createParser(contentSample); assertEquals(JsonToken.START_OBJECT, parser.nextToken()); assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("id", parser.getCurrentName()); assertEquals(JsonToken.VALUE_STRING, parser.nextToken()); String id = parser.getText(); assertEquals("Canon Raw", id); assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("dependent", parser.getCurrentName()); assertEquals(JsonToken.VALUE_FALSE, parser.nextToken()); boolean dependent = parser.getBooleanValue(); assertFalse(dependent);/*from w w w .ja va 2s . c o m*/ assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("extension", parser.getCurrentName()); assertEquals(JsonToken.START_OBJECT, parser.nextToken()); assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("extension", parser.getCurrentName()); assertEquals(JsonToken.VALUE_STRING, parser.nextToken()); String extension = parser.getText(); assertEquals("cr2", extension); assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("default", parser.getCurrentName()); assertEquals(JsonToken.VALUE_TRUE, parser.nextToken()); boolean isDefault = parser.getBooleanValue(); assertTrue(isDefault); assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("delimiter", parser.getCurrentName()); assertEquals(JsonToken.VALUE_STRING, parser.nextToken()); String delimiter = parser.getText(); assertEquals(".", delimiter); assertEquals(JsonToken.END_OBJECT, parser.nextToken()); assertEquals(JsonToken.END_OBJECT, parser.nextToken()); assertNull(parser.nextToken()); parser.close(); FileType type = new FileType(id, new Extension(delimiter, extension, isDefault), dependent); assertNotNull(type); } }
From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
@Override public List<Carrier> parseCarriers(final InputStream inputStream) { checkNotNull(inputStream);/* w w w .j a va2s .c o m*/ JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String reportId = null; String description = null; int mutations = 0; List<Carrier> carriers = new ArrayList<Carrier>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else if ("carriers".equals(field)) { while (parser.nextToken() != JsonToken.END_ARRAY) { while (parser.nextToken() != JsonToken.END_OBJECT) { String carrierField = parser.getCurrentName(); parser.nextToken(); if ("report_id".equals(carrierField)) { reportId = parser.getText(); } else if ("description".equals(carrierField)) { description = parser.getText(); } else if ("mutations".equals(carrierField)) { mutations = Integer.parseInt(parser.getText()); } } carriers.add(new Carrier(id, reportId, description, mutations)); reportId = null; description = null; mutations = 0; } } } return carriers; } catch (IOException e) { logger.warn("could not parse carriers", e); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return null; }
From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
@Override public List<DrugResponse> parseDrugResponses(final InputStream inputStream) { checkNotNull(inputStream);//from www . j a v a2 s .c o m JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String reportId = null; String description = null; String status = null; List<DrugResponse> drugResponses = new ArrayList<DrugResponse>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else if ("drug_responses".equals(field)) { while (parser.nextToken() != JsonToken.END_ARRAY) { while (parser.nextToken() != JsonToken.END_OBJECT) { String drugResponseField = parser.getCurrentName(); parser.nextToken(); if ("report_id".equals(drugResponseField)) { reportId = parser.getText(); } else if ("description".equals(drugResponseField)) { description = parser.getText(); } else if ("status".equals(drugResponseField)) { status = parser.getText(); } } drugResponses.add(new DrugResponse(id, reportId, description, status)); reportId = null; description = null; status = null; } } } return drugResponses; } catch (IOException e) { logger.warn("could not parse drug responses", e); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return null; }
From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java
/** * Parses a sequence of coordinates array expressed as * * [ [100.0, 0.0], [101.0, 1.0] ]/* ww w .java 2 s. c om*/ * * @param jp * @throws IOException * @throws SQLException * @return Coordinate[] */ private Coordinate[] parseCoordinates(JsonParser jp) throws IOException { jp.nextToken(); // START_ARRAY [ to parse the each positions ArrayList<Coordinate> coords = new ArrayList<Coordinate>(); while (jp.getCurrentToken() != JsonToken.END_ARRAY) { coords.add(parseCoordinate(jp)); } return coords.toArray(new Coordinate[coords.size()]); }