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

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

Introduction

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

Prototype

public abstract String getText() throws IOException, JsonParseException;

Source Link

Document

Method for accessing textual representation of the current token; if no current token (before first call to #nextToken , or after encountering end-of-input), returns null.

Usage

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 v  a 2 s .c o 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: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  a va2s  .c o m
 * @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

/**
 * Check if the geometry is well formatted and contained an array of coordinates.
 * /*from w  ww  .jav a 2s .c o m*/
 * @param jp
 * @param metadataBuilder
 * @throws SQLException
 * @throws IOException 
 */
private void checkCoordinates(JsonParser jp, StringBuilder metadataBuilder, String geometryType)
        throws SQLException, IOException {
    jp.nextToken(); // FIELD_NAME coordinates
    if (jp.getText().equalsIgnoreCase(GeoJsonField.COORDINATES)) {
        jp.nextToken();//START coordinates array
        jp.skipChildren();
        if (isH2) {
            metadataBuilder.append("THE_GEOM ").append(geometryType).append(",");
        } else {
            metadataBuilder.append("THE_GEOM GEOMETRY(").append(geometryType).append(",").append(parsedSRID)
                    .append("),");
        }
    } else {
        throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + jp.getText() + "'");
    }
}

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Parses a GeoJSON geometry and returns its JTS representation.
 *
 * Syntax://from ww  w  .j a v a2s  .co  m
 *
 * "geometry":{"type": "Point", "coordinates": [102.0,0.5]}
 *
 * @param jsParser
 * @throws IOException
 * @return Geometry
 */
private Geometry parseGeometry(JsonParser jsParser) throws IOException, SQLException {
    jsParser.nextToken(); // FIELD_NAME type     
    jsParser.nextToken(); //VALUE_STRING Point
    String geomType = jsParser.getText();
    if (geomType.equalsIgnoreCase(GeoJsonField.POINT)) {
        return parsePoint(jsParser);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.MULTIPOINT)) {
        return parseMultiPoint(jsParser);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.LINESTRING)) {
        return parseLinestring(jsParser);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.MULTILINESTRING)) {
        return parseMultiLinestring(jsParser);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.POLYGON)) {
        return parsePolygon(jsParser);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.MULTIPOLYGON)) {
        return parseMultiPolygon(jsParser);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.GEOMETRYCOLLECTION)) {
        return parseGeometryCollection(jsParser);
    } else {
        throw new SQLException("Unsupported geometry : " + geomType);
    }
}

From source file:org.wso2.extension.siddhi.map.json.sourcemapper.JsonSourceMapper.java

private Event convertToSingleEventForDefaultMapping(Object eventObject) throws IOException {
    Event event = new Event(attributesSize);
    Object[] data = event.getData();
    JsonParser parser;
    int numberOfProvidedAttributes = 0;
    try {/*  www .j av  a2s.  c o  m*/
        parser = factory.createParser(eventObject.toString());
    } catch (IOException e) {
        throw new SiddhiAppRuntimeException(
                "Initializing a parser failed for the event string." + eventObject.toString());
    }
    int position;
    while (!parser.isClosed()) {
        JsonToken jsonToken = parser.nextToken();
        if (JsonToken.START_OBJECT.equals(jsonToken)) {
            parser.nextToken();
            if (DEFAULT_JSON_EVENT_IDENTIFIER.equalsIgnoreCase(parser.getText())) {
                parser.nextToken();
            } else {
                log.error("Default json message " + eventObject
                        + " contains an invalid event identifier. Required \"event\", " + "but found \""
                        + parser.getText() + "\". Hence dropping the message.");
                return null;
            }
        } else if (JsonToken.FIELD_NAME.equals(jsonToken)) {
            String key = parser.getCurrentName();
            numberOfProvidedAttributes++;
            position = findDefaultMappingPosition(key);
            if (position == -1) {
                log.error("Stream \"" + streamDefinition.getId() + "\" does not have an attribute named \""
                        + key + "\", but the received event " + eventObject.toString()
                        + " does. Hence dropping the message.");
                return null;
            }
            jsonToken = parser.nextToken();
            Attribute.Type type = streamAttributes.get(position).getType();

            if (JsonToken.VALUE_NULL.equals(jsonToken)) {
                data[position] = null;
            } else {
                switch (type) {
                case BOOL:
                    if (JsonToken.VALUE_TRUE.equals(jsonToken) || JsonToken.VALUE_FALSE.equals(jsonToken)) {
                        data[position] = parser.getValueAsBoolean();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type BOOL. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case INT:
                    if (JsonToken.VALUE_NUMBER_INT.equals(jsonToken)) {
                        data[position] = parser.getValueAsInt();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type INT. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case DOUBLE:
                    if (JsonToken.VALUE_NUMBER_FLOAT.equals(jsonToken)) {
                        data[position] = parser.getValueAsDouble();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type DOUBLE. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case STRING:
                    if (JsonToken.VALUE_STRING.equals(jsonToken)) {
                        data[position] = parser.getValueAsString();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type STRING. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case FLOAT:
                    if (JsonToken.VALUE_NUMBER_FLOAT.equals(jsonToken)
                            || JsonToken.VALUE_NUMBER_INT.equals(jsonToken)) {
                        data[position] = attributeConverter.getPropertyValue(parser.getValueAsString(),
                                Attribute.Type.FLOAT);
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type FLOAT. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case LONG:
                    if (JsonToken.VALUE_NUMBER_INT.equals(jsonToken)) {
                        data[position] = parser.getValueAsLong();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type LONG. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                default:
                    return null;
                }
            }
        }
    }

    if (failOnMissingAttribute && (numberOfProvidedAttributes != attributesSize)) {
        log.error("Json message " + eventObject.toString()
                + " contains missing attributes. Hence dropping the message.");
        return null;
    }
    return event;
}

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Read the CRS element and return the database SRID.
 * //from   w w w  . j  av  a 2 s  . co m
 * Parsed syntax:
 * 
 * "crs":{
 * "type":"name",
 * "properties":
 * {"name":"urn:ogc:def:crs:EPSG::4326"
 * }
 * }
 * 
 * @param jp
 * @return 
 */
private int readCRS(JsonParser jp) throws IOException, SQLException {
    int srid = 0;
    jp.nextToken(); //START_OBJECT {
    jp.nextToken();// crs type
    jp.nextToken(); // crs name
    String firstField = jp.getText();
    if (firstField.equalsIgnoreCase(GeoJsonField.NAME)) {
        jp.nextToken(); // crs properties
        jp.nextToken(); //START_OBJECT {
        jp.nextToken(); // crs name
        jp.nextToken(); // crs value
        String crsURI = jp.getText();
        String[] split = crsURI.toLowerCase().split(GeoJsonField.CRS_URN_EPSG);
        if (split != null) {
            srid = Integer.valueOf(split[1]);
        } else {
            log.warn("The CRS URN " + crsURI + " is not supported.");
        }
        jp.nextToken(); //END_OBJECT }
        jp.nextToken(); //END_OBJECT }
        jp.nextToken(); //Go to features
    } else if (firstField.equalsIgnoreCase(GeoJsonField.LINK)) {
        log.warn("Linked CRS is not supported.");
        jp.nextToken();
        jp.nextToken();
        jp.nextToken(); //END_OBJECT }
        jp.nextToken(); //END_OBJECT }
        jp.nextToken(); //Go to features
    } else {
        throw new SQLException("Malformed GeoJSON CRS element.");
    }

    return srid;
}

From source file:de.alexkamp.sandbox.ChrootSandbox.java

@Override
public void run() {
    try {/*w  w w  .  j a  va  2 s .  c o m*/
        JsonParser parser = factory.createParser(socket.getInputStream());

        String caller = null;
        String channel = null;
        String message = null;
        JsonToken jt = null;
        while (null != (jt = parser.nextToken())) {
            if (jt.isStructStart()) {
                caller = null;
                channel = null;
                message = null;
            } else if (jt.isStructEnd()) {
                try {
                    handle(caller, channel, message);
                } catch (Exception ex) {
                    handleAsyncError(ex);
                }
            } else {
                String name = parser.getCurrentName();
                parser.nextToken();
                switch (name) {
                case "Caller":
                    caller = parser.getText();
                    break;
                case "Channel":
                    channel = parser.getText();
                    break;
                case "Message":
                    message = parser.getText();
                    break;
                }
            }
        }

    } catch (Exception e) {
        handleAsyncError(e);
    }
}

From source file:com.sdl.odata.unmarshaller.json.core.JsonProcessor.java

/**
 * Process all things that do not contain special ODataTags.
 *
 * @param jsonParser the parser//from w  w  w . j a v a2s. c  o m
 * @throws ODataUnmarshallingException If unable to unmarshall
 * @throws IOException If unable to read input parser
 */
private void process(JsonParser jsonParser) throws IOException, ODataUnmarshallingException {
    if (jsonParser.getCurrentToken() == JsonToken.FIELD_NAME) {
        LOG.info("Starting to parse {} token", jsonParser.getCurrentName());
        String key = jsonParser.getCurrentName();
        jsonParser.nextToken();

        JsonToken token = jsonParser.getCurrentToken();
        if (token == JsonToken.START_ARRAY) {
            if (JsonConstants.VALUE.equals(key)) {
                throw new ODataUnmarshallingException("Feed is not supported");
            }
            values.put(key, getCollectionValue(jsonParser));
        } else if (token == JsonToken.START_OBJECT) {
            values.put(key, getEmbeddedObject(jsonParser));
        } else {
            if (token.equals(JsonToken.VALUE_NULL)) {
                values.put(key, null);
            } else {
                values.put(key, jsonParser.getText());
            }
        }
    }
}

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Parses the metadata properties.//  w  ww.  j a  va  2s  .c o  m
 *
 * @param jp
 * @return index
 */
private int parseMetadataProperties(JsonParser jp, StringBuilder metadataBuilder, int fieldIndex)
        throws IOException {
    jp.nextToken();//START_OBJECT {
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldName = jp.getText().toUpperCase(); //FIELD_NAME columnName            
        JsonToken value = jp.nextToken();
        if (value == JsonToken.VALUE_STRING) {
            metadataBuilder.append(fieldName).append(" VARCHAR");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_TRUE) {
            metadataBuilder.append(fieldName).append(" BOOLEAN");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_FALSE) {
            metadataBuilder.append(fieldName).append(" BOOLEAN");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NUMBER_FLOAT) {
            metadataBuilder.append(fieldName).append(" DOUBLE");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NUMBER_INT) {
            metadataBuilder.append(fieldName).append(" INT");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NULL) {
            metadataBuilder.append(fieldName).append(" VARCHAR");
            fieldIndex++;
        } else {
            // TODO: ignore value.
        }
        metadataBuilder.append(",");
    }
    return fieldIndex;
}

From source file:org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer.java

@Override
public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    JsonToken t = jp.getCurrentToken();//  ww  w .  jav  a  2  s .  com
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    Map<String, Object> errorParams = new HashMap<String, Object>();
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        // Must point to field name
        String fieldName = jp.getCurrentName();
        // And then the value...
        t = jp.nextToken();
        // Note: must handle null explicitly here; value deserializers won't
        Object value;
        if (t == JsonToken.VALUE_NULL) {
            value = null;
        }
        // Some servers might send back complex content
        else if (t == JsonToken.START_ARRAY) {
            value = jp.readValueAs(List.class);
        } else if (t == JsonToken.START_OBJECT) {
            value = jp.readValueAs(Map.class);
        } else {
            value = jp.getText();
        }
        errorParams.put(fieldName, value);
    }

    Object errorCode = errorParams.get("error");
    String errorMessage = errorParams.containsKey("error_description")
            ? errorParams.get("error_description").toString()
            : null;
    if (errorMessage == null) {
        errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString();
    }

    OAuth2Exception ex;
    if ("invalid_client".equals(errorCode)) {
        ex = new InvalidClientException(errorMessage);
    } else if ("unauthorized_client".equals(errorCode)) {
        ex = new UnauthorizedUserException(errorMessage);
    } else if ("invalid_grant".equals(errorCode)) {
        if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) {
            ex = new RedirectMismatchException(errorMessage);
        } else {
            ex = new InvalidGrantException(errorMessage);
        }
    } else if ("invalid_scope".equals(errorCode)) {
        ex = new InvalidScopeException(errorMessage);
    } else if ("invalid_token".equals(errorCode)) {
        ex = new InvalidTokenException(errorMessage);
    } else if ("invalid_request".equals(errorCode)) {
        ex = new InvalidRequestException(errorMessage);
    } else if ("redirect_uri_mismatch".equals(errorCode)) {
        ex = new RedirectMismatchException(errorMessage);
    } else if ("unsupported_grant_type".equals(errorCode)) {
        ex = new UnsupportedGrantTypeException(errorMessage);
    } else if ("unsupported_response_type".equals(errorCode)) {
        ex = new UnsupportedResponseTypeException(errorMessage);
    } else if ("insufficient_scope".equals(errorCode)) {
        ex = new InsufficientScopeException(errorMessage,
                OAuth2Utils.parseParameterList((String) errorParams.get("scope")));
    } else if ("access_denied".equals(errorCode)) {
        ex = new UserDeniedAuthorizationException(errorMessage);
    } else {
        ex = new OAuth2Exception(errorMessage);
    }

    Set<Map.Entry<String, Object>> entries = errorParams.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        if (!"error".equals(key) && !"error_description".equals(key)) {
            Object value = entry.getValue();
            ex.addAdditionalInformation(key, value == null ? null : value.toString());
        }
    }

    return ex;

}