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

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

Introduction

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

Prototype

public abstract JsonToken nextToken() throws IOException, JsonParseException;

Source Link

Document

Main iteration method, which will advance stream enough to determine type of the next token, if any.

Usage

From source file:com.ntsync.shared.RawContact.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T extends ListType> List<ListRawData<T>> readJsonList(String rowId,
        List<ListRawData<T>> listData, JsonParser jp, String fieldname, ListType defaultType,
        Class<T> typeClass) throws IOException {
    List<ListRawData<T>> newListData = listData;
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        String number = null;/*from   w w w.j  a va  2  s .  co m*/
        ListType type = defaultType;
        String label = null;
        boolean isSuperPrimary = false;
        boolean isPrimary = false;
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String namefield = jp.getCurrentName();
            // move to value
            if (jp.nextToken() == null) {
                throw new JsonParseException("Invalid JSON-Structure. End of Array missing.",
                        jp.getCurrentLocation());
            }
            if (ContactConstants.DATA.equals(namefield)) {
                number = jp.getValueAsString();
            } else if (ContactConstants.TYPE.equals(namefield)) {
                type = ContactConstants.fromVal(typeClass, jp.getValueAsInt());
                if (type == null) {
                    type = defaultType;
                }
            } else if (ContactConstants.SUPERPRIMARY.equals(namefield)) {
                isSuperPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.PRIMARY.equals(namefield)) {
                isPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.LABEL.equals(namefield)) {
                label = jp.getValueAsString();
            } else {
                LOG.error(JSON_FIELDNOTRECOGNIZED + rowId + " Fieldname:" + fieldname + " Unrecognized: "
                        + namefield);
                break;
            }
        }
        if (number != null) {
            if (newListData == null) {
                newListData = new ArrayList();
            }
            newListData.add(new ListRawData(number, type, label, isPrimary, isSuperPrimary));
        }
    }
    return newListData;
}

From source file:com.adobe.communities.ugc.migration.importer.ForumImportServlet.java

protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    final ResourceResolver resolver = request.getResourceResolver();

    UGCImportHelper.checkUserPrivileges(resolver, rrf);

    final UGCImportHelper importHelper = new UGCImportHelper();
    importHelper.setForumOperations(forumOperations);
    importHelper.setTallyService(tallyOperationsService);
    // get the forum we'll be adding new topics to
    final String path = request.getRequestParameter("path").getString();
    final Resource resource = request.getResourceResolver().getResource(path);
    if (resource == null) {
        throw new ServletException("Could not find a valid resource for import");
    }//w w  w  . j av a2 s. c  o  m

    // finally get the uploaded file
    final RequestParameter[] fileRequestParameters = request.getRequestParameters("file");
    if (fileRequestParameters != null && fileRequestParameters.length > 0
            && !fileRequestParameters[0].isFormField()) {

        InputStream inputStream = fileRequestParameters[0].getInputStream();
        JsonParser jsonParser = new JsonFactory().createParser(inputStream);
        jsonParser.nextToken(); // get the first token

        if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
            jsonParser.nextToken();
            if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT_TYPE)) {
                jsonParser.nextToken();
                final String contentType = jsonParser.getValueAsString();
                if (contentType.equals(getContentType())) {
                    jsonParser.nextToken(); // content
                    if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT)) {
                        jsonParser.nextToken(); // startObject
                        if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
                            JsonToken token = jsonParser.nextToken(); // social:key
                            try {
                                while (!token.equals(JsonToken.END_OBJECT)) {
                                    importHelper.extractTopic(jsonParser, resource,
                                            resource.getResourceResolver(), getOperationsService());
                                    token = jsonParser.nextToken();
                                }
                            } catch (final IOException e) {
                                throw new ServletException("Encountered an IOException", e);
                            }
                        } else {
                            throw new ServletException("Start object token not found for content");
                        }
                    } else {
                        throw new ServletException("Content not found");
                    }
                } else {
                    throw new ServletException("Expected forum data");
                }
            } else {
                throw new ServletException("Content Type not specified");
            }
        } else {
            throw new ServletException("Invalid Json format");
        }
    }
}

From source file:org.helm.notation2.wsadapter.MonomerWSSaver.java

/**
 * Adds or updates a single monomer to the monomer store using the URL configured in {@code MonomerStoreConfiguration}
 * .//w  ww  .  j ava 2 s. c om
 * 
 * @param monomer to save
 */
public String saveMonomerToStore(Monomer monomer) {
    String res = "";
    CloseableHttpResponse response = null;

    try {
        response = WSAdapterUtils.putResource(monomer.toJSON(),
                MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesPutFullURL());
        LOG.debug(response.getStatusLine().toString());

        JsonFactory jsonf = new JsonFactory();
        InputStream instream = response.getEntity().getContent();

        JsonParser jsonParser = jsonf.createParser(instream);

        while (!jsonParser.isClosed()) {
            JsonToken jsonToken = jsonParser.nextToken();
            if (JsonToken.FIELD_NAME.equals(jsonToken)) {
                String fieldName = jsonParser.getCurrentName();
                LOG.debug("Field name: " + fieldName);
                jsonParser.nextToken();
                if (fieldName.equals("monomerShortName")) {
                    res = jsonParser.getValueAsString();
                    break;
                }
            }
        }

        EntityUtils.consume(response.getEntity());

    } catch (Exception e) {
        LOG.error("Saving monomer failed!", e);
        return "";
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            LOG.debug("Closing resources failed.", e);
            return res;
        }
    }

    return res;
}

From source file:com.netflix.discovery.converters.jackson.serializer.ApplicationXmlDeserializer.java

@Override
public Application deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    String name = null;//w ww  . jav a2s  .  c o m
    List<InstanceInfo> instances = new ArrayList<>();
    while (jp.nextToken() == JsonToken.FIELD_NAME) {
        String fieldName = jp.getCurrentName();
        jp.nextToken(); // to point to value
        if ("name".equals(fieldName)) {
            name = jp.getValueAsString();
        } else if ("instance".equals(fieldName)) {
            instances.add(jp.readValueAs(InstanceInfo.class));
        } else {
            throw new JsonMappingException("Unexpected field " + fieldName, jp.getCurrentLocation());
        }
    }
    return new Application(name, instances);
}

From source file:eu.trentorise.opendata.semtext.jackson.MetadataDeserializer.java

@Override
public Map<String, Object> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {

    ImmutableMap.Builder<String, Object> retb = ImmutableMap.builder();

    while (jp.nextToken() != JsonToken.END_OBJECT) {

        String namespace = jp.getCurrentName();
        // current token is "name",
        // move to next, which is "name"'s value
        jp.nextToken();/*from   ww  w  .j a  v a2  s . com*/

        ImmutableSet<String> namespaces = SemTextModule.getMetadataNamespaces(hasMetadataClass);
        if (namespaces.contains(namespace)) {
            TypeReference typeRef = SemTextModule.getMetadataTypeReference(hasMetadataClass, namespace);

            Object metadata;

            try {
                metadata = jp.readValueAs(typeRef);
            } catch (Exception ex) {
                throw new SemTextMetadataException("Jackson error while deserializing metadata - ",
                        hasMetadataClass, namespace, typeRef, ex);
            }

            if (metadata == null) {
                throw new SemTextMetadataException("Found null metadata while deserializing!", hasMetadataClass,
                        namespace, typeRef);
            }

            retb.put(namespace, metadata);
        } else {
            throw new SemTextMetadataException(
                    "Found metadata under not registered namespace while deserializing!", hasMetadataClass,
                    namespace, null);
        }
    }

    return retb.build();
}

From source file:net.troja.eve.crest.CrestDataProcessor.java

private <T> void processItems(final CrestApiProcessor<T> processor, final CrestContainer<T> container,
        final JsonParser jsonParser) throws IOException {
    if (jsonParser.isExpectedStartArrayToken()) {
        while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
            container.addEntry(processor.parseEntry((JsonNode) mapper.readTree(jsonParser)));
        }/*from w w  w . j a  va2s.  c  o m*/
    }
}

From source file:com.cedarsoft.serialization.test.performance.JacksonTest.java

@Test
public void testParse() throws Exception {
    JsonParser parser = jsonFactory.createJsonParser(JSON);

    assertEquals(JsonToken.START_OBJECT, parser.nextToken());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("id", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals("Canon Raw", parser.getText());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("dependent", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_FALSE, parser.nextToken());
    assertFalse(parser.getBooleanValue());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("extension", parser.getCurrentName());
    assertEquals(JsonToken.START_OBJECT, parser.nextToken());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("extension", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals("cr2", parser.getText());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("default", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_TRUE, parser.nextToken());
    assertTrue(parser.getBooleanValue());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("delimiter", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals(".", parser.getText());

    assertEquals(JsonToken.END_OBJECT, parser.nextToken());
    assertEquals(JsonToken.END_OBJECT, parser.nextToken());
    assertNull(parser.nextToken());// w w w.  j  a va2 s.  c o  m
}

From source file:com.ntsync.shared.RawContact.java

/**
 * Creates and returns an instance of the RawContact from encrypted data
 * //from   w  w  w  .j  a v a 2 s. c o m
 * */
public static RawContact valueOf(String rowId, Map<Byte, ByteBuffer> values, Key privateKey)
        throws InvalidKeyException {
    try {
        String serverContactId = null;
        long rawContactId = -1;
        if (values.containsKey(ContactConstants.SERVERROW_ID)) {
            serverContactId = readRawString(values.get(ContactConstants.SERVERROW_ID));
        }
        String lastModStr = readRawString(values.get(ContactConstants.MODIFIED));
        Date lastModified = null;
        if (lastModStr != null) {
            lastModified = new Date(Long.parseLong(lastModStr));
        }

        if (serverContactId == null || !serverContactId.equals(rowId)) {
            // If ServerContactId is different, then rowId is the clientId
            rawContactId = Long.parseLong(rowId);
        }

        if (serverContactId == null && rawContactId < 0) {
            throw new IllegalArgumentException("Missing RowId in data");
        }

        AEADBlockCipher cipher = CryptoHelper.getCipher();
        final boolean deleted = values.containsKey(ContactConstants.DELETED);

        final String textData = CryptoHelper.decodeStringValue(ContactConstants.TEXTDATA, values, cipher,
                privateKey);

        if (textData == null && !deleted) {
            LOG.error("No textdata found for row with Id:" + rowId);
            return null;
        }

        String fullName = null;
        String firstName = null;
        String lastName = null;
        String middleName = null;
        String prefixName = null;
        String suffixName = null;
        String phonecticFirst = null;
        String phonecticMiddle = null;
        String phonecticLast = null;
        List<String> groupSourceIds = null;
        String note = null;
        List<ListRawData<PhoneType>> phones = null;
        List<ListRawData<EmailType>> emails = null;
        List<ListRawData<WebsiteType>> websites = null;
        List<ListRawData<EventType>> events = null;
        List<ListRawData<RelationType>> relations = null;
        List<ListRawData<SipAddressType>> sipaddresses = null;
        List<ListRawData<NicknameType>> nicknames = null;
        List<RawAddressData> addresses = null;
        List<RawImData> imAddresses = null;
        RawOrganizationData organization = null;
        boolean photoSuperPrimary = false;
        boolean starred = false;
        String customRingtone = null;
        boolean sendToVoiceMail = false;

        if (!SyncDataHelper.isEmpty(textData)) {
            JsonFactory fac = new JsonFactory();
            JsonParser jp = fac.createParser(textData);
            jp.nextToken();
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String fieldname = jp.getCurrentName();
                // move to value, or START_OBJECT/START_ARRAY
                jp.nextToken();
                if (ContactConstants.STRUCTUREDNAME.equals(fieldname)) {
                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                        String namefield = jp.getCurrentName();
                        // move to value
                        if (jp.nextToken() == null) {
                            throw new JsonParseException("Invalid JSON-Structure. End of Object missing.",
                                    jp.getCurrentLocation());
                        }
                        if (ContactConstants.DISPLAY_NAME.equals(namefield)) {
                            fullName = jp.getValueAsString();
                        } else if (ContactConstants.FAMILY_NAME.equals(namefield)) {
                            lastName = jp.getValueAsString();
                        } else if (ContactConstants.GIVEN_NAME.equals(namefield)) {
                            firstName = jp.getValueAsString();
                        } else if (ContactConstants.MIDDLE_NAME.equals(namefield)) {
                            middleName = jp.getValueAsString();
                        } else if (ContactConstants.SUFFIX_NAME.equals(namefield)) {
                            suffixName = jp.getValueAsString();
                        } else if (ContactConstants.PREFIX_NAME.equals(namefield)) {
                            prefixName = jp.getValueAsString();
                        } else if (ContactConstants.PHONETIC_FAMILY.equals(namefield)) {
                            phonecticLast = jp.getValueAsString();
                        } else if (ContactConstants.PHONETIC_GIVEN.equals(namefield)) {
                            phonecticFirst = jp.getValueAsString();
                        } else if (ContactConstants.PHONETIC_MIDDLE.equals(namefield)) {
                            phonecticMiddle = jp.getValueAsString();
                        } else {
                            LOG.error("Unrecognized structurednamefield for row with Id:" + rowId
                                    + " Fieldname:" + fieldname);
                            break;
                        }
                    }
                } else if (ContactConstants.STRUCTUREDPOSTAL.equals(fieldname)) {
                    addresses = readAddressList(rowId, addresses, jp);
                } else if (ContactConstants.PHONE.equals(fieldname)) {
                    phones = readJsonList(rowId, phones, jp, fieldname, PhoneType.TYPE_OTHER, PhoneType.class);
                } else if (ContactConstants.EMAIL.equals(fieldname)) {
                    emails = readJsonList(rowId, emails, jp, fieldname, EmailType.TYPE_OTHER, EmailType.class);
                } else if (ContactConstants.WEBSITE.equals(fieldname)) {
                    websites = readJsonList(rowId, websites, jp, fieldname, WebsiteType.TYPE_OTHER,
                            WebsiteType.class);
                } else if (ContactConstants.EVENT.equals(fieldname)) {
                    events = readJsonList(rowId, events, jp, fieldname, EventType.TYPE_OTHER, EventType.class);
                } else if (ContactConstants.RELATION.equals(fieldname)) {
                    relations = readJsonList(rowId, relations, jp, fieldname, RelationType.TYPE_CUSTOM,
                            RelationType.class);
                } else if (ContactConstants.SIPADDRESS.equals(fieldname)) {
                    sipaddresses = readJsonList(rowId, sipaddresses, jp, fieldname, SipAddressType.TYPE_OTHER,
                            SipAddressType.class);
                } else if (ContactConstants.NICKNAME.equals(fieldname)) {
                    nicknames = readJsonList(rowId, nicknames, jp, fieldname, NicknameType.TYPE_DEFAULT,
                            NicknameType.class);
                } else if (ContactConstants.IM.equals(fieldname)) {
                    imAddresses = readImList(rowId, imAddresses, jp);
                } else if (ContactConstants.NOTE.equals(fieldname)) {
                    note = jp.getValueAsString();
                } else if (ContactConstants.GROUPMEMBERSHIP.equals(fieldname)) {
                    while (jp.nextToken() != JsonToken.END_ARRAY) {
                        String groupSourceId = jp.getValueAsString();
                        if (groupSourceIds == null) {
                            groupSourceIds = new ArrayList<String>();
                        }
                        groupSourceIds.add(groupSourceId);
                    }
                } else if (ContactConstants.ORGANIZATION.equals(fieldname)) {
                    organization = readOrg(rowId, jp);
                } else if (ContactConstants.PHOTO_SUPERPRIMARY.equals(fieldname)) {
                    photoSuperPrimary = jp.getValueAsBoolean();
                } else if (ContactConstants.STARRED.equals(fieldname)) {
                    starred = jp.getValueAsBoolean();
                } else if (ContactConstants.SEND_TO_VOICE_MAIL.equals(fieldname)) {
                    sendToVoiceMail = jp.getValueAsBoolean();
                } else if (ContactConstants.DROID_CUSTOM_RINGTONE.equals(fieldname)) {
                    customRingtone = jp.getValueAsString();
                } else {
                    LOG.error("Unrecognized field for row with Id:" + rowId + " Fieldname:" + fieldname);
                }
            }
            jp.close();
        }

        final byte[] photo = CryptoHelper.decodeValue(ContactConstants.PHOTO, values, cipher, privateKey);

        return new RawContact(fullName, firstName, lastName, middleName, prefixName, suffixName, phonecticFirst,
                phonecticMiddle, phonecticLast, phones, emails, websites, addresses, events, relations,
                sipaddresses, nicknames, imAddresses, note, organization, photo, photoSuperPrimary,
                groupSourceIds, null, starred, customRingtone, sendToVoiceMail, lastModified, deleted,
                serverContactId, rawContactId, false, -1);
    } catch (InvalidCipherTextException ex) {
        throw new InvalidKeyException("Invalid key detected.", ex);
    } catch (final IOException ex) {
        LOG.info("Error parsing contact data. Reason:" + ex.toString(), ex);
    } catch (IllegalArgumentException ex) {
        LOG.warn("Error parsing contact data. Reason:" + ex.toString(), ex);
    }

    return null;
}

From source file:com.cedarsoft.serialization.jackson.JacksonTest.java

@Test
public void testNull() throws Exception {
    generator.writeNull();//w  w w .  ja v  a  2s. c  o m
    verifyGenerator("null");

    JsonParser parser = jsonFactory.createJsonParser("null");
    assertEquals(null, parser.getCurrentToken());
    assertEquals(JsonToken.VALUE_NULL, parser.nextToken());
    assertEquals(null, parser.nextToken());
}

From source file:com.msopentech.odatajclient.engine.data.metadata.edm.EdmxDeserializer.java

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

    final Edmx edmx = new Edmx();

    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        final JsonToken token = jp.getCurrentToken();
        if (token == JsonToken.FIELD_NAME) {
            if ("Version".equals(jp.getCurrentName())) {
                edmx.setVersion(jp.nextTextValue());
            } else if ("DataServices".equals(jp.getCurrentName())) {
                jp.nextToken();// ww  w.  ja va 2s  .  com
                edmx.setDataServices(jp.getCodec().readValue(jp, DataServices.class));
            }
        }
    }

    return edmx;
}