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

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

Introduction

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

Prototype

public abstract JsonToken getCurrentToken();

Source Link

Document

Accessor to find which token parser currently points to, if any; null will be returned if none.

Usage

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 w ww .  jav a  2  s.  c  om
    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.google.openrtb.json.OpenRtbJsonReader.java

protected void readNativeField(JsonParser par, Native.Builder nativ, String fieldName) throws IOException {
    switch (fieldName) {
    case "request":
        if (par.getCurrentToken() == JsonToken.VALUE_STRING) {
            nativ.setRequestNative(factory().newNativeReader().readNativeRequest(
                    new CharArrayReader(par.getTextCharacters(), par.getTextOffset(), par.getTextLength())));
        } else { // Object
            nativ.setRequestNative(factory().newNativeReader().readNativeRequest(par));
        }//from  w w w .  j a  va  2 s  . c  o  m
        break;
    case "ver":
        nativ.setVer(par.getText());
        break;
    case "api":
        for (startArray(par); endArray(par); par.nextToken()) {
            APIFramework value = APIFramework.valueOf(par.getIntValue());
            if (checkEnum(value)) {
                nativ.addApi(value);
            }
        }
        break;
    case "battr":
        for (startArray(par); endArray(par); par.nextToken()) {
            CreativeAttribute value = CreativeAttribute.valueOf(par.getIntValue());
            if (checkEnum(value)) {
                nativ.addBattr(value);
            }
        }
        break;
    default:
        readOther(nativ, par, fieldName);
    }
}

From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java

/**
 * General version used when handling needs more advanced
 * features./*from  w  w w .j  av  a2 s  .  co  m*/
 */
@Override
public Object deserializeFromObject(JsonParser jp, DeserializationContext ctxt) throws IOException {
    if (_nonStandardCreation) {
        if (_unwrappedPropertyHandler != null) {
            return deserializeWithUnwrapped(jp, ctxt);
        }
        if (_externalTypeIdHandler != null) {
            return deserializeWithExternalTypeId(jp, ctxt);
        }
        return deserializeFromObjectUsingNonDefault(jp, ctxt);
    }
    final Object bean = _valueInstantiator.createUsingDefault(ctxt);
    if (jp.canReadObjectId()) {
        Object id = jp.getObjectId();
        if (id != null) {
            _handleTypedObjectId(jp, ctxt, bean, id);
        }
    }
    if (_injectables != null) {
        injectValues(ctxt, bean);
    }
    if (_needViewProcesing) {
        Class<?> view = ctxt.getActiveView();
        if (view != null) {
            return deserializeWithView(jp, ctxt, bean, view);
        }
    }
    beanDeserializerAdvice.before(bean, jp, ctxt);
    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        String propName = jp.getCurrentName();
        // Skip field name:
        jp.nextToken();

        if (beanDeserializerAdvice.intercept(bean, propName, jp, ctxt)) {
            continue;
        }

        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) { // normal case
            try {
                prop.deserializeAndSet(jp, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
        handleUnknownVanilla(jp, ctxt, bean, propName);
    }
    beanDeserializerAdvice.after(bean, jp, ctxt);
    return bean;
}

From source file:com.google.openrtb.json.OpenRtbJsonReader.java

protected void readBidField(JsonParser par, Bid.Builder bid, String fieldName) throws IOException {
    switch (fieldName) {
    case "id":
        bid.setId(par.getText());/*from  w  w w  .  java  2 s . c om*/
        break;
    case "impid":
        bid.setImpid(par.getText());
        break;
    case "price":
        bid.setPrice(par.getValueAsDouble());
        break;
    case "adid":
        bid.setAdid(par.getText());
        break;
    case "nurl":
        bid.setNurl(par.getText());
        break;
    case "adm":
        if (par.getCurrentToken() == JsonToken.VALUE_STRING) {
            String valueString = par.getText();
            if (valueString.startsWith("{")) {
                bid.setAdmNative(factory().newNativeReader().readNativeResponse(valueString));
            } else {
                bid.setAdm(valueString);
            }
        } else { // Object
            bid.setAdmNative(factory().newNativeReader().readNativeResponse(par));
        }
        break;
    case "adomain":
        for (startArray(par); endArray(par); par.nextToken()) {
            bid.addAdomain(par.getText());
        }
        break;
    case "bundle":
        bid.setBundle(par.getText());
        break;
    case "iurl":
        bid.setIurl(par.getText());
        break;
    case "cid":
        bid.setCid(par.getText());
        break;
    case "crid":
        bid.setCrid(par.getText());
        break;
    case "cat":
        for (startArray(par); endArray(par); par.nextToken()) {
            String cat = par.getText();
            if (checkContentCategory(cat)) {
                bid.addCat(cat);
            }
        }
        break;
    case "attr":
        for (startArray(par); endArray(par); par.nextToken()) {
            CreativeAttribute value = CreativeAttribute.valueOf(par.getIntValue());
            if (checkEnum(value)) {
                bid.addAttr(value);
            }
        }
        break;
    case "dealid":
        bid.setDealid(par.getText());
        break;
    case "w":
        bid.setW(par.getIntValue());
        break;
    case "h":
        bid.setH(par.getIntValue());
        break;
    case "api": {
        APIFramework value = APIFramework.valueOf(par.getIntValue());
        if (checkEnum(value)) {
            bid.setApi(value);
        }
    }
        break;
    case "protocol": {
        Protocol value = Protocol.valueOf(par.getIntValue());
        if (checkEnum(value)) {
            bid.setProtocol(value);
        }
    }
        break;
    case "qagmediarating": {
        QAGMediaRating value = QAGMediaRating.valueOf(par.getIntValue());
        if (checkEnum(value)) {
            bid.setQagmediarating(value);
        }
    }
        break;
    case "exp":
        bid.setExp(par.getIntValue());
        break;
    default:
        readOther(bid, par, fieldName);
    }
}

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

/**
 * Read the first feature to create the table
 * @param jp//from   ww  w  .  j a  va  2s .co  m
 */
private void readFeatures(JsonParser jp, String geomType, StringBuilder metadataBuilder)
        throws IOException, SQLException {
    jp.nextToken(); // START_ARRAY [
    JsonToken token = jp.nextToken(); // START_OBJECT {
    if (token != JsonToken.END_ARRAY) {
        jp.nextToken(); // FIELD_NAME type"name"
        jp.nextToken(); // VALUE_STRING Feature
        geomType = jp.getText();
        if (geomType.equalsIgnoreCase(GeoJsonField.FEATURE)) {
            jp.nextToken(); // FIELD_NAME geometry
            String firstField = jp.getText();
            if (firstField.equalsIgnoreCase(GeoJsonField.GEOMETRY)) {
                parseGeometryMetadata(jp, metadataBuilder);
                hasGeometryField = true;
                fieldIndex++;
                jp.nextToken();//END_OBJECT } geometry
            } else if (firstField.equalsIgnoreCase(GeoJsonField.PROPERTIES)) {
                fieldIndex = parseMetadataProperties(jp, metadataBuilder, fieldIndex);
                hasProperties = true;
            }
            // If there is only one geometry field in the feature them the next
            // token corresponds to the end object of the feature.
            jp.nextToken();
            if (jp.getCurrentToken() != JsonToken.END_OBJECT) {
                String secondParam = jp.getText();
                if (secondParam.equalsIgnoreCase(GeoJsonField.GEOMETRY)) {
                    parseGeometryMetadata(jp, metadataBuilder);
                    hasGeometryField = true;
                    fieldIndex++;
                    jp.nextToken();//END_OBJECT } geometry;
                } else if (secondParam.equalsIgnoreCase(GeoJsonField.PROPERTIES)) {
                    fieldIndex = parseMetadataProperties(jp, metadataBuilder, fieldIndex);
                    hasProperties = true;
                }
                jp.nextToken(); //END_OBJECT } feature
            }
            if (!hasProperties) {
                metadataBuilder.append("ID INT, PRIMARY KEY (ID)");
                fieldIndex++;
            }
            metadataBuilder.append(")");
        } else {
            throw new SQLException("Malformed GeoJSON file. Expected 'Feature', found '" + geomType + "'");
        }
    }
}

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

private DataImporter<Object> consumeItems(JsonParser jsonParser, String group, String name, String acceptGroup,
        String acceptName) throws IOException {

    Map<String, DataImporterDefinition<Object>> dataImporterDefinitionMap = allDataImporters.get(group);

    if (dataImporterDefinitionMap == null) {
        throw SeedException.createNew(DataErrorCode.NO_IMPORTER_FOUND).put(GROUP, group).put(NAME, name);
    }// w ww. ja v a2s. c  om

    DataImporterDefinition<Object> currentImporterDefinition = dataImporterDefinitionMap.get(name);

    if (currentImporterDefinition == null) {
        throw SeedException.createNew(DataErrorCode.NO_IMPORTER_FOUND).put(GROUP, group).put(NAME, name);
    }

    if (!group.equals(currentImporterDefinition.getGroup())) {
        throw SeedException.createNew(DataErrorCode.UNEXPECTED_DATA_TYPE)
                .put(DATA_SET, String.format(CLASSES_MAP_KEY, group, name))
                .put(IMPORTER_CLASS, currentImporterDefinition.getDataImporterClass().getName());
    }

    if (!name.equals(currentImporterDefinition.getName())) {
        throw SeedException.createNew(DataErrorCode.UNEXPECTED_DATA_TYPE)
                .put(DATA_SET, String.format(CLASSES_MAP_KEY, group, name))
                .put(IMPORTER_CLASS, currentImporterDefinition.getDataImporterClass().getName());
    }

    DataImporter<Object> currentDataImporter = null;
    if ((acceptGroup == null || acceptGroup.equals(group)) && (acceptName == null || acceptName.equals(name))) {

        currentDataImporter = injector.getInstance(currentImporterDefinition.getDataImporterClass());

        // Check if items contains an array

        if (jsonParser.nextToken() != JsonToken.START_ARRAY) {
            throw new IllegalArgumentException("Items should be an array");
        }

        jsonParser.nextToken();

        // If the array is not empty consume it
        if (jsonParser.getCurrentToken() != JsonToken.END_ARRAY) {
            Iterator<Object> objectIterator = jsonParser
                    .readValuesAs(currentImporterDefinition.getImportedClass());

            while (objectIterator.hasNext()) {
                currentDataImporter.importData(objectIterator.next());
            }

            // The array should end correctly
            if (jsonParser.getCurrentToken() != JsonToken.END_ARRAY) {
                throw new IllegalArgumentException("end array expected");
            }
        }
    }

    // the data importer containing the data
    return currentDataImporter;
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

private ContentValues parseObject(JsonParser parser, SQLiteDatabase tempDb, String parentId, int seq)
        throws JsonParseException, IOException {
    // TODO : Grab id of root topic here, and store it in shared prefs, in case it ever
    //        changes. Currently we assume "root" and a change would be catastrophic.
    ContentValues result = new ContentValues();
    ChildArrayResults childResults = null;
    boolean badKind = false;

    result.put("parentTopic_id", parentId);
    result.put("seq", seq);

    while (parser.nextValue() != JsonToken.END_OBJECT) {

        // Allows us to burn through the rest of the object once we discover it's an exercise or something else we don't care about.
        if (badKind)
            continue;

        String fieldName = parser.getCurrentName();

        // Keys present will determine object type.
        if (stringFields.contains(fieldName)) {
            // Use getValueAsString over getText; getText returns "null" while getValueAsString returns null.
            String value = parser.getValueAsString();
            result.put(fieldName, value);

            if ("id".equals(fieldName)) {
                if (childResults != null) {
                    addParentIdToChildren(tempDb, childResults, value);
                }//from   w w  w  .java  2  s .co m
            }
        } else if (intFields.contains(fieldName)) {
            result.put(fieldName, parser.getIntValue());
        } else if (booleanFields.contains(fieldName)) {
            result.put(fieldName, parser.getBooleanValue());
        } else if ("children".equals(fieldName)) {
            childResults = parseChildArray(parser, tempDb,
                    result.containsKey("id") ? result.getAsString("id") : null);
            result.put("video_count", childResults.videoCount);
            result.put("child_kind", childResults.childKind);
            result.put("thumb_id", childResults.thumbId);
        } else if ("download_urls".equals(fieldName)) {
            parseDownloadUrls(parser, result);
        } else if (null == fieldName) {
            // Noop. Just in case.
        } else {
            JsonToken next = parser.getCurrentToken();
            if (next == JsonToken.START_OBJECT || next == JsonToken.START_ARRAY) {
                // Skip this object or array, leaving us pointing at the matching end_object / end_array token.
                parser.skipChildren();
            }
        }
    }

    // Ignore types we don't need.
    if (badKind) {
        return null;
    }

    // Having parsed this whole object, we can insert it.
    if (result.containsKey("kind")) {
        String kind = result.getAsString("kind");
        if ("Topic".equals(kind)) {
            if (result.containsKey("id")) {
                result.put("_id", result.getAsString("id"));
                result.remove("id");
            }
            if (result.containsKey("child_kind")) {
                String child_kind = result.getAsString("child_kind");
                if ("Topic".equals(child_kind) || "Video".equals(child_kind)) {
                    insertTopic(tempDb, result);
                }
            }
        } else if ("Video".equals(kind)) {
            if (result.containsKey("id")) {
                result.put("video_id", result.getAsString("id"));
                result.remove("id");
            }
            insertTopicVideo(tempDb, result);
            insertVideo(tempDb, result);
        }
    }

    return result;
}

From source file:org.apache.hadoop.hbase.rest.TestTableScan.java

@Test
public void testStreamingJSON() throws Exception {
    //Test with start row and end row.
    StringBuilder builder = new StringBuilder();
    builder.append("/*");
    builder.append("?");
    builder.append(Constants.SCAN_COLUMN + "=" + COLUMN_1);
    builder.append("&");
    builder.append(Constants.SCAN_START_ROW + "=aaa");
    builder.append("&");
    builder.append(Constants.SCAN_END_ROW + "=aay");
    Response response = client.get("/" + TABLE + builder.toString(), Constants.MIMETYPE_JSON);
    assertEquals(200, response.getCode());

    int count = 0;
    ObjectMapper mapper = new JacksonJaxbJsonProvider().locateMapper(CellSetModel.class,
            MediaType.APPLICATION_JSON_TYPE);
    JsonFactory jfactory = new JsonFactory(mapper);
    JsonParser jParser = jfactory.createJsonParser(response.getStream());
    boolean found = false;
    while (jParser.nextToken() != JsonToken.END_OBJECT) {
        if (jParser.getCurrentToken() == JsonToken.START_OBJECT && found) {
            RowModel row = jParser.readValueAs(RowModel.class);
            assertNotNull(row.getKey());
            for (int i = 0; i < row.getCells().size(); i++) {
                if (count == 0) {
                    assertEquals("aaa", Bytes.toString(row.getKey()));
                }/*from w  ww  .java 2 s.co  m*/
                if (count == 23) {
                    assertEquals("aax", Bytes.toString(row.getKey()));
                }
                count++;
            }
            jParser.skipChildren();
        } else {
            found = jParser.getCurrentToken() == JsonToken.START_ARRAY;
        }
    }
    assertEquals(24, count);
}

From source file:org.apache.olingo.client.core.edm.xml.ActionDeserializer.java

@Override
protected ActionImpl doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final ActionImpl action = new ActionImpl();

    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        final JsonToken token = jp.getCurrentToken();
        if (token == JsonToken.FIELD_NAME) {
            if ("Name".equals(jp.getCurrentName())) {
                action.setName(jp.nextTextValue());
            } else if ("IsBound".equals(jp.getCurrentName())) {
                action.setBound(BooleanUtils.toBoolean(jp.nextTextValue()));
            } else if ("EntitySetPath".equals(jp.getCurrentName())) {
                action.setEntitySetPath(jp.nextTextValue());
            } else if ("Parameter".equals(jp.getCurrentName())) {
                jp.nextToken();//  w ww . j av  a2  s. com
                action.getParameters().add(jp.readValueAs(ParameterImpl.class));
            } else if ("ReturnType".equals(jp.getCurrentName())) {
                action.setReturnType(parseReturnType(jp, "Action"));
            } else if ("Annotation".equals(jp.getCurrentName())) {
                jp.nextToken();
                action.getAnnotations().add(jp.readValueAs(AnnotationImpl.class));
            }
        }
    }

    return action;
}