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:org.elasticsearch.client.sniff.ElasticsearchNodesSniffer.java

private static Node readNode(String nodeId, JsonParser parser, Scheme scheme) throws IOException {
    HttpHost publishedHost = null;//from  www. j av  a  2s.  c  o  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.adobe.communities.ugc.migration.importer.UGCImportHelper.java

public static Map<String, Object> extractSubmap(final JsonParser jsonParser) throws IOException {
    jsonParser.nextToken(); // skip the START_OBJECT token
    final Map<String, Object> subMap = new HashMap<String, Object>();
    while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
        final String label = jsonParser.getCurrentName(); // get the current label
        final JsonToken token = jsonParser.nextToken(); // get the current value
        if (!token.isScalarValue()) {
            if (token.equals(JsonToken.START_OBJECT)) {
                // if the next token starts a new object, recurse into it
                subMap.put(label, extractSubmap(jsonParser));
            } else if (token.equals(JsonToken.START_ARRAY)) {
                final List<String> subArray = new ArrayList<String>();
                jsonParser.nextToken(); // skip the START_ARRAY token
                while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) {
                    subArray.add(jsonParser.getValueAsString());
                    jsonParser.nextToken();
                }/*w ww  .  jav  a 2s. c  o  m*/
                subMap.put(label, subArray);
                jsonParser.nextToken(); // skip the END_ARRAY token
            }
        } else {
            // either a string, boolean, or long value
            if (token.isNumeric()) {
                subMap.put(label, jsonParser.getValueAsLong());
            } else {
                final String value = jsonParser.getValueAsString();
                if (value.equals("true") || value.equals("false")) {
                    subMap.put(label, jsonParser.getValueAsBoolean());
                } else {
                    subMap.put(label, value);
                }
            }
        }
        jsonParser.nextToken(); // next token will either be an "END_OBJECT" or a new label
    }
    jsonParser.nextToken(); // skip the END_OBJECT token
    return subMap;
}

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

/**
 * Process OData links./*from  w w w .  j  a  v a 2  s. c  om*/
 *
 * @param jsonParser the parser
 * @throws IOException If unable to read input parser
 */
private void processLinks(JsonParser jsonParser) throws IOException {

    LOG.info("@odata.bind tag found - start parsing");

    final String fullLinkFieldName = jsonParser.getText();
    final String key = fullLinkFieldName.substring(0, fullLinkFieldName.indexOf(ODATA_BIND));
    JsonToken token = jsonParser.nextToken();
    if (token != JsonToken.START_ARRAY) {
        // Single link
        links.put(key, processLink(jsonParser));
    } else {
        // Array of links
        final List<String> linksList = new ArrayList<>();
        while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
            linksList.add(processLink(jsonParser));
        }
        this.links.put(key, linksList);

    }
}

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

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

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

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

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

/**
 * Handles the callback from the client; expects either an object or an array of objects
 * @param request/*  w ww .  j  a v  a 2  s  . c  om*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
public void processRequest(Reader request, Writer response) throws ServletException, IOException {
    s_currentHandler.set(this);
    ObjectMapper objectMapper = tracker.getObjectMapper();
    try {
        if (log.isDebugEnabled()) {
            StringWriter sw = new StringWriter();
            char[] buffer = new char[32 * 1024];
            int length;
            while ((length = request.read(buffer)) > 0) {
                sw.write(buffer, 0, length);
            }
            log.debug("Received: " + sw.toString());
            request = new StringReader(sw.toString());
        }
        JsonParser jp = objectMapper.getJsonFactory().createJsonParser(request);
        if (jp.nextToken() == JsonToken.START_ARRAY) {
            while (jp.nextToken() != JsonToken.END_ARRAY)
                processCommand(jp);
        } else if (jp.getCurrentToken() == JsonToken.START_OBJECT)
            processCommand(jp);

        if (tracker.hasDataToFlush()) {
            Writer actualResponse = response;
            if (log.isDebugEnabled()) {
                final Writer tmp = response;
                actualResponse = new Writer() {
                    @Override
                    public void close() throws IOException {
                        tmp.close();
                    }

                    @Override
                    public void flush() throws IOException {
                        tmp.flush();
                    }

                    @Override
                    public void write(char[] arg0, int arg1, int arg2) throws IOException {
                        System.out.print(new String(arg0, arg1, arg2));
                        tmp.write(arg0, arg1, arg2);
                    }
                };
            }
            objectMapper.writeValue(actualResponse, tracker.getQueue());
        }

    } catch (ProxyTypeSerialisationException e) {
        log.fatal("Unable to serialise type information to client: " + e.getMessage(), e);

    } catch (ProxyException e) {
        handleException(response, objectMapper, e);

    } catch (Exception e) {
        log.error("Exception during callback: " + e.getMessage(), e);
        tracker.getQueue().queueCommand(CommandType.EXCEPTION, null, null,
                new ExceptionDetails(e.getClass().getName(), e.getMessage()));
        objectMapper.writeValue(response, tracker.getQueue());

    } finally {
        s_currentHandler.set(null);
    }
}

From source file:org.gvnix.web.json.DataBinderDeserializer.java

/**
 * Deserializes JSON array into Map<String, String> format to use it in a
 * Spring {@link DataBinder}.//  ww w.  jav a2 s. com
 * <p/>
 * Iterate over every array's item to generate a prefix for property names
 * on DataBinder style (
 * <em>{prefix}[{index}].<em>) and delegates on {@link #readField(JsonParser, DeserializationContext, JsonToken, String)}
 * 
 * @param parser JSON parser
 * @param ctxt context
 * @param prefix array dataBinder path
 * @return
 * @throws IOException
 * @throws JsonProcessingException
 */
protected Map<String, String> readArray(JsonParser parser, DeserializationContext ctxt, String prefix)
        throws IOException, JsonProcessingException {
    JsonToken t = parser.getCurrentToken();

    if (t == JsonToken.START_ARRAY) {
        t = parser.nextToken();
        // Skip it to locate on first array data token
    }

    // Deserialize array properties
    int i = 0;
    Map<String, String> deserObj = new HashMap<String, String>();
    for (; t != JsonToken.END_ARRAY; t = parser.nextToken()) {
        // Property name must include prefix this way:
        // degrees[0].description
        Map<String, String> field = readField(parser, ctxt, t,
                prefix.concat("[").concat(Integer.toString(i++)).concat("]."));
        deserObj.putAll(field);
    }
    return deserObj;
}

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

private void importMessages(final SlingHttpServletRequest request, final JsonParser jsonParser,
        final Map<String, Object> messageModifiers) throws ServletException {

    if (!jsonParser.getCurrentToken().equals(JsonToken.START_ARRAY)) {
        throw new ServletException("unexpected starting token " + jsonParser.getCurrentToken().asString());
    }//from w  w  w .j av a  2 s  .  c  o  m

    try {
        jsonParser.nextToken(); //presumably, we will advance to a "start object" token
        while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) {
            final Map<String, Map<String, Boolean>> recipientModifiers = new HashMap<String, Map<String, Boolean>>();
            final Map<String, Object> props = new HashMap<String, Object>();
            final Map<String, Object> messageModifier = new HashMap<String, Object>();
            List<FileDataSource> attachments = new ArrayList<FileDataSource>();
            String sender = "";
            jsonParser.nextToken(); //field name
            while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
                final String fieldName = jsonParser.getCurrentName();
                jsonParser.nextToken(); //value
                if (fieldName.equals("senderId")) {
                    sender = URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8");
                } else if (fieldName.equals("added")) {
                    final Calendar calendar = new GregorianCalendar();
                    calendar.setTimeInMillis(jsonParser.getLongValue());
                    messageModifier.put("added", calendar);
                } else if (fieldName.equals("recipients")) {
                    // build the string for the "to" property and also create the modifiers we'll need later
                    final StringBuilder recipientString = new StringBuilder();
                    //iterate over each key (each being a recipient id)
                    if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
                        jsonParser.nextToken(); // should get first recipientId
                        while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
                            final String recipientId = jsonParser.getCurrentName();
                            jsonParser.nextToken(); //start object
                            jsonParser.nextToken(); //first label
                            final Map<String, Boolean> interactionModifiers = new HashMap<String, Boolean>();
                            while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
                                final String label = jsonParser.getCurrentName();
                                jsonParser.nextToken();
                                final Boolean labelValue = jsonParser.getBooleanValue();
                                interactionModifiers.put(label, labelValue);
                                jsonParser.nextToken(); //next label or end object
                            }
                            try {
                                final String userPath = userPropertiesService.getAuthorizablePath(recipientId);
                                recipientModifiers.put(userPath, interactionModifiers);
                                recipientString.append(recipientId);
                            } catch (final RepositoryException e) {
                                // log the fact that a recipient specified in the json file doesn't exist in this
                                // environment
                                throw new ServletException(
                                        "A recipient specified in the migration file couldn't "
                                                + "be found in this environment",
                                        e);
                            }
                            jsonParser.nextToken(); // next recipientId or end object
                            if (jsonParser.getCurrentToken().equals(JsonToken.FIELD_NAME)) {
                                recipientString.append(';');
                            }
                        }
                        props.put("to", recipientString);
                        messageModifier.put("recipientDetails", recipientModifiers);
                    }
                } else if (fieldName.equals(ContentTypeDefinitions.LABEL_ATTACHMENTS)) {
                    UGCImportHelper.getAttachments(jsonParser, attachments);
                } else {
                    props.put(fieldName, URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8"));
                }
                jsonParser.nextToken(); //either next field name or end object
            }
            final Random range = new Random();
            final String key = String.valueOf(range.nextInt(Integer.MAX_VALUE))
                    + String.valueOf(range.nextInt(Integer.MAX_VALUE));
            // we're going to temporarily overwrite the subject (to do a search) and need to track its initial value
            if (props.containsKey("subject")) {
                messageModifier.put("subject", props.get("subject"));
            } else {
                messageModifier.put("subject", "");
            }
            props.put("subject", key); //use subject as the search key
            messageModifiers.put(key, messageModifier);
            try {
                short result = messagingService.create(request.getResourceResolver(), request.getResource(),
                        sender, props, attachments,
                        clientUtilsFactory.getClientUtilities(xss, request, socialUtils));

                if (result != 200) {
                    throw new ServletException("Message sending failed. Return code was " + result);
                }
            } catch (final OperationException e) {
                throw new ServletException("Unable to create a message through the operation service", e);
            }
            jsonParser.nextToken(); //either END_ARRAY or START_OBJECT
        }

    } catch (final IOException e) {
        throw new ServletException("Encountered exception while parsing json content", e);
    }
}

From source file:data.DefaultExchanger.java

public void importData(String dbName, JsonParser parser, JdbcTemplate jdbcTemplate) throws IOException {
    PlatformTransactionManager tm = new DataSourceTransactionManager(jdbcTemplate.getDataSource());
    TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());

    try {/* www.j a v  a2 s.  c om*/
        if (dbName.equals("MySQL")) {
            jdbcTemplate.update("SET FOREIGN_KEY_CHECKS = 0");
            jdbcTemplate.update("SET NAMES \'utf8mb4\'");
        }

        final Configuration config = Configuration.root();
        int batchSize = config.getInt(DATA_BATCH_SIZE_KEY, DEFAULT_BATCH_SIZE);
        if (parser.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = parser.getCurrentName();
            play.Logger.debug("importing {}", fieldName);
            if (fieldName.equalsIgnoreCase(getTable())) {
                truncateTable(jdbcTemplate);
                JsonToken current = parser.nextToken();
                if (current == JsonToken.START_ARRAY) {
                    importDataFromArray(parser, jdbcTemplate, batchSize);
                    importSequence(dbName, parser, jdbcTemplate);
                } else {
                    play.Logger.info("Error: records should be an array: skipping.");
                    parser.skipChildren();
                }
            }
        }
        tm.commit(ts);
    } catch (Exception e) {
        e.printStackTrace();
        tm.rollback(ts);
    } finally {
        if (dbName.equals("MySQL")) {
            jdbcTemplate.update("SET FOREIGN_KEY_CHECKS = 1");
        }
    }
}

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

@Override
public Object readItem() throws Exception {
    if (rowNumber >= end) {
        return null;
    }/*from  www  .  j a  va 2 s  .c o m*/

    JsonToken token;
    final Object readValue;

    if (!rawAccess) {
        do {
            token = csvParser.nextToken();
            if (token == null) {
                return null;
            }
            if (token == JsonToken.START_OBJECT) {
                if (++rowNumber >= start) {
                    break;
                }
            }
        } while (true);

        readValue = objectMapper.readValue(csvParser, beanType);
        if (!skipBeanValidation) {
            ItemReaderWriterBase.validate(readValue);
        }
    } else {
        do {
            token = csvParser.nextToken();
            if (token == null) {
                return null;
            }
            if (token == JsonToken.START_ARRAY) {
                if (++rowNumber >= start) {
                    break;
                }
            }
        } while (true);

        readValue = objectMapper.readValue(csvParser, beanType);
    }
    return readValue;
}

From source file:com.sdl.odata.renderer.json.writer.JsonPropertyWriterTest.java

private Map<String, Object> getMapFromJson(String json) throws IOException {
    Map<String, Object> map = new HashMap<>();
    JsonParser jsonParser = new JsonFactory().createParser(json);
    jsonParser.nextToken();/*from  ww  w .  java  2s  . c  om*/
    while (jsonParser.nextToken() != null) {
        String key = jsonParser.getText();
        jsonParser.nextToken();
        if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) {
            map.put(key, getJsonArray(jsonParser));
        } else {
            map.put(key, jsonParser.getText());
        }
    }
    return map;
}