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

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

Introduction

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

Prototype

public abstract JsonParser skipChildren() throws IOException, JsonParseException;

Source Link

Document

Method that will skip all child tokens of an array or object token that the parser currently points to, iff stream points to JsonToken#START_OBJECT or JsonToken#START_ARRAY .

Usage

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

@SuppressWarnings("resource")
protected Object deserializeWithUnwrapped(JsonParser jp, DeserializationContext ctxt, Object bean)
        throws IOException {
    JsonToken t = jp.getCurrentToken();/*from   w w  w  . j av a 2 s. c o m*/
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    TokenBuffer tokens = new TokenBuffer(jp);
    tokens.writeStartObject();
    final Class<?> activeView = _needViewProcesing ? ctxt.getActiveView() : null;
    beanDeserializerAdvice.before(bean, jp, ctxt);
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        String propName = jp.getCurrentName();

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

        SettableBeanProperty prop = _beanProperties.find(propName);
        jp.nextToken();
        if (prop != null) { // normal case
            if (activeView != null && !prop.visibleInView(activeView)) {
                jp.skipChildren();
                continue;
            }
            try {
                prop.deserializeAndSet(jp, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
        if (_ignorableProps != null && _ignorableProps.contains(propName)) {
            handleIgnoredProperty(jp, ctxt, bean, propName);
            continue;
        }
        // but... others should be passed to unwrapped property deserializers
        tokens.writeFieldName(propName);
        tokens.copyCurrentStructure(jp);
        // how about any setter? We'll get copies but...
        if (_anySetter != null) {
            _anySetter.deserializeAndSet(jp, ctxt, bean, propName);
        }
    }
    tokens.writeEndObject();
    _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens);
    beanDeserializerAdvice.after(bean, jp, ctxt);
    return bean;
}

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

protected Object deserializeWithExternalTypeId(JsonParser jp, DeserializationContext ctxt, Object bean)
        throws IOException {
    final Class<?> activeView = _needViewProcesing ? ctxt.getActiveView() : null;
    final ExternalTypeHandler ext = _externalTypeIdHandler.start();
    beanDeserializerAdvice.before(bean, jp, ctxt);
    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        String propName = jp.getCurrentName();
        jp.nextToken();//from   www.j  a va2s  .  co  m

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

        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) { // normal case
            // [JACKSON-831]: may have property AND be used as external type id:
            if (jp.getCurrentToken().isScalarValue()) {
                ext.handleTypePropertyValue(jp, ctxt, propName, bean);
            }
            if (activeView != null && !prop.visibleInView(activeView)) {
                jp.skipChildren();
                continue;
            }
            try {
                prop.deserializeAndSet(jp, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
        // ignorable things should be ignored
        if (_ignorableProps != null && _ignorableProps.contains(propName)) {
            handleIgnoredProperty(jp, ctxt, bean, propName);
            continue;
        }
        // but others are likely to be part of external type id thingy...
        if (ext.handlePropertyValue(jp, ctxt, propName, bean)) {
            continue;
        }
        // if not, the usual fallback handling:
        if (_anySetter != null) {
            try {
                _anySetter.deserializeAndSet(jp, ctxt, bean, propName);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
        // Unknown: let's call handler method
        handleUnknownProperty(jp, ctxt, bean, propName);
    }
    // and when we get this far, let's try finalizing the deal:
    ext.complete(jp, ctxt, bean);
    beanDeserializerAdvice.after(bean, jp, ctxt);
    return bean;
}

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 www.  j ava  2s .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:org.elasticsearch.client.sniff.ElasticsearchNodesSniffer.java

private static Node readNode(String nodeId, JsonParser parser, Scheme scheme) throws IOException {
    HttpHost publishedHost = null;/* w  w  w  . jav  a2 s.co m*/
    /*
     * We sniff the bound hosts so we can look up the node based on any
     * address on which it is listening. This is useful in Elasticsearch's
     * test framework where we sometimes publish ipv6 addresses but the
     * tests contact the node on ipv4.
     */
    Set<HttpHost> boundHosts = new HashSet<>();
    String name = null;
    String version = null;
    /*
     * Multi-valued attributes come with key = `real_key.index` and we
     * unflip them after reading them because we can't rely on the order
     * that they arive.
     */
    final Map<String, String> protoAttributes = new HashMap<String, String>();

    boolean sawRoles = false;
    boolean master = false;
    boolean data = false;
    boolean ingest = false;

    String fieldName = null;
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        if (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
            fieldName = parser.getCurrentName();
        } else if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
            if ("http".equals(fieldName)) {
                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    if (parser.getCurrentToken() == JsonToken.VALUE_STRING
                            && "publish_address".equals(parser.getCurrentName())) {
                        URI publishAddressAsURI = URI.create(scheme + "://" + parser.getValueAsString());
                        publishedHost = new HttpHost(publishAddressAsURI.getHost(),
                                publishAddressAsURI.getPort(), publishAddressAsURI.getScheme());
                    } else if (parser.currentToken() == JsonToken.START_ARRAY
                            && "bound_address".equals(parser.getCurrentName())) {
                        while (parser.nextToken() != JsonToken.END_ARRAY) {
                            URI boundAddressAsURI = URI.create(scheme + "://" + parser.getValueAsString());
                            boundHosts.add(new HttpHost(boundAddressAsURI.getHost(),
                                    boundAddressAsURI.getPort(), boundAddressAsURI.getScheme()));
                        }
                    } else if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
                        parser.skipChildren();
                    }
                }
            } else if ("attributes".equals(fieldName)) {
                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    if (parser.getCurrentToken() == JsonToken.VALUE_STRING) {
                        String oldValue = protoAttributes.put(parser.getCurrentName(),
                                parser.getValueAsString());
                        if (oldValue != null) {
                            throw new IOException("repeated attribute key [" + parser.getCurrentName() + "]");
                        }
                    } else {
                        parser.skipChildren();
                    }
                }
            } else {
                parser.skipChildren();
            }
        } else if (parser.currentToken() == JsonToken.START_ARRAY) {
            if ("roles".equals(fieldName)) {
                sawRoles = true;
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    switch (parser.getText()) {
                    case "master":
                        master = true;
                        break;
                    case "data":
                        data = true;
                        break;
                    case "ingest":
                        ingest = true;
                        break;
                    default:
                        logger.warn("unknown role [" + parser.getText() + "] on node [" + nodeId + "]");
                    }
                }
            } else {
                parser.skipChildren();
            }
        } else if (parser.currentToken().isScalarValue()) {
            if ("version".equals(fieldName)) {
                version = parser.getText();
            } else if ("name".equals(fieldName)) {
                name = parser.getText();
            }
        }
    }
    //http section is not present if http is not enabled on the node, ignore such nodes
    if (publishedHost == null) {
        logger.debug("skipping node [" + nodeId + "] with http disabled");
        return null;
    }

    Map<String, List<String>> realAttributes = new HashMap<>(protoAttributes.size());
    List<String> keys = new ArrayList<>(protoAttributes.keySet());
    for (String key : keys) {
        if (key.endsWith(".0")) {
            String realKey = key.substring(0, key.length() - 2);
            List<String> values = new ArrayList<>();
            int i = 0;
            while (true) {
                String value = protoAttributes.remove(realKey + "." + i);
                if (value == null) {
                    break;
                }
                values.add(value);
                i++;
            }
            realAttributes.put(realKey, unmodifiableList(values));
        }
    }
    for (Map.Entry<String, String> entry : protoAttributes.entrySet()) {
        realAttributes.put(entry.getKey(), singletonList(entry.getValue()));
    }

    if (version.startsWith("2.")) {
        /*
         * 2.x doesn't send roles, instead we try to read them from
         * attributes.
         */
        boolean clientAttribute = v2RoleAttributeValue(realAttributes, "client", false);
        Boolean masterAttribute = v2RoleAttributeValue(realAttributes, "master", null);
        Boolean dataAttribute = v2RoleAttributeValue(realAttributes, "data", null);
        master = masterAttribute == null ? false == clientAttribute : masterAttribute;
        data = dataAttribute == null ? false == clientAttribute : dataAttribute;
    } else {
        assert sawRoles : "didn't see roles for [" + nodeId + "]";
    }
    assert boundHosts.contains(publishedHost) : "[" + nodeId
            + "] doesn't make sense! publishedHost should be in boundHosts";
    logger.trace("adding node [" + nodeId + "]");
    return new Node(publishedHost, boundHosts, name, version, new Roles(master, data, ingest),
            unmodifiableMap(realAttributes));
}

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

/**
 * Method called when there are declared "unwrapped" properties
 * which need special handling/*from  www  . j  a  v  a2  s.  c  om*/
 */
@SuppressWarnings("resource")
protected Object deserializeWithUnwrapped(JsonParser jp, DeserializationContext ctxt) throws IOException {
    if (_delegateDeserializer != null) {
        return _valueInstantiator.createUsingDelegate(ctxt, _delegateDeserializer.deserialize(jp, ctxt));
    }
    if (_propertyBasedCreator != null) {
        return deserializeUsingPropertyBasedWithUnwrapped(jp, ctxt);
    }
    TokenBuffer tokens = new TokenBuffer(jp);
    tokens.writeStartObject();
    final Object bean = _valueInstantiator.createUsingDefault(ctxt);

    if (_injectables != null) {
        injectValues(ctxt, bean);
    }
    final Class<?> activeView = _needViewProcesing ? ctxt.getActiveView() : null;
    beanDeserializerAdvice.before(bean, jp, ctxt);
    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        String propName = jp.getCurrentName();
        jp.nextToken();

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

        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) { // normal case
            if (activeView != null && !prop.visibleInView(activeView)) {
                jp.skipChildren();
                continue;
            }
            try {
                prop.deserializeAndSet(jp, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
        // ignorable things should be ignored
        if (_ignorableProps != null && _ignorableProps.contains(propName)) {
            handleIgnoredProperty(jp, ctxt, bean, propName);
            continue;
        }
        // but... others should be passed to unwrapped property deserializers
        tokens.writeFieldName(propName);
        tokens.copyCurrentStructure(jp);
        // how about any setter? We'll get copies but...
        if (_anySetter != null) {
            try {
                _anySetter.deserializeAndSet(jp, ctxt, bean, propName);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
    }
    tokens.writeEndObject();
    _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens);
    beanDeserializerAdvice.after(bean, jp, ctxt);
    return bean;
}

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

/**
 * Parses geometry metadata.//w  w w  .  ja  v  a 2 s.c  o m
 *
 * @param jp
 * @param metadataBuilder
 */
private void parseGeometryMetadata(JsonParser jp, StringBuilder metadataBuilder)
        throws IOException, SQLException {
    jp.nextToken(); //START_OBJECT {
    jp.nextToken(); // FIELD_NAME type     
    jp.nextToken(); //VALUE_STRING Point
    String geomType = jp.getText();
    if (geomType.equalsIgnoreCase(GeoJsonField.POINT)) {
        checkCoordinates(jp, metadataBuilder, GeoJsonField.POINT);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.LINESTRING)) {
        checkCoordinates(jp, metadataBuilder, GeoJsonField.LINESTRING);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.POLYGON)) {
        checkCoordinates(jp, metadataBuilder, GeoJsonField.POLYGON);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.MULTIPOINT)) {
        checkCoordinates(jp, metadataBuilder, GeoJsonField.MULTIPOINT);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.MULTILINESTRING)) {
        checkCoordinates(jp, metadataBuilder, GeoJsonField.MULTILINESTRING);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.MULTIPOLYGON)) {
        checkCoordinates(jp, metadataBuilder, GeoJsonField.MULTIPOLYGON);
    } else if (geomType.equalsIgnoreCase(GeoJsonField.GEOMETRYCOLLECTION)) {
        jp.nextToken();//START geometries array
        if (jp.getText().equalsIgnoreCase(GeoJsonField.GEOMETRIES)) {
            jp.skipChildren();
            if (isH2) {
                metadataBuilder.append("THE_GEOM GEOMETRY,");
            } else {
                metadataBuilder.append("THE_GEOM GEOMETRY(geometry,").append(parsedSRID).append("),");
            }
        } else {
            throw new SQLException(
                    "Malformed GeoJSON file. Expected 'geometries', found '" + jp.getText() + "'");
        }
    } else {
        throw new SQLException("Unsupported geometry : " + geomType);
    }
}

From source file:org.agorava.twitter.jackson.TweetDeserializer.java

@Override
public Tweet deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    JsonNode tree = jp.readValueAsTree();
    long id = tree.get("id").asLong();
    String text = tree.get("text").asText();
    JsonNode fromUserNode = tree.get("user");
    String fromScreenName = null;
    long fromId = 0;
    String fromImageUrl = null;//from   ww  w  . j ava 2  s.  co m
    String dateFormat = TIMELINE_DATE_FORMAT;
    if (fromUserNode != null) {
        fromScreenName = fromUserNode.get("screen_name").asText();
        fromId = fromUserNode.get("id").asLong();
        fromImageUrl = fromUserNode.get("profile_image_url").asText();
    } else {
        fromScreenName = tree.get("from_user").asText();
        fromId = tree.get("from_user_id").asLong();
        fromImageUrl = tree.get("profile_image_url").asText();
        dateFormat = SEARCH_DATE_FORMAT;
    }
    Date createdAt = toDate(tree.get("created_at").asText(), new SimpleDateFormat(dateFormat, Locale.ENGLISH));
    String source = tree.get("source").asText();
    JsonNode toUserIdNode = tree.get("in_reply_to_user_id");
    Long toUserId = toUserIdNode != null ? toUserIdNode.longValue() : null;
    JsonNode languageCodeNode = tree.get("iso_language_code");
    String languageCode = languageCodeNode != null ? languageCodeNode.asText() : null;
    Tweet tweet = new Tweet(id, text, createdAt, fromScreenName, fromImageUrl, toUserId, fromId, languageCode,
            source);
    JsonNode inReplyToStatusIdNode = tree.get("in_reply_to_status_id");
    Long inReplyToStatusId = inReplyToStatusIdNode != null && !inReplyToStatusIdNode.isNull()
            ? inReplyToStatusIdNode.longValue()
            : null;
    tweet.setInReplyToStatusId(inReplyToStatusId);
    JsonNode retweetCountNode = tree.get("retweet_count");
    Integer retweetCount = retweetCountNode != null && !retweetCountNode.isNull() ? retweetCountNode.intValue()
            : null;
    tweet.setRetweetCount(retweetCount);
    JsonNode favoritedNode = tree.get("favorited");
    boolean favorited = favoritedNode != null && !favoritedNode.isNull() ? favoritedNode.booleanValue() : false;
    tweet.setFavorited(favorited);
    jp.skipChildren();
    return tweet;
}

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);
                }/* w  w w  . j  a va  2  s . c o 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:no.ssb.jsonstat.v2.deser.DatasetDeserializer.java

@Override
public DatasetBuildable deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    if (p.getCurrentToken() == JsonToken.START_OBJECT) {
        p.nextToken();//www  .ja v  a  2 s.co  m
    }

    Set<String> ids = Collections.emptySet();
    List<Integer> sizes = Collections.emptyList();
    Multimap<String, String> roles = ArrayListMultimap.create();
    Map<String, Dimension.Builder> dims = Collections.emptyMap();
    List<Number> values = Collections.emptyList();

    DatasetBuilder builder = Dataset.create();
    Optional<String> version = Optional.empty();
    Optional<String> clazz = Optional.empty();
    Optional<ObjectNode> extension = Optional.empty();

    while (p.nextValue() != JsonToken.END_OBJECT) {
        switch (p.getCurrentName()) {
        case "label":
            builder.withLabel(_parseString(p, ctxt));
            break;
        case "source":
            builder.withSource(_parseString(p, ctxt));
            break;
        case "href":
            break;
        case "updated":
            Instant updated = parseEcmaDate(_parseString(p, ctxt));
            builder.updatedAt(updated);
            break;
        case "value":
            values = parseValues(p, ctxt);
            break;
        case "dimension":
            if (!version.orElse("1.x").equals("2.0")) {
                dims = Maps.newHashMap();
                // Deal with the id, size and role inside dimension.
                while (p.nextValue() != JsonToken.END_OBJECT) {
                    switch (p.getCurrentName()) {
                    case "id":
                        ids = p.readValueAs(ID_SET);
                        break;
                    case "size":
                        sizes = p.readValueAs(SIZE_LIST);
                        break;
                    case "role":
                        roles = p.readValueAs(ROLE_MULTIMAP);
                        break;
                    default:
                        dims.put(p.getCurrentName(), ctxt.readValue(p, Dimension.Builder.class));
                    }
                }
            } else {
                dims = p.readValueAs(DIMENSION_MAP);
            }
            break;
        case "id":
            ids = p.readValueAs(ID_SET);
            break;
        case "size":
            sizes = p.readValueAs(SIZE_LIST);
            break;
        case "role":
            roles = p.readValueAs(ROLE_MULTIMAP);
            break;
        case "extension":
            extension = Optional.of(ctxt.readValue(p, ObjectNode.class));
            break;
        case "link":
        case "status":
            // TODO
            p.skipChildren();
            break;
        case "version":
            version = Optional.of(_parseString(p, ctxt));
            break;
        case "class":
            // TODO
            clazz = Optional.of(_parseString(p, ctxt));
            break;
        default:
            boolean handled = ctxt.handleUnknownProperty(p, this, Dimension.Builder.class, p.getCurrentName());
            if (!handled)
                p.skipChildren();
            break;
        }
    }

    // Setup roles
    for (Map.Entry<String, String> dimRole : roles.entries()) {
        Dimension.Roles role = Dimension.Roles.valueOf(dimRole.getKey().toUpperCase());
        Dimension.Builder dimension = checkNotNull(dims.get(dimRole.getValue()),
                "could not assign the role {} to the dimension {}. The dimension did not exist", role,
                dimRole.getValue()

        );
        dimension.withRole(role);
    }

    List<Dimension.Builder> orderedDimensions = Lists.newArrayList();
    for (String dimensionName : ids) {
        orderedDimensions.add(dims.get(dimensionName));
    }

    // TODO: Check size?

    // Check ids and add to the data set.
    checkArgument(ids.size() == dims.size(), "dimension and size did not match");

    if (extension.isPresent()) {
        builder.withExtension(extension.get());
    }

    return builder.withDimensions(orderedDimensions).withValues(values);
}

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

protected void extractEvent(final JsonParser jsonParser, final Resource resource) throws IOException {

    String author = null;/*from ww w . j av a2  s  .  co m*/
    final JSONObject requestParams = new JSONObject();
    try {
        jsonParser.nextToken();
        JsonToken token = jsonParser.getCurrentToken();
        while (token.equals(JsonToken.FIELD_NAME)) {
            String field = jsonParser.getCurrentName();
            jsonParser.nextToken();

            if (field.equals(PN_START) || field.equals(PN_END)) {
                final Long value = jsonParser.getValueAsLong();
                final Calendar calendar = new GregorianCalendar();
                calendar.setTimeInMillis(value);
                final Date date = calendar.getTime();
                final TimeZone tz = TimeZone.getTimeZone("UTC");
                // this is the ISO-8601 format expected by the CalendarOperations object
                final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm+00:00");
                df.setTimeZone(tz);
                if (field.equals(PN_START)) {
                    requestParams.put(CalendarRequestConstants.START_DATE, df.format(date));
                } else {
                    requestParams.put(CalendarRequestConstants.END_DATE, df.format(date));
                }
            } else if (field.equals(CalendarRequestConstants.TAGS)) {
                List<String> tags = new ArrayList<String>();
                if (jsonParser.getCurrentToken().equals(JsonToken.START_ARRAY)) {
                    token = jsonParser.nextToken();
                    while (!token.equals(JsonToken.END_ARRAY)) {
                        tags.add(URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8"));
                        token = jsonParser.nextToken();
                    }
                    requestParams.put(CalendarRequestConstants.TAGS, tags);
                } else {
                    LOG.warn("Tags field came in without an array of tags in it - not processed");
                    // do nothing, just log the error
                }
            } else if (field.equals("jcr:createdBy")) {
                author = URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8");
            } else if (field.equals(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS)) {
                jsonParser.skipChildren(); // we do nothing with these because they're going to be put into json
            } else {
                try {
                    final String value = URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8");
                    requestParams.put(field, value);
                } catch (NullPointerException e) {
                    throw e;
                }
            }
            token = jsonParser.nextToken();
        }
    } catch (final JSONException e) {
        throw new IOException("Unable to build a JSON object with the inputs provided", e);
    }
    try {
        Map<String, Object> eventParams = new HashMap<String, Object>();
        eventParams.put("event", requestParams.toString());
        calendarOperations.create(resource, author, eventParams, null,
                resource.getResourceResolver().adaptTo(Session.class));
    } catch (final OperationException e) {
        //probably caused by creating a folder that already exists. We ignore it, but still log the event.
        LOG.info("There was an operation exception while creating an event");
    }
}