List of usage examples for com.fasterxml.jackson.core JsonParser getCurrentToken
public abstract JsonToken getCurrentToken();
From source file:com.google.openrtb.json.OpenRtbNativeJsonReader.java
/** * Desserializes a {@link NativeResponse} from JSON, with a provided {@link JsonParser} * which allows several choices of input and encoding. */// w ww . j ava 2 s . c om public final NativeResponse.Builder readNativeResponse(JsonParser par) throws IOException { if (emptyToNull(par)) { return null; } NativeResponse.Builder resp = NativeResponse.newBuilder(); boolean rootNativeField = false; boolean firstField = true; for (startObject(par); endObject(par); par.nextToken()) { String fieldName = getCurrentName(par); if (par.nextToken() != JsonToken.VALUE_NULL) { if (firstField) { firstField = false; if ((rootNativeField = "native".equals(fieldName)) == true) { startObject(par); fieldName = getCurrentName(par); par.nextToken(); } } if (par.getCurrentToken() != JsonToken.VALUE_NULL) { readNativeResponseField(par, resp, fieldName); } } } if (rootNativeField && !endObject(par)) { par.nextToken(); } return resp; }
From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java
/** * Each element in the geometries array of a GeometryCollection is one of * the geometry objects described above: * * { "type": "GeometryCollection", "geometries": [ { "type": "Point", * "coordinates": [100.0, 0.0] }, { "type": "LineString", "coordinates": [ * [101.0, 0.0], [102.0, 1.0] ] } ]//from ww w.j ava 2 s. com * * @param jp * * @throws IOException * @throws SQLException * @return GeometryCollection */ private GeometryCollection parseGeometryCollection(JsonParser jp) throws IOException, SQLException { jp.nextToken(); // FIELD_NAME geometries String coordinatesField = jp.getText(); if (coordinatesField.equalsIgnoreCase(GeoJsonField.GEOMETRIES)) { jp.nextToken();//START array jp.nextToken();//START object ArrayList<Geometry> geometries = new ArrayList<Geometry>(); while (jp.getCurrentToken() != JsonToken.END_ARRAY) { geometries.add(parseGeometry(jp)); jp.nextToken(); } jp.nextToken();//END_OBJECT } geometry return GF.createGeometryCollection(geometries.toArray(new Geometry[geometries.size()])); } else { throw new SQLException( "Malformed GeoJSON file. Expected 'geometries', found '" + coordinatesField + "'"); } }
From source file:com.microsoft.windowsazure.storage.table.TableParser.java
/** * Reserved for internal use. Parses the operation response as a collection of entities. Reads entity data from the * specified input stream using the specified class type and optionally projects each entity result with the * specified resolver into an {@link ODataPayload} containing a collection of {@link TableResult} objects. * // www. j a v a2s . c om * @param inStream * The <code>InputStream</code> to read the data to parse from. * @param clazzType * The class type <code>T</code> implementing {@link TableEntity} for the entities returned. Set to * <code>null</code> to ignore the returned entities and copy only response properties into the * {@link TableResult} objects. * @param resolver * An {@link EntityResolver} instance to project the entities into instances of type <code>R</code>. Set * to <code>null</code> to return the entities as instances of the class type <code>T</code>. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * @return * An {@link ODataPayload} containing a collection of {@link TableResult} objects with the parsed operation * response. * @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. */ @SuppressWarnings("unchecked") private static <T extends TableEntity, R> ODataPayload<?> parseJsonQueryResponse(final InputStream inStream, final Class<T> clazzType, final EntityResolver<R> resolver, final TableRequestOptions options, final OperationContext opContext) throws ParseException, InstantiationException, IllegalAccessException, StorageException, JsonParseException, IOException { ODataPayload<T> corePayload = null; ODataPayload<R> resolvedPayload = null; ODataPayload<?> commonPayload = null; JsonParser parser = createJsonParserFromStream(inStream); try { if (resolver != null) { resolvedPayload = new ODataPayload<R>(); commonPayload = resolvedPayload; } else { corePayload = new ODataPayload<T>(); commonPayload = corePayload; } if (!parser.hasCurrentToken()) { parser.nextToken(); } ODataUtilities.assertIsStartObjectJsonToken(parser); // move into data parser.nextToken(); // if there is a clazz type and if JsonNoMetadata, create a classProperties dictionary to use for type inference once // instead of querying the cache many times HashMap<String, PropertyPair> classProperties = null; if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata && clazzType != null) { classProperties = PropertyPair.generatePropertyPairs(clazzType); } while (parser.getCurrentToken() != null) { if (parser.getCurrentToken() == JsonToken.FIELD_NAME && parser.getCurrentName().equals(ODataConstants.VALUE)) { // move to start of array parser.nextToken(); ODataUtilities.assertIsStartArrayJsonToken(parser); // go to properties parser.nextToken(); while (parser.getCurrentToken() == JsonToken.START_OBJECT) { final TableResult res = parseJsonEntity(parser, clazzType, classProperties, resolver, options, opContext); if (corePayload != null) { corePayload.tableResults.add(res); } if (resolver != null) { resolvedPayload.results.add((R) res.getResult()); } else { corePayload.results.add((T) res.getResult()); } parser.nextToken(); } ODataUtilities.assertIsEndArrayJsonToken(parser); } parser.nextToken(); } } finally { parser.close(); } return commonPayload; }
From source file:com.zenesis.qx.remote.RequestHandler.java
/** * Handles the callback from the client; expects either an object or an array of objects * @param request//from ww w . jav a2 s . co m * @param response * @throws ServletException * @throws IOException */ public void processRequest(Reader request, Writer response) throws ServletException, IOException { s_currentHandler.set(this); ObjectMapper objectMapper = tracker.getObjectMapper(); try { if (log.isDebugEnabled()) { StringWriter sw = new StringWriter(); char[] buffer = new char[32 * 1024]; int length; while ((length = request.read(buffer)) > 0) { sw.write(buffer, 0, length); } log.debug("Received: " + sw.toString()); request = new StringReader(sw.toString()); } JsonParser jp = objectMapper.getJsonFactory().createJsonParser(request); if (jp.nextToken() == JsonToken.START_ARRAY) { while (jp.nextToken() != JsonToken.END_ARRAY) processCommand(jp); } else if (jp.getCurrentToken() == JsonToken.START_OBJECT) processCommand(jp); if (tracker.hasDataToFlush()) { Writer actualResponse = response; if (log.isDebugEnabled()) { final Writer tmp = response; actualResponse = new Writer() { @Override public void close() throws IOException { tmp.close(); } @Override public void flush() throws IOException { tmp.flush(); } @Override public void write(char[] arg0, int arg1, int arg2) throws IOException { System.out.print(new String(arg0, arg1, arg2)); tmp.write(arg0, arg1, arg2); } }; } objectMapper.writeValue(actualResponse, tracker.getQueue()); } } catch (ProxyTypeSerialisationException e) { log.fatal("Unable to serialise type information to client: " + e.getMessage(), e); } catch (ProxyException e) { handleException(response, objectMapper, e); } catch (Exception e) { log.error("Exception during callback: " + e.getMessage(), e); tracker.getQueue().queueCommand(CommandType.EXCEPTION, null, null, new ExceptionDetails(e.getClass().getName(), e.getMessage())); objectMapper.writeValue(response, tracker.getQueue()); } finally { s_currentHandler.set(null); } }
From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java
/** * Parses an array of positions defined as: * * { "type": "MultiLineString", "coordinates": [ [ [100.0, 0.0], [101.0, * 1.0] ], [ [102.0, 2.0], [103.0, 3.0] ] ] } * * @param jsParser//from w w w. j a v a 2s. co m * @return MultiLineString */ private MultiLineString parseMultiLinestring(JsonParser jp) throws IOException, SQLException { jp.nextToken(); // FIELD_NAME coordinates String coordinatesField = jp.getText(); if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) { ArrayList<LineString> lineStrings = new ArrayList<LineString>(); jp.nextToken();//START_ARRAY [ coordinates jp.nextToken(); // START_ARRAY [ coordinates line while (jp.getCurrentToken() != JsonToken.END_ARRAY) { lineStrings.add(GF.createLineString(parseCoordinates(jp))); jp.nextToken(); } MultiLineString line = GF .createMultiLineString(lineStrings.toArray(new LineString[lineStrings.size()])); jp.nextToken();//END_OBJECT } geometry return line; } else { throw new SQLException( "Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'"); } }
From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java
/** * Coordinates of a MultiPolygon are an array of Polygon coordinate arrays: * * { "type": "MultiPolygon", "coordinates": [ [[[102.0, 2.0], [103.0, 2.0], * [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], * [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], [[100.2, 0.2], [100.8, 0.2], * [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] } * * @param jp/*from w w w . j av a 2 s .c om*/ * @throws IOException * @throws SQLException * @return MultiPolygon */ private MultiPolygon parseMultiPolygon(JsonParser jp) throws IOException, SQLException { jp.nextToken(); // FIELD_NAME coordinates String coordinatesField = jp.getText(); if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) { ArrayList<Polygon> polygons = new ArrayList<Polygon>(); jp.nextToken(); // START_ARRAY [ coordinates jp.nextToken(); //Start the polygon while (jp.getCurrentToken() != JsonToken.END_ARRAY) { //Parse the polygon jp.nextToken(); //Start the RING int linesIndex = 0; LinearRing linearRing = null; ArrayList<LinearRing> holes = new ArrayList<LinearRing>(); while (jp.getCurrentToken() != JsonToken.END_ARRAY) { if (linesIndex == 0) { linearRing = GF.createLinearRing(parseCoordinates(jp)); } else { holes.add(GF.createLinearRing(parseCoordinates(jp))); } jp.nextToken();//END RING linesIndex++; } if (linesIndex > 1) { jp.nextToken();//END_OBJECT polygons.add(GF.createPolygon(linearRing, holes.toArray(new LinearRing[holes.size()]))); } else { jp.nextToken();//END_OBJECT polygons.add(GF.createPolygon(linearRing, null)); } } jp.nextToken();//END_OBJECT } geometry return GF.createMultiPolygon(polygons.toArray(new Polygon[polygons.size()])); } else { throw new SQLException( "Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'"); } }
From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java
/** * Coordinates of a Polygon are an array of LinearRing coordinate arrays. * The first element in the array represents the exterior ring. Any * subsequent elements represent interior rings (or holes). * * Syntax:/*from w w w . j a va 2 s . co m*/ * * No holes: * * { "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0], * [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] } * * With holes: * * { "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0], * [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], [ [100.2, 0.2], [100.8, 0.2], * [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] ] } * * * * @param jp * @return Polygon */ private Polygon parsePolygon(JsonParser jp) throws IOException, SQLException { jp.nextToken(); // FIELD_NAME coordinates String coordinatesField = jp.getText(); if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) { jp.nextToken(); // START_ARRAY [ coordinates jp.nextToken(); //Start the RING int linesIndex = 0; LinearRing linearRing = null; ArrayList<LinearRing> holes = new ArrayList<LinearRing>(); while (jp.getCurrentToken() != JsonToken.END_ARRAY) { if (linesIndex == 0) { linearRing = GF.createLinearRing(parseCoordinates(jp)); } else { holes.add(GF.createLinearRing(parseCoordinates(jp))); } jp.nextToken();//END RING linesIndex++; } if (linesIndex > 1) { jp.nextToken();//END_OBJECT } geometry return GF.createPolygon(linearRing, holes.toArray(new LinearRing[holes.size()])); } else { jp.nextToken();//END_OBJECT } geometry return GF.createPolygon(linearRing, null); } } else { throw new SQLException( "Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'"); } }
From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java
/** * Method called when there are declared "unwrapped" properties * which need special handling// ww w . j a v a 2 s . co m */ @SuppressWarnings("resource") protected Object deserializeWithUnwrapped(JsonParser jp, DeserializationContext ctxt) throws IOException { if (_delegateDeserializer != null) { return _valueInstantiator.createUsingDelegate(ctxt, _delegateDeserializer.deserialize(jp, ctxt)); } if (_propertyBasedCreator != null) { return deserializeUsingPropertyBasedWithUnwrapped(jp, ctxt); } TokenBuffer tokens = new TokenBuffer(jp); tokens.writeStartObject(); final Object bean = _valueInstantiator.createUsingDefault(ctxt); if (_injectables != null) { injectValues(ctxt, bean); } final Class<?> activeView = _needViewProcesing ? ctxt.getActiveView() : null; beanDeserializerAdvice.before(bean, jp, ctxt); for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) { String propName = jp.getCurrentName(); jp.nextToken(); if (beanDeserializerAdvice.intercept(bean, propName, jp, ctxt)) { continue; } SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { // normal case if (activeView != null && !prop.visibleInView(activeView)) { jp.skipChildren(); continue; } try { prop.deserializeAndSet(jp, ctxt, bean); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } // ignorable things should be ignored if (_ignorableProps != null && _ignorableProps.contains(propName)) { handleIgnoredProperty(jp, ctxt, bean, propName); continue; } // but... others should be passed to unwrapped property deserializers tokens.writeFieldName(propName); tokens.copyCurrentStructure(jp); // how about any setter? We'll get copies but... if (_anySetter != null) { try { _anySetter.deserializeAndSet(jp, ctxt, bean, propName); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } } tokens.writeEndObject(); _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens); beanDeserializerAdvice.after(bean, jp, ctxt); return bean; }
From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java
/** * Features in GeoJSON contain a geometry object and additional properties * * Syntax:// www. j a v a2s . c om * * { "type": "Feature", "geometry":{"type": "Point", "coordinates": [102.0, * 0.5]}, "properties": {"prop0": "value0"} } * * @param jsParser */ private void parseFeature(JsonParser jp) throws IOException, SQLException { jp.nextToken(); // FIELD_NAME geometry String firstField = jp.getText(); fieldIndex = 1; if (firstField.equalsIgnoreCase(GeoJsonField.GEOMETRY)) { jp.nextToken(); //START_OBJECT { getPreparedStatement().setObject(fieldIndex, parseGeometry(jp)); fieldIndex++; } else if (firstField.equalsIgnoreCase(GeoJsonField.PROPERTIES)) { parseProperties(jp, fieldIndex); } //If there is only one geometry field in the feature them the next //token corresponds to the end object of the feature jp.nextToken(); if (jp.getCurrentToken() != JsonToken.END_OBJECT) { String secondParam = jp.getText();// field name if (secondParam.equalsIgnoreCase(GeoJsonField.GEOMETRY)) { jp.nextToken(); //START_OBJECT { getPreparedStatement().setObject(fieldIndex, parseGeometry(jp)); fieldIndex++; } else if (secondParam.equalsIgnoreCase(GeoJsonField.PROPERTIES)) { parseProperties(jp, fieldIndex); } jp.nextToken(); //END_OBJECT } feature } if (!hasProperties) { getPreparedStatement().setObject(fieldIndex, featureCounter); } getPreparedStatement().execute(); }
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. * //from w ww . j a v a2 s.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 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; }