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

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

Introduction

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

Prototype

public abstract JsonToken nextValue() throws IOException, JsonParseException;

Source Link

Document

Iteration method that will advance stream enough to determine type of the next token that is a value type (including JSON Array and Object start/end markers).

Usage

From source file:com.boundary.zoocreeper.Restore.java

private static ACL readACL(JsonParser jp) throws IOException {
    expectCurrentToken(jp, JsonToken.START_OBJECT);
    String scheme = null;//w w w.  ja  v a2  s .  co  m
    String id = null;
    int perms = -1;
    final Set<String> seenFields = Sets.newHashSet();
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        jp.nextValue();
        final String fieldName = jp.getCurrentName();
        seenFields.add(fieldName);
        if (Backup.FIELD_ACL_SCHEME.equals(fieldName)) {
            scheme = jp.getValueAsString();
        } else if (Backup.FIELD_ACL_ID.equals(fieldName)) {
            id = jp.getValueAsString();
        } else if (Backup.FIELD_ACL_PERMS.equals(fieldName)) {
            perms = jp.getIntValue();
        } else {
            throw new IOException("Unexpected field: " + fieldName);
        }
    }
    if (!seenFields.containsAll(REQUIRED_ACL_FIELDS)) {
        throw new IOException("Missing required ACL fields: " + REQUIRED_ACL_FIELDS);
    }
    final Id zkId;
    if (Ids.ANYONE_ID_UNSAFE.getScheme().equals(scheme) && Ids.ANYONE_ID_UNSAFE.getId().equals(id)) {
        zkId = Ids.ANYONE_ID_UNSAFE;
    } else {
        zkId = new Id(scheme, id);
    }
    return new ACL(perms, zkId);
}

From source file:com.boundary.zoocreeper.Restore.java

private static BackupZNode readZNode(JsonParser jp, String path) throws IOException {
    expectNextToken(jp, JsonToken.START_OBJECT);
    long ephemeralOwner = 0;
    byte[] data = null;
    final List<ACL> acls = Lists.newArrayList();
    final Set<String> seenFields = Sets.newHashSet();
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        jp.nextValue();
        final String fieldName = jp.getCurrentName();
        seenFields.add(fieldName);/* ww  w.  ja va 2  s. c  o m*/
        if (Backup.FIELD_EPHEMERAL_OWNER.equals(fieldName)) {
            ephemeralOwner = jp.getLongValue();
        } else if (Backup.FIELD_DATA.equals(fieldName)) {
            if (jp.getCurrentToken() == JsonToken.VALUE_NULL) {
                data = null;
            } else {
                data = jp.getBinaryValue();
            }
        } else if (Backup.FIELD_ACLS.equals(fieldName)) {
            readACLs(jp, acls);
        } else {
            LOGGER.debug("Ignored field: {}", fieldName);
        }
    }
    if (!seenFields.containsAll(REQUIRED_ZNODE_FIELDS)) {
        throw new IOException("Missing required fields: " + REQUIRED_ZNODE_FIELDS);
    }
    return new BackupZNode(path, ephemeralOwner, data, acls);
}

From source file:com.microsoft.azure.storage.table.TableStorageErrorDeserializer.java

/**
 * Gets the Extended Error information.//from w  ww  .  j  a va2  s  .  c o  m
 * 
 * @return the Extended Error information.
 * 
 * @param reader
 *            the input stream to read error details from.
 * @param format
 *            The {@link TablePayloadFormat} to use for parsing
 * @throws IOException
 *             if an error occurs while accessing the stream with Json.
 * @throws JsonParseException
 *             if an error occurs while parsing the stream.
 */
public static StorageExtendedErrorInformation getExtendedErrorInformation(final Reader reader,
        final TablePayloadFormat format) throws JsonParseException, IOException {
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser parser = jsonFactory.createParser(reader);
    try {
        final StorageExtendedErrorInformation errorInfo = new StorageExtendedErrorInformation();

        if (!parser.hasCurrentToken()) {
            parser.nextToken();
        }

        JsonUtilities.assertIsStartObjectJsonToken(parser);

        parser.nextToken();
        JsonUtilities.assertIsFieldNameJsonToken(parser);
        JsonUtilities.assertIsExpectedFieldName(parser, "odata.error");

        // start getting extended error information
        parser.nextToken();
        JsonUtilities.assertIsStartObjectJsonToken(parser);

        // get code
        parser.nextValue();
        JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_CODE);
        errorInfo.setErrorCode(parser.getValueAsString());

        // get message
        parser.nextToken();
        JsonUtilities.assertIsFieldNameJsonToken(parser);
        JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_MESSAGE);

        parser.nextToken();
        JsonUtilities.assertIsStartObjectJsonToken(parser);

        parser.nextValue();
        JsonUtilities.assertIsExpectedFieldName(parser, "lang");

        parser.nextValue();
        JsonUtilities.assertIsExpectedFieldName(parser, "value");
        errorInfo.setErrorMessage(parser.getValueAsString());

        parser.nextToken();
        JsonUtilities.assertIsEndObjectJsonToken(parser);

        parser.nextToken();

        // get innererror if it exists
        if (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
            JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.INNER_ERROR);
            errorInfo.getAdditionalDetails().putAll(parseJsonErrorException(parser));
            parser.nextToken();
        }

        // end code object
        JsonUtilities.assertIsEndObjectJsonToken(parser);

        // end odata.error object
        parser.nextToken();
        JsonUtilities.assertIsEndObjectJsonToken(parser);

        return errorInfo;
    } finally {
        parser.close();
    }
}

From source file:no.ssb.jsonstat.v2.deser.DatasetDeserializerTest.java

@Test
public void testDimensionOrder() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new JavaTimeModule());
    mapper.registerModule(new JsonStatModule());

    URL resource = getResource(getClass(), "dimOrder.json");

    JsonParser jsonParser = mapper.getFactory().createParser(resource.openStream());
    jsonParser.nextValue();

    DatasetBuildable deserialize = ds.deserialize(jsonParser, mapper.getDeserializationContext());

    assertThat(deserialize.build().getDimension().keySet()).containsExactly("A", "B", "C");

}

From source file:no.ssb.jsonstat.v2.deser.DatasetDeserializerTest.java

@Test
public void testParseValues() throws Exception {
    ObjectMapper mapper = new ObjectMapper();

    JsonParser mapParser = mapper.getFactory()
            .createParser("" + "{ " + "  \"0\": 10," + "  \"1\": 20," + "  \"3\": 30," + "  \"4\": 40}");
    mapParser.nextValue();

    JsonParser arrayParser = mapper.getFactory().createParser("[ 10, 20, null, 30, 40 ]");
    arrayParser.nextValue();/*from  w w  w .  java  2  s .c o m*/

    List<Number> fromMap = ds.parseValues(mapParser, null);
    List<Number> fromArray = ds.parseValues(arrayParser, null);
    List<Number> expected = Lists.newArrayList(10, 20, null, 30, 40);

    SoftAssertions softly = new SoftAssertions();
    softly.assertThat(fromMap).as("deserialize values from map").isEqualTo(expected);
    softly.assertThat(fromArray).as("deserialize values from array").isEqualTo(expected);
    softly.assertAll();

}

From source file:org.intelligentsia.dowsers.core.serializers.jackson.ClassInformationDeserializer.java

@Override
public ClassInformation deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    String description = null;//from   w  ww  . jav a 2  s. co m

    if (jp.hasCurrentToken()) {
        if (jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
            jp.nextValue();
            description = jp.getText();
            jp.nextToken();
        }
    }

    return description != null ? ClassInformation.parse(description) : null;
}

From source file:no.ssb.jsonstat.v2.deser.DimensionDeserializer.java

private void parseCategory(Dimension.Builder dimension, JsonParser p, DeserializationContext ctxt)
        throws IOException {
    Map<String, String> index = null;
    Map<String, String> label = null;
    while (p.nextValue() != JsonToken.END_OBJECT) {
        switch (p.getCurrentName()) {
        case "index":
            index = parseIndex(p, ctxt);
            break;
        case "label":
            label = parseCategoryLabel(p, ctxt);
            break;
        case "unit":
            // TODO: Support units.
            parseUnit(p, ctxt);/*from  ww w .  j ava 2 s  .  com*/
            break;
        default:
            ctxt.handleUnknownProperty(p, this, Dimension.Builder.class, p.getCurrentName());
            break;
        }
    }
    checkArgument(!(index == null && label == null), "either label or index is required");

    // Once we have everything, we can build the dimension.

    if (index == null) {
        checkArgument(label.size() >= 1,
                "category label must contain a least one element if " + "no index is provided");
        dimension.withIndexedLabels(ImmutableMap.copyOf(label));
        return;
    }
    if (label == null) {
        dimension.withCategories(ImmutableSet.copyOf(index.keySet()));
        return;
    }

    // TODO: Maybe the checks should reside inside the builder?
    checkArgument(label.size() == index.size(), "label and index's sizes were inconsistent");

    ImmutableMap<String, String> withIndex = index.keySet().stream()
            .collect(toImmutableMap(Function.identity(), label::get));
    dimension.withIndexedLabels(withIndex);

}

From source file:com.cedarsoft.couchdb.test.utils.AttachmentsTest.java

License:asdf

@Test
public void testInlined() throws Exception {
    CouchDoc<String> doc = new CouchDoc<String>(new DocId("asdf"), "the object");
    doc.addAttachment(new CouchDoc.InlineAttachment(new AttachmentId("daid"), MediaType.TEXT_XML_TYPE,
            "<x/>".getBytes()));
    doc.addAttachment(new CouchDoc.InlineAttachment(new AttachmentId("hehe"), MediaType.APPLICATION_XML_TYPE,
            "<x2/>".getBytes()));

    AbstractJacksonSerializer<String> serializer = new AbstractJacksonSerializer<String>("daString",
            VersionRange.single(1, 0, 0)) {
        @Override//from   www . j  a v a 2  s . c om
        public void serialize(@Nonnull JsonGenerator serializeTo, @Nonnull String object,
                @Nonnull Version formatVersion) throws IOException, VersionException, JsonProcessingException {
            serializeTo.writeStringField("daString", object);
        }

        @Nonnull
        @Override
        public String deserialize(@Nonnull JsonParser deserializeFrom, @Nonnull Version formatVersion)
                throws IOException, VersionException, JsonProcessingException {
            deserializeFrom.nextToken();
            deserializeFrom.nextValue();

            try {
                return deserializeFrom.getText();
            } finally {
                deserializeFrom.nextToken();
            }
        }
    };
    assertEquals(201, db().put(doc, serializer).getStatus());

    JsonUtils.assertJsonEquals(getClass().getResource("doc_with_2_attachments.json"),
            new String(ByteStreams.toByteArray(db().get(doc.getId()))));

    CouchDoc<String> resolvedDoc = db().get(doc.getId(), serializer);
    assertEquals("the object", resolvedDoc.getObject());
    assertEquals(2, resolvedDoc.getAttachments().size());
    assertEquals("daid", resolvedDoc.getAttachments().get(0).getId().asString());
    assertEquals("text/xml", resolvedDoc.getAttachments().get(0).getContentType().toString());
    assertEquals("hehe", resolvedDoc.getAttachments().get(1).getId().asString());
    assertEquals("application/xml", resolvedDoc.getAttachments().get(1).getContentType().toString());
}

From source file:no.ssb.jsonstat.v2.deser.DimensionDeserializer.java

@Override
public Dimension.Builder deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    // Get the name first.
    String name = parseName(p, ctxt);

    if (p.getCurrentToken() == JsonToken.START_OBJECT) {
        p.nextToken();//from  w w w.j  a va2s  .c  o  m
    }

    Dimension.Builder dimension;
    dimension = Dimension.create(name);

    while (p.nextValue() != JsonToken.END_OBJECT) {
        switch (p.getCurrentName()) {
        case "category":
            parseCategory(dimension, p, ctxt);
            break;
        case "label":
            dimension.withLabel(parseLabel(p, ctxt));
            break;
        default:
            ctxt.handleUnknownProperty(p, this, Dimension.Builder.class, p.getCurrentName());
            break;
        }
    }

    return dimension;
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

private void parseDownloadUrls(JsonParser parser, ContentValues result) throws JsonParseException, IOException {
    // parser points at begin object token right now
    if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
        while (parser.nextValue() != JsonToken.END_OBJECT) {
            String fieldName = parser.getCurrentName();

            if (downloadUrlFields.contains(fieldName)) {
                result.put(fieldName + "url", parser.getValueAsString());
            }/*from  w w  w  .  java 2  s.  c om*/
        }
    }
    //      else we must not have any download urls (null, '', something like that.)
}