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

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

Introduction

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

Prototype

JsonToken END_OBJECT

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

Click Source Link

Document

END_OBJECT is returned when encountering '}' which signals ending of an Object value

Usage

From source file:com.quinsoft.zeidon.standardoe.ActivateOisFromJsonStream.java

private EntityMeta readEntityMeta(EntityInstanceImpl ei) throws Exception {
    EntityMeta meta = new EntityMeta();
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldName = jp.getCurrentName();

        switch (fieldName) {
        case "incrementals":
            readIncrementals(meta);//from  w  w  w. java2s.c o m
            break;
        case "isLinkedSource":
            meta.isLinkedSource = true;
            break;
        case "entityKey":
            meta.entityKey = jp.getText();
            break;
        case "linkedSource":
            meta.linkedSource = jp.getText();
            break;
        case "selected":
            selectedInstances.add(ei);
            break;
        case "incomplete":
            meta.incomplete = true;
            break;
        case "lazyLoaded":
            meta.lazyLoaded = jp.getText();
            break;

        default:
            task.log().warn("Unknown entity meta value %s", fieldName);
        }
    }

    return meta;
}

From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java

protected boolean Sync(String service, String scope, String params) {
    final Date start = new Date();
    boolean hasError = false;
    if (params == null)
        params = "";
    final SQLiteDatabase db = mDB.getWritableDatabase();
    final ArrayList<TableInfo> notifyTableInfo = new ArrayList<TableInfo>();

    final String download = String.format(contentHelper.DOWNLOAD_SERVICE_URI, service, scope, params);
    final String upload = String.format(contentHelper.UPLOAD_SERVICE_URI, service, scope, params);
    final String scopeServerBlob = String.format("%s.%s.%s", service, scope, _.serverBlob);
    String serverBlob = null;//from w  w  w  . j a v a  2s.c o  m
    Cursor cur = db.query(BlobsTable.NAME, new String[] { BlobsTable.C_VALUE }, BlobsTable.C_NAME + "=?",
            new String[] { scopeServerBlob }, null, null, null);
    final String originalBlob;
    if (cur.moveToFirst()) {
        originalBlob = serverBlob = cur.getString(0);
    } else {
        originalBlob = null;
    }
    cur.close();
    db.beginTransaction();
    try {
        boolean nochanges = false;
        if (serverBlob != null) {
            nochanges = !contentHelper.hasDirtTable(db, scope);
        }
        boolean resolve = false;
        final Metadata meta = new Metadata();
        final HashMap<String, Object> vals = new HashMap<String, Object>();
        final ContentValues cv = new ContentValues(2);
        JsonFactory jsonFactory = new JsonFactory();
        JsonToken current = null;
        String name = null;
        boolean moreChanges = false;
        boolean forceMoreChanges = false;
        do {
            final int requestMethod;
            final String serviceRequestUrl;
            final ContentProducer contentProducer;

            if (serverBlob != null) {
                requestMethod = HTTP_POST;
                if (nochanges) {
                    serviceRequestUrl = download;
                } else {
                    serviceRequestUrl = upload;
                    forceMoreChanges = true;
                }
                contentProducer = new SyncContentProducer(jsonFactory, db, scope, serverBlob, !nochanges,
                        notifyTableInfo, contentHelper);
                nochanges = true;
            } else {
                requestMethod = HTTP_GET;
                serviceRequestUrl = download;
                contentProducer = null;

            }
            if (moreChanges) {
                db.beginTransaction();
            }

            Result result = executeRequest(requestMethod, serviceRequestUrl, contentProducer);
            if (result.getStatus() == HttpStatus.SC_OK) {
                final JsonParser jp = jsonFactory.createParser(result.getInputStream());

                jp.nextToken(); // skip ("START_OBJECT(d) expected");
                jp.nextToken(); // skip ("FIELD_NAME(d) expected");
                if (jp.nextToken() != JsonToken.START_OBJECT)
                    throw new Exception("START_OBJECT(d - object) expected");
                while (jp.nextToken() != JsonToken.END_OBJECT) {
                    name = jp.getCurrentName();
                    if (_.__sync.equals(name)) {
                        current = jp.nextToken();
                        while (jp.nextToken() != JsonToken.END_OBJECT) {
                            name = jp.getCurrentName();
                            current = jp.nextToken();
                            if (_.serverBlob.equals(name)) {
                                serverBlob = jp.getText();
                            } else if (_.moreChangesAvailable.equals(name)) {
                                moreChanges = jp.getBooleanValue() || forceMoreChanges;
                                forceMoreChanges = false;
                            } else if (_.resolveConflicts.equals(name)) {
                                resolve = jp.getBooleanValue();
                            }
                        }
                    } else if (_.results.equals(name)) {
                        if (jp.nextToken() != JsonToken.START_ARRAY)
                            throw new Exception("START_ARRAY(results) expected");
                        while (jp.nextToken() != JsonToken.END_ARRAY) {
                            meta.isDeleted = false;
                            meta.tempId = null;
                            vals.clear();
                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                name = jp.getCurrentName();
                                current = jp.nextToken();
                                if (current == JsonToken.VALUE_STRING) {
                                    vals.put(name, jp.getText());
                                } else if (current == JsonToken.VALUE_NUMBER_INT) {
                                    vals.put(name, jp.getLongValue());
                                } else if (current == JsonToken.VALUE_NUMBER_FLOAT) {
                                    vals.put(name, jp.getDoubleValue());
                                } else if (current == JsonToken.VALUE_FALSE) {
                                    vals.put(name, 0L);
                                } else if (current == JsonToken.VALUE_TRUE) {
                                    vals.put(name, 1L);
                                } else if (current == JsonToken.VALUE_NULL) {
                                    vals.put(name, null);
                                } else {
                                    if (current == JsonToken.START_OBJECT) {
                                        if (_.__metadata.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.uri.equals(name)) {
                                                    meta.uri = jp.getText();
                                                } else if (_.type.equals(name)) {
                                                    meta.type = jp.getText();
                                                } else if (_.isDeleted.equals(name)) {
                                                    meta.isDeleted = jp.getBooleanValue();
                                                } else if (_.tempId.equals(name)) {
                                                    meta.tempId = jp.getText();
                                                }
                                            }
                                        } else if (_.__syncConflict.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.isResolved.equals(name)) {
                                                } else if (_.conflictResolution.equals(name)) {
                                                } else if (_.conflictingChange.equals(name)) {
                                                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                        name = jp.getCurrentName();
                                                        current = jp.nextToken();
                                                        if (current == JsonToken.START_OBJECT) {
                                                            if (_.__metadata.equals(name)) {
                                                                while (jp.nextToken() != JsonToken.END_OBJECT) {

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            // resolve conf

                                        } else if (_.__syncError.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                            }
                                        }
                                    }
                                }
                            }
                            TableInfo tab = contentHelper.getTableFromType(meta.type);
                            if (meta.isDeleted) {
                                tab.DeleteWithUri(meta.uri, db);
                            } else {
                                tab.SyncJSON(vals, meta, db);
                            }
                            if (!notifyTableInfo.contains(tab))
                                notifyTableInfo.add(tab);
                        }
                    }
                }
                jp.close();
                if (!hasError) {
                    cv.clear();
                    cv.put(BlobsTable.C_NAME, scopeServerBlob);
                    cv.put(BlobsTable.C_VALUE, serverBlob);
                    cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
                    cv.put(BlobsTable.C_STATE, 0);
                    db.replace(BlobsTable.NAME, null, cv);
                    db.setTransactionSuccessful();
                    db.endTransaction();
                    if (DEBUG) {
                        Log.d(TAG, "CP-Sync: commit changes");
                    }
                    final ContentResolver cr = getContext().getContentResolver();
                    for (TableInfo t : notifyTableInfo) {
                        final Uri nu = contentHelper.getDirUri(t.name, false);
                        cr.notifyChange(nu, null, false);
                        // false - do not force sync cause we are in sync
                        if (DEBUG) {
                            Log.d(TAG, "CP-Sync: notifyChange table: " + t.name + ", uri: " + nu);
                        }

                        for (String n : t.notifyUris) {
                            cr.notifyChange(Uri.parse(n), null, false);
                            if (DEBUG) {
                                Log.d(TAG, "+uri: " + n);
                            }
                        }
                    }
                    notifyTableInfo.clear();
                }
            } else {
                if (DEBUG) {
                    Log.e(TAG, "Server error in fetching remote contacts: " + result.getStatus());
                }
                hasError = true;
                break;
            }
        } while (moreChanges);
    } catch (final ConnectTimeoutException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ConnectTimeoutException", e);
        }
    } catch (final IOException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    } catch (final ParseException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    } catch (final Exception e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    }
    if (hasError) {
        db.endTransaction();
        ContentValues cv = new ContentValues();
        cv.put(BlobsTable.C_NAME, scopeServerBlob);
        cv.put(BlobsTable.C_VALUE, originalBlob);
        cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
        cv.put(BlobsTable.C_STATE, -1);
        db.replace(BlobsTable.NAME, null, cv);
    }
    /*-if (!hasError) {
    final ContentValues cv = new ContentValues(2);
     cv.put(BlobsTable.C_NAME, scopeServerBlob);
     cv.put(BlobsTable.C_VALUE, serverBlob);
     db.replace(BlobsTable.NAME, null, cv);
     db.setTransactionSuccessful();
    }
    db.endTransaction();
    if (!hasError) {
     for (String t : notifyTableInfo) {
    getContext().getContentResolver().notifyChange(getDirUri(t),
          null);
     }
    }*/
    if (DEBUG) {
        Helpers.LogInfo(start);
    }
    return !hasError;
}

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Parses the properties of a feature/*from w w w .  j  a va  2 s.  co m*/
 *
 * Syntax:
 *
 * "properties": {"prop0": "value0"}
 *
 * @param jsParser
 */
private void parseProperties(JsonParser jp, int fieldIndex) throws IOException, SQLException {
    jp.nextToken();//START_OBJECT {
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        JsonToken value = jp.nextToken();
        if (value == JsonToken.VALUE_STRING) {
            getPreparedStatement().setObject(fieldIndex, jp.getText());
            fieldIndex++;
        } else if (value == JsonToken.VALUE_TRUE) {
            getPreparedStatement().setObject(fieldIndex, jp.getValueAsBoolean());
            fieldIndex++;
        } else if (value == JsonToken.VALUE_FALSE) {
            getPreparedStatement().setObject(fieldIndex, jp.getValueAsBoolean());
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NUMBER_FLOAT) {
            getPreparedStatement().setObject(fieldIndex, jp.getValueAsDouble());
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NUMBER_INT) {
            getPreparedStatement().setObject(fieldIndex, jp.getValueAsInt());
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NULL) {
            getPreparedStatement().setObject(fieldIndex, null);
            fieldIndex++;
        } else {
            //ignore other value
        }
    }

}

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

@Override
public List<Relative> parseRelatives(final InputStream inputStream) {
    checkNotNull(inputStream);/*from w  ww .j  ava  2  s .c  o m*/
    JsonParser parser = null;
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        List<Relative> relatives = new ArrayList<Relative>();

        String profileId = null;
        String matchId = null;
        double similarity = 0.0d;
        int sharedSegments = 0;
        Relationship relationship = null;
        Relationship userRelationship = null;
        Set<Relationship> range = new HashSet<Relationship>();

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

            if ("id".equals(field)) {
                profileId = parser.getText();
            } else if ("relatives".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    while (parser.nextToken() != JsonToken.END_OBJECT) {
                        String relativeField = parser.getCurrentName();
                        parser.nextToken();

                        if ("match_id".equals(relativeField)) {
                            matchId = parser.getText();
                        } else if ("similarity".equals(relativeField)) {
                            similarity = Double.parseDouble(parser.getText());
                        } else if ("shared_segments".equals(relativeField)) {
                            sharedSegments = parser.getIntValue();
                        } else if ("relationship".equals(relativeField)) {
                            relationship = Relationship.fromDescription(parser.getText());
                        } else if ("user_relationship_code".equals(relativeField)) {
                            String code = parser.getText();
                            userRelationship = code == "null" ? null
                                    : Relationship.fromCode(Integer.parseInt(code));
                        } else if ("predicted_relationship_code".equals(relativeField)) {
                            if (relationship == null) {
                                String code = parser.getText();
                                relationship = code == "null" ? null
                                        : Relationship.fromCode(Integer.parseInt(code));
                            }
                        } else if ("range".equals(relativeField)) {
                            while (parser.nextToken() != JsonToken.END_ARRAY) {
                                range.add(Relationship.fromDescription(parser.getText()));
                            }
                        }
                        // ignored nested fields
                        else if ("family_locations".equals(relativeField)) {
                            while (parser.nextToken() != JsonToken.END_ARRAY) {
                                // ignore
                            }
                        } else if ("family_surnames".equals(relativeField)) {
                            while (parser.nextToken() != JsonToken.END_ARRAY) {
                                // ignore
                            }
                        } else if ("profile_picture_urls".equals(relativeField)) {
                            while (parser.nextToken() != JsonToken.END_OBJECT) {
                                // ignore
                            }
                        }
                    }
                }
                relatives.add(new Relative(profileId, matchId, similarity, sharedSegments, relationship,
                        userRelationship, range));
                matchId = null;
                similarity = 0.0d;
                sharedSegments = 0;
                relationship = null;
                userRelationship = null;
                range.clear();
            }
        }
        return relatives;
    } catch (IOException e) {
        logger.warn("could not parse relatives", e);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
    return null;
}

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

protected void extractTopic(final JsonParser jsonParser, final Resource resource,
        final ResourceResolver resolver, final CommentOperations operations)
        throws IOException, ServletException {
    if (jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
        return; // replies could just be an empty object (i.e. "ugc:replies":{} ) in which case, do nothing
    }/*w  w w .j a  v a2 s.co m*/
    final Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("social:key", jsonParser.getCurrentName());
    Resource post = null;
    jsonParser.nextToken();
    if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
        jsonParser.nextToken();
        String author = null;
        List<DataSource> attachments = new ArrayList<DataSource>();
        while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
            final String label = jsonParser.getCurrentName();
            JsonToken token = jsonParser.nextToken();
            if (jsonParser.getCurrentToken().isScalarValue()) {

                // either a string, boolean, or long value
                if (token.isNumeric()) {
                    properties.put(label, jsonParser.getValueAsLong());
                } else {
                    final String value = jsonParser.getValueAsString();
                    if (value.equals("true") || value.equals("false")) {
                        properties.put(label, jsonParser.getValueAsBoolean());
                    } else {
                        final String decodedValue = URLDecoder.decode(value, "UTF-8");
                        if (label.equals("language")) {
                            properties.put("mtlanguage", decodedValue);
                        } else {
                            properties.put(label, decodedValue);
                            if (label.equals("userIdentifier")) {
                                author = decodedValue;
                            } else if (label.equals("jcr:description")) {
                                properties.put("message", decodedValue);
                            }
                        }
                    }
                }
            } else if (label.equals(ContentTypeDefinitions.LABEL_ATTACHMENTS)) {
                attachments = getAttachments(jsonParser);
            } else if (label.equals(ContentTypeDefinitions.LABEL_REPLIES)
                    || label.equals(ContentTypeDefinitions.LABEL_TALLY)
                    || label.equals(ContentTypeDefinitions.LABEL_TRANSLATION)
                    || label.equals(ContentTypeDefinitions.LABEL_SUBNODES)) {
                // replies and sub-nodes ALWAYS come after all other properties and attachments have been listed,
                // so we can create the post now if we haven't already, and then dive in
                if (post == null) {
                    try {
                        post = createPost(resource, author, properties, attachments,
                                resolver.adaptTo(Session.class), operations);
                        resProvider = SocialResourceUtils.getSocialResource(post).getResourceProvider();
                    } catch (Exception e) {
                        throw new ServletException(e.getMessage(), e);
                    }
                }
                if (label.equals(ContentTypeDefinitions.LABEL_REPLIES)) {
                    if (token.equals(JsonToken.START_OBJECT)) {
                        jsonParser.nextToken();
                        while (!token.equals(JsonToken.END_OBJECT)) {
                            extractTopic(jsonParser, post, resolver, operations);
                            token = jsonParser.nextToken();
                        }
                    } else {
                        throw new IOException("Expected an object for the subnodes");
                    }
                } else if (label.equals(ContentTypeDefinitions.LABEL_SUBNODES)) {
                    if (token.equals(JsonToken.START_OBJECT)) {
                        token = jsonParser.nextToken();
                        try {
                            while (!token.equals(JsonToken.END_OBJECT)) {
                                final String subnodeType = jsonParser.getCurrentName();
                                token = jsonParser.nextToken();
                                if (token.equals(JsonToken.START_OBJECT)) {
                                    jsonParser.skipChildren();
                                    token = jsonParser.nextToken();
                                }
                            }
                        } catch (final IOException e) {
                            throw new IOException("unable to skip child of sub-nodes", e);
                        }
                    } else {
                        final String field = jsonParser.getValueAsString();
                        throw new IOException("Expected an object for the subnodes. Instead: " + field);
                    }
                } else if (label.equals(ContentTypeDefinitions.LABEL_TALLY)) {
                    UGCImportHelper.extractTally(post, jsonParser, resProvider, tallyOperationsService);
                } else if (label.equals(ContentTypeDefinitions.LABEL_TRANSLATION)) {
                    importTranslation(jsonParser, post);
                    resProvider.commit(post.getResourceResolver());
                }

            } else if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
                properties.put(label, UGCImportHelper.extractSubmap(jsonParser));
            } else if (jsonParser.getCurrentToken().equals(JsonToken.START_ARRAY)) {
                jsonParser.nextToken(); // skip the START_ARRAY token
                if (label.equals(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS)) {
                    while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) {
                        final String timestampLabel = jsonParser.getValueAsString();
                        if (properties.containsKey(timestampLabel)
                                && properties.get(timestampLabel) instanceof Long) {
                            final Calendar calendar = new GregorianCalendar();
                            calendar.setTimeInMillis((Long) properties.get(timestampLabel));
                            properties.put(timestampLabel, calendar.getTime());
                        }
                        jsonParser.nextToken();
                    }
                } else {
                    final List<String> subArray = new ArrayList<String>();
                    while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) {
                        subArray.add(jsonParser.getValueAsString());
                        jsonParser.nextToken();
                    }
                    String[] strings = new String[subArray.size()];
                    for (int i = 0; i < subArray.size(); i++) {
                        strings[i] = subArray.get(i);
                    }
                    properties.put(label, strings);
                }
            }
            jsonParser.nextToken();
        }
        if (post == null) {
            try {
                post = createPost(resource, author, properties, attachments, resolver.adaptTo(Session.class),
                        operations);
                if (null == resProvider) {
                    resProvider = SocialResourceUtils.getSocialResource(post).getResourceProvider();
                }
                // resProvider.commit(resolver);
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        }
    } else {
        throw new IOException("Improperly formed JSON - expected an OBJECT_START token, but got "
                + jsonParser.getCurrentToken().toString());
    }
}

From source file:com.quinsoft.zeidon.standardoe.ActivateOisFromJsonStream.java

private JsonToken readOiMeta() throws Exception {
    String odName = null;//from   w  w w.  j a v a  2 s  .  co m
    readOnlyOi = false;
    readOnly = false;
    totalRootCount = null;

    jp.nextToken();
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldName = jp.getCurrentName();
        jp.nextToken(); // Move to value.
        switch (fieldName) {
        case "application":
            application = task.getApplication(jp.getValueAsString());
            break;
        case "odName":
            odName = jp.getValueAsString();
            break; // Save OD name for later.
        case "incremental":
            incremental = jp.getValueAsBoolean();
            break;
        case "readOnlyOi":
            readOnlyOi = jp.getValueAsBoolean();
            break;
        case "readOnly":
            readOnly = jp.getValueAsBoolean();
            break;
        case "totalRootCount":
            totalRootCount = jp.getValueAsInt();
            break;

        default:
            task.log().warn("Unknown .oimeta fieldname %s", fieldName);
            break;
        }
    }

    if (odName == null)
        throw new ZeidonException("LodDef not specified in JSON .oimeta");

    // We don't load the LodDef until now because it's valid JSON to reorder
    // the values in the .oimeta object.
    lodDef = application.getLodDef(task, odName);
    view = task.activateEmptyObjectInstance(lodDef);
    returnList.add(view);
    JsonToken token = jp.nextToken();

    // Create a list to keep track of selected instances.
    selectedInstances = new ArrayList<>();

    // If the next token is FIELD_NAME then OI data is next so get the next token.
    // If it's not the the OI is EMPTY and token should be END_OBJECT.
    if (token == JsonToken.FIELD_NAME)
        token = jp.nextToken();
    else
        assert token == JsonToken.END_OBJECT;

    return token;
}

From source file:org.apache.lucene.server.handlers.AddDocumentHandler.java

/** Parse one value for a field, which is either an
 *  object matching the type of the field, or a {boost:
 *  ..., value: ...}. *///from w  w w  . j a  v  a2 s  .  c  o  m
private static boolean parseOneValue(FieldDef fd, JsonParser p, Document doc) throws IOException {

    Object o = null;
    float boost = 1.0f;

    JsonToken token = p.nextToken();
    if (token == JsonToken.START_ARRAY) {
        if ("hierarchy".equals(fd.faceted) || fd.valueType == FieldDef.FieldValueType.LAT_LON) {
            o = getNativeValue(fd, token, p);
        } else {
            if (fd.multiValued == false) {
                fail(fd.name, "expected single value, not array, since this field is not multiValued");
            }
            while (true) {
                if (!parseOneValue(fd, p, doc)) {
                    break;
                }
            }
            return true;
        }
    } else {

        if (token == JsonToken.END_ARRAY) {
            assert fd.multiValued;
            return false;
        }

        if (fd.fieldType.indexOptions() != IndexOptions.NONE && token == JsonToken.START_OBJECT) {
            // Parse a {boost: X, value: Y}
            while (true) {
                token = p.nextToken();
                if (token == JsonToken.END_OBJECT) {
                    break;
                }
                assert token == JsonToken.FIELD_NAME;
                String key = p.getText();
                if (key.equals("boost")) {
                    token = p.nextToken();
                    if (token == JsonToken.VALUE_NUMBER_INT || token == JsonToken.VALUE_NUMBER_FLOAT) {
                        boost = p.getFloatValue();
                    } else {
                        fail(fd.name, "boost in inner object field value must have float or int value; got: "
                                + token);
                    }
                } else if (key.equals("value")) {
                    o = getNativeValue(fd, p.nextToken(), p);
                } else {
                    fail(fd.name, "unrecognized json key \"" + key
                            + "\" in inner object field value; must be boost or value");
                }
            }
            if (o == null) {
                fail(fd.name, "missing 'value' key");
            }
        } else {
            // Parse a native value:
            o = getNativeValue(fd, token, p);
        }
    }

    parseOneNativeValue(fd, doc, o, boost);
    return true;
}

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

/**
 * Creates and returns an instance of the RawContact from encrypted data
 * //from  w w  w  . java2  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.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

@Override
public List<Risk> parseRisks(final InputStream inputStream) {
    checkNotNull(inputStream);//w w  w.j  a  v  a2  s. com
    JsonParser parser = null;
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String reportId = null;
        String description = null;
        double risk = 0.0d;
        double populationRisk = 0.0d;
        List<Risk> risks = new ArrayList<Risk>();
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();

            if ("id".equals(field)) {
                id = parser.getText();
            } else if ("risks".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    while (parser.nextToken() != JsonToken.END_OBJECT) {
                        String riskField = parser.getCurrentName();
                        parser.nextToken();

                        if ("report_id".equals(riskField)) {
                            reportId = parser.getText();
                        } else if ("description".equals(riskField)) {
                            description = parser.getText();
                        } else if ("risk".equals(riskField)) {
                            risk = Double.parseDouble(parser.getText());
                        } else if ("population_risk".equals(riskField)) {
                            populationRisk = Double.parseDouble(parser.getText());
                        }
                    }
                    risks.add(new Risk(id, reportId, description, risk, populationRisk));
                    reportId = null;
                    description = null;
                    risk = 0.0d;
                    populationRisk = 0.0d;
                }
            }
        }
        return risks;
    } catch (IOException e) {
        logger.warn("could not parse risks", e);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
    return null;
}