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

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

Introduction

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

Prototype

public abstract String getCurrentName() throws IOException, JsonParseException;

Source Link

Document

Method that can be called to get the name associated with the current token: for JsonToken#FIELD_NAME s it will be the same as what #getText returns; for field values it will be preceding field name; and for others (array values, root-level values) null.

Usage

From source file:com.cedarsoft.couchdb.io.ActionFailedExceptionSerializer.java

@Nonnull
public ActionFailedException deserialize(int status, @Nonnull InputStream in)
        throws VersionException, IOException {
    try (MaxLengthByteArrayOutputStream teedOut = new MaxLengthByteArrayOutputStream();
            TeeInputStream teeInputStream = new TeeInputStream(in, teedOut)) {

        JsonFactory jsonFactory = JacksonSupport.getJsonFactory();

        JsonParser parser = jsonFactory.createJsonParser(teeInputStream);
        JacksonParserWrapper parserWrapper = new JacksonParserWrapper(parser);

        parserWrapper.nextToken(JsonToken.START_OBJECT);

        String error = null;/*from w w w. ja v  a  2  s.  c  om*/
        String reason = null;

        while (parser.nextToken() == JsonToken.FIELD_NAME) {
            String currentName = parser.getCurrentName();

            if (currentName.equals(PROPERTY_ERROR)) {
                parserWrapper.nextToken(JsonToken.VALUE_STRING);
                error = parser.getText();
                continue;
            }

            if (currentName.equals(PROPERTY_REASON)) {
                parserWrapper.nextToken(JsonToken.VALUE_STRING);
                reason = parser.getText();
                continue;
            }

            throw new IllegalStateException("Unexpected field reached <" + currentName + ">");
        }

        parserWrapper.verifyDeserialized(error, PROPERTY_ERROR);
        parserWrapper.verifyDeserialized(reason, PROPERTY_REASON);
        assert reason != null;
        assert error != null;

        parserWrapper.ensureObjectClosed();

        return new ActionFailedException(status, error, reason, teedOut.toByteArray());
    }
}

From source file:com.netflix.hollow.jsonadapter.HollowJsonAdapterPrimaryKeyFinder.java

private void addObject(JsonParser parser, HollowObjectSchema schema, StringBuilder currentFieldPath)
        throws IOException {
    JsonToken token = parser.nextToken();

    String fieldName = null;//  w w w  .  j a v  a  2s .  c o m
    try {
        while (token != JsonToken.END_OBJECT) {
            fieldName = parser.getCurrentName();
            addObjectField(parser, token, schema, fieldName, currentFieldPath);
            token = parser.nextToken();
        }
    } catch (Exception ex) {
        throw new IOException(
                "Failed to parse field=" + fieldName + ", schema=" + schema.getName() + ", token=" + token, ex);
    }
}

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. jav 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.SocialGraphImportServlet.java

private void importFile(final JsonParser jsonParser, final SlingHttpServletRequest request)
        throws ServletException, IOException {

    JsonToken token = jsonParser.nextToken();
    while (!token.equals(JsonToken.END_OBJECT)) {
        if (!token.equals(JsonToken.FIELD_NAME)) {
            throw new ServletException("Expected a field name, got " + token);
        }/*from   w ww  .  j  a  va  2  s . c  o m*/
        final String userId = jsonParser.getCurrentName();
        token = jsonParser.nextToken();
        if (!token.equals(JsonToken.START_ARRAY)) {
            throw new ServletException("Expected an array start token, got " + token);
        }
        token = jsonParser.nextToken();
        final Resource tmpParent = request.getResourceResolver().getResource("/tmp");
        while (!token.equals(JsonToken.END_ARRAY)) {
            final Map<String, Object> props = new HashMap<String, Object>();
            props.put("resourceType", Following.RESOURCE_TYPE);
            props.put("userId", userId);
            props.put("followedId", jsonParser.getValueAsString());
            Resource resource;
            resource = request.getResourceResolver().create(tmpParent, "following", props);
            final SocialComponentFactory factory = componentFactoryManager
                    .getSocialComponentFactory(Following.RESOURCE_TYPE);
            final Following following = (Following) factory.getSocialComponent(resource, request);
            request.getResourceResolver().delete(resource); // need to delete it so we can create it again next time
            final Vertex node = following.userNode();
            final Vertex other = following.followedNode();
            final String relType = "USER";
            try {
                node.createRelationshipTo(other, Edge.FOLLOWING_RELATIONSHIP_TYPE, relType);
                following.socialGraph().save();
            } catch (final IllegalArgumentException e) {
                // The relationship already exists. Do nothing.
            }
            token = jsonParser.nextToken();
        }
        token = jsonParser.nextToken(); // skip over END_ARRAY
    }
}

From source file:com.joliciel.jochre.search.webClient.SearchResults.java

public SearchResults(String json) {
    try {/* w ww .  j a v a2 s  . co m*/
        scoreDocs = new ArrayList<SearchDocument>();
        Reader reader = new StringReader(json);
        JsonFactory jsonFactory = new JsonFactory(); // or, for data binding, org.codehaus.jackson.mapper.MappingJsonFactory 
        JsonParser jsonParser = jsonFactory.createJsonParser(reader);
        // Sanity check: verify that we got "Json Object":
        if (jsonParser.nextToken() != JsonToken.START_OBJECT)
            throw new RuntimeException("Expected START_OBJECT, but was " + jsonParser.getCurrentToken() + " at "
                    + jsonParser.getCurrentLocation());
        while (jsonParser.nextToken() != JsonToken.END_OBJECT) {

            String baseName = jsonParser.getCurrentName();
            LOG.debug("Found baseName: " + baseName);
            if (jsonParser.nextToken() != JsonToken.START_OBJECT)
                throw new RuntimeException("Expected START_OBJECT, but was " + jsonParser.getCurrentToken()
                        + " at " + jsonParser.getCurrentLocation());

            SearchDocument doc = new SearchDocument(baseName, jsonParser);
            scoreDocs.add(doc);

        } // next scoreDoc
    } catch (JsonParseException e) {
        LOG.error(e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        LOG.error(e);
        throw new RuntimeException(e);
    }
}

From source file:com.netflix.hollow.jsonadapter.discover.HollowJsonAdapterSchemaDiscoverer.java

private void discoverSubMapSchemas(JsonParser parser, HollowDiscoveredSchema objectSchema) throws IOException {
    JsonToken token = parser.nextToken();
    if (isDebug)/* ww w. j  av  a 2 s.  c om*/
        System.out.println(
                "discoverSubMapSchemas[START]: token=" + token + ", fieldname=" + parser.getCurrentName());

    while (token != JsonToken.END_OBJECT) {
        if (isDebug)
            System.out.println(
                    "discoverSubMapSchemas[LOOP]: token=" + token + ", fieldname=" + parser.getCurrentName());
        if (token != JsonToken.FIELD_NAME) {
            if (token == JsonToken.START_OBJECT) {
                if (isDebug)
                    System.out.println("discoverSubMapSchemas[LOOP] discoverSchemas: token=" + token
                            + ", fieldname=" + parser.getCurrentName());
                discoverSchemas(parser, objectSchema);
            } else {
                if (isDebug)
                    System.out.println("discoverSubMapSchemas[LOOP] discoverSchemaField: token=" + token
                            + ", fieldname=" + parser.getCurrentName());
                discoverSchemaField(parser, token, "value", objectSchema);
            }
        }
        token = parser.nextToken();
    }

    if (isDebug)
        System.out.println("discoverSubMapSchemas[END]: token=" + token);
}

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

private void doRestore(JsonParser jp, ZooKeeper zk) throws IOException, KeeperException, InterruptedException {
    expectNextToken(jp, JsonToken.START_OBJECT);
    final Set<String> createdPaths = Sets.newHashSet();
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        final BackupZNode zNode = readZNode(jp, jp.getCurrentName());
        // We are the root
        if (path.isEmpty()) {
            path.add(zNode);//from  ww w  .j  a  v a2 s .co  m
        } else {
            for (ListIterator<BackupZNode> it = path.listIterator(path.size()); it.hasPrevious();) {
                final BackupZNode parent = it.previous();
                if (zNode.path.startsWith(parent.path)) {
                    break;
                }
                it.remove();
            }
            path.add(zNode);
        }
        if (zNode.ephemeralOwner != 0) {
            LOGGER.info("Skipping ephemeral ZNode: {}", zNode.path);
            continue;
        }
        if (!zNode.path.startsWith(options.rootPath)) {
            LOGGER.info("Skipping ZNode (not under root path '{}'): {}", options.rootPath, zNode.path);
            continue;
        }
        if (options.isPathExcluded(LOGGER, zNode.path) || !options.isPathIncluded(LOGGER, zNode.path)) {
            continue;
        }
        for (BackupZNode pathComponent : path) {
            if (createdPaths.add(pathComponent.path)) {
                restoreNode(zk, pathComponent);
            }
        }
    }
}

From source file:org.onosproject.north.aaa.api.parser.impl.ClientParser.java

public ClientCredential jsonToClientCredential(JsonParser jp) throws ParseException, IOException {
    ClientCredential.Builder builder = ClientCredential.builder();

    while (true) {
        JsonToken token = jp.nextToken();
        if (JsonToken.END_OBJECT.equals(token)) {
            // bail out
            break;
        }/*from  ww w. j a  va 2s  .c om*/

        if (JsonToken.FIELD_NAME.equals(token) && "appId".equals(jp.getCurrentName())) {
            jp.nextToken();
            builder.buildAppId(jp.getText());
        } else if (JsonToken.FIELD_NAME.equals(token) && "grants".equals(jp.getCurrentName())) {
            token = jp.nextToken();
            if (!JsonToken.START_ARRAY.equals(token)) {
                // bail out
                throw new ParseException("expected ARRAY after grants");
            }
            Set<String> grants = new HashSet<>();

            while (true) {
                token = jp.nextToken();
                if (JsonToken.END_ARRAY.equals(token)) {
                    // bail out
                    break;
                }
                grants.add(jp.getText());
            }
            builder.buildGrants(grants);

        } else if (JsonToken.FIELD_NAME.equals(token) && "scopes".equals(jp.getCurrentName())) {
            token = jp.nextToken();
            if (!JsonToken.START_ARRAY.equals(token)) {
                // bail out
                throw new ParseException("expected ARRAY after scopes");
            }
            Set<String> scopes = new HashSet<>();

            while (true) {
                token = jp.nextToken();
                if (JsonToken.END_ARRAY.equals(token)) {
                    // bail out
                    break;
                }
                scopes.add(jp.getText());
            }
            builder.buildScopes(scopes);

        } else if (JsonToken.FIELD_NAME.equals(token) && "redirectUri".equals(jp.getCurrentName())) {
            jp.nextToken();
            String uri = jp.getText();

            // verify uri by uri regex
            Pattern emailPattern = Pattern.compile(URI_PATTERN);
            if (!emailPattern.matcher(uri).matches()) {
                // bail out
                throw new ParseException("uri is not valid");
            }
            builder.buildRedirectUri(uri);
        } else if (JsonToken.FIELD_NAME.equals(token) && "clientId".equals(jp.getCurrentName())) {
            jp.nextToken();
            builder.buildClientId(jp.getText());
        } else if (JsonToken.FIELD_NAME.equals(token) && "clientSecret".equals(jp.getCurrentName())) {
            jp.nextToken();
            builder.buildClientSecret(jp.getText());
        }
    }
    return builder.buildAll();
}