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

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

Introduction

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

Prototype

public abstract JsonToken getCurrentToken();

Source Link

Document

Accessor to find which token parser currently points to, if any; null will be returned if none.

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 ww. j av a  2 s.com
    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.adobe.communities.ugc.migration.importer.UGCImportHelper.java

public static Map<String, Object> extractSubmap(final JsonParser jsonParser) throws IOException {
    jsonParser.nextToken(); // skip the START_OBJECT token
    final Map<String, Object> subMap = new HashMap<String, Object>();
    while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
        final String label = jsonParser.getCurrentName(); // get the current label
        final JsonToken token = jsonParser.nextToken(); // get the current value
        if (!token.isScalarValue()) {
            if (token.equals(JsonToken.START_OBJECT)) {
                // if the next token starts a new object, recurse into it
                subMap.put(label, extractSubmap(jsonParser));
            } else if (token.equals(JsonToken.START_ARRAY)) {
                final List<String> subArray = new ArrayList<String>();
                jsonParser.nextToken(); // skip the START_ARRAY token
                while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) {
                    subArray.add(jsonParser.getValueAsString());
                    jsonParser.nextToken();
                }/* w  w  w.j av  a 2  s. com*/
                subMap.put(label, subArray);
                jsonParser.nextToken(); // skip the END_ARRAY token
            }
        } else {
            // either a string, boolean, or long value
            if (token.isNumeric()) {
                subMap.put(label, jsonParser.getValueAsLong());
            } else {
                final String value = jsonParser.getValueAsString();
                if (value.equals("true") || value.equals("false")) {
                    subMap.put(label, jsonParser.getValueAsBoolean());
                } else {
                    subMap.put(label, value);
                }
            }
        }
        jsonParser.nextToken(); // next token will either be an "END_OBJECT" or a new label
    }
    jsonParser.nextToken(); // skip the END_OBJECT token
    return subMap;
}

From source file:com.unboundid.scim2.common.utils.Parser.java

/**
 * Read a filter from the reader./*from  w w w .ja  v a2s  . co  m*/
 *
 * @param reader The reader to read the filter from.
 * @param isValueFilter Whether to read the filter as a value filter.
 * @return The parsed filter.
 * @throws BadRequestException If the filter string could not be parsed.
 */
private static Filter readFilter(final StringReader reader, final boolean isValueFilter)
        throws BadRequestException {
    final Stack<Filter> outputStack = new Stack<Filter>();
    final Stack<String> precedenceStack = new Stack<String>();

    String token;
    String previousToken = null;

    while ((token = readFilterToken(reader, isValueFilter)) != null) {
        if (token.equals("(") && expectsNewFilter(previousToken)) {
            precedenceStack.push(token);
        } else if (token.equalsIgnoreCase(FilterType.NOT.getStringValue()) && expectsNewFilter(previousToken)) {
            // "not" should be followed by an (
            String nextToken = readFilterToken(reader, isValueFilter);
            if (nextToken == null) {
                throw BadRequestException.invalidFilter("Unexpected end of filter string");
            }
            if (!nextToken.equals("(")) {
                final String msg = String.format("Expected '(' at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }
            precedenceStack.push(token);
        } else if (token.equals(")") && !expectsNewFilter(previousToken)) {
            String operator = closeGrouping(precedenceStack, outputStack, false);
            if (operator == null) {
                final String msg = String.format(
                        "No opening parenthesis matching closing " + "parenthesis at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }
            if (operator.equalsIgnoreCase(FilterType.NOT.getStringValue())) {
                // Treat "not" the same as "(" except wrap everything in a not filter.
                outputStack.push(Filter.not(outputStack.pop()));
            }
        } else if (token.equalsIgnoreCase(FilterType.AND.getStringValue())
                && !expectsNewFilter(previousToken)) {
            // and has higher precedence than or.
            precedenceStack.push(token);
        } else if (token.equalsIgnoreCase(FilterType.OR.getStringValue()) && !expectsNewFilter(previousToken)) {
            // pop all the pending ands first before pushing or.
            LinkedList<Filter> andComponents = new LinkedList<Filter>();
            while (!precedenceStack.isEmpty()) {
                if (precedenceStack.peek().equalsIgnoreCase(FilterType.AND.getStringValue())) {
                    precedenceStack.pop();
                    andComponents.addFirst(outputStack.pop());
                } else {
                    break;
                }
                if (!andComponents.isEmpty()) {
                    andComponents.addFirst(outputStack.pop());
                    outputStack.push(Filter.and(andComponents));
                }
            }

            precedenceStack.push(token);
        } else if (token.endsWith("[") && expectsNewFilter(previousToken)) {
            // This is a complex value filter.
            final Path filterAttribute;
            try {
                filterAttribute = parsePath(token.substring(0, token.length() - 1));
            } catch (final BadRequestException e) {
                Debug.debugException(e);
                final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark,
                        e.getMessage());
                throw BadRequestException.invalidFilter(msg);
            }

            if (filterAttribute.isRoot()) {
                final String msg = String.format("Attribute path expected at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }

            outputStack.push(Filter.hasComplexValue(filterAttribute, readFilter(reader, true)));
        } else if (isValueFilter && token.equals("]") && !expectsNewFilter(previousToken)) {
            break;
        } else if (expectsNewFilter(previousToken)) {
            // This must be an attribute path followed by operator and maybe value.
            final Path filterAttribute;
            try {
                filterAttribute = parsePath(token);
            } catch (final BadRequestException e) {
                Debug.debugException(e);
                final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark,
                        e.getMessage());
                throw BadRequestException.invalidFilter(msg);
            }

            if (filterAttribute.isRoot()) {
                final String msg = String.format("Attribute path expected at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }

            String op = readFilterToken(reader, isValueFilter);

            if (op == null) {
                throw BadRequestException.invalidFilter("Unexpected end of filter string");
            }

            if (op.equalsIgnoreCase(FilterType.PRESENT.getStringValue())) {
                outputStack.push(Filter.pr(filterAttribute));
            } else {
                ValueNode valueNode;
                try {
                    // Mark the beginning of the JSON value so we can later reset back
                    // to this position and skip the actual chars that were consumed
                    // by Jackson. The Jackson parser is buffered and reads everything
                    // until the end of string.
                    reader.mark(0);
                    ScimJsonFactory scimJsonFactory = (ScimJsonFactory) JsonUtils.getObjectReader()
                            .getFactory();
                    JsonParser parser = scimJsonFactory.createScimFilterParser(reader);
                    // The object mapper will return a Java null for JSON null.
                    // Have to distinguish between reading a JSON null and encountering
                    // the end of string.
                    if (parser.getCurrentToken() == null && parser.nextToken() == null) {
                        // End of string.
                        valueNode = null;
                    } else {
                        valueNode = parser.readValueAsTree();

                        // This is actually a JSON null. Use NullNode.
                        if (valueNode == null) {
                            valueNode = JsonUtils.getJsonNodeFactory().nullNode();
                        }
                    }
                    // Reset back to the beginning of the JSON value.
                    reader.reset();
                    // Skip the number of chars consumed by JSON parser.
                    reader.skip(parser.getCurrentLocation().getCharOffset());
                } catch (IOException e) {
                    final String msg = String.format("Invalid comparison value at position %d: %s", reader.mark,
                            e.getMessage());
                    throw BadRequestException.invalidFilter(msg);
                }

                if (valueNode == null) {
                    throw BadRequestException.invalidFilter("Unexpected end of filter string");
                }

                if (op.equalsIgnoreCase(FilterType.EQUAL.getStringValue())) {
                    outputStack.push(Filter.eq(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.NOT_EQUAL.getStringValue())) {
                    outputStack.push(Filter.ne(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.CONTAINS.getStringValue())) {
                    outputStack.push(Filter.co(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.STARTS_WITH.getStringValue())) {
                    outputStack.push(Filter.sw(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.ENDS_WITH.getStringValue())) {
                    outputStack.push(Filter.ew(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.GREATER_THAN.getStringValue())) {
                    outputStack.push(Filter.gt(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.GREATER_OR_EQUAL.getStringValue())) {
                    outputStack.push(Filter.ge(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.LESS_THAN.getStringValue())) {
                    outputStack.push(Filter.lt(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.LESS_OR_EQUAL.getStringValue())) {
                    outputStack.push(Filter.le(filterAttribute, valueNode));
                } else {
                    final String msg = String.format("Unrecognized attribute operator '%s' at position %d. "
                            + "Expected: eq,ne,co,sw,ew,pr,gt,ge,lt,le", op, reader.mark);
                    throw BadRequestException.invalidFilter(msg);
                }
            }
        } else {
            final String msg = String.format("Unexpected character '%s' at position %d", token, reader.mark);
            throw BadRequestException.invalidFilter(msg);
        }
        previousToken = token;
    }

    closeGrouping(precedenceStack, outputStack, true);

    if (outputStack.isEmpty()) {
        throw BadRequestException.invalidFilter("Unexpected end of filter string");
    }
    return outputStack.pop();
}

From source file:com.basistech.rosette.dm.jackson.VersionCheckDeserializer.java

@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    if (p.getCurrentToken() != JsonToken.VALUE_STRING) {
        throw ctxt.wrongTokenException(p, JsonToken.VALUE_STRING, "The value of 'version' must be a string");
    }/*from   w w  w.j av a 2 s  .  com*/
    String version = p.readValueAs(String.class);
    String[] bits = version.split("\\.");
    if (bits.length < 3) { // allow for a fourth digit for some reason some day.
        throw ctxt.weirdStringException(version, String.class, "Versions must be of the form x.y.z");
    }
    if (!"1".equals(bits[0])) {
        throw ctxt.weirdStringException(version, String.class,
                String.format("Incompatible ADM version %s", version));
    }
    return version;
}

From source file:com.animedetour.api.sched.deserialization.PanelDateDeserializerTest.java

@Test(expected = JsonMappingException.class)
public void deserializationFailure() throws IOException {
    PanelDateDeserializer deserializer = new PanelDateDeserializer();
    JsonParser parser = Mockito.mock(JsonParser.class);
    Mockito.when(parser.getCurrentToken()).thenReturn(JsonToken.VALUE_FALSE);
    DeserializationContext context = Mockito.mock(DeserializationContext.class);
    Mockito.when(context.mappingException(Mockito.anyString()))
            .thenReturn(new JsonMappingException("Mapping failure"));

    deserializer.deserialize(parser, context);
}

From source file:com.basistech.rosette.dm.jackson.array.MorphoAnalysisListArrayDeserializer.java

@Override
public List<MorphoAnalysis> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    if (jp.getCurrentToken() != JsonToken.START_ARRAY) {
        throw ctxt.wrongTokenException(jp, JsonToken.START_ARRAY, "Expected array of items");
    }/*from  w w  w .j  ava 2s.  co m*/
    List<MorphoAnalysis> results = Lists.newArrayList();
    MorphoAnalysisTypes type = MorphoAnalysisTypes.PLAIN;
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        if (jp.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) {
            type = MorphoAnalysisTypes.byOrdinal(jp.getIntValue());
            jp.nextToken();
        }
        results.add(jp.readValueAs(type.getMorphoAnalysisClass()));
    }
    return ImmutableList.copyOf(results);
}

From source file:org.elasticsoftware.elasticactors.geoevents.serialization.JacksonGeoHashDeserializer.java

@Override
public GeoHash deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken curr = jp.getCurrentToken();
    // Usually should just get string value:
    if (curr == JsonToken.VALUE_STRING) {
        return GeoHash.fromGeohashString(jp.getText());
    }//from  w  ww .ja  va  2 s.c om
    throw ctxt.mappingException(_valueClass, curr);
}

From source file:org.hyperledger.jackson.BIDDeserializer.java

@Override
public BID deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.VALUE_STRING) {
        String hashString = jp.getText().trim();
        if (hashString.length() == 0) {
            return null;
        }//w w w  .  ja v  a2  s .co  m

        return new BID(hashString);
    }

    throw ctxt.mappingException(handledType());
}

From source file:org.hyperledger.jackson.HashDeserializer.java

@Override
public Hash deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.VALUE_STRING) {
        String hashString = jp.getText().trim();
        if (hashString.length() == 0) {
            return null;
        }//from   w w w. j  av a 2  s  .c o  m

        return new Hash(hashString);
    }

    throw ctxt.mappingException(handledType());
}

From source file:org.hyperledger.jackson.TIDDeserializer.java

@Override
public TID deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.VALUE_STRING) {
        String hashString = jp.getText().trim();
        if (hashString.length() == 0) {
            return null;
        }//  ww  w.  j  ava 2  s .  c om

        return new TID(hashString);
    }

    throw ctxt.mappingException(handledType());
}