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

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

Introduction

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

Prototype

public String getValueAsString() throws IOException, JsonParseException 

Source Link

Document

Method that will try to convert value of current token to a java.lang.String .

Usage

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

private static List<RawImData> readImList(String rowId, List<RawImData> imAddresses, JsonParser jp)
        throws IOException {
    List<RawImData> newImAddresses = imAddresses;
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        ImType type = null;//from   w w w .  j  a v  a2s. c  o  m
        ImProtocolType proType = null;
        String customProctocolName = null;
        String imAddress = null;
        String imTypeLabel = 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 Object missing.",
                        jp.getCurrentLocation());
            }
            if (ContactConstants.DATA.equals(namefield)) {
                imAddress = jp.getValueAsString();
            } else if (ContactConstants.TYPE.equals(namefield)) {
                type = ImType.fromVal(jp.getValueAsInt());
            } else if (ContactConstants.SUPERPRIMARY.equals(namefield)) {
                isSuperPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.PRIMARY.equals(namefield)) {
                isPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.LABEL.equals(namefield)) {
                imTypeLabel = jp.getValueAsString();
            } else if (ContactConstants.PROTOCOL_TYPE.equals(namefield)) {
                proType = ImProtocolType.fromVal(jp.getValueAsInt());
            } else if (ContactConstants.PROTOCOL_CUSTOM_PROT.equals(namefield)) {
                customProctocolName = jp.getValueAsString();
            } else {
                LOG.error(JSON_FIELDNOTRECOGNIZED + rowId + " Fieldname:" + namefield);
            }
        }
        if (newImAddresses == null) {
            newImAddresses = new ArrayList<RawImData>();
        }
        if (type == null) {
            type = ImType.TYPE_OTHER;
        }

        newImAddresses.add(new RawImData(imAddress, type, imTypeLabel, isPrimary, isSuperPrimary, proType,
                customProctocolName));
    }
    return newImAddresses;
}

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 a  va2 s  .c o  m
    /*
     * 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:com.ntsync.shared.RawContact.java

private static List<RawAddressData> readAddressList(String rowId, List<RawAddressData> addresses, JsonParser jp)
        throws IOException {
    List<RawAddressData> newAddresses = addresses;
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        AddressType type = null;/*ww w . ja  v a 2 s .c om*/
        String label = null;
        String street = null;
        String city = null;
        String postcode = null;
        String country = null;
        String region = null;
        String pobox = null;
        String neighborhood = 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.NEIGHBORHOOD.equals(namefield)) {
                neighborhood = jp.getValueAsString();
            } else if (ContactConstants.TYPE.equals(namefield)) {
                type = AddressType.fromVal(jp.getValueAsInt());
            } 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 if (ContactConstants.STREET.equals(namefield)) {
                street = jp.getValueAsString();
            } else if (ContactConstants.REGION.equals(namefield)) {
                region = jp.getValueAsString();
            } else if (ContactConstants.CITY.equals(namefield)) {
                city = jp.getValueAsString();
            } else if (ContactConstants.POSTCODE.equals(namefield)) {
                postcode = jp.getValueAsString();
            } else if (ContactConstants.COUNTRY.equals(namefield)) {
                country = jp.getValueAsString();
            } else if (ContactConstants.REGION.equals(namefield)) {
                region = jp.getValueAsString();
            } else if (ContactConstants.POBOX.equals(namefield)) {
                pobox = jp.getValueAsString();
            } else {
                LOG.error(JSON_FIELDNOTRECOGNIZED + rowId + " Fieldname:" + namefield);
            }
        }
        if (newAddresses == null) {
            newAddresses = new ArrayList<RawAddressData>();
        }
        if (type == null) {
            type = AddressType.TYPE_OTHER;
        }

        newAddresses.add(new RawAddressData(type, label, isPrimary, isSuperPrimary, street, pobox, neighborhood,
                city, region, postcode, country));
    }
    return newAddresses;
}

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  va  2  s .co  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:io.debezium.document.JacksonReader.java

private Array parseArray(JsonParser parser, boolean nested) throws IOException {
    // Iterate over the values in the array ...
    BasicArray array = new BasicArray();
    JsonToken token = null;//from   w w w .j  a  v  a2 s  .  c  o m
    if (!nested) {
        // We expect the START_ARRAY token ...
        token = parser.nextToken();
        if (!nested && token != JsonToken.START_ARRAY) {
            throw new IOException("Expected data to start with an Array, but was " + token);
        }
    }
    token = parser.nextToken();
    while (token != JsonToken.END_ARRAY) {
        switch (token) {
        case START_OBJECT:
            array.add(parseDocument(parser, true));
            break;
        case START_ARRAY:
            array.add(parseArray(parser, true));
            break;
        case VALUE_STRING:
            array.add(parser.getValueAsString());
            break;
        case VALUE_TRUE:
            array.add(true);
            break;
        case VALUE_FALSE:
            array.add(false);
            break;
        case VALUE_NULL:
            array.addNull();
            break;
        case VALUE_NUMBER_FLOAT:
        case VALUE_NUMBER_INT:
            switch (parser.getNumberType()) {
            case FLOAT:
                array.add(parser.getFloatValue());
                break;
            case DOUBLE:
                array.add(parser.getDoubleValue());
                break;
            case BIG_DECIMAL:
                array.add(parser.getDecimalValue());
                break;
            case INT:
                array.add(parser.getIntValue());
                break;
            case LONG:
                array.add(parser.getLongValue());
                break;
            case BIG_INTEGER:
                array.add(parser.getBigIntegerValue());
                break;
            }
            break;
        case VALUE_EMBEDDED_OBJECT:
            // disregard this, since it's an extension ...
            break;
        case NOT_AVAILABLE:
            throw new JsonParseException("Non-blocking parsers are not supported", parser.getCurrentLocation());
        case FIELD_NAME:
            throw new JsonParseException("Not expecting a FIELD_NAME token", parser.getCurrentLocation());
        case END_ARRAY:
            throw new JsonParseException("Not expecting an END_ARRAY token", parser.getCurrentLocation());
        case END_OBJECT:
            throw new JsonParseException("Not expecting an END_OBJECT token", parser.getCurrentLocation());
        }
        token = parser.nextToken();
    }
    return array;
}

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

/**
 * Handle each of the importable types of ugc content
 * @param jsonParser - the parsing stream
 * @param resource - the parent resource of whatever it is we're importing (must already exist)
 * @throws ServletException//from   w w w.  ja va 2  s  .c  o m
 * @throws IOException
 */
private void importFile(final JsonParser jsonParser, final Resource resource, final ResourceResolver resolver)
        throws ServletException, IOException {
    final UGCImportHelper importHelper = new UGCImportHelper();
    JsonToken token1 = jsonParser.getCurrentToken();
    if (token1.equals(JsonToken.START_OBJECT)) {
        jsonParser.nextToken();
        if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT_TYPE)) {
            jsonParser.nextToken();
            final String contentType = jsonParser.getValueAsString();
            if (contentType.equals(ContentTypeDefinitions.LABEL_QNA_FORUM)) {
                importHelper.setQnaForumOperations(qnaForumOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_FORUM)) {
                importHelper.setForumOperations(forumOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_COMMENTS)) {
                importHelper.setCommentOperations(commentOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_CALENDAR)) {
                importHelper.setCalendarOperations(calendarOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_JOURNAL)) {
                importHelper.setJournalOperations(journalOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_TALLY)) {
                importHelper.setSocialUtils(socialUtils);
            }
            importHelper.setTallyService(tallyOperationsService); // (everything potentially needs tally)
            jsonParser.nextToken(); // content
            if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT)) {
                jsonParser.nextToken();
                token1 = jsonParser.getCurrentToken();
                if (token1.equals(JsonToken.START_OBJECT) || token1.equals(JsonToken.START_ARRAY)) {
                    if (!resolver.isLive()) {
                        throw new ServletException("Resolver is already closed");
                    }
                } else {
                    throw new ServletException("Start object token not found for content");
                }
                if (token1.equals(JsonToken.START_OBJECT)) {
                    try {
                        if (contentType.equals(ContentTypeDefinitions.LABEL_QNA_FORUM)) {
                            importHelper.importQnaContent(jsonParser, resource, resolver);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_FORUM)) {
                            importHelper.importForumContent(jsonParser, resource, resolver);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_COMMENTS)) {
                            importHelper.importCommentsContent(jsonParser, resource, resolver);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_JOURNAL)) {
                            importHelper.importJournalContent(jsonParser, resource, resolver);
                        } else {
                            LOG.info("Unsupported content type: {}", contentType);
                            jsonParser.skipChildren();
                        }
                        jsonParser.nextToken();
                    } catch (final IOException e) {
                        throw new ServletException(e);
                    }
                    jsonParser.nextToken(); // skip over END_OBJECT
                } else {
                    try {
                        if (contentType.equals(ContentTypeDefinitions.LABEL_CALENDAR)) {
                            importHelper.importCalendarContent(jsonParser, resource);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_TALLY)) {
                            importHelper.importTallyContent(jsonParser, resource);
                        } else {
                            LOG.info("Unsupported content type: {}", contentType);
                            jsonParser.skipChildren();
                        }
                        jsonParser.nextToken();
                    } catch (final IOException e) {
                        throw new ServletException(e);
                    }
                    jsonParser.nextToken(); // skip over END_ARRAY
                }
            } else {
                throw new ServletException("Content not found");
            }
        } else {
            throw new ServletException("No content type specified");
        }
    } else {
        throw new ServletException("Invalid Json format");
    }
}

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

private void importFile(final JsonParser jsonParser, final SlingHttpServletRequest request)
        throws ServletException, IOException {

    JsonToken token = jsonParser.nextToken();
    while (!token.equals(JsonToken.END_OBJECT)) {
        if (!token.equals(JsonToken.FIELD_NAME)) {
            throw new ServletException("Expected a field name, got " + token);
        }//from ww  w.  j a  va  2s .  co  m
        final String userId = jsonParser.getCurrentName();
        token = jsonParser.nextToken();
        if (!token.equals(JsonToken.START_ARRAY)) {
            throw new ServletException("Expected an array start token, got " + token);
        }
        token = jsonParser.nextToken();
        final Resource tmpParent = request.getResourceResolver().getResource("/tmp");
        while (!token.equals(JsonToken.END_ARRAY)) {
            final Map<String, Object> props = new HashMap<String, Object>();
            props.put("resourceType", Following.RESOURCE_TYPE);
            props.put("userId", userId);
            props.put("followedId", jsonParser.getValueAsString());
            Resource resource;
            resource = request.getResourceResolver().create(tmpParent, "following", props);
            final SocialComponentFactory factory = componentFactoryManager
                    .getSocialComponentFactory(Following.RESOURCE_TYPE);
            final Following following = (Following) factory.getSocialComponent(resource, request);
            request.getResourceResolver().delete(resource); // need to delete it so we can create it again next time
            final Vertex node = following.userNode();
            final Vertex other = following.followedNode();
            final String relType = "USER";
            try {
                node.createRelationshipTo(other, Edge.FOLLOWING_RELATIONSHIP_TYPE, relType);
                following.socialGraph().save();
            } catch (final IllegalArgumentException e) {
                // The relationship already exists. Do nothing.
            }
            token = jsonParser.nextToken();
        }
        token = jsonParser.nextToken(); // skip over END_ARRAY
    }
}

From source file:org.quantumbadger.redreader.jsonwrap.JsonValue.java

protected JsonValue(final JsonParser jp, final JsonToken firstToken) throws IOException {

    switch (firstToken) {

    case START_OBJECT:
        type = TYPE_OBJECT;/*w w  w.j  a v  a 2  s.  co m*/
        value = new JsonBufferedObject();
        this.jp = jp;
        break;

    case START_ARRAY:
        type = TYPE_ARRAY;
        value = new JsonBufferedArray();
        this.jp = jp;
        break;

    case VALUE_FALSE:
        type = TYPE_BOOLEAN;
        value = false;
        break;

    case VALUE_TRUE:
        type = TYPE_BOOLEAN;
        value = true;
        break;

    case VALUE_NULL:
        type = TYPE_NULL;
        value = null;
        break;

    case VALUE_STRING:
        type = TYPE_STRING;
        value = jp.getValueAsString();
        break;

    case VALUE_NUMBER_FLOAT:

        //noinspection FloatingPointEquality,UnnecessaryExplicitNumericCast
        if (jp.getValueAsDouble() == (double) jp.getValueAsLong()) {
            type = TYPE_INTEGER;
            value = jp.getValueAsLong();
        } else {
            type = TYPE_FLOAT;
            value = jp.getValueAsDouble();
        }

        break;

    case VALUE_NUMBER_INT:
        type = TYPE_INTEGER;
        value = jp.getValueAsLong();
        break;

    default:
        throw new JsonParseException("Expecting an object, literal, or array", jp.getCurrentLocation());
    }
}

From source file:com.ryan.ryanreader.jsonwrap.JsonValue.java

protected JsonValue(final JsonParser jp, final JsonToken firstToken) throws IOException {

    switch (firstToken) {

    case START_OBJECT:
        type = Type.OBJECT;/*from  w w w .  j a  v a2s .  c o m*/
        value = new JsonBufferedObject();
        this.jp = jp;
        break;

    case START_ARRAY:
        type = Type.ARRAY;
        value = new JsonBufferedArray();
        this.jp = jp;
        break;

    case VALUE_FALSE:
        type = Type.BOOLEAN;
        value = false;
        break;

    case VALUE_TRUE:
        type = Type.BOOLEAN;
        value = true;
        break;

    case VALUE_NULL:
        type = Type.NULL;
        value = null;
        break;

    case VALUE_STRING:
        type = Type.STRING;
        value = jp.getValueAsString();
        break;

    case VALUE_NUMBER_FLOAT:

        //noinspection FloatingPointEquality,UnnecessaryExplicitNumericCast
        if (jp.getValueAsDouble() == (double) jp.getValueAsLong()) {
            type = Type.INTEGER;
            value = jp.getValueAsLong();
        } else {
            type = Type.FLOAT;
            value = jp.getValueAsDouble();
        }

        break;

    case VALUE_NUMBER_INT:
        type = Type.INTEGER;
        value = jp.getValueAsLong();
        break;

    default:
        throw new JsonParseException("Expecting an object, literal, or array", jp.getCurrentLocation());
    }
}

From source file:org.debezium.core.doc.JacksonReader.java

private Document parseDocument(JsonParser parser, boolean nested) throws IOException {
    // Iterate over the fields in the top-level document ...
    BasicDocument doc = new BasicDocument();
    JsonToken token = null;//from w  w  w.  ja  va2s . c  om
    if (!nested) {
        // We expect the START_OBJECT token ...
        token = parser.nextToken();
        if (!nested && token != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object, but was " + token);
        }
    }
    String fieldName = null;
    token = parser.nextToken();
    while (token != JsonToken.END_OBJECT) {
        switch (token) {
        case FIELD_NAME:
            fieldName = parser.getCurrentName();
            break;
        case START_OBJECT:
            doc.setDocument(fieldName, parseDocument(parser, true));
            break;
        case START_ARRAY:
            doc.setArray(fieldName, parseArray(parser));
            break;
        case VALUE_STRING:
            doc.setString(fieldName, parser.getValueAsString());
            break;
        case VALUE_TRUE:
            doc.setBoolean(fieldName, true);
            break;
        case VALUE_FALSE:
            doc.setBoolean(fieldName, false);
            break;
        case VALUE_NULL:
            doc.setNull(fieldName);
            break;
        case VALUE_NUMBER_FLOAT:
        case VALUE_NUMBER_INT:
            switch (parser.getNumberType()) {
            case FLOAT:
                doc.setNumber(fieldName, parser.getFloatValue());
                break;
            case DOUBLE:
                doc.setNumber(fieldName, parser.getDoubleValue());
                break;
            case BIG_DECIMAL:
                doc.setNumber(fieldName, parser.getDecimalValue());
                break;
            case INT:
                doc.setNumber(fieldName, parser.getIntValue());
                break;
            case LONG:
                doc.setNumber(fieldName, parser.getLongValue());
                break;
            case BIG_INTEGER:
                doc.setNumber(fieldName, parser.getBigIntegerValue());
                break;
            }
            break;
        case VALUE_EMBEDDED_OBJECT:
            // disregard this, since it's an extension ...
            break;
        case NOT_AVAILABLE:
            throw new JsonParseException("Non-blocking parsers are not supported", parser.getCurrentLocation());
        case END_ARRAY:
            throw new JsonParseException("Not expecting an END_ARRAY token", parser.getCurrentLocation());
        case END_OBJECT:
            throw new JsonParseException("Not expecting an END_OBJECT token", parser.getCurrentLocation());
        }
        token = parser.nextToken();
    }
    return doc;
}