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

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

Introduction

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

Prototype

JsonToken END_ARRAY

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

Click Source Link

Document

END_ARRAY is returned when encountering ']' which signals ending of an Array value

Usage

From source file:org.fluentd.jvmwatcher.JvmWatcher.java

/**
 * @param parser// w  w w  .  j  av a  2 s  .c  om
 * @throws JsonParseException
 * @throws IOException
 */
private void loadTarget(JsonParser parser) throws JsonParseException, IOException {
    if (parser.nextToken() == JsonToken.START_ARRAY) {
        while (parser.nextToken() != JsonToken.END_ARRAY) {
            if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
                String shortName = null;
                String pattern = null;
                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    if ((parser.getCurrentToken() == JsonToken.FIELD_NAME)
                            && (parser.getText().compareTo("shortname") == 0)) {
                        if (parser.nextToken() == JsonToken.VALUE_STRING) {
                            shortName = parser.getText();
                        }
                    }
                    if ((parser.getCurrentToken() == JsonToken.FIELD_NAME)
                            && (parser.getText().compareTo("pattern") == 0)) {
                        if (parser.nextToken() == JsonToken.VALUE_STRING) {
                            pattern = parser.getText();
                        }
                    }
                }
                // add target pattern
                Pattern regexPattern = Pattern.compile(pattern);
                LocalJvmInfo.addTargetProcessPattern(shortName, regexPattern);
            }
        }
    }
}

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

private static void readACLs(JsonParser jp, List<ACL> acls) throws IOException {
    expectCurrentToken(jp, JsonToken.START_ARRAY);
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        acls.add(readACL(jp));//  w  w  w . j  a va  2 s.  c  o m
    }
}

From source file:org.elasticsearch.client.sniff.ElasticsearchNodesSniffer.java

private static Node readNode(String nodeId, JsonParser parser, Scheme scheme) throws IOException {
    HttpHost publishedHost = null;/* ww w .j a v  a2 s . 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();
                }//from   ww  w . j ava 2 s .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 va 2s. c o  m
 *
 * @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:io.apiman.manager.api.exportimport.json.JsonImportReader.java

public void readApis() throws Exception {
    current = nextToken();/*from ww  w  .ja v a2 s  .  c o m*/
    if (current == JsonToken.END_ARRAY) {
        return;
    }
    while (nextToken() != JsonToken.END_ARRAY) {
        // Traverse each api definition
        while (nextToken() != JsonToken.END_OBJECT) {
            if (jp.getCurrentName().equals(ApiBean.class.getSimpleName())) {
                current = nextToken();
                ApiBean apiBean = jp.readValueAs(ApiBean.class);
                dispatcher.api(apiBean);
            } else {
                OrgElementsEnum fieldName = OrgElementsEnum.valueOf(jp.getCurrentName());
                current = nextToken();
                switch (fieldName) {
                case Versions:
                    readApiVersions();
                    break;
                default:
                    throw new RuntimeException("Unhandled entity " + fieldName + " with token " + current);
                }
            }
        }
    }
}

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 w  w. j  a v a 2s .  co  m*/
 * @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.seedstack.seed.core.internal.data.DataManagerImpl.java

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

    try {/*w w  w  .j  a v a 2  s.co  m*/
        ParsingState state = ParsingState.START;
        String group = null;
        String name = null;
        JsonParser jsonParser = this.jsonFactory
                .createParser(new InputStreamReader(inputStream, Charset.forName(UTF_8)));
        JsonToken jsonToken = jsonParser.nextToken();

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

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

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

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

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

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

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

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

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

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

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

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

/**
 * Deserializes JSON array into Map<String, String> format to use it in a
 * Spring {@link DataBinder}./* w  w  w.j  a va2  s  .c o  m*/
 * <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());
    }/*  w  w w  .  j  a v  a 2s . c  om*/

    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);
    }
}