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

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

Introduction

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

Prototype

public String getValueAsString() throws IOException, JsonParseException 

Source Link

Document

Method that will try to convert value of current token to a java.lang.String .

Usage

From source file:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java

protected static void importTranslation(final JsonParser jsonParser, final Resource post) throws IOException {
    JsonToken token = jsonParser.getCurrentToken();
    final Map<String, Object> properties = new HashMap<String, Object>();
    if (token != JsonToken.START_OBJECT) {
        throw new IOException("expected a start object token, got " + token.asString());
    }/*w w w. j a va 2 s  .  co m*/
    properties.put("jcr:primaryType", "social:asiResource");
    Resource translationFolder = null;
    token = jsonParser.nextToken();
    while (token == JsonToken.FIELD_NAME) {
        token = jsonParser.nextToken(); //advance to the field value
        if (jsonParser.getCurrentName().equals((ContentTypeDefinitions.LABEL_TRANSLATIONS))) {
            if (null == translationFolder) {
                // begin by creating the translation folder resource
                translationFolder = post.getResourceResolver().create(post, "translation", properties);
            }
            //now check to see if any translations exist
            if (token == JsonToken.START_OBJECT) {
                token = jsonParser.nextToken();
                if (token == JsonToken.FIELD_NAME) {
                    while (token == JsonToken.FIELD_NAME) { // each new field represents another translation
                        final Map<String, Object> translationProperties = new HashMap<String, Object>();
                        translationProperties.put("jcr:primaryType", "social:asiResource");
                        String languageLabel = jsonParser.getCurrentName();
                        token = jsonParser.nextToken();
                        if (token != JsonToken.START_OBJECT) {
                            throw new IOException("expected a start object token for translation item, got "
                                    + token.asString());
                        }
                        token = jsonParser.nextToken();
                        while (token != JsonToken.END_OBJECT) {
                            jsonParser.nextToken(); //get next field value
                            if (jsonParser.getCurrentName()
                                    .equals(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS)) {
                                jsonParser.nextToken(); // advance to first field name
                                while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) {
                                    final String timestampLabel = jsonParser.getValueAsString();
                                    if (translationProperties.containsKey(timestampLabel)) {
                                        final Calendar calendar = new GregorianCalendar();
                                        calendar.setTimeInMillis(Long
                                                .parseLong((String) translationProperties.get(timestampLabel)));
                                        translationProperties.put(timestampLabel, calendar.getTime());
                                    }
                                    jsonParser.nextToken();
                                }
                            } else if (jsonParser.getCurrentName()
                                    .equals(ContentTypeDefinitions.LABEL_SUBNODES)) {
                                jsonParser.skipChildren();
                            } else {
                                translationProperties.put(jsonParser.getCurrentName(),
                                        URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8"));
                            }
                            token = jsonParser.nextToken(); //get next field label
                        }
                        // add the language-specific translation under the translation folder resource
                        Resource translation = post.getResourceResolver().create(post.getChild("translation"),
                                languageLabel, translationProperties);
                        if (null == translation) {
                            throw new IOException("translation not actually imported");
                        }
                    }
                    jsonParser.nextToken(); //skip END_OBJECT token for translation
                } else if (token == JsonToken.END_OBJECT) {
                    // no actual translation to import, so we're done here
                    jsonParser.nextToken();
                }
            } else {
                throw new IOException(
                        "expected translations to be contained in an object, saw instead: " + token.asString());
            }
        } else if (jsonParser.getCurrentName().equals("mtlanguage")
                || jsonParser.getCurrentName().equals("jcr:createdBy")) {
            properties.put(jsonParser.getCurrentName(), jsonParser.getValueAsString());
        } else if (jsonParser.getCurrentName().equals("jcr:created")) {
            final Calendar calendar = new GregorianCalendar();
            calendar.setTimeInMillis(jsonParser.getLongValue());
            properties.put("jcr:created", calendar.getTime());
        }
        token = jsonParser.nextToken();
    }
    if (null == translationFolder && properties.containsKey("mtlanguage")) {
        // it's possible that no translations existed, so we need to make sure the translation resource (which
        // includes the original post's detected language) is created anyway
        post.getResourceResolver().create(post, "translation", properties);
    }
}

From source file:com.netflix.hollow.jsonadapter.HollowJsonAdapter.java

private void addObjectField(JsonParser parser, JsonToken token, ObjectMappedFieldPath mappedFieldPath)
        throws IOException {
    if (mappedFieldPath == null) {
        skipObjectField(parser, token);//  w  w  w  .j  ava  2 s. com
    } else {

        HollowObjectWriteRecord writeRec = mappedFieldPath.getWriteRecord();
        HollowObjectSchema schema = writeRec.getSchema();
        String fieldName = mappedFieldPath.getFieldName();
        int fieldPosition = mappedFieldPath.getFieldPosition();

        FieldProcessor processor = mappedFieldPath.getFieldProcessor();
        if (processor != null && token != JsonToken.VALUE_NULL) {
            processor.processField(parser, stateEngine, writeRec);
            return;
        }

        switch (token) {
        case START_ARRAY:
        case START_OBJECT:
            int refOrdinal = parseSubType(parser, token, schema.getReferencedType(fieldPosition));
            writeRec.setReference(fieldName, refOrdinal);
            break;
        case VALUE_FALSE:
        case VALUE_TRUE:
        case VALUE_NUMBER_INT:
        case VALUE_NUMBER_FLOAT:
        case VALUE_STRING:
            switch (schema.getFieldType(fieldPosition)) {
            case BOOLEAN:
                writeRec.setBoolean(fieldName, parser.getBooleanValue());
                break;
            case INT:
                writeRec.setInt(fieldName, parser.getIntValue());
                break;
            case LONG:
                writeRec.setLong(fieldName, parser.getLongValue());
                break;
            case DOUBLE:
                writeRec.setDouble(fieldName, parser.getDoubleValue());
                break;
            case FLOAT:
                writeRec.setFloat(fieldName, parser.getFloatValue());
                break;
            case STRING:
                writeRec.setString(fieldName, parser.getValueAsString());
                break;
            case REFERENCE:
                HollowObjectWriteRecord referencedRec = (HollowObjectWriteRecord) getWriteRecord(
                        schema.getReferencedType(fieldPosition));
                referencedRec.reset();
                String refFieldName = referencedRec.getSchema().getFieldName(0);
                switch (referencedRec.getSchema().getFieldType(0)) {
                case BOOLEAN:
                    referencedRec.setBoolean(refFieldName, parser.getBooleanValue());
                    break;
                case INT:
                    referencedRec.setInt(refFieldName, parser.getIntValue());
                    break;
                case LONG:
                    referencedRec.setLong(refFieldName, parser.getLongValue());
                    break;
                case DOUBLE:
                    referencedRec.setDouble(refFieldName, parser.getDoubleValue());
                    break;
                case FLOAT:
                    referencedRec.setFloat(refFieldName, parser.getFloatValue());
                    break;
                case STRING:
                    referencedRec.setString(refFieldName, parser.getValueAsString());
                    break;
                default:
                }

                int referencedOrdinal = stateEngine.add(schema.getReferencedType(fieldPosition), referencedRec);
                writeRec.setReference(fieldName, referencedOrdinal);
                break;
            default:
            }
        case VALUE_NULL:
            break;
        default:
        }
    }
}

From source file:org.apache.airavata.db.AbstractThriftDeserializer.java

@Override
public T deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    final T instance = newInstance();
    final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    final ObjectNode rootNode = mapper.readTree(jp);
    final Iterator<Map.Entry<String, JsonNode>> iterator = rootNode.fields();

    while (iterator.hasNext()) {
        final Map.Entry<String, JsonNode> currentField = iterator.next();
        try {/*from  w  ww .  jav a 2  s .c  om*/
            /*
             * If the current node is not a null value, process it.  Otherwise,
             * skip it.  Jackson will treat the null as a 0 for primitive
             * number types, which in turn will make Thrift think the field
             * has been set. Also we ignore the MongoDB specific _id field
             */
            if (!currentField.getKey().equalsIgnoreCase("_id")
                    && currentField.getValue().getNodeType() != JsonNodeType.NULL) {
                final E field = getField(
                        CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, currentField.getKey()));
                final JsonParser parser = currentField.getValue().traverse();
                parser.setCodec(mapper);
                final Object value = mapper.readValue(parser, generateValueType(instance, field));
                if (value != null) {
                    log.debug(String.format("Field %s produced value %s of type %s.", currentField.getKey(),
                            value, value.getClass().getName()));
                    instance.setFieldValue(field, value);
                } else {
                    log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
                }
            } else {
                log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
            }
        } catch (final NoSuchFieldException | IllegalArgumentException e) {
            log.error("Unable to de-serialize field '{}'.", currentField.getKey(), e);
            ctxt.mappingException(e.getMessage());
        }
    }

    try {
        // Validate that the instance contains all required fields.
        validate(instance);
    } catch (final TException e) {
        log.error(String.format("Unable to deserialize JSON '%s' to type '%s'.", jp.getValueAsString(),
                instance.getClass().getName(), e));
        ctxt.mappingException(e.getMessage());
    }

    return instance;
}

From source file:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java

protected void extractEvent(final JsonParser jsonParser, final Resource resource) throws IOException {

    String author = null;//w w  w .j a  va  2  s  .  c om
    final JSONObject requestParams = new JSONObject();
    try {
        jsonParser.nextToken();
        JsonToken token = jsonParser.getCurrentToken();
        while (token.equals(JsonToken.FIELD_NAME)) {
            String field = jsonParser.getCurrentName();
            jsonParser.nextToken();

            if (field.equals(PN_START) || field.equals(PN_END)) {
                final Long value = jsonParser.getValueAsLong();
                final Calendar calendar = new GregorianCalendar();
                calendar.setTimeInMillis(value);
                final Date date = calendar.getTime();
                final TimeZone tz = TimeZone.getTimeZone("UTC");
                // this is the ISO-8601 format expected by the CalendarOperations object
                final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm+00:00");
                df.setTimeZone(tz);
                if (field.equals(PN_START)) {
                    requestParams.put(CalendarRequestConstants.START_DATE, df.format(date));
                } else {
                    requestParams.put(CalendarRequestConstants.END_DATE, df.format(date));
                }
            } else if (field.equals(CalendarRequestConstants.TAGS)) {
                List<String> tags = new ArrayList<String>();
                if (jsonParser.getCurrentToken().equals(JsonToken.START_ARRAY)) {
                    token = jsonParser.nextToken();
                    while (!token.equals(JsonToken.END_ARRAY)) {
                        tags.add(URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8"));
                        token = jsonParser.nextToken();
                    }
                    requestParams.put(CalendarRequestConstants.TAGS, tags);
                } else {
                    LOG.warn("Tags field came in without an array of tags in it - not processed");
                    // do nothing, just log the error
                }
            } else if (field.equals("jcr:createdBy")) {
                author = URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8");
            } else if (field.equals(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS)) {
                jsonParser.skipChildren(); // we do nothing with these because they're going to be put into json
            } else {
                try {
                    final String value = URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8");
                    requestParams.put(field, value);
                } catch (NullPointerException e) {
                    throw e;
                }
            }
            token = jsonParser.nextToken();
        }
    } catch (final JSONException e) {
        throw new IOException("Unable to build a JSON object with the inputs provided", e);
    }
    try {
        Map<String, Object> eventParams = new HashMap<String, Object>();
        eventParams.put("event", requestParams.toString());
        calendarOperations.create(resource, author, eventParams, null,
                resource.getResourceResolver().adaptTo(Session.class));
    } catch (final OperationException e) {
        //probably caused by creating a folder that already exists. We ignore it, but still log the event.
        LOG.info("There was an operation exception while creating an event");
    }
}

From source file:com.netflix.hollow.jsonadapter.HollowJsonAdapterPrimaryKeyFinder.java

private void addObjectField(JsonParser parser, JsonToken token, HollowObjectSchema schema, String fieldName,
        StringBuilder currentFieldPath) throws IOException {
    if (token != JsonToken.FIELD_NAME) {
        int fieldPosition = schema.getPosition(fieldName);

        if (fieldPosition == -1) {
            skipObjectField(parser, token);
        } else {/* w w  w  . j av  a 2s  .  c o  m*/
            int parentFieldPathLength = currentFieldPath.length();
            if (parentFieldPathLength > 0)
                currentFieldPath.append(".");
            currentFieldPath.append(fieldName);
            Integer keyFieldPosition = keyFieldPathPositions.get(currentFieldPath.toString());

            switch (token) {
            case START_ARRAY:
                skipSubArray(parser);
                break;
            case START_OBJECT:
                String referencedType = schema.getReferencedType(fieldName);
                HollowSchema referencedSchema = hollowSchemas.get(referencedType);

                if (referencedSchema.getSchemaType() == SchemaType.OBJECT)
                    addObject(parser, (HollowObjectSchema) referencedSchema, currentFieldPath);
                else
                    skipObject(parser);

                break;
            case VALUE_FALSE:
            case VALUE_TRUE:
            case VALUE_NUMBER_INT:
            case VALUE_NUMBER_FLOAT:
            case VALUE_STRING:
                switch (schema.getFieldType(fieldPosition)) {
                case BOOLEAN:
                    if (keyFieldPosition != null)
                        keyElementArray[keyFieldPosition.intValue()] = Boolean
                                .valueOf(parser.getBooleanValue());
                    break;
                case INT:
                    if (keyFieldPosition != null)
                        keyElementArray[keyFieldPosition.intValue()] = Integer.valueOf(parser.getIntValue());
                    break;
                case LONG:
                    if (keyFieldPosition != null)
                        keyElementArray[keyFieldPosition.intValue()] = Long.valueOf(parser.getLongValue());
                    break;
                case DOUBLE:
                    if (keyFieldPosition != null)
                        keyElementArray[keyFieldPosition.intValue()] = Double.valueOf(parser.getDoubleValue());
                    break;
                case FLOAT:
                    if (keyFieldPosition != null)
                        keyElementArray[keyFieldPosition.intValue()] = Float.valueOf(parser.getFloatValue());
                    break;
                case STRING:
                    if (keyFieldPosition != null)
                        keyElementArray[keyFieldPosition.intValue()] = parser.getValueAsString();
                    break;
                case REFERENCE:
                    if (keyFieldPosition != null)
                        throw new IllegalStateException("Key elements must not be REFERENCE");
                    HollowObjectSchema subSchema = (HollowObjectSchema) hollowSchemas
                            .get(schema.getReferencedType(fieldPosition));
                    currentFieldPath.append(".").append(subSchema.getFieldName(0));
                    keyFieldPosition = keyFieldPathPositions.get(currentFieldPath.toString());
                    if (keyFieldPosition != null) {
                        switch (subSchema.getFieldType(0)) {
                        case BOOLEAN:
                            if (keyFieldPosition != null)
                                keyElementArray[keyFieldPosition.intValue()] = Boolean
                                        .valueOf(parser.getBooleanValue());
                            break;
                        case INT:
                            if (keyFieldPosition != null)
                                keyElementArray[keyFieldPosition.intValue()] = Integer
                                        .valueOf(parser.getIntValue());
                            break;
                        case LONG:
                            if (keyFieldPosition != null)
                                keyElementArray[keyFieldPosition.intValue()] = Long
                                        .valueOf(parser.getLongValue());
                            break;
                        case DOUBLE:
                            if (keyFieldPosition != null)
                                keyElementArray[keyFieldPosition.intValue()] = Double
                                        .valueOf(parser.getDoubleValue());
                            break;
                        case FLOAT:
                            if (keyFieldPosition != null)
                                keyElementArray[keyFieldPosition.intValue()] = Float
                                        .valueOf(parser.getFloatValue());
                            break;
                        case STRING:
                            if (keyFieldPosition != null)
                                keyElementArray[keyFieldPosition.intValue()] = parser.getValueAsString();
                            break;
                        case REFERENCE:
                            throw new IllegalStateException("Key elements must not be REFERENCE");
                        default:
                        }
                    }

                default:
                }
            case VALUE_NULL:
                break;
            default:
            }

            currentFieldPath.setLength(parentFieldPathLength);
        }
    }
}

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 {//from ww  w. j  a  v  a  2 s. 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:com.netflix.hollow.jsonadapter.discover.HollowJsonAdapterSchemaDiscoverer.java

private void discoverSchemaField(JsonParser parser, JsonToken token, String fieldName,
        HollowDiscoveredSchema schema) throws IOException {

    if (token != JsonToken.FIELD_NAME) {
        switch (token) {
        case START_ARRAY:
            String listName = schemaNamer.subCollectionName(schema.schemaName, "ArrayOf", fieldName);
            String elementName = schemaNamer.subObjectName(schema.schemaName, "", fieldName);
            if (isDebug)
                System.out.println(String.format(
                        "\t ARR[START] token=%s schemaName=%s fieldName=%s listName=%s elementName=%s", token,
                        schema.schemaName, fieldName, listName, elementName));

            discoveredSchema(listName, DiscoveredSchemaType.LIST, elementName);
            schema.addField(fieldName, FieldType.REFERENCE, listName);

            HollowDiscoveredSchema elementSchema = discoveredSchema(elementName, DiscoveredSchemaType.OBJECT,
                    null);//from  ww w.j  ava 2 s.c  o  m
            discoverSubArraySchemas(parser, elementSchema);
            if (isDebug)
                System.out.println(String.format(
                        "\t ARR[END] token=%s schemaName=%s fieldName=%s listName=%s elementName=%s elementSchema=%s",
                        token, schema.schemaName, fieldName, listName, elementName, elementSchema));

            break;
        case START_OBJECT:
            String subObjectName = schemaNamer.subObjectName(schema.schemaName, "", fieldName);
            //if (isDebug) System.out.println("\t\t [MAP CHECK] subObjectName=" + subObjectName + "\t" + mapTypes.contains(subObjectName) + "\t" + mapTypes);
            if (mapTypes.contains(subObjectName)) {
                String subMapName = schemaNamer.subCollectionName(schema.schemaName, "MapOf", fieldName);
                if (isDebug)
                    System.out.println(String.format(
                            "\t MAP[START] token=%s schemaName=%s fieldName=%s subMapName=%s subObjectName=%s",
                            token, schema.schemaName, fieldName, subMapName, subObjectName));

                discoveredSchema(subMapName, DiscoveredSchemaType.MAP, subObjectName);
                schema.addField(fieldName, FieldType.REFERENCE, subMapName);

                HollowDiscoveredSchema valueSchema = discoveredSchema(subObjectName,
                        DiscoveredSchemaType.OBJECT, null);
                discoverSubMapSchemas(parser, valueSchema);
                if (isDebug)
                    System.out.println(String.format(
                            "\t MAP[END] token=%s schemaName=%s fieldName=%s subMapName=%s subObjectName=%s valueSchema=%s",
                            token, schema.schemaName, fieldName, subMapName, subObjectName, valueSchema));
            } else {
                if (isDebug)
                    System.out.println(
                            String.format("\t OBJ[START] token=%s schemaName=%s fieldName=%s subObjectName=%s",
                                    token, schema.schemaName, fieldName, subObjectName));
                HollowDiscoveredSchema subObjectSchema = discoveredSchema(subObjectName,
                        DiscoveredSchemaType.OBJECT, null);
                if (fieldName != null)
                    schema.addField(fieldName, FieldType.REFERENCE, subObjectName);

                discoverSchemas(parser, subObjectSchema);
                if (isDebug)
                    System.out.println(String.format(
                            "\t OBJ[END] token=%s schemaName=%s fieldName=%s subObjectName=%s subObjectSchema=%s",
                            token, schema.schemaName, fieldName, subObjectName, subObjectSchema));
            }

            break;
        case VALUE_NUMBER_INT:
            if (isDebug)
                System.out.println(String.format("\t FIELD token=%s schemaName=%s fieldName=%s value=%s", token,
                        schema.schemaName, fieldName, parser.getLongValue()));
            schema.addField(fieldName, FieldType.LONG);
            break;
        case VALUE_NUMBER_FLOAT:
            if (isDebug)
                System.out.println(String.format("\t FIELD token=%s schemaName=%s fieldName=%s value=%s", token,
                        schema.schemaName, fieldName, parser.getDoubleValue()));
            schema.addField(fieldName, FieldType.DOUBLE);
            break;
        case VALUE_NULL:
            if (isDebug)
                System.out.println(String.format("\t FIELD token=%s schemaName=%s fieldName=%s", token,
                        schema.schemaName, fieldName));
            break;
        case VALUE_STRING:
            if (isDebug)
                System.out.println(String.format("\t FIELD token=%s schemaName=%s fieldName=%s value=%s", token,
                        schema.schemaName, fieldName, parser.getValueAsString()));
            schema.addField(fieldName, FieldType.STRING);
            break;
        case VALUE_FALSE:
        case VALUE_TRUE:
            if (isDebug)
                System.out.println(String.format("\t FIELD token=%s schemaName=%s fieldName=%s value=%s", token,
                        schema.schemaName, fieldName, parser.getBooleanValue()));
            schema.addField(fieldName, FieldType.BOOLEAN);
            break;
        default:
        }
    }
}

From source file:org.openhab.binding.weather.internal.parser.JsonWeatherParser.java

/**
 * Iterates through the JSON structure and collects weather data.
 *///from w w w.ja va  2  s  . co m
private void handleToken(JsonParser jp, String property, Weather weather) throws Exception {
    JsonToken token = jp.getCurrentToken();
    String prop = PropertyResolver.add(property, jp.getCurrentName());

    if (token.isStructStart()) {
        boolean isObject = token == JsonToken.START_OBJECT || token == JsonToken.END_OBJECT;

        Weather forecast = !isObject ? weather : startIfForecast(weather, prop);
        while (!jp.nextValue().isStructEnd()) {
            handleToken(jp, prop, forecast);
        }
        if (isObject) {
            endIfForecast(weather, forecast, prop);
        }
    } else {
        try {
            setValue(weather, prop, jp.getValueAsString());
        } catch (Exception ex) {
            logger.error("Error setting property '{}' with value '{}' ({})", prop, jp.getValueAsString(),
                    ex.getMessage());
        }
    }
}

From source file:org.openo.msb.wrapper.consul.util.Base64EncodingDeserializer.java

/**
 * {@inheritDoc}/*  w w  w  .j  a  va  2 s  .c o  m*/
 */
@Override
public Optional<String> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    String value = p.getValueAsString();

    if (StringUtils.isNotEmpty(value)) {
        return Optional.of(new String(BaseEncoding.base64().decode(value)));
    }
    return Optional.absent();
}

From source file:org.openo.msb.wrapper.consul.util.SecondsDeserializer.java

@Override
public Long deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    String value = p.getValueAsString();

    if (StringUtils.isNotEmpty(value)) {
        value = value.replaceAll("[a-zA-Z]", "");
        return Long.valueOf(value);
    } else {//from  w  w  w. ja v a2s . co m
        return null;
    }
}