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

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

Introduction

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

Prototype

public abstract String getText() throws IOException, JsonParseException;

Source Link

Document

Method for accessing textual representation of the current token; if no current token (before first call to #nextToken , or after encountering end-of-input), returns null.

Usage

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

/**
 * @param parser//w  ww.j a  v  a  2s .c  om
 * @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:net.opentsdb.utils.TestJSON.java

/** Helper to parse an input stream into a map */
private HashMap<String, String> parseToMap(final JsonParser jp) throws Exception {
    HashMap<String, String> map = new HashMap<String, String>();
    String field = "";
    String value;/*from   w  ww. j a  v  a  2s .  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: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 ww  .  j  ava2s  .c  om*/
    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:net.floodlightcontroller.loadbalancer.PoolsResource.java

protected LBPool jsonToPool(String json) throws IOException {
    if (json == null)
        return null;

    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    LBPool pool = new LBPool();

    try {//from w w w .j  av  a  2  s.  com
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }

    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }

        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals(""))
            continue;
        if (n.equals("id")) {
            pool.id = jp.getText();
            continue;
        }
        if (n.equals("tenant_id")) {
            pool.tenantId = jp.getText();
            continue;
        }
        if (n.equals("name")) {
            pool.name = jp.getText();
            continue;
        }
        if (n.equals("network_id")) {
            pool.netId = jp.getText();
            continue;
        }
        if (n.equals("lb_method")) {
            pool.lbMethod = Short.parseShort(jp.getText());
            continue;
        }
        if (n.equals("protocol")) {
            String tmp = jp.getText();
            if (tmp.equalsIgnoreCase("TCP")) {
                pool.protocol = IPv4.PROTOCOL_TCP;
            } else if (tmp.equalsIgnoreCase("UDP")) {
                pool.protocol = IPv4.PROTOCOL_UDP;
            } else if (tmp.equalsIgnoreCase("ICMP")) {
                pool.protocol = IPv4.PROTOCOL_ICMP;
            }
            continue;
        }
        if (n.equals("vip_id")) {
            pool.vipId = jp.getText();
            continue;
        }

        log.warn("Unrecognized field {} in " + "parsing Pools", jp.getText());
    }
    jp.close();

    return pool;
}

From source file:net.floodlightcontroller.loadbalancer.VipsResource.java

protected LBVip jsonToVip(String json) throws IOException {

    if (json == null)
        return null;

    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    LBVip vip = new LBVip();

    try {//from   w  w  w. j  a v  a  2 s  .  c o  m
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }

    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }

        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals(""))
            continue;

        if (n.equals("id")) {
            vip.id = jp.getText();
            continue;
        }
        if (n.equals("tenant_id")) {
            vip.tenantId = jp.getText();
            continue;
        }
        if (n.equals("name")) {
            vip.name = jp.getText();
            continue;
        }
        if (n.equals("network_id")) {
            vip.netId = jp.getText();
            continue;
        }
        if (n.equals("protocol")) {
            String tmp = jp.getText();
            if (tmp.equalsIgnoreCase("TCP")) {
                vip.protocol = IPv4.PROTOCOL_TCP;
            } else if (tmp.equalsIgnoreCase("UDP")) {
                vip.protocol = IPv4.PROTOCOL_UDP;
            } else if (tmp.equalsIgnoreCase("ICMP")) {
                vip.protocol = IPv4.PROTOCOL_ICMP;
            }
            continue;
        }
        if (n.equals("address")) {
            vip.address = IPv4.toIPv4Address(jp.getText());
            continue;
        }
        if (n.equals("port")) {
            vip.port = Short.parseShort(jp.getText());
            continue;
        }
        if (n.equals("pool_id")) {
            vip.pools.add(jp.getText());
            continue;
        }

        log.warn("Unrecognized field {} in " + "parsing Vips", jp.getText());
    }
    jp.close();

    return vip;
}

From source file:org.metis.utils.Utils.java

/**
 * Recursively steps through JSON object and arrays of objects. We support
 * only a single object or an array of objects, where each object represents
 * an entity (e.g., a student, a customer, an account, etc.).
 * /*from  www  .  j  av a 2 s .  c  o m*/
 * All objects must have the same identical set of keys.
 * 
 * @param jp
 * @param params
 * @throws Exception
 */
private static void parseJson(JsonParser jp, List<Map<String, String>> rows) throws Exception {

    // get the next json token
    JsonToken current = jp.nextToken();

    // base case: return if we've reached end of json stream
    if (current == null) {
        return;
    }

    // all rows must have the identical set of keys!
    Map<String, String> firstRow = null;
    if (!rows.isEmpty()) {
        firstRow = rows.get(0);
    }

    // we only accept objects or arrays of objects
    switch (current) {
    case START_OBJECT:
        HashMap<String, String> row = new HashMap<String, String>();
        while (jp.nextToken() != END_OBJECT) {
            // parser should be on 'key' token
            String key = jp.getCurrentName().toLowerCase();
            // ensure all rows have the identical set of keys!
            if (firstRow != null && firstRow.get(key) == null) {
                String eStr = "parseJson: given list of json objects do " + "not have identical set of keys";
                LOG.error(eStr);
                throw new Exception(eStr);
            }
            // now advance to 'value' token
            jp.nextToken();
            String value = jp.getText();
            row.put(key, value);
        }
        // if row is not null, add it to the rows list
        if (!row.isEmpty()) {
            // ensure all rows have the identical set of keys!
            if (firstRow != null && firstRow.size() != row.size()) {
                String eStr = "parseJson: given list of json objects do "
                        + "not have identical set of keys; number of " + "keys vary";
                LOG.error(eStr);
                throw new Exception(eStr);
            }
            rows.add(row);
        }
        break;
    case START_ARRAY:
    case END_ARRAY:
        break;
    default:
        LOG.error("parseJson: ERROR, json token is neither object nor array");
        throw new Exception("parseJson: ERROR, json token is neither object nor array");
    }

    // go on to the next start-of-array, end-of-array, start-of-object, or
    // end of stream
    parseJson(jp, rows);
}

From source file:de.konqi.fitapi.auth.PublicKeysManager.java

/**
 * Forces a refresh of the public certificates downloaded from {@link #getPublicCertsEncodedUrl}.
 *
 * <p>//  w w w. ja v a 2  s .c  o m
 * This method is automatically called from {@link #getPublicKeys()} if the public keys have not
 * yet been initialized or if the expiration time is very close, so normally this doesn't need to
 * be called. Only call this method to explicitly force the public keys to be updated.
 * </p>
 */
public PublicKeysManager refresh() throws GeneralSecurityException, IOException {
    lock.lock();
    try {
        publicKeys = new ArrayList<PublicKey>();
        // HTTP request to public endpoint
        CertificateFactory factory = SecurityUtils.getX509CertificateFactory();
        HttpResponse certsResponse = transport.createRequestFactory()
                .buildGetRequest(new GenericUrl(publicCertsEncodedUrl)).execute();
        expirationTimeMilliseconds = clock.currentTimeMillis()
                + getCacheTimeInSec(certsResponse.getHeaders()) * 1000;
        // parse each public key in the JSON response
        JsonParser parser = jsonFactory.createJsonParser(certsResponse.getContent());
        JsonToken currentToken = parser.getCurrentToken();
        // token is null at start, so get next token
        if (currentToken == null) {
            currentToken = parser.nextToken();
        }
        Preconditions.checkArgument(currentToken == JsonToken.START_OBJECT);
        try {
            while (parser.nextToken() != JsonToken.END_OBJECT) {
                parser.nextToken();
                String certValue = parser.getText();
                X509Certificate x509Cert = (X509Certificate) factory
                        .generateCertificate(new ByteArrayInputStream(StringUtils.getBytesUtf8(certValue)));
                publicKeys.add(x509Cert.getPublicKey());
            }
            publicKeys = Collections.unmodifiableList(publicKeys);
        } finally {
            parser.close();
        }
        return this;
    } finally {
        lock.unlock();
    }
}

From source file:org.graylog2.gelfclient.encoder.GelfMessageJsonEncoderTest.java

@Test
public void testOptionalFullMessage() throws Exception {
    final EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageJsonEncoder());
    final GelfMessage message = new GelfMessageBuilder("test").build();
    assertTrue(channel.writeOutbound(message));
    assertTrue(channel.finish());/*from   w  w w . jav  a  2s.  c  om*/

    final ByteBuf byteBuf = (ByteBuf) channel.readOutbound();
    final byte[] bytes = new byte[byteBuf.readableBytes()];
    byteBuf.getBytes(0, bytes).release();
    final JsonFactory json = new JsonFactory();
    final JsonParser parser = json.createParser(bytes);

    String version = null;
    Number timestamp = null;
    String host = null;
    String short_message = null;
    String full_message = null;
    Number level = null;

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

        if (key == null) {
            continue;
        }

        parser.nextToken();

        switch (key) {
        case "version":
            version = parser.getText();
            break;
        case "timestamp":
            timestamp = parser.getNumberValue();
            break;
        case "host":
            host = parser.getText();
            break;
        case "short_message":
            short_message = parser.getText();
            break;
        case "full_message":
            full_message = parser.getText();
            break;
        case "level":
            level = parser.getNumberValue();
            break;
        default:
            throw new Exception("Found unexpected field in JSON payload: " + key);
        }
    }

    assertEquals(message.getVersion().toString(), version);
    assertEquals(message.getTimestamp(), timestamp);
    assertEquals(message.getHost(), host);
    assertEquals(message.getMessage(), short_message);
    assertNull(full_message);
    assertEquals(message.getLevel().getNumericLevel(), level);
}

From source file:org.apache.ode.jacob.soup.jackson.MessageDeserializer.java

@Override
public Message deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    long id = 0;/*from   www . j av  a 2s .co m*/
    String action = null;
    ChannelRef to = null;
    ChannelRef replyTo = null;
    Map<String, Object> headers = null;
    Object body = null;

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldname = jp.getCurrentName();
        if (jp.getCurrentToken() == JsonToken.FIELD_NAME) {
            // if we're not already on the field, advance by one.
            jp.nextToken();
        }

        if ("id".equals(fieldname)) {
            id = jp.getLongValue();
        } else if ("action".equals(fieldname)) {
            action = jp.getText();
        } else if ("to".equals(fieldname)) {
            to = jp.readValueAs(ChannelRef.class);
        } else if ("replyTo".equals(fieldname)) {
            replyTo = jp.readValueAs(ChannelRef.class);
        } else if ("headers".equals(fieldname)) {
            headers = jp.readValueAs(mapTypeRef);
        } else if ("body".equals(fieldname)) {
            body = jp.readValueAs(Object.class);
        }
    }

    if (action == null) {
        throw ctxt.mappingException(Message.class);
    }

    if (to == null) {
        throw ctxt.mappingException(Message.class);
    }

    Message msg = new Message(to, replyTo, action);
    msg.setHeaders(headers);
    msg.setBody(body);
    msg.setId(id);

    return msg;
}

From source file:org.graylog2.gelfclient.encoder.GelfMessageJsonEncoderTest.java

@Test
public void testNullLevel() throws Exception {
    final EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageJsonEncoder());
    final GelfMessage message = new GelfMessageBuilder("test").build();

    message.setLevel(null);//  w  w  w . j  ava2s  .c  o m

    assertTrue(channel.writeOutbound(message));
    assertTrue(channel.finish());

    final ByteBuf byteBuf = (ByteBuf) channel.readOutbound();
    final byte[] bytes = new byte[byteBuf.readableBytes()];
    byteBuf.getBytes(0, bytes).release();
    final JsonFactory json = new JsonFactory();
    final JsonParser parser = json.createParser(bytes);

    String version = null;
    Number timestamp = null;
    String host = null;
    String short_message = null;
    String full_message = null;
    Number level = null;

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

        if (key == null) {
            continue;
        }

        parser.nextToken();

        switch (key) {
        case "version":
            version = parser.getText();
            break;
        case "timestamp":
            timestamp = parser.getNumberValue();
            break;
        case "host":
            host = parser.getText();
            break;
        case "short_message":
            short_message = parser.getText();
            break;
        case "full_message":
            full_message = parser.getText();
            break;
        case "level":
            level = parser.getNumberValue();
            break;
        default:
            throw new Exception("Found unexpected field in JSON payload: " + key);
        }
    }

    assertEquals(message.getVersion().toString(), version);
    assertEquals(message.getTimestamp(), timestamp);
    assertEquals(message.getHost(), host);
    assertEquals(message.getMessage(), short_message);
    assertNull(full_message);
    assertNull(level);
}