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

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

Introduction

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

Prototype

JsonToken START_OBJECT

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

Click Source Link

Document

START_OBJECT is returned when encountering '{' which signals starting of an Object value.

Usage

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

@Override
public boolean isExpectedStartArrayToken() {
    JsonToken t = _currToken;// w  ww. j  av a  2  s  . com
    if (t == JsonToken.START_OBJECT) {
        //FIX FOR ISSUE #31:
        //if this method is called, this usually means the caller wants
        //to parse an array (i.e. this method is called by array
        //deserializers such as StringArrayDeserializer. If we're currently
        //at the start of an object, check if this object might as well
        //be an array (it's just a quick sanity check).
        boolean isarray;
        if (_in.markSupported()) {
            _in.mark(3);
            try {
                //check the first key in the object. if it is '0' this
                //could indeed be an array

                //read type
                byte tpe = _in.readByte();
                if (tpe != BsonConstants.TYPE_END) {
                    //read key (CString)
                    if (_in.readByte() == '0' && _in.readByte() == '\0') {
                        //the object could indeed be an array!
                        isarray = true;
                    } else {
                        //the first key was not '0'. this can't be an array!
                        isarray = false;
                    }
                } else {
                    //object is empty. it could be an empty array.
                    isarray = true;
                }
            } catch (IOException e) {
                //we cannot check. just assume it would work. the caller
                //should know what he does.
                isarray = true;
            } finally {
                try {
                    _in.reset();
                } catch (IOException re) {
                    throw new IllegalStateException("Could not reset input stream", re);
                }
            }
        } else {
            //we cannot check. just assume it would work. the caller
            //should know what he does.
            isarray = true;
        }

        if (isarray) {
            //replace START_OBJECT token by START_ARRAY, update current context
            _currToken = JsonToken.START_ARRAY;
            _currentContext = _currentContext.copy(_currentContext.parent, true);
            return true;
        }
    }
    return super.isExpectedStartArrayToken();
}

From source file:org.jberet.support.io.JsonItemReader.java

@Override
public Object readItem() throws Exception {
    if (rowNumber >= end) {
        return null;
    }//from   w ww.jav  a 2 s  .  c o m
    int nestedObjectLevel = 0;
    do {
        token = jsonParser.nextToken();
        if (token == null) {
            return null;
        } else if (token == JsonToken.START_OBJECT) {
            nestedObjectLevel++;
            if (nestedObjectLevel == 1) {
                rowNumber++;
            } else if (nestedObjectLevel < 1) {
                throw SupportMessages.MESSAGES.unexpectedJsonContent(jsonParser.getCurrentLocation());
            }
            if (rowNumber >= start) {
                break;
            }
        } else if (token == JsonToken.END_OBJECT) {
            nestedObjectLevel--;
        }
    } while (true);
    final Object readValue = objectMapper.readValue(jsonParser, beanType);
    if (!skipBeanValidation) {
        ItemReaderWriterBase.validate(readValue);
    }
    return readValue;
}

From source file:org.messic.server.api.musicinfo.youtube.MusicInfoYoutubePlugin.java

private String search(Locale locale, String search) throws IOException {

    // http://ctrlq.org/code/19608-youtube-search-api
    // Based con code writted by Amit Agarwal

    // YouTube Data API base URL (JSON response)
    String surl = "v=2&alt=jsonc";
    // set paid-content as false to hide movie rentals
    surl = surl + "&paid-content=false";
    // set duration as long to filter partial uploads
    // url = url + "&duration=long";
    // order search results by view count
    surl = surl + "&orderby=viewCount";
    // we can request a maximum of 50 search results in a batch
    surl = surl + "&max-results=50";
    surl = surl + "&q=" + search;

    URI uri = null;//from   ww  w  .j a  v  a2 s. c o m
    try {
        uri = new URI("http", "gdata.youtube.com", "/feeds/api/videos", surl, null);
    } catch (URISyntaxException e) {
        log.error("failed!", e);
    }

    URL url = new URL(uri.toASCIIString());
    log.info(surl);
    Proxy proxy = getProxy();
    URLConnection connection = (proxy != null ? url.openConnection(proxy) : url.openConnection());
    InputStream is = connection.getInputStream();

    JsonFactory jsonFactory = new JsonFactory(); // or, for data binding,
                                                 // org.codehaus.jackson.mapper.MappingJsonFactory
    JsonParser jParser = jsonFactory.createParser(is);

    String htmlCode = "<script type=\"text/javascript\">";
    htmlCode = htmlCode + "  function musicInfoYoutubeDestroy(){";
    htmlCode = htmlCode + "       $('.messic-musicinfo-youtube-overlay').remove();";
    htmlCode = htmlCode + "       $('.messic-musicinfo-youtube-iframe').remove();";
    htmlCode = htmlCode + "  }";
    htmlCode = htmlCode + "  function musicInfoYoutubePlay(id){";
    htmlCode = htmlCode
            + "      var code='<div class=\"messic-musicinfo-youtube-overlay\" onclick=\"musicInfoYoutubeDestroy()\"></div>';";
    htmlCode = htmlCode
            + "      code=code+'<iframe class=\"messic-musicinfo-youtube-iframe\" src=\"http://www.youtube.com/embed/'+id+'\" frameborder=\"0\" allowfullscreen></iframe>';";
    htmlCode = htmlCode + "      $(code).hide().appendTo('body').fadeIn();";
    htmlCode = htmlCode + "  }";
    htmlCode = htmlCode + "</script>";

    // loop until token equal to "}"
    while (jParser.nextToken() != null) {
        String fieldname = jParser.getCurrentName();
        if ("items".equals(fieldname)) {
            jParser.nextToken();
            while (jParser.nextToken() != JsonToken.END_OBJECT) {
                YoutubeItem yi = new YoutubeItem();
                while (jParser.nextToken() != JsonToken.END_OBJECT) {
                    if (jParser.getCurrentToken() == JsonToken.START_OBJECT) {
                        jParser.skipChildren();
                    }
                    fieldname = jParser.getCurrentName();

                    if ("id".equals(fieldname)) {
                        jParser.nextToken();
                        yi.id = jParser.getText();
                    }
                    if ("category".equals(fieldname)) {
                        jParser.nextToken();
                        yi.category = jParser.getText();
                    }
                    if ("title".equals(fieldname)) {
                        jParser.nextToken();
                        yi.title = jParser.getText();
                    }
                    if ("description".equals(fieldname)) {
                        jParser.nextToken();
                        yi.description = jParser.getText();
                    }
                    if ("thumbnail".equals(fieldname)) {
                        jParser.nextToken();
                        jParser.nextToken();
                        jParser.nextToken();
                        jParser.nextToken();
                        fieldname = jParser.getCurrentName();
                        if ("hqDefault".equals(fieldname)) {
                            jParser.nextToken();
                            yi.thumbnail = jParser.getText();
                        }
                        jParser.nextToken();
                    }
                }

                if (yi.category != null && "MUSIC".equals(yi.category.toUpperCase()) || (yi.category == null)) {
                    if (yi.title != null) {
                        htmlCode = htmlCode + "<div class=\"messic-musicinfo-youtube-item\"><img src=\""
                                + yi.thumbnail
                                + "\"/><div class=\"messic-musicinfo-youtube-item-play\" onclick=\"musicInfoYoutubePlay('"
                                + yi.id + "')\"></div>" + "<div class=\"messic-musicinfo-youtube-description\">"
                                + "  <div class=\"messic-musicinfo-youtube-item-title\">" + yi.title + "</div>"
                                + "  <div class=\"messic-musicinfo-youtube-item-description\">" + yi.description
                                + "</div>" + "</div>" + "</div>";
                    }
                }
            }
        }

    }
    return htmlCode;
}

From source file:com.cedarsoft.couchdb.DesignDocumentsUpdater.java

/**
 * Returns the current revision (if there is one) or null
 *
 * @param path the path/*from w ww.j a  v  a2s  .co  m*/
 * @return the revision or null if there is no revision
 */
@Nullable
private static Revision getRevision(@Nonnull WebResource path) throws ActionFailedException, IOException {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("HEAD: " + path.toString());
    }
    ClientResponse response = path.get(ClientResponse.class);
    try {
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("\tStatus: " + response.getStatus());
        }
        if (response.getClientResponseStatus() == ClientResponse.Status.NOT_FOUND) {
            return null;
        }

        ActionResponseSerializer.verifyNoError(response);

        if (response.getClientResponseStatus() != ClientResponse.Status.OK) {
            throw new IllegalStateException(
                    "Invalid response: " + response.getStatus() + ": " + response.getEntity(String.class));
        }

        JsonFactory jsonFactory = JacksonSupport.getJsonFactory();
        try (InputStream entityInputStream = response.getEntityInputStream()) {
            JsonParser parser = jsonFactory.createJsonParser(entityInputStream);
            JacksonParserWrapper wrapper = new JacksonParserWrapper(parser);

            wrapper.nextToken(JsonToken.START_OBJECT);

            wrapper.nextFieldValue("_id");
            wrapper.nextFieldValue("_rev");
            return new Revision(wrapper.getText());
        }
    } finally {
        response.close();
    }
}

From source file:org.seedstack.seed.core.internal.data.DataManagerImpl.java

@Override
public void importData(InputStream inputStream, String acceptGroup, String acceptName, boolean clear) {
    Set<DataImporter<Object>> usedDataImporters = new HashSet<>();

    try {//from www. ja  v  a 2  s . c o m
        ParsingState state = ParsingState.START;
        String group = null;
        String name = null;
        JsonParser jsonParser = this.jsonFactory
                .createParser(new InputStreamReader(inputStream, Charset.forName(UTF_8)));
        JsonToken jsonToken = jsonParser.nextToken();

        while (jsonToken != null) {
            switch (state) {
            case START:
                if (jsonToken == JsonToken.START_ARRAY) {
                    state = ParsingState.DEFINITION_START;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "start array expected");
                }

                break;
            case DEFINITION_START:
                if (jsonToken == JsonToken.START_OBJECT) {
                    state = ParsingState.DEFINITION_GROUP;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "start object expected");
                }

                break;
            case DEFINITION_GROUP:
                if (jsonToken == JsonToken.FIELD_NAME && GROUP.equals(jsonParser.getCurrentName())) {
                    group = jsonParser.nextTextValue();
                    state = ParsingState.DEFINITION_NAME;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "group field expected");
                }

                break;
            case DEFINITION_NAME:
                if (jsonToken == JsonToken.FIELD_NAME && NAME.equals(jsonParser.getCurrentName())) {
                    name = jsonParser.nextTextValue();
                    state = ParsingState.DEFINITION_ITEMS;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "name field expected");
                }

                break;
            case DEFINITION_ITEMS:
                if (jsonToken == JsonToken.FIELD_NAME && ITEMS.equals(jsonParser.getCurrentName())) {
                    usedDataImporters.add(consumeItems(jsonParser, group, name, acceptGroup, acceptName));
                    state = ParsingState.DEFINITION_END;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "items field expected");
                }

                break;
            case DEFINITION_END:
                if (jsonToken == JsonToken.END_OBJECT) {
                    group = null;
                    name = null;
                    state = ParsingState.END;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "end object expected");
                }

                break;
            case END:
                if (jsonToken == JsonToken.START_OBJECT) {
                    state = ParsingState.DEFINITION_GROUP;
                } else if (jsonToken == JsonToken.END_ARRAY) {
                    state = ParsingState.START;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "start object or end array expected");
                }

                break;
            default:
                throwParsingError(jsonParser.getCurrentLocation(), "unexpected parser state");
            }

            jsonToken = jsonParser.nextToken();
        }
    } catch (Exception e1) {
        for (DataImporter<Object> usedDataImporter : usedDataImporters) {
            try {
                usedDataImporter.rollback();
            } catch (Exception e2) {
                e2.initCause(e1);
                throw SeedException.wrap(e2, DataErrorCode.FAILED_TO_ROLLBACK_IMPORT).put(IMPORTER_CLASS,
                        usedDataImporter.getClass().getName());
            }
        }

        throw SeedException.wrap(e1, DataErrorCode.IMPORT_FAILED);
    }

    for (DataImporter<Object> usedDataImporter : usedDataImporters) {
        try {
            usedDataImporter.commit(clear);
        } catch (Exception e) {
            throw SeedException.wrap(e, DataErrorCode.FAILED_TO_COMMIT_IMPORT).put(IMPORTER_CLASS,
                    usedDataImporter.getClass().getName());
        }
    }
}

From source file:com.cedarsoft.couchdb.io.CouchDocSerializer.java

@Nonnull
public <T> CouchDoc<T> deserialize(@Nonnull JacksonSerializer<T> wrappedSerializer,
        @Nonnull JacksonParserWrapper parserWrapper) throws InvalidTypeException, IOException {
    parserWrapper.nextToken(JsonToken.START_OBJECT);

    parserWrapper.nextFieldValue(PROPERTY_ID);
    String id = parserWrapper.getText();

    parserWrapper.nextFieldValue(PROPERTY_REV);
    String rev = parserWrapper.getText();

    //Type and Version
    parserWrapper.nextFieldValue(AbstractJacksonSerializer.PROPERTY_TYPE);
    wrappedSerializer.verifyType(parserWrapper.getText());
    parserWrapper.nextFieldValue(AbstractJacksonSerializer.PROPERTY_VERSION);
    Version version = Version.parse(parserWrapper.getText());

    //The wrapped object
    T wrapped = wrappedSerializer.deserialize(parserWrapper.getParser(), version);

    //the attachments - if there are any....
    List<? extends CouchDoc.Attachment> attachments = deserializeAttachments(parserWrapper);

    parserWrapper.ensureObjectClosed();/*from w  w  w .  j ava 2 s  .  c  o  m*/
    CouchDoc<T> doc = new CouchDoc<>(new DocId(id), rev == null ? null : new Revision(rev), wrapped);
    doc.addAttachments(attachments);
    return doc;
}

From source file:com.cedarsoft.couchdb.io.RowSerializer.java

@Nonnull
public <K, V, D> Row<K, V, D> deserialize(@Nonnull JacksonSerializer<? super K> keySerializer,
        @Nonnull JacksonSerializer<? super V> valueSerializer,
        @Nullable JacksonSerializer<? extends D> documentSerializer, @Nonnull InputStream in)
        throws IOException, InvalidTypeException {
    JsonFactory jsonFactory = JacksonSupport.getJsonFactory();

    JsonParser parser = jsonFactory.createJsonParser(in);
    JacksonParserWrapper parserWrapper = new JacksonParserWrapper(parser);
    parserWrapper.nextToken(JsonToken.START_OBJECT);

    return deserialize(keySerializer, valueSerializer, documentSerializer, parser);
}

From source file:com.sdl.odata.unmarshaller.json.core.JsonProcessor.java

/**
 * Process an embedded object./*from   ww w. ja  v a  2s. co m*/
 *
 * @param jsonParser the parser
 * @return map with embedded object key:values
 * @throws IOException If unable to read input parser
 */
private Object getEmbeddedObject(JsonParser jsonParser) throws IOException {
    LOG.info("Start parsing an embedded object.");
    Map<String, Object> embeddedMap = new HashMap<>();
    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String key = jsonParser.getText();
        jsonParser.nextToken();
        JsonToken token = jsonParser.getCurrentToken();
        if (token == JsonToken.START_ARRAY) {
            Object embeddedArray = getCollectionValue(jsonParser);
            embeddedMap.put(key, embeddedArray);
        } else if (token == JsonToken.START_OBJECT) {
            Object embeddedObject = getEmbeddedObject(jsonParser);
            embeddedMap.put(key, embeddedObject);
        } else {
            if (token.equals(JsonToken.VALUE_NULL)) {
                embeddedMap.put(key, null);
            } else {
                embeddedMap.put(key, jsonParser.getText());
            }
        }
    }
    return embeddedMap;
}

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

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

From source file:ai.susi.geo.GeoJsonReader.java

private static Map<String, String> parseMap(JsonParser parser) throws JsonParseException, IOException {
    Map<String, String> map = new HashMap<>();
    JsonToken token = parser.nextToken();
    if (!JsonToken.START_OBJECT.equals(token))
        return map;

    while (!parser.isClosed() && (token = parser.nextToken()) != null && token != JsonToken.END_OBJECT) {
        String name = parser.getCurrentName();
        token = parser.nextToken();/* w  w  w.  j  av  a2s  .c  o  m*/
        String value = parser.getText();
        map.put(name.toLowerCase(), value);
    }
    return map;
}