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

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

Introduction

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

Prototype

public abstract String getCurrentName() throws IOException, JsonParseException;

Source Link

Document

Method that can be called to get the name associated with the current token: for JsonToken#FIELD_NAME s it will be the same as what #getText returns; for field values it will be preceding field name; and for others (array values, root-level values) null.

Usage

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

private int addStructuredMap(JsonParser parser, String mapTypeName, HollowMapWriteRecord mapRec)
        throws IOException {
    JsonToken token = parser.nextToken();
    mapRec.reset();/* ww w. j a v a 2s.c om*/

    HollowMapSchema schema = (HollowMapSchema) hollowSchemas.get(mapTypeName);

    while (token != JsonToken.END_ARRAY) {
        if (token == JsonToken.START_OBJECT) {
            int keyOrdinal = -1, valueOrdinal = -1;
            while (token != JsonToken.END_OBJECT) {

                if (token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) {
                    if ("key".equals(parser.getCurrentName()))
                        keyOrdinal = parseSubType(parser, token, schema.getKeyType());
                    else if ("value".equals(parser.getCurrentName()))
                        valueOrdinal = parseSubType(parser, token, schema.getValueType());
                }

                token = parser.nextToken();
            }

            mapRec.addEntry(keyOrdinal, valueOrdinal);
        }

        token = parser.nextToken();
    }

    return stateEngine.add(schema.getName(), mapRec);
}

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

List<Ancestry> parseSubPopulation(final String id, final List<Ancestry> ancestries, final JsonParser parser)
        throws IOException {
    String label = null;/*from ww w  . j a v a  2  s.c  om*/
    double proportion = 0.0d;
    double unassigned = 0.0d;
    List<Ancestry> subPopulations = new ArrayList<Ancestry>();
    while (parser.nextToken() != JsonToken.END_ARRAY) {
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();

            if ("label".equals(field)) {
                label = parser.getText();
            } else if ("proportion".equals(field)) {
                proportion = Double.parseDouble(parser.getText());
            } else if ("unassigned".equals(field)) {
                unassigned = Double.parseDouble(parser.getText());
            } else if ("sub_populations".equals(field)) {
                subPopulations = parseSubPopulation(id, subPopulations, parser);
            }
        }
        Ancestry ancestry = new Ancestry(id, label, proportion, unassigned, subPopulations);
        ancestries.add(ancestry);
        label = null;
        proportion = 0.0d;
        unassigned = 0.0d;
        subPopulations.clear();
    }
    return ancestries;
}

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 v  a2s .co  m
    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.basistech.rosette.dm.jackson.ListAttributeDeserializer.java

@SuppressWarnings("unchecked")
private ListAttribute deserialize(JsonParser jp, DeserializationContext ctxt, TokenBuffer tb)
        throws IOException {
    jp.nextToken();//from  w  w  w  .j  a  v a  2s  . co m
    String keyName = jp.getText();

    if (tb != null) { // need to put back skipped properties?
        jp = JsonParserSequence.createFlattened(tb.asParser(jp), jp);
    }
    // Must point to the next value; tb had no current, jp pointed to VALUE_STRING:

    KnownAttribute attribute = KnownAttribute.getAttributeForKey(keyName);
    if (attribute == null) {
        attribute = KnownAttribute.UNKNOWN;
    }
    Class<? extends BaseAttribute> itemClass = attribute.attributeClass();

    ListAttribute.Builder<BaseAttribute> builder = new ListAttribute.Builder<>(attribute.attributeClass());
    List<BaseAttribute> items = Lists.newArrayList();

    JsonToken nextToken;
    while ((nextToken = jp.nextToken()) != JsonToken.END_OBJECT) {
        if (nextToken != JsonToken.FIELD_NAME) {
            throw ctxt.wrongTokenException(jp, JsonToken.END_OBJECT, "Expected field name.");
        } else {
            String name = jp.getCurrentName();
            if ("items".equals(name)) {
                // the actual list items.
                nextToken = jp.nextToken();
                if (nextToken == JsonToken.VALUE_EMBEDDED_OBJECT) {
                    Object o = jp.getEmbeddedObject();
                    if (o instanceof List) { // could it be an array, also?!?
                        // when using JsonTree, sometimes Jackson just sticks the entire Java object in here.
                        items.addAll((List) o);
                    } else {
                        throw ctxt.mappingException(
                                "List contains VALUE_EMBEDDED_OBJECT for items, but it wasn't a list.");
                    }
                } else if (nextToken != JsonToken.START_ARRAY) { // what about nothing?
                    throw ctxt.wrongTokenException(jp, JsonToken.START_ARRAY, "Expected array of items");
                } else {
                    // the START_ARRAY case, which is _normal_. Read the elements.
                    while (jp.nextToken() != JsonToken.END_ARRAY) {
                        items.add(jp.readValueAs(itemClass));
                    }
                }
            } else {
                nextToken = jp.nextToken();
                Object value;
                if (nextToken == JsonToken.VALUE_EMBEDDED_OBJECT) {
                    value = jp.getEmbeddedObject();
                } else {
                    value = jp.readValueAs(Object.class);
                }
                builder.extendedProperty(name, value);
            }
        }
    }
    builder.setItems(items);
    return builder.build();
}

From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java

@SuppressWarnings("resource")
protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser jp, DeserializationContext ctxt)
        throws IOException {
    final PropertyBasedCreator creator = _propertyBasedCreator;
    PropertyValueBuffer buffer = creator.startBuilding(jp, ctxt, _objectIdReader);

    TokenBuffer tokens = new TokenBuffer(jp);
    tokens.writeStartObject();/*from  w  w  w .  j a  v a2  s. c  om*/

    JsonToken t = jp.getCurrentToken();
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        String propName = jp.getCurrentName();
        jp.nextToken(); // to point to value
        // creator property?
        SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
        if (creatorProp != null) {
            // Last creator property to set?
            Object value = creatorProp.deserialize(jp, ctxt);
            if (buffer.assignParameter(creatorProp.getCreatorIndex(), value)) {
                t = jp.nextToken(); // to move to following FIELD_NAME/END_OBJECT
                Object bean;
                try {
                    bean = creator.build(ctxt, buffer);
                } catch (Exception e) {
                    wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
                    continue; // never gets here
                }
                // if so, need to copy all remaining tokens into buffer
                while (t == JsonToken.FIELD_NAME) {
                    jp.nextToken(); // to skip name
                    tokens.copyCurrentStructure(jp);
                    t = jp.nextToken();
                }
                tokens.writeEndObject();
                if (bean.getClass() != _beanType.getRawClass()) {
                    // !!! 08-Jul-2011, tatu: Could probably support; but for now
                    //   it's too complicated, so bail out
                    tokens.close();
                    throw ctxt.mappingException("Can not create polymorphic instances with unwrapped values");
                }
                return _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens);
            }
            continue;
        }
        // Object Id property?
        if (buffer.readIdProperty(propName)) {
            continue;
        }

        // regular property? needs buffering
        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) {
            buffer.bufferProperty(prop, prop.deserialize(jp, ctxt));
            continue;
        }
        /* As per [JACKSON-313], things marked as ignorable should not be
         * passed to any setter
         */
        if (_ignorableProps != null && _ignorableProps.contains(propName)) {
            handleIgnoredProperty(jp, ctxt, handledType(), propName);
            continue;
        }
        tokens.writeFieldName(propName);
        tokens.copyCurrentStructure(jp);
        // "any property"?
        if (_anySetter != null) {
            buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(jp, ctxt));
        }
    }

    // We hit END_OBJECT, so:
    Object bean;
    try {
        bean = creator.build(ctxt, buffer);
    } catch (Exception e) {
        wrapInstantiationProblem(e, ctxt);
        return null; // never gets here
    }
    return _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens);
}

From source file:com.zenesis.qx.remote.RequestHandler.java

private Object[] readParameters(JsonParser jp, Class[] types) throws IOException {
    if (types == null) {
        // Check for parameters
        if (jp.getCurrentToken() == JsonToken.FIELD_NAME && jp.getCurrentName().equals("parameters")
                && jp.nextToken() == JsonToken.START_ARRAY) {
            while (jp.nextToken() != JsonToken.END_ARRAY)
                ;// ww  w  .j a v  a2s  . c  o m
        }
        return null;
    }
    Object[] values = new Object[types.length];
    Object[] params = null;

    // Check for parameters
    if (jp.getCurrentToken() == JsonToken.FIELD_NAME && jp.getCurrentName().equals("parameters")
            && jp.nextToken() == JsonToken.START_ARRAY) {

        params = readArray(jp, types);
    }

    for (int i = 0; i < values.length; i++)
        if (i < params.length)
            values[i] = params[i];
        else
            values[i] = null;

    return values;
}

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

/**
 * Parse the specified input stream and return a user.
 *
 * @param inputStream input stream// w  w w.j  a  v  a2  s  . c  om
 * @return the specified input stream parsed into a user
 */
@Override
public User parseUser(final InputStream inputStream) {
    checkNotNull(inputStream);
    JsonParser parser = null;
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String profileId = null;
        boolean genotyped = false;
        List<Profile> profiles = new ArrayList<Profile>();

        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();
            if ("id".equals(field)) {
                id = parser.getText();
            } else if ("profiles".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    while (parser.nextToken() != JsonToken.END_OBJECT) {
                        String profileField = parser.getCurrentName();
                        parser.nextToken();
                        if ("id".equals(profileField)) {
                            profileId = parser.getText();
                        } else if ("genotyped".equals(profileField)) {
                            genotyped = parser.getBooleanValue();
                        }
                    }
                    profiles.add(new Profile(profileId, genotyped));
                }
            }
        }
        return new User(id, profiles);
    } catch (IOException e) {
        logger.warn("could not parse user", e);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
    return null;
}

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

@Override
public Genotype parseGenotypes(final InputStream inputStream) {
    checkNotNull(inputStream);/*www . j  a  va2  s. c  o m*/
    JsonParser parser = null;
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String location = null;
        String interpretation = null;
        Map<String, String> values = new HashMap<String, String>();

        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();

            if ("id".equals(field)) {
                id = parser.getText();
            } else {
                location = field;
                interpretation = parser.getText();
                values.put(location, interpretation);
            }
        }
        return new Genotype(id, values);
    } catch (IOException e) {
        logger.warn("could not parse genotypes");
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
    return null;
}

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

@Override
public List<Carrier> parseCarriers(final InputStream inputStream) {
    checkNotNull(inputStream);/*  w w  w .jav a  2s.co  m*/
    JsonParser parser = null;
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String reportId = null;
        String description = null;
        int mutations = 0;
        List<Carrier> carriers = new ArrayList<Carrier>();
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();

            if ("id".equals(field)) {
                id = parser.getText();
            } else if ("carriers".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    while (parser.nextToken() != JsonToken.END_OBJECT) {
                        String carrierField = parser.getCurrentName();
                        parser.nextToken();

                        if ("report_id".equals(carrierField)) {
                            reportId = parser.getText();
                        } else if ("description".equals(carrierField)) {
                            description = parser.getText();
                        } else if ("mutations".equals(carrierField)) {
                            mutations = Integer.parseInt(parser.getText());
                        }
                    }
                    carriers.add(new Carrier(id, reportId, description, mutations));
                    reportId = null;
                    description = null;
                    mutations = 0;
                }
            }
        }
        return carriers;
    } catch (IOException e) {
        logger.warn("could not parse carriers", e);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
    return null;
}

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

@Override
public Ancestry parseAncestry(final InputStream inputStream) {
    checkNotNull(inputStream);//w ww. j  a v  a2 s  .co  m
    JsonParser parser = null;
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String label = null;
        double proportion = 0.0d;
        double unassigned = 0.0d;
        List<Ancestry> subPopulations = new ArrayList<Ancestry>();
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();

            if ("id".equals(field)) {
                id = parser.getText();
            } else if ("ancestry".equals(field)) {
                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    String ancestryField = parser.getCurrentName();
                    parser.nextToken();

                    if ("label".equals(ancestryField)) {
                        label = parser.getText();
                    } else if ("proportion".equals(ancestryField)) {
                        proportion = Double.parseDouble(parser.getText());
                    } else if ("unassigned".equals(ancestryField)) {
                        unassigned = Double.parseDouble(parser.getText());
                    } else if ("sub_populations".equals(ancestryField)) {
                        subPopulations = parseSubPopulation(id, subPopulations, parser);
                    }
                }
            }
        }
        return new Ancestry(id, label, proportion, unassigned, subPopulations);
    } catch (IOException e) {
        logger.warn("could not parse ancestry", e);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
    return null;
}