Example usage for com.fasterxml.jackson.core JsonToken FIELD_NAME

List of usage examples for com.fasterxml.jackson.core JsonToken FIELD_NAME

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonToken FIELD_NAME.

Prototype

JsonToken FIELD_NAME

To view the source code for com.fasterxml.jackson.core JsonToken FIELD_NAME.

Click Source Link

Document

FIELD_NAME is returned when a String token is encountered as a field name (same lexical value, different function)

Usage

From source file:com.cinnober.msgcodec.json.TypeScannerJsonParser.java

private void skipField(Iterator<Token> it) throws NoSuchElementException, DecodeException {
    Token token = it.next();//from  w  w w. java 2s  .  co m
    if (token.getType() != JsonToken.FIELD_NAME) {
        throw new DecodeException("Expected field, got " + token.getType());
    }
}

From source file:org.elasticsearch.client.sniff.ElasticsearchNodesSniffer.java

private static Node readNode(String nodeId, JsonParser parser, Scheme scheme) throws IOException {
    HttpHost publishedHost = null;//from w w  w .jav a 2 s.  c om
    /*
     * We sniff the bound hosts so we can look up the node based on any
     * address on which it is listening. This is useful in Elasticsearch's
     * test framework where we sometimes publish ipv6 addresses but the
     * tests contact the node on ipv4.
     */
    Set<HttpHost> boundHosts = new HashSet<>();
    String name = null;
    String version = null;
    /*
     * Multi-valued attributes come with key = `real_key.index` and we
     * unflip them after reading them because we can't rely on the order
     * that they arive.
     */
    final Map<String, String> protoAttributes = new HashMap<String, String>();

    boolean sawRoles = false;
    boolean master = false;
    boolean data = false;
    boolean ingest = false;

    String fieldName = null;
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        if (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
            fieldName = parser.getCurrentName();
        } else if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
            if ("http".equals(fieldName)) {
                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    if (parser.getCurrentToken() == JsonToken.VALUE_STRING
                            && "publish_address".equals(parser.getCurrentName())) {
                        URI publishAddressAsURI = URI.create(scheme + "://" + parser.getValueAsString());
                        publishedHost = new HttpHost(publishAddressAsURI.getHost(),
                                publishAddressAsURI.getPort(), publishAddressAsURI.getScheme());
                    } else if (parser.currentToken() == JsonToken.START_ARRAY
                            && "bound_address".equals(parser.getCurrentName())) {
                        while (parser.nextToken() != JsonToken.END_ARRAY) {
                            URI boundAddressAsURI = URI.create(scheme + "://" + parser.getValueAsString());
                            boundHosts.add(new HttpHost(boundAddressAsURI.getHost(),
                                    boundAddressAsURI.getPort(), boundAddressAsURI.getScheme()));
                        }
                    } else if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
                        parser.skipChildren();
                    }
                }
            } else if ("attributes".equals(fieldName)) {
                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    if (parser.getCurrentToken() == JsonToken.VALUE_STRING) {
                        String oldValue = protoAttributes.put(parser.getCurrentName(),
                                parser.getValueAsString());
                        if (oldValue != null) {
                            throw new IOException("repeated attribute key [" + parser.getCurrentName() + "]");
                        }
                    } else {
                        parser.skipChildren();
                    }
                }
            } else {
                parser.skipChildren();
            }
        } else if (parser.currentToken() == JsonToken.START_ARRAY) {
            if ("roles".equals(fieldName)) {
                sawRoles = true;
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    switch (parser.getText()) {
                    case "master":
                        master = true;
                        break;
                    case "data":
                        data = true;
                        break;
                    case "ingest":
                        ingest = true;
                        break;
                    default:
                        logger.warn("unknown role [" + parser.getText() + "] on node [" + nodeId + "]");
                    }
                }
            } else {
                parser.skipChildren();
            }
        } else if (parser.currentToken().isScalarValue()) {
            if ("version".equals(fieldName)) {
                version = parser.getText();
            } else if ("name".equals(fieldName)) {
                name = parser.getText();
            }
        }
    }
    //http section is not present if http is not enabled on the node, ignore such nodes
    if (publishedHost == null) {
        logger.debug("skipping node [" + nodeId + "] with http disabled");
        return null;
    }

    Map<String, List<String>> realAttributes = new HashMap<>(protoAttributes.size());
    List<String> keys = new ArrayList<>(protoAttributes.keySet());
    for (String key : keys) {
        if (key.endsWith(".0")) {
            String realKey = key.substring(0, key.length() - 2);
            List<String> values = new ArrayList<>();
            int i = 0;
            while (true) {
                String value = protoAttributes.remove(realKey + "." + i);
                if (value == null) {
                    break;
                }
                values.add(value);
                i++;
            }
            realAttributes.put(realKey, unmodifiableList(values));
        }
    }
    for (Map.Entry<String, String> entry : protoAttributes.entrySet()) {
        realAttributes.put(entry.getKey(), singletonList(entry.getValue()));
    }

    if (version.startsWith("2.")) {
        /*
         * 2.x doesn't send roles, instead we try to read them from
         * attributes.
         */
        boolean clientAttribute = v2RoleAttributeValue(realAttributes, "client", false);
        Boolean masterAttribute = v2RoleAttributeValue(realAttributes, "master", null);
        Boolean dataAttribute = v2RoleAttributeValue(realAttributes, "data", null);
        master = masterAttribute == null ? false == clientAttribute : masterAttribute;
        data = dataAttribute == null ? false == clientAttribute : dataAttribute;
    } else {
        assert sawRoles : "didn't see roles for [" + nodeId + "]";
    }
    assert boundHosts.contains(publishedHost) : "[" + nodeId
            + "] doesn't make sense! publishedHost should be in boundHosts";
    logger.trace("adding node [" + nodeId + "]");
    return new Node(publishedHost, boundHosts, name, version, new Roles(master, data, ingest),
            unmodifiableMap(realAttributes));
}

From source file:org.emfjson.jackson.tests.custom.CustomDeserializersTest.java

@Test
public void testDeserializeReferenceAsStrings() throws JsonProcessingException {
    EMFModule module = new EMFModule();
    module.configure(EMFModule.Feature.OPTION_USE_ID, true);
    module.configure(EMFModule.Feature.OPTION_SERIALIZE_TYPE, false);

    module.setReferenceDeserializer(new JsonDeserializer<ReferenceEntry>() {
        @Override//from w  w  w .  j  av a2  s.  c om
        public ReferenceEntry deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            final EObject parent = EMFContext.getParent(ctxt);
            final EReference reference = EMFContext.getReference(ctxt);

            if (p.getCurrentToken() == JsonToken.FIELD_NAME) {
                p.nextToken();
            }

            return new ReferenceEntry.Base(parent, reference, p.getText());
        }
    });

    mapper.registerModule(module);

    JsonNode data = mapper.createArrayNode()
            .add(mapper.createObjectNode().put("@id", "1").put("name", "Paul").put("uniqueFriend", "2"))
            .add(mapper.createObjectNode().put("@id", "2").put("name", "Franck"));

    Resource resource = mapper.reader().withAttribute(RESOURCE_SET, resourceSet)
            .withAttribute(ROOT_ELEMENT, ModelPackage.Literals.USER).treeToValue(data, Resource.class);

    assertEquals(2, resource.getContents().size());

    User u1 = (User) resource.getContents().get(0);
    User u2 = (User) resource.getContents().get(1);

    assertSame(u2, u1.getUniqueFriend());
}

From source file:com.cedarsoft.couchdb.io.RowSerializer.java

@Nonnull
public <K, V, D> Row<K, V, D> deserialize(@Nonnull JacksonSerializer<? super K> keySerializer,
        @Nonnull JacksonSerializer<? super V> valueSerializer,
        @Nullable JacksonSerializer<? extends D> documentSerializer, @Nonnull JsonParser parser)
        throws IOException, InvalidTypeException {
    JacksonParserWrapper wrapper = new JacksonParserWrapper(parser);
    wrapper.nextToken(JsonToken.FIELD_NAME);
    String fieldName = wrapper.getCurrentName();

    //The id/*from  w  w  w.  j  av  a  2s.  c  om*/
    @Nullable
    final DocId id;
    if (fieldName.equals(PROPERTY_ID)) {
        wrapper.nextValue();
        id = new DocId(wrapper.getText());
        wrapper.nextField(PROPERTY_KEY);
    } else {
        id = null;
    }

    //The key
    K key = (K) keySerializer.deserialize(parser);

    //The value
    wrapper.nextField(PROPERTY_VALUE);

    @Nullable
    V value = (V) valueSerializer.deserialize(parser);

    //The doc - if available
    @Nullable
    CouchDoc<? extends D> doc;

    JsonToken nextToken = wrapper.nextToken();
    if (nextToken == JsonToken.FIELD_NAME) {
        if (documentSerializer == null) {
            throw new NullPointerException("No document serializer found");
        }
        doc = couchDocSerializer.deserialize(documentSerializer, new JacksonParserWrapper(parser));

        wrapper.closeObject();
    } else {
        doc = null;
    }

    wrapper.verifyCurrentToken(JsonToken.END_OBJECT);
    return new Row<>(id, key, value, doc);
}

From source file:timezra.dropbox.maven.plugin.client.DbxClientWrapper.java

private static <C> WithChildrenC<C> readWithNulls(final JsonParser parser,
        final Collector<DbxEntry, ? extends C> collector) throws IOException, JsonReadException {
    final JsonLocation top = JsonReader.expectObjectStart(parser);

    String size = null;// www  .jav a  2  s.co  m
    long bytes = -1;
    String path = null;
    Boolean is_dir = null;
    Boolean is_deleted = null;
    String rev = null;
    Boolean thumb_exists = null;
    String icon = null;
    Date modified = null;
    Date client_mtime = null;
    String hash = null;
    C contents = null;

    while (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
        final String fieldName = parser.getCurrentName();
        JsonReader.nextToken(parser);

        final int fi = FM.get(fieldName);
        try {
            switch (fi) {
            case -1:
                JsonReader.skipValue(parser);
                break;
            case FM_size:
                size = JsonReader.StringReader.readField(parser, fieldName, size);
                break;
            case FM_bytes:
                bytes = JsonReader.readUnsignedLongField(parser, fieldName, bytes);
                break;
            case FM_path:
                path = JsonReader.StringReader.readField(parser, fieldName, path);
                break;
            case FM_is_dir:
                is_dir = JsonReader.BooleanReader.readField(parser, fieldName, is_dir);
                break;
            case FM_is_deleted:
                is_deleted = JsonReader.BooleanReader.readField(parser, fieldName, is_deleted);
                break;
            case FM_rev:
                rev = JsonReader.StringReader.readField(parser, fieldName, rev);
                break;
            case FM_thumb_exists:
                thumb_exists = JsonReader.BooleanReader.readField(parser, fieldName, thumb_exists);
                break;
            case FM_icon:
                icon = JsonReader.StringReader.readField(parser, fieldName, icon);
                break;
            case FM_modified:
                modified = JsonDateReader.Dropbox.readField(parser, fieldName, modified);
                break;
            case FM_client_mtime:
                client_mtime = JsonDateReader.Dropbox.readField(parser, fieldName, client_mtime);
                break;
            case FM_hash:
                if (collector == null) {
                    throw new JsonReadException(
                            "not expecting \"hash\" field, since we didn't ask for children",
                            parser.getCurrentLocation());
                }
                hash = JsonReader.StringReader.readField(parser, fieldName, hash);
                break;
            case FM_contents:
                if (collector == null) {
                    throw new JsonReadException(
                            "not expecting \"contents\" field, since we didn't ask for children",
                            parser.getCurrentLocation());
                }
                contents = JsonArrayReader.mk(Reader, collector).readField(parser, fieldName, contents);
                break;
            default:
                throw new AssertionError("bad index: " + fi + ", field = \"" + fieldName + "\"");
            }
        } catch (final JsonReadException ex) {
            throw ex.addFieldContext(fieldName);
        }
    }

    JsonReader.expectObjectEnd(parser);

    if (path == null) {
        throw new JsonReadException("missing field \"path\"", top);
    }
    if (icon == null) {
        throw new JsonReadException("missing field \"icon\"", top);
    }
    if (is_deleted == null) {
        is_deleted = Boolean.FALSE;
    }
    if (is_dir == null) {
        is_dir = Boolean.FALSE;
    }
    if (thumb_exists == null) {
        thumb_exists = Boolean.FALSE;
    }

    if (is_dir && (contents != null || hash != null)) {
        if (hash == null) {
            throw new JsonReadException("missing \"hash\", when we asked for children", top);
        }
        if (contents == null) {
            throw new JsonReadException("missing \"contents\", when we asked for children", top);
        }
    }

    DbxEntry e;
    if (is_dir) {
        e = new Folder(path, icon, thumb_exists);
    } else {
        // Normal File
        if (size == null) {
            throw new JsonReadException("missing \"size\" for a file entry", top);
        }
        if (bytes == -1) {
            throw new JsonReadException("missing \"bytes\" for a file entry", top);
        }
        if (modified == null) {
            throw new JsonReadException("missing \"modified\" for a file entry", top);
        }
        if (client_mtime == null) {
            throw new JsonReadException("missing \"client_mtime\" for a file entry", top);
        }
        if (rev == null) {
            throw new JsonReadException("missing \"rev\" for a file entry", top);
        }
        e = new File(path, icon, thumb_exists, bytes, size, modified, client_mtime, rev);
    }

    return new WithChildrenC<C>(e, hash, contents);
}

From source file:org.fluentd.jvmwatcher.JvmWatcher.java

/**
 * @param parser//w  w w .  ja  va2 s. com
 * @throws JsonParseException
 * @throws IOException
 */
private void loadTarget(JsonParser parser) throws JsonParseException, IOException {
    if (parser.nextToken() == JsonToken.START_ARRAY) {
        while (parser.nextToken() != JsonToken.END_ARRAY) {
            if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
                String shortName = null;
                String pattern = null;
                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    if ((parser.getCurrentToken() == JsonToken.FIELD_NAME)
                            && (parser.getText().compareTo("shortname") == 0)) {
                        if (parser.nextToken() == JsonToken.VALUE_STRING) {
                            shortName = parser.getText();
                        }
                    }
                    if ((parser.getCurrentToken() == JsonToken.FIELD_NAME)
                            && (parser.getText().compareTo("pattern") == 0)) {
                        if (parser.nextToken() == JsonToken.VALUE_STRING) {
                            pattern = parser.getText();
                        }
                    }
                }
                // add target pattern
                Pattern regexPattern = Pattern.compile(pattern);
                LocalJvmInfo.addTargetProcessPattern(shortName, regexPattern);
            }
        }
    }
}

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

private int addObject(JsonParser parser, String typeName) throws IOException {
    ObjectFieldMapping objectMapping = getObjectFieldMapping(typeName);

    Boolean passthroughDecoratedTypes = null;

    JsonToken token = parser.nextToken();

    PassthroughWriteRecords rec = null;//ww w  .  j a v a2 s.c om

    String fieldName = null;
    try {
        while (token != JsonToken.END_OBJECT) {
            if (token != JsonToken.FIELD_NAME) {
                fieldName = parser.getCurrentName();
                ObjectMappedFieldPath mappedFieldPath = objectMapping.getMappedFieldPath(fieldName);

                if (mappedFieldPath != null) {
                    addObjectField(parser, token, mappedFieldPath);
                } else {
                    if (passthroughDecoratedTypes == null) {
                        passthroughDecoratedTypes = Boolean
                                .valueOf(this.passthroughDecoratedTypes.contains(typeName));

                        if (passthroughDecoratedTypes.booleanValue()) {
                            rec = getPassthroughWriteRecords();
                        }
                    }
                    if (passthroughDecoratedTypes.booleanValue()) {
                        addPassthroughField(parser, token, fieldName, rec);
                    } else {
                        skipObjectField(parser, token);
                    }
                }
            }

            token = parser.nextToken();
        }
    } catch (Exception ex) {
        throw new IOException(
                "Failed to parse field=" + fieldName + ", schema=" + typeName + ", token=" + token, ex);
    }

    if (passthroughDecoratedTypes != null && passthroughDecoratedTypes.booleanValue()) {
        rec.passthroughRec.setReference("singleValues",
                stateEngine.add("SingleValuePassthroughMap", rec.singleValuePassthroughMapRec));
        rec.passthroughRec.setReference("multiValues",
                stateEngine.add("MultiValuePassthroughMap", rec.multiValuePassthroughMapRec));

        int passthroughOrdinal = stateEngine.add("PassthroughData", rec.passthroughRec);

        return objectMapping.build(passthroughOrdinal);
    }

    return objectMapping.build(-1);
}

From source file:eu.project.ttc.readers.TermSuiteJsonCasDeserializer.java

private static void FillFixedExpressions(JsonParser parser, JsonToken token, FixedExpression fe, CAS cas)
        throws IOException {
    if (token.equals(JsonToken.FIELD_NAME)) {
        switch (parser.getCurrentName()) {
        case F_BEGIN:
            fe.setBegin(parser.nextIntValue(0));
            break;
        case F_END:
            fe.setEnd(parser.nextIntValue(0));
            break;
        }//from w  w  w.  j a  v  a2 s  . c  o  m
    }
}

From source file:com.cinnober.msgcodec.json.TypeScannerJsonParser.java

private void parseField() throws DecodeException, IOException {
    JsonToken token = p.getCurrentToken();
    if (token != JsonToken.FIELD_NAME) {
        throw new DecodeException("Expected field, got " + token);
    }//from  w  w w  . ja va2 s.  co  m
    tokens.add(new ValueToken(JsonToken.FIELD_NAME, p.getText()));
    p.nextToken();
}

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

/**
 * Secondary deserialization method, called in cases where POJO
 * instance is created as part of deserialization, potentially
 * after collecting some or all of the properties to set.
 *//*from   www  .j ava 2 s . c o m*/
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt, Object bean) throws IOException {
    if (_injectables != null) {
        injectValues(ctxt, bean);
    }
    if (_unwrappedPropertyHandler != null) {
        return deserializeWithUnwrapped(jp, ctxt, bean);
    }
    if (_externalTypeIdHandler != null) {
        return deserializeWithExternalTypeId(jp, ctxt, bean);
    }
    JsonToken t = jp.getCurrentToken();
    // 23-Mar-2010, tatu: In some cases, we start with full JSON object too...
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    if (_needViewProcesing) {
        Class<?> view = ctxt.getActiveView();
        if (view != null) {
            return deserializeWithView(jp, ctxt, bean, view);
        }
    }
    beanDeserializerAdvice.before(bean, jp, ctxt);
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        String propName = jp.getCurrentName();
        // Skip field name:
        jp.nextToken();

        if (beanDeserializerAdvice.intercept(bean, propName, jp, ctxt)) {
            continue;
        }

        SettableBeanProperty prop = _beanProperties.find(propName);

        if (prop != null) { // normal case
            try {
                prop.deserializeAndSet(jp, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
        handleUnknownVanilla(jp, ctxt, bean, propName);
    }
    beanDeserializerAdvice.after(bean, jp, ctxt);
    return bean;
}