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

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

Introduction

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

Prototype

JsonToken START_ARRAY

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

Click Source Link

Document

START_ARRAY is returned when encountering '[' which signals starting of an Array value

Usage

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

@Override
public long nextLongValue(long defaultValue) throws IOException, JsonParseException {
    if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName'
        _nameCopied = false;/* w  ww .jav  a  2  s .  co  m*/
        JsonToken t = _nextToken;
        _nextToken = null;
        _currToken = t;
        if (t == JsonToken.VALUE_NUMBER_INT) {
            return getLongValue();
        }
        if (t == JsonToken.START_ARRAY) {
            _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol);
        } else if (t == JsonToken.START_OBJECT) {
            _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol);
        }
        return defaultValue;
    }
    // !!! TODO: optimize this case as well
    return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue;
}

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

protected void readAudioField(JsonParser par, Audio.Builder audio, String fieldName) throws IOException {
    // Video & Audio common

    switch (fieldName) {
    case "mimes":
        for (startArray(par); endArray(par); par.nextToken()) {
            audio.addMimes(par.getText());
        }/*from ww  w  .ja va2  s. com*/
        break;
    case "minduration":
        audio.setMinduration(par.getIntValue());
        break;
    case "maxduration":
        audio.setMaxduration(par.getIntValue());
        break;
    case "protocols":
        for (startArray(par); endArray(par); par.nextToken()) {
            Protocol value = Protocol.valueOf(par.getIntValue());
            if (checkEnum(value)) {
                audio.addProtocols(value);
            }
        }
        break;
    case "startdelay":
        audio.setStartdelay(par.getIntValue());
        break;
    case "sequence":
        audio.setSequence(par.getIntValue());
        break;
    case "battr":
        for (startArray(par); endArray(par); par.nextToken()) {
            CreativeAttribute value = CreativeAttribute.valueOf(par.getIntValue());
            if (checkEnum(value)) {
                audio.addBattr(value);
            }
        }
        break;
    case "maxextended":
        audio.setMaxextended(par.getIntValue());
        break;
    case "minbitrate":
        audio.setMinbitrate(par.getIntValue());
        break;
    case "maxbitrate":
        audio.setMaxbitrate(par.getIntValue());
        break;
    case "delivery":
        for (startArray(par); endArray(par); par.nextToken()) {
            ContentDeliveryMethod value = ContentDeliveryMethod.valueOf(par.getIntValue());
            if (checkEnum(value)) {
                audio.addDelivery(value);
            }
        }
        break;
    case "companionad":
        if (peekStructStart(par) == JsonToken.START_ARRAY) {
            // OpenRTB 2.2+
            for (startArray(par); endArray(par); par.nextToken()) {
                audio.addCompanionad(readBanner(par));
            }
        }
        break;
    case "api":
        for (startArray(par); endArray(par); par.nextToken()) {
            APIFramework value = APIFramework.valueOf(par.getIntValue());
            if (checkEnum(value)) {
                audio.addApi(value);
            }
        }
        break;
    case "companiontype":
        for (startArray(par); endArray(par); par.nextToken()) {
            CompanionType value = CompanionType.valueOf(par.getIntValue());
            if (checkEnum(value)) {
                audio.addCompaniontype(value);
            }
        }
        break;

    // Audio only

    case "maxseq":
        audio.setMaxseq(par.getIntValue());
        break;
    case "feed": {
        FeedType feed = FeedType.valueOf(par.getIntValue());
        if (checkEnum(feed)) {
            audio.setFeed(feed);
        }
    }
        break;
    case "stitched":
        audio.setStitched(par.getValueAsBoolean());
        break;
    case "nvol": {
        VolumeNormalizationMode value = VolumeNormalizationMode.valueOf(par.getIntValue());
        if (checkEnum(value)) {
            audio.setNvol(value);
        }
    }
        break;

    default:
        readOther(audio, par, fieldName);
    }
}

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

@Override
public Boolean nextBooleanValue() throws IOException, JsonParseException {
    if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName'
        _nameCopied = false;/* w  w w. j a v a  2  s  .  co m*/
        JsonToken t = _nextToken;
        _nextToken = null;
        _currToken = t;
        if (t == JsonToken.VALUE_TRUE) {
            return Boolean.TRUE;
        }
        if (t == JsonToken.VALUE_FALSE) {
            return Boolean.FALSE;
        }
        if (t == JsonToken.START_ARRAY) {
            _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol);
        } else if (t == JsonToken.START_OBJECT) {
            _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol);
        }
        return null;
    }
    switch (nextToken()) {
    case VALUE_TRUE:
        return Boolean.TRUE;
    case VALUE_FALSE:
        return Boolean.FALSE;
    }
    return null;
}

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Handles dynamic changes to a qa.data.Array instance without having a complete replacement; expects a 
 * serverId, propertyName, type (one of "add", "remove", "order"), start, end, and optional array of items 
 * @param jp/*  ww  w.  j av  a  2  s . c o m*/
 * @throws ServletException
 * @throws IOException
 */
protected void cmdEditArray(JsonParser jp) throws ServletException, IOException {
    // Get the basics
    int serverId = getFieldValue(jp, "serverId", Integer.class);
    String propertyName = getFieldValue(jp, "propertyName", String.class);
    String action = getFieldValue(jp, "type", String.class);
    Integer start = null;
    Integer end = null;

    if (!action.equals("replaceAll")) {
        start = getFieldValue(jp, "start", Integer.class);
        end = getFieldValue(jp, "end", Integer.class);
    }

    // Get our info
    Proxied serverObject = getProxied(serverId);
    ProxyType type = ProxyTypeManager.INSTANCE.getProxyType(serverObject.getClass());
    ProxyProperty prop = getProperty(type, propertyName);

    if (prop.getPropertyClass().isMap()) {
        Map items = null;

        // Get the optional array of items
        if (jp.nextToken() == JsonToken.FIELD_NAME && jp.getCurrentName().equals("items")
                && jp.nextToken() == JsonToken.START_OBJECT) {

            items = readMap(jp, prop.getPropertyClass().getKeyClass(), prop.getPropertyClass().getJavaType());
        }

        // Quick logging
        if (log.isInfoEnabled()) {
            String str = "";
            if (items != null)
                for (Object key : items.keySet()) {
                    if (str.length() > 0)
                        str += ", ";
                    str += String.valueOf(key) + "=" + String.valueOf(items.get(key));
                }
            log.info("edit-array: property=" + prop + ", type=" + action + ", start=" + start + ", end=" + end
                    + str);
        }

        if (action.equals("replaceAll")) {
            Map map = (Map) prop.getValue(serverObject);
            if (map == null) {
                try {
                    map = (Map) prop.getPropertyClass().getCollectionClass().newInstance();
                } catch (Exception e) {
                    throw new IllegalArgumentException(e.getMessage(), e);
                }
                prop.setValue(serverObject, map);
            }
            map.clear();
            map.putAll(items);
        } else
            throw new IllegalArgumentException("Unsupported action in cmdEditArray: " + action);

        // Because collection properties are objects and we change them without the serverObject's
        //   knowledge, we have to make sure we notify other trackers ourselves
        ProxyManager.propertyChanged(serverObject, propertyName, items, null);

        jp.nextToken();
    } else {
        // NOTE: items is an Array!!  But because it may be an array of primitive types, we have
        //   to use java.lang.reflect.Array to access members because we cannot cast arrays of
        //   primitives to Object[]
        Object items = null;

        // Get the optional array of items
        if (jp.nextToken() == JsonToken.FIELD_NAME && jp.getCurrentName().equals("items")
                && jp.nextToken() == JsonToken.START_ARRAY) {

            items = readArray(jp, prop.getPropertyClass().getJavaType());
        }
        int itemsLength = Array.getLength(items);

        // Quick logging
        if (log.isInfoEnabled()) {
            String str = "";
            if (items != null)
                for (int i = 0; i < itemsLength; i++) {
                    if (str.length() != 0)
                        str += ", ";
                    str += Array.get(items, i);
                }
            log.info("edit-array: property=" + prop + ", type=" + action + ", start=" + start + ", end=" + end
                    + str);
        }

        if (action.equals("replaceAll")) {
            if (prop.getPropertyClass().isCollection()) {
                Collection list = (Collection) prop.getValue(serverObject);
                if (list == null) {
                    try {
                        list = (Collection) prop.getPropertyClass().getCollectionClass().newInstance();
                    } catch (Exception e) {
                        throw new IllegalArgumentException(e.getMessage(), e);
                    }
                    prop.setValue(serverObject, list);
                }
                list.clear();
                if (items != null)
                    for (int i = 0; i < itemsLength; i++)
                        list.add(Array.get(items, i));

                // Because collection properties are objects and we change them without the serverObject's
                //   knowledge, we have to make sure we notify other trackers ourselves
                ProxyManager.propertyChanged(serverObject, propertyName, list, null);
            } else {
                prop.setValue(serverObject, items);
            }
        } else
            throw new IllegalArgumentException("Unsupported action in cmdEditArray: " + action);

        jp.nextToken();
    }
}

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

/**
 * Handle each of the importable types of ugc content
 * @param jsonParser - the parsing stream
 * @param resource - the parent resource of whatever it is we're importing (must already exist)
 * @throws ServletException/*w  w w.  ja  va2s  .  c om*/
 * @throws IOException
 */
private void importFile(final JsonParser jsonParser, final Resource resource, final ResourceResolver resolver)
        throws ServletException, IOException {
    final UGCImportHelper importHelper = new UGCImportHelper();
    JsonToken token1 = jsonParser.getCurrentToken();
    if (token1.equals(JsonToken.START_OBJECT)) {
        jsonParser.nextToken();
        if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT_TYPE)) {
            jsonParser.nextToken();
            final String contentType = jsonParser.getValueAsString();
            if (contentType.equals(ContentTypeDefinitions.LABEL_QNA_FORUM)) {
                importHelper.setQnaForumOperations(qnaForumOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_FORUM)) {
                importHelper.setForumOperations(forumOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_COMMENTS)) {
                importHelper.setCommentOperations(commentOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_CALENDAR)) {
                importHelper.setCalendarOperations(calendarOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_JOURNAL)) {
                importHelper.setJournalOperations(journalOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_TALLY)) {
                importHelper.setSocialUtils(socialUtils);
            }
            importHelper.setTallyService(tallyOperationsService); // (everything potentially needs tally)
            jsonParser.nextToken(); // content
            if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT)) {
                jsonParser.nextToken();
                token1 = jsonParser.getCurrentToken();
                if (token1.equals(JsonToken.START_OBJECT) || token1.equals(JsonToken.START_ARRAY)) {
                    if (!resolver.isLive()) {
                        throw new ServletException("Resolver is already closed");
                    }
                } else {
                    throw new ServletException("Start object token not found for content");
                }
                if (token1.equals(JsonToken.START_OBJECT)) {
                    try {
                        if (contentType.equals(ContentTypeDefinitions.LABEL_QNA_FORUM)) {
                            importHelper.importQnaContent(jsonParser, resource, resolver);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_FORUM)) {
                            importHelper.importForumContent(jsonParser, resource, resolver);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_COMMENTS)) {
                            importHelper.importCommentsContent(jsonParser, resource, resolver);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_JOURNAL)) {
                            importHelper.importJournalContent(jsonParser, resource, resolver);
                        } else {
                            LOG.info("Unsupported content type: {}", contentType);
                            jsonParser.skipChildren();
                        }
                        jsonParser.nextToken();
                    } catch (final IOException e) {
                        throw new ServletException(e);
                    }
                    jsonParser.nextToken(); // skip over END_OBJECT
                } else {
                    try {
                        if (contentType.equals(ContentTypeDefinitions.LABEL_CALENDAR)) {
                            importHelper.importCalendarContent(jsonParser, resource);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_TALLY)) {
                            importHelper.importTallyContent(jsonParser, resource);
                        } else {
                            LOG.info("Unsupported content type: {}", contentType);
                            jsonParser.skipChildren();
                        }
                        jsonParser.nextToken();
                    } catch (final IOException e) {
                        throw new ServletException(e);
                    }
                    jsonParser.nextToken(); // skip over END_ARRAY
                }
            } else {
                throw new ServletException("Content not found");
            }
        } else {
            throw new ServletException("No content type specified");
        }
    } else {
        throw new ServletException("Invalid Json format");
    }
}

From source file:org.instagram4j.DefaultInstagramClient.java

private <T> Result<T> requestEntity(HttpRequestBase method, Class<T> type, boolean signableRequest)
        throws InstagramException {
    method.getParams().setParameter("http.useragent", "Instagram4j/1.0");

    JsonParser jp = null;//from   w w w.  j  a  v a  2  s.  c om
    HttpResponse response = null;
    ResultMeta meta = null;

    try {
        method.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        if (signableRequest)
            setEnforceHeader(method);

        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 15000);
        client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 30000);

        if (LOG.isDebugEnabled())
            LOG.debug(String.format("Requesting entity entry point %s, method %s", method.getURI().toString(),
                    method.getMethod()));

        autoThrottle();

        response = client.execute(method);

        jp = createParser(response, method);

        JsonToken tok = jp.nextToken();
        if (tok != JsonToken.START_OBJECT) {
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                        null, null);

            throw createInstagramException("Invalid response format from Instagram API",
                    method.getURI().toString(), response, null, null);
        }

        T data = null;

        while (true) {
            tok = jp.nextValue();
            if (tok == JsonToken.START_ARRAY) {
                throw createInstagramException("Unexpected array in entity response " + jp.getCurrentName(),
                        method.getURI().toString(), response, meta, null);
            } else if (tok == JsonToken.START_OBJECT) {
                // Should be "data" or "meta"
                String name = jp.getCurrentName();
                if ("meta".equals(name))
                    meta = jp.readValueAs(ResultMeta.class);
                else if ("data".equals(name)) {
                    if (type != null)
                        data = jp.readValueAs(type);
                    else
                        jp.readValueAs(Map.class); // Consume & ignore
                } else
                    throw createInstagramException("Unexpected field name " + name, method.getURI().toString(),
                            response, meta, null);
            } else
                break;
        }

        if (data == null && meta == null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
            throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                    null, null);

        Result<T> result = new Result<T>(null, meta, data);
        setRateLimits(response, result);

        return result;
    } catch (JsonParseException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (JsonProcessingException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (IOException e) {
        throw createInstagramException("Error communicating with Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } finally {
        if (jp != null)
            try {
                jp.close();
            } catch (IOException e) {
            }
        method.releaseConnection();
    }
}

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

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

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

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

From source file:org.instagram4j.DefaultInstagramClient.java

@SuppressWarnings("unchecked")
private <T> Result<T[]> requestEntities(HttpRequestBase method, Class<T> type) throws InstagramException {
    method.getParams().setParameter("http.useragent", "Instagram4j/1.0");

    JsonParser jp = null;/* ww w.j  a v a 2s . c o m*/
    HttpResponse response = null;
    ResultMeta meta = null;

    try {
        method.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        setEnforceHeader(method);

        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 15000);
        client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 30000);

        if (LOG.isDebugEnabled())
            LOG.debug(String.format("Requesting entities entry point %s, method %s", method.getURI().toString(),
                    method.getMethod()));

        autoThrottle();

        response = client.execute(method);

        jp = createParser(response, method);

        JsonToken tok = jp.nextToken();
        if (tok != JsonToken.START_OBJECT) {
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                        null, null);

            throw createInstagramException("Invalid response format from Instagram API",
                    method.getURI().toString(), response, null, null);
        }

        Pagination pagination = null;
        T[] data = null;

        while (true) {
            tok = jp.nextValue();
            if (tok == JsonToken.START_ARRAY) {
                // Should be "data"
                String name = jp.getCurrentName();
                if (!"data".equals(name))
                    throw createInstagramException("Unexpected field name " + name, method.getURI().toString(),
                            response, meta, null);

                List<T> items = new ArrayList<T>();

                tok = jp.nextToken();
                if (tok == JsonToken.START_OBJECT) {
                    if (type != null) {
                        T item;
                        while ((item = jp.readValueAs(type)) != null)
                            items.add(item);
                    } else
                        jp.readValueAs(Map.class); // Consume & ignore
                }

                data = (T[]) Array.newInstance(type, items.size());
                System.arraycopy(items.toArray(), 0, data, 0, items.size());
            } else if (tok == JsonToken.START_OBJECT) {
                // Should be "pagination" or "meta"
                String name = jp.getCurrentName();
                if ("pagination".equals(name))
                    pagination = jp.readValueAs(Pagination.class);
                else if ("meta".equals(name))
                    meta = jp.readValueAs(ResultMeta.class);
                else
                    throw createInstagramException("Unexpected field name " + name, method.getURI().toString(),
                            response, meta, null);
            } else
                break;
        }

        if (data == null && meta == null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
            throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                    null, null);

        Result<T[]> result = new Result<T[]>(pagination, meta, data);
        setRateLimits(response, result);

        return result;
    } catch (JsonParseException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (JsonProcessingException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (IOException e) {
        throw createInstagramException("Error communicating with Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } finally {
        if (jp != null)
            try {
                jp.close();
            } catch (IOException e) {
            }
        method.releaseConnection();
    }
}

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;//w  w  w  . j  a  v  a2  s  .c o 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");
    }
}

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Reads an array from JSON, where each value is of the listed in types; EG the first element
 * is class type[0], the second element is class type[1] etc
 * @param jp/* ww  w  .j a  v  a2  s . com*/
 * @param types
 * @return
 * @throws IOException
 */
private Object[] readArray(JsonParser jp, Class[] types) throws IOException {
    if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
        return null;

    ArrayList result = new ArrayList();
    for (int paramIndex = 0; jp.nextToken() != JsonToken.END_ARRAY; paramIndex++) {
        Class type = null;
        if (types != null && paramIndex < types.length)
            type = types[paramIndex];

        if (type != null && type.isArray()) {
            if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
                result.add(null);
            else if (jp.getCurrentToken() == JsonToken.START_ARRAY) {
                Object obj = readArray(jp, type.getComponentType());
                result.add(obj);
            } else
                throw new IllegalStateException("Expected array but found " + jp.getCurrentToken());

        } else if (type != null && Proxied.class.isAssignableFrom(type)) {
            Integer id = jp.readValueAs(Integer.class);
            if (id != null) {
                Proxied obj = getProxied(id);
                result.add(obj);
            } else
                result.add(null);

        } else if (type != null && Enum.class.isAssignableFrom(type)) {
            Object obj = jp.readValueAs(Object.class);
            if (obj != null) {
                String str = Helpers.camelCaseToEnum(obj.toString());
                obj = Enum.valueOf(type, str);
                result.add(obj);
            }
        } else {
            Object obj = jp.readValueAs(type != null ? type : Object.class);
            result.add(obj);
        }
    }
    return result.toArray(new Object[result.size()]);
}