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

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

Introduction

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

Prototype

JsonToken VALUE_FALSE

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

Click Source Link

Document

VALUE_FALSE is returned when encountering literal "false" in value context

Usage

From source file:org.mongojack.internal.object.BsonObjectCursor.java

private static JsonToken getToken(Object o) {
    if (o == null) {
        return JsonToken.VALUE_NULL;
    } else if (o instanceof Iterable) {
        return JsonToken.START_ARRAY;
    } else if (o instanceof BSONObject) {
        return JsonToken.START_OBJECT;
    } else if (o instanceof Number) {
        if (o instanceof Double || o instanceof Float || o instanceof BigDecimal) {
            return JsonToken.VALUE_NUMBER_FLOAT;
        } else {/*w ww. j  a  v a 2  s .  c  om*/
            return JsonToken.VALUE_NUMBER_INT;
        }
    } else if (o instanceof Boolean) {
        if ((Boolean) o) {
            return JsonToken.VALUE_TRUE;
        } else {
            return JsonToken.VALUE_FALSE;
        }
    } else if (o instanceof CharSequence) {
        return JsonToken.VALUE_STRING;
    } else if (o instanceof ObjectId) {
        return JsonToken.VALUE_EMBEDDED_OBJECT;
    } else if (o instanceof DBRef) {
        return JsonToken.VALUE_EMBEDDED_OBJECT;
    } else if (o instanceof Date) {
        return JsonToken.VALUE_EMBEDDED_OBJECT;
    } else if (o instanceof byte[]) {
        return JsonToken.VALUE_EMBEDDED_OBJECT;
    } else {
        throw new IllegalStateException("Don't know how to parse type: " + o.getClass());
    }
}

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

@Test
public void testParse() throws Exception {
    JsonParser parser = jsonFactory.createJsonParser(Hex.decodeHex(BSON.toCharArray()));

    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());//from www . ja va2 s  . co  m
}

From source file:de.undercouch.bson4jackson.BsonParser.java

@Override
public JsonToken nextToken() throws IOException, JsonParseException {
    Context ctx = _currentContext;
    if (_currToken == null && ctx == null) {
        try {/*  www . j  a  va 2  s.  c  o m*/
            _currToken = handleNewDocument(false);
        } catch (EOFException e) {
            //there is nothing more to read. indicate EOF
            return null;
        }
    } else {
        _tokenPos = _counter.getPosition();
        if (ctx == null) {
            if (_currToken == JsonToken.END_OBJECT) {
                //end of input
                return null;
            }
            throw new JsonParseException("Found element outside the document", getTokenLocation());
        }

        if (ctx.state == State.DONE) {
            //next field
            ctx.reset();
        }

        boolean readValue = true;
        if (ctx.state == State.FIELDNAME) {
            readValue = false;
            while (true) {
                //read field name or end of document
                ctx.type = _in.readByte();
                if (ctx.type == BsonConstants.TYPE_END) {
                    //end of document
                    _currToken = (ctx.array ? JsonToken.END_ARRAY : JsonToken.END_OBJECT);
                    _currentContext = _currentContext.parent;
                } else if (ctx.type == BsonConstants.TYPE_UNDEFINED) {
                    //skip field name and then ignore this token
                    skipCString();
                    continue;
                } else {
                    ctx.state = State.VALUE;
                    _currToken = JsonToken.FIELD_NAME;

                    if (ctx.array) {
                        //immediately read value of array element (discard field name)
                        readValue = true;
                        skipCString();
                        ctx.fieldName = null;
                    } else {
                        //read field name
                        ctx.fieldName = readCString();
                    }
                }
                break;
            }
        }

        if (readValue) {
            //parse element's value
            switch (ctx.type) {
            case BsonConstants.TYPE_DOUBLE:
                ctx.value = _in.readDouble();
                _currToken = JsonToken.VALUE_NUMBER_FLOAT;
                break;

            case BsonConstants.TYPE_STRING:
                ctx.value = readString();
                _currToken = JsonToken.VALUE_STRING;
                break;

            case BsonConstants.TYPE_DOCUMENT:
                _currToken = handleNewDocument(false);
                break;

            case BsonConstants.TYPE_ARRAY:
                _currToken = handleNewDocument(true);
                break;

            case BsonConstants.TYPE_BINARY:
                _currToken = handleBinary();
                break;

            case BsonConstants.TYPE_OBJECTID:
                ctx.value = readObjectId();
                _currToken = JsonToken.VALUE_EMBEDDED_OBJECT;
                break;

            case BsonConstants.TYPE_BOOLEAN:
                boolean b = _in.readBoolean();
                ctx.value = b;
                _currToken = (b ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE);
                break;

            case BsonConstants.TYPE_DATETIME:
                ctx.value = new Date(_in.readLong());
                _currToken = JsonToken.VALUE_EMBEDDED_OBJECT;
                break;

            case BsonConstants.TYPE_NULL:
                _currToken = JsonToken.VALUE_NULL;
                break;

            case BsonConstants.TYPE_REGEX:
                _currToken = handleRegEx();
                break;

            case BsonConstants.TYPE_DBPOINTER:
                _currToken = handleDBPointer();
                break;

            case BsonConstants.TYPE_JAVASCRIPT:
                ctx.value = new JavaScript(readString());
                _currToken = JsonToken.VALUE_EMBEDDED_OBJECT;
                break;

            case BsonConstants.TYPE_SYMBOL:
                ctx.value = readSymbol();
                _currToken = JsonToken.VALUE_EMBEDDED_OBJECT;
                break;

            case BsonConstants.TYPE_JAVASCRIPT_WITH_SCOPE:
                _currToken = handleJavascriptWithScope();
                break;

            case BsonConstants.TYPE_INT32:
                ctx.value = _in.readInt();
                _currToken = JsonToken.VALUE_NUMBER_INT;
                break;

            case BsonConstants.TYPE_TIMESTAMP:
                ctx.value = readTimestamp();
                _currToken = JsonToken.VALUE_EMBEDDED_OBJECT;
                break;

            case BsonConstants.TYPE_INT64:
                ctx.value = _in.readLong();
                _currToken = JsonToken.VALUE_NUMBER_INT;
                break;

            case BsonConstants.TYPE_MINKEY:
                ctx.value = "MinKey";
                _currToken = JsonToken.VALUE_STRING;
                break;

            case BsonConstants.TYPE_MAXKEY:
                ctx.value = "MaxKey";
                _currToken = JsonToken.VALUE_STRING;
                break;

            default:
                throw new JsonParseException("Unknown element type " + ctx.type, getTokenLocation());
            }
            ctx.state = State.DONE;
        }
    }
    return _currToken;
}

From source file:org.wso2.extension.siddhi.map.json.sourcemapper.JsonSourceMapper.java

private Event convertToSingleEventForDefaultMapping(Object eventObject) throws IOException {
    Event event = new Event(attributesSize);
    Object[] data = event.getData();
    JsonParser parser;/*from w  w  w. j av a2  s  .c om*/
    int numberOfProvidedAttributes = 0;
    try {
        parser = factory.createParser(eventObject.toString());
    } catch (IOException e) {
        throw new SiddhiAppRuntimeException(
                "Initializing a parser failed for the event string." + eventObject.toString());
    }
    int position;
    while (!parser.isClosed()) {
        JsonToken jsonToken = parser.nextToken();
        if (JsonToken.START_OBJECT.equals(jsonToken)) {
            parser.nextToken();
            if (DEFAULT_JSON_EVENT_IDENTIFIER.equalsIgnoreCase(parser.getText())) {
                parser.nextToken();
            } else {
                log.error("Default json message " + eventObject
                        + " contains an invalid event identifier. Required \"event\", " + "but found \""
                        + parser.getText() + "\". Hence dropping the message.");
                return null;
            }
        } else if (JsonToken.FIELD_NAME.equals(jsonToken)) {
            String key = parser.getCurrentName();
            numberOfProvidedAttributes++;
            position = findDefaultMappingPosition(key);
            if (position == -1) {
                log.error("Stream \"" + streamDefinition.getId() + "\" does not have an attribute named \""
                        + key + "\", but the received event " + eventObject.toString()
                        + " does. Hence dropping the message.");
                return null;
            }
            jsonToken = parser.nextToken();
            Attribute.Type type = streamAttributes.get(position).getType();

            if (JsonToken.VALUE_NULL.equals(jsonToken)) {
                data[position] = null;
            } else {
                switch (type) {
                case BOOL:
                    if (JsonToken.VALUE_TRUE.equals(jsonToken) || JsonToken.VALUE_FALSE.equals(jsonToken)) {
                        data[position] = parser.getValueAsBoolean();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type BOOL. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case INT:
                    if (JsonToken.VALUE_NUMBER_INT.equals(jsonToken)) {
                        data[position] = parser.getValueAsInt();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type INT. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case DOUBLE:
                    if (JsonToken.VALUE_NUMBER_FLOAT.equals(jsonToken)) {
                        data[position] = parser.getValueAsDouble();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type DOUBLE. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case STRING:
                    if (JsonToken.VALUE_STRING.equals(jsonToken)) {
                        data[position] = parser.getValueAsString();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type STRING. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case FLOAT:
                    if (JsonToken.VALUE_NUMBER_FLOAT.equals(jsonToken)
                            || JsonToken.VALUE_NUMBER_INT.equals(jsonToken)) {
                        data[position] = attributeConverter.getPropertyValue(parser.getValueAsString(),
                                Attribute.Type.FLOAT);
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type FLOAT. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                case LONG:
                    if (JsonToken.VALUE_NUMBER_INT.equals(jsonToken)) {
                        data[position] = parser.getValueAsLong();
                    } else {
                        log.error("Json message " + eventObject.toString()
                                + " contains incompatible attribute types and values. Value " + parser.getText()
                                + " is not compatible with type LONG. " + "Hence dropping the message.");
                        return null;
                    }
                    break;
                default:
                    return null;
                }
            }
        }
    }

    if (failOnMissingAttribute && (numberOfProvidedAttributes != attributesSize)) {
        log.error("Json message " + eventObject.toString()
                + " contains missing attributes. Hence dropping the message.");
        return null;
    }
    return event;
}

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

/**
 * Parses the metadata properties.//from   ww  w.  j a v a 2s.co  m
 *
 * @param jp
 * @return index
 */
private int parseMetadataProperties(JsonParser jp, StringBuilder metadataBuilder, int fieldIndex)
        throws IOException {
    jp.nextToken();//START_OBJECT {
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldName = jp.getText().toUpperCase(); //FIELD_NAME columnName            
        JsonToken value = jp.nextToken();
        if (value == JsonToken.VALUE_STRING) {
            metadataBuilder.append(fieldName).append(" VARCHAR");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_TRUE) {
            metadataBuilder.append(fieldName).append(" BOOLEAN");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_FALSE) {
            metadataBuilder.append(fieldName).append(" BOOLEAN");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NUMBER_FLOAT) {
            metadataBuilder.append(fieldName).append(" DOUBLE");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NUMBER_INT) {
            metadataBuilder.append(fieldName).append(" INT");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NULL) {
            metadataBuilder.append(fieldName).append(" VARCHAR");
            fieldIndex++;
        } else {
            // TODO: ignore value.
        }
        metadataBuilder.append(",");
    }
    return fieldIndex;
}

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

/** Parses the current json token into the corresponding
 *  java object. *//*from   w  ww . j  a v a  2 s  . c  om*/
private static Object getNativeValue(FieldDef fd, JsonToken token, JsonParser p) throws IOException {
    Object o;
    if (token == JsonToken.VALUE_STRING) {
        o = p.getText();
    } else if (token == JsonToken.VALUE_NUMBER_INT) {
        o = Long.valueOf(p.getLongValue());
    } else if (token == JsonToken.VALUE_NUMBER_FLOAT) {
        o = Double.valueOf(p.getDoubleValue());
    } else if (token == JsonToken.VALUE_TRUE) {
        o = Boolean.TRUE;
    } else if (token == JsonToken.VALUE_FALSE) {
        o = Boolean.FALSE;
    } else if (fd.faceted.equals("hierarchy") && token == JsonToken.START_ARRAY) {
        if (fd.multiValued == false) {
            List<String> values = new ArrayList<>();
            while (true) {
                token = p.nextToken();
                if (token == JsonToken.END_ARRAY) {
                    break;
                } else if (token != JsonToken.VALUE_STRING) {
                    if (token == JsonToken.START_ARRAY) {
                        fail(fd.name, "expected array of strings, but saw array inside array");
                    } else {
                        fail(fd.name, "expected array of strings, but saw " + token + " inside array");
                    }
                }
                values.add(p.getText());
            }
            o = values;
        } else {
            List<List<String>> values = new ArrayList<>();
            while (true) {
                token = p.nextToken();
                if (token == JsonToken.END_ARRAY) {
                    break;
                } else if (token == JsonToken.START_ARRAY) {
                    List<String> sub = new ArrayList<>();
                    values.add(sub);
                    while (true) {
                        token = p.nextToken();
                        if (token == JsonToken.VALUE_STRING) {
                            sub.add(p.getText());
                        } else if (token == JsonToken.END_ARRAY) {
                            break;
                        } else {
                            fail(fd.name, "expected array of strings or array of array of strings, but saw "
                                    + token + " inside inner array");
                        }
                    }
                } else if (token == JsonToken.VALUE_STRING) {
                    List<String> sub = new ArrayList<>();
                    values.add(sub);
                    sub.add(p.getText());
                } else if (token == JsonToken.START_ARRAY) {
                    fail(fd.name, "expected array of strings, but saw array inside array");
                } else {
                    fail(fd.name, "expected array of strings, but saw " + token + " inside array");
                }
            }
            o = values;
        }
    } else if (fd.valueType == FieldDef.FieldValueType.LAT_LON) {
        if (token != JsonToken.START_ARRAY) {
            fail(fd.name, "latlon field must be [lat, lon] value; got " + token);
        }
        double[] latLon = new double[2];
        token = p.nextToken();
        if (token != JsonToken.VALUE_NUMBER_FLOAT) {
            fail(fd.name, "latlon field must be [lat, lon] value; got " + token);
        }
        latLon[0] = p.getDoubleValue();
        token = p.nextToken();
        if (token != JsonToken.VALUE_NUMBER_FLOAT) {
            fail(fd.name, "latlon field must be [lat, lon] value; got " + token);
        }
        latLon[1] = p.getDoubleValue();
        token = p.nextToken();
        if (token != JsonToken.END_ARRAY) {
            fail(fd.name, "latlon field must be [lat, lon] value; got " + token);
        }
        o = latLon;
    } else {
        String message;
        if (token == JsonToken.VALUE_NULL) {
            message = "null field value not supported; just omit this field from the document instead";
        } else {
            message = "value in inner object field value should be string, int/long, float/double or boolean; got "
                    + token;
        }

        fail(fd.name, message);

        // Dead code but compiler disagrees:
        o = null;
    }
    return o;
}

From source file:com.bazaarvoice.jackson.rison.RisonParser.java

/**
 * @return Next token from the stream, if any found, or null
 *   to indicate end-of-input/* w  w w  . jav  a 2 s  . com*/
 */
@Override
public JsonToken nextToken() throws IOException, JsonParseException {
    _numTypesValid = NR_UNKNOWN;

    if (_currToken == null && _parsingContext.inRoot()) {
        if (isRisonEnabled(Feature.A_RISON)) {
            _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol);
            return (_currToken = JsonToken.START_ARRAY);
        } else if (isRisonEnabled(Feature.O_RISON)) {
            _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol);
            return (_currToken = JsonToken.START_OBJECT);
        }
    }

    /* First: field names are special -- we will always tokenize
     * (part of) value along with field name to simplify
     * state handling. If so, can and need to use secondary token:
     */
    if (_currToken == JsonToken.FIELD_NAME) {
        return _nextAfterName();
    }
    if (_tokenIncomplete) {
        _skipString(); // only strings can be partial
    }
    int i = _nextChOrEnd();
    if (i < 0) { // end-of-input
        /* 19-Feb-2009, tatu: Should actually close/release things
         *    like input source, symbol table and recyclable buffers now.
         */
        close();
        if (_parsingContext.getParent().inRoot()) {
            if (isRisonEnabled(Feature.A_RISON) && _parsingContext.inArray()) {
                _parsingContext = _parsingContext.getParent();
                return (_currToken = JsonToken.END_ARRAY);
            }
            if (isRisonEnabled(Feature.O_RISON) && _parsingContext.inObject()) {
                _parsingContext = _parsingContext.getParent();
                return (_currToken = JsonToken.END_OBJECT);
            }
        }
        _handleEOF();
        return (_currToken = null);
    }

    /* First, need to ensure we know the starting location of token
     * after skipping leading white space
     */
    _tokenInputTotal = _currInputProcessed + _inputPtr - 1;
    _tokenInputRow = _currInputRow;
    _tokenInputCol = _inputPtr - _currInputRowStart - 1;

    // finally: clear any data retained so far
    _binaryValue = null;

    // Closing scope?
    if (i == ')') {
        if (_parsingContext.inArray()) {
            _parsingContext = _parsingContext.getParent();
            return (_currToken = JsonToken.END_ARRAY);
        }
        if (_parsingContext.inObject()) {
            _parsingContext = _parsingContext.getParent();
            return (_currToken = JsonToken.END_OBJECT);
        }
        _reportMismatchedEndMarker(i, ')');
    }

    // Nope: do we then expect a comma?
    if (_parsingContext.expectComma()) {
        if (i != INT_COMMA) {
            _reportUnexpectedChar(i,
                    "was expecting comma to separate " + _parsingContext.getTypeDesc() + " entries");
        }
        i = _nextCh();
    }

    /* And should we now have a name? Always true for
     * Object contexts, since the intermediate 'expect-value'
     * state is never retained.
     */
    boolean inObject = _parsingContext.inObject();
    if (inObject) {
        // First, field name itself:
        String name;
        if (i != INT_APOSTROPHE) {
            name = _parseUnquotedFieldName(i);
        } else {
            name = _parseFieldName(i);
        }
        _parsingContext.setCurrentName(name);
        _currToken = JsonToken.FIELD_NAME;
        i = _nextCh();
        if (i != INT_COLON) {
            _reportUnexpectedChar(i, "was expecting a colon to separate field name and value");
        }
        i = _nextCh();
    }

    // Ok: we must have a value... what is it?

    JsonToken t;

    switch (i) {
    case INT_APOSTROPHE:
        _tokenIncomplete = true;
        t = JsonToken.VALUE_STRING;
        break;
    case '(':
        if (!inObject) {
            _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol);
        }
        t = JsonToken.START_OBJECT;
        break;
    case ')':
        // Error: ')' is not valid at this point; valid closers have
        // been handled earlier
        _reportUnexpectedChar(i, "expected a value");

    case INT_MINUS:
        /* Should we have separate handling for plus? Although
        * it is not allowed per se, it may be erroneously used,
        * and could be indicate by a more specific error message.
        */
    case INT_0:
    case INT_1:
    case INT_2:
    case INT_3:
    case INT_4:
    case INT_5:
    case INT_6:
    case INT_7:
    case INT_8:
    case INT_9:
        t = parseNumberText(i);
        break;

    case '!':
        i = _nextCh();
        switch (i) {
        case '(':
            if (!inObject) {
                _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol);
            }
            t = JsonToken.START_ARRAY;
            break;
        case INT_t:
            t = JsonToken.VALUE_TRUE;
            break;
        case INT_f:
            t = JsonToken.VALUE_FALSE;
            break;
        case INT_n:
            t = JsonToken.VALUE_NULL;
            break;
        default:
            t = _handleUnexpectedValue(i);
            break;
        }
        break;
    default:
        if (IdentifierUtils.isIdStartLenient(i)) {
            t = JsonToken.VALUE_STRING;
            _inputPtr--; // push back the first char
            _parseUnquotedString();
        } else {
            t = _handleUnexpectedValue(i);
        }
        break;
    }

    if (inObject) {
        _nextToken = t;
        return _currToken;
    }
    _currToken = t;
    return t;
}

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

private static EdmType evaluateEdmType(JsonToken token, String value) {
    EdmType edmType = null;//from  w ww. j  av  a  2  s  .co m

    if (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE) {
        edmType = EdmType.BOOLEAN;
    } else if (token == JsonToken.VALUE_NUMBER_FLOAT) {
        edmType = EdmType.DOUBLE;
    } else if (token == JsonToken.VALUE_NUMBER_INT) {
        edmType = EdmType.INT32;
    } else {
        edmType = EdmType.STRING;
    }

    return edmType;
}

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

/**
 * Parses the properties of a feature//from  w w w .ja  v  a2s  .com
 *
 * 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: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;//ww  w. j av a  2s. co 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;
}