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

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

Introduction

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

Prototype

JsonToken VALUE_STRING

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

Click Source Link

Document

VALUE_STRING is returned when a String token is encountered in value context (array element, field value, or root-level stand-alone value)

Usage

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.j  av 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.n52.movingcode.runtime.processors.config.ProcessorConfig.java

/**
 * Parsing routine for processor objects
 * //from w w w.j a va 2s .  com
 * @param jp
 * @return
 * @throws JsonParseException
 * @throws IOException
 */
private static final ProcessorDescription parseProcessorJSON(JsonParser jp)
        throws JsonParseException, IOException {
    ProcessorDescription p = new ProcessorDescription();
    while (jp.nextToken() != END_OBJECT) {
        JsonToken jt = jp.getCurrentToken();

        // look for ID and parse it
        if (jp.getCurrentName().equalsIgnoreCase(KEY_ID) && jt == VALUE_STRING) {
            p.setId(jp.getValueAsString());
        }

        // look for temp workspace and parse it
        if (jp.getCurrentName().equalsIgnoreCase(KEY_TEMPWORKSPACE) && jt == VALUE_STRING) {
            p.setTempWorkspace(jp.getValueAsString());
        }

        // look for containers and parse them (Value Case)
        if (jp.getCurrentName().equalsIgnoreCase(KEY_SUPPORTED_CONTAINER) && jt == VALUE_STRING) {
            p.addContainer(jp.getValueAsString());
        }

        // look for containers and parse them (Array Case)
        if (jp.getCurrentName().equalsIgnoreCase(KEY_SUPPORTED_CONTAINER) && jt == START_ARRAY) {
            while (jp.nextToken() != END_ARRAY) {
                if (jp.getCurrentToken() == VALUE_STRING) {
                    p.addPlatform(jp.getValueAsString());
                }
            }
        }

        // look for platforms and parse them (Array Case)
        if (jp.getCurrentName().equalsIgnoreCase(KEY_AVAILABLE_PLATFORMS) && jt == JsonToken.START_ARRAY) {
            while (jp.nextToken() != END_ARRAY) {
                if (jp.getCurrentToken() == VALUE_STRING) {
                    p.addPlatform(jp.getValueAsString());
                }
            }
        }

        // look for platforms and parse them (Value Case)
        if (jp.getCurrentName().equalsIgnoreCase(KEY_AVAILABLE_PLATFORMS) && jt == JsonToken.VALUE_STRING) {
            p.addPlatform(jp.getValueAsString());
        }

        // look for properties and parse them
        if (jp.getCurrentName().equalsIgnoreCase(KEY_PROPERTIES) && jt == JsonToken.START_ARRAY) {
            HashMap<String, String> props = new HashMap<String, String>();
            while (jp.nextToken() != END_ARRAY) {
                if (jp.getCurrentToken() == FIELD_NAME) {
                    props.put(jp.getCurrentName(), jp.nextTextValue());
                }

            }

            p.setProperties(props);

        }
    }

    return p;
}

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

/**
 * @param parser//from ww w . j a v a 2s.c  o m
 * @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.bazaarvoice.jackson.rison.RisonParser.java

/**
 * Method for accessing textual representation of the current event;
 * if no current event (before first call to {@link #nextToken}, or
 * after encountering end-of-input), returns null.
 * Method can be called for any event.//  w  w w  .ja v a2  s .  co m
 */
@Override
public String getText() throws IOException, JsonParseException {
    JsonToken t = _currToken;
    if (t == JsonToken.VALUE_STRING) {
        if (_tokenIncomplete) {
            _tokenIncomplete = false;
            _finishString(); // only strings can be incomplete
        }
        return _textBuffer.contentsAsString();
    }
    return _getText2(t);
}

From source file:de.undercouch.bson4jackson.BsonParser.java

@Override
public JsonToken nextToken() throws IOException, JsonParseException {
    Context ctx = _currentContext;
    if (_currToken == null && ctx == null) {
        try {//from w  w  w  . j  a  v a 2 s. co m
            _currToken = handleNewDocument(false);
        } catch (EOFException e) {
            //there is nothing more to read. indicate EOF
            return null;
        }
    } else {
        _tokenPos = _counter.getPosition();
        if (ctx == null) {
            if (_currToken == JsonToken.END_OBJECT) {
                //end of input
                return null;
            }
            throw new JsonParseException("Found element outside the document", getTokenLocation());
        }

        if (ctx.state == State.DONE) {
            //next field
            ctx.reset();
        }

        boolean readValue = true;
        if (ctx.state == State.FIELDNAME) {
            readValue = false;
            while (true) {
                //read field name or end of document
                ctx.type = _in.readByte();
                if (ctx.type == BsonConstants.TYPE_END) {
                    //end of document
                    _currToken = (ctx.array ? JsonToken.END_ARRAY : JsonToken.END_OBJECT);
                    _currentContext = _currentContext.parent;
                } else if (ctx.type == BsonConstants.TYPE_UNDEFINED) {
                    //skip field name and then ignore this token
                    skipCString();
                    continue;
                } else {
                    ctx.state = State.VALUE;
                    _currToken = JsonToken.FIELD_NAME;

                    if (ctx.array) {
                        //immediately read value of array element (discard field name)
                        readValue = true;
                        skipCString();
                        ctx.fieldName = null;
                    } else {
                        //read field name
                        ctx.fieldName = readCString();
                    }
                }
                break;
            }
        }

        if (readValue) {
            //parse element's value
            switch (ctx.type) {
            case BsonConstants.TYPE_DOUBLE:
                ctx.value = _in.readDouble();
                _currToken = JsonToken.VALUE_NUMBER_FLOAT;
                break;

            case BsonConstants.TYPE_STRING:
                ctx.value = readString();
                _currToken = JsonToken.VALUE_STRING;
                break;

            case BsonConstants.TYPE_DOCUMENT:
                _currToken = handleNewDocument(false);
                break;

            case BsonConstants.TYPE_ARRAY:
                _currToken = handleNewDocument(true);
                break;

            case BsonConstants.TYPE_BINARY:
                _currToken = handleBinary();
                break;

            case BsonConstants.TYPE_OBJECTID:
                ctx.value = readObjectId();
                _currToken = JsonToken.VALUE_EMBEDDED_OBJECT;
                break;

            case BsonConstants.TYPE_BOOLEAN:
                boolean b = _in.readBoolean();
                ctx.value = b;
                _currToken = (b ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE);
                break;

            case BsonConstants.TYPE_DATETIME:
                ctx.value = new Date(_in.readLong());
                _currToken = JsonToken.VALUE_EMBEDDED_OBJECT;
                break;

            case BsonConstants.TYPE_NULL:
                _currToken = JsonToken.VALUE_NULL;
                break;

            case BsonConstants.TYPE_REGEX:
                _currToken = handleRegEx();
                break;

            case BsonConstants.TYPE_DBPOINTER:
                _currToken = handleDBPointer();
                break;

            case BsonConstants.TYPE_JAVASCRIPT:
                ctx.value = new JavaScript(readString());
                _currToken = JsonToken.VALUE_EMBEDDED_OBJECT;
                break;

            case BsonConstants.TYPE_SYMBOL:
                ctx.value = readSymbol();
                _currToken = JsonToken.VALUE_EMBEDDED_OBJECT;
                break;

            case BsonConstants.TYPE_JAVASCRIPT_WITH_SCOPE:
                _currToken = handleJavascriptWithScope();
                break;

            case BsonConstants.TYPE_INT32:
                ctx.value = _in.readInt();
                _currToken = JsonToken.VALUE_NUMBER_INT;
                break;

            case BsonConstants.TYPE_TIMESTAMP:
                ctx.value = readTimestamp();
                _currToken = JsonToken.VALUE_EMBEDDED_OBJECT;
                break;

            case BsonConstants.TYPE_INT64:
                ctx.value = _in.readLong();
                _currToken = JsonToken.VALUE_NUMBER_INT;
                break;

            case BsonConstants.TYPE_MINKEY:
                ctx.value = "MinKey";
                _currToken = JsonToken.VALUE_STRING;
                break;

            case BsonConstants.TYPE_MAXKEY:
                ctx.value = "MaxKey";
                _currToken = JsonToken.VALUE_STRING;
                break;

            default:
                throw new JsonParseException("Unknown element type " + ctx.type, getTokenLocation());
            }
            ctx.state = State.DONE;
        }
    }
    return _currToken;
}

From source file:com.bazaarvoice.jackson.rison.RisonParser.java

@Override
public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException {
    if (_currToken != JsonToken.VALUE_STRING
            && (_currToken != JsonToken.VALUE_EMBEDDED_OBJECT || _binaryValue == null)) {
        _reportError("Current token (" + _currToken
                + ") not VALUE_STRING or VALUE_EMBEDDED_OBJECT, can not access as binary");
    }//from  w  ww .  j ava 2  s .  c om
    /* To ensure that we won't see inconsistent data, better clear up
     * state...
     */
    if (_tokenIncomplete) {
        try {
            _binaryValue = _decodeBase64(b64variant);
        } catch (IllegalArgumentException iae) {
            throw _constructError(
                    "Failed to decode VALUE_STRING as base64 (" + b64variant + "): " + iae.getMessage());
        }
        /* let's clear incomplete only now; allows for accessing other
         * textual content in error cases
         */
        _tokenIncomplete = false;
    } else { // may actually require conversion...
        if (_binaryValue == null) {
            ByteArrayBuilder builder = _getByteArrayBuilder();
            _decodeBase64(getText(), builder, b64variant);
            _binaryValue = builder.toByteArray();
        }
    }
    return _binaryValue;
}

From source file:com.google.openrtb.json.OpenRtbJsonReader.java

protected void readNativeField(JsonParser par, Native.Builder nativ, String fieldName) throws IOException {
    switch (fieldName) {
    case "request":
        if (par.getCurrentToken() == JsonToken.VALUE_STRING) {
            nativ.setRequestNative(factory().newNativeReader().readNativeRequest(
                    new CharArrayReader(par.getTextCharacters(), par.getTextOffset(), par.getTextLength())));
        } else { // Object
            nativ.setRequestNative(factory().newNativeReader().readNativeRequest(par));
        }/*from  w  ww .j a  v  a2  s .  c  o  m*/
        break;
    case "ver":
        nativ.setVer(par.getText());
        break;
    case "api":
        for (startArray(par); endArray(par); par.nextToken()) {
            APIFramework value = APIFramework.valueOf(par.getIntValue());
            if (checkEnum(value)) {
                nativ.addApi(value);
            }
        }
        break;
    case "battr":
        for (startArray(par); endArray(par); par.nextToken()) {
            CreativeAttribute value = CreativeAttribute.valueOf(par.getIntValue());
            if (checkEnum(value)) {
                nativ.addBattr(value);
            }
        }
        break;
    default:
        readOther(nativ, par, fieldName);
    }
}

From source file:com.turn.shapeshifter.NamedSchemaSerializerTest.java

@Test
public void testLongAsString() throws Exception {
    NamedSchema schema = NamedSchema.of(Union.getDescriptor(), "Union").surfaceLongsAsStrings()
            .useSchema("union_value", "Union").useSchema("union_repeated", "Union");

    Union union = Union.newBuilder().setInt64Value(1234567890L).addInt64Repeated(1234567L).build();
    SchemaRegistry registry = new SchemaRegistry();
    registry.register(schema);// w  w w . j  a  va  2 s.  co  m
    JsonNode result = schema.getSerializer().serialize(union, registry);
    Assert.assertTrue(result.isObject());
    Assert.assertEquals(JsonToken.VALUE_STRING, result.get("int64Value").asToken());
    Assert.assertEquals("1234567890", result.get("int64Value").asText());
    JsonNode arrayItem = result.get("int64Repeated").get(0);
    Assert.assertEquals(JsonToken.VALUE_STRING, arrayItem.asToken());
    Assert.assertEquals("1234567", arrayItem.asText());
}

From source file:net.opentsdb.utils.TestJSON.java

/** Helper to parse an input stream into a map */
private HashMap<String, String> parseToMap(final InputStream is) throws Exception {
    JsonParser jp = JSON.parseToStream(is);
    HashMap<String, String> map = new HashMap<String, String>();
    String field = "";
    String value;/*from   w w w .  ja va  2 s. c o m*/
    while (jp.nextToken() != null) {
        if (jp.getCurrentToken() == JsonToken.FIELD_NAME && jp.getCurrentName() != null) {
            field = jp.getCurrentName();
        } else if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
            value = jp.getText();
            map.put(field, value);
        }
    }
    return map;
}

From source file:com.turn.shapeshifter.NamedSchemaSerializerTest.java

@Test
public void testSerializeBytes() throws Exception {
    NamedSchema schema = NamedSchema.of(Union.getDescriptor(), "Union").surfaceLongsAsStrings()
            .setFormat("bytes_value", "byte");

    byte[] bytes = new byte[] { (byte) 0xe0, 0x4f, (byte) 0xd0, 0x20, (byte) 0xea, 0x3a, 0x69, 0x10,
            (byte) 0xa2, (byte) 0xd8, 0x08, 0x00, 0x2b, 0x30, 0x30, (byte) 0x9d };
    Union union = Union.newBuilder().setBytesValue(ByteString.copyFrom(bytes)).build();

    SchemaRegistry registry = new SchemaRegistry();
    registry.register(schema);// w w  w  . j a va 2 s .c om
    JsonNode result = schema.getSerializer().serialize(union, registry);
    Assert.assertTrue(result.isObject());
    Assert.assertEquals(JsonToken.VALUE_STRING, result.get("bytesValue").asToken());
    Assert.assertEquals(bytes.length, result.get("bytesValue").asText().length());
    for (int i = 0; i < bytes.length; i++) {
        if (bytes[i] != (byte) result.get("bytesValue").asText().charAt(i)) {
            Assert.fail("bytes value has been interpolated!");
        }
    }
}