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.sdl.odata.unmarshaller.json.JsonLinkUnmarshaller.java

@Override
protected String getToEntityId(ODataRequestContext requestContext) throws ODataUnmarshallingException {
    // The body is expected to contain a single entity reference
    // See OData JSON specification chapter 13

    String bodyText;/*www.jav a  2  s .  c om*/
    try {
        bodyText = requestContext.getRequest().getBodyText(StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        throw new ODataSystemException("UTF-8 is not supported", e);
    }

    String idValue = null;
    try {
        JsonParser parser = new JsonFactory().createParser(bodyText);
        while (idValue == null && !parser.isClosed()) {
            JsonToken token = parser.nextToken();
            if (token == null) {
                break;
            }

            if (token.equals(JsonToken.FIELD_NAME) && parser.getCurrentName().equals(JsonConstants.ID)) {
                token = parser.nextToken();
                if (token.equals(JsonToken.VALUE_STRING)) {
                    idValue = parser.getText();
                }
            }
        }
    } catch (IOException e) {
        throw new ODataUnmarshallingException("Error while parsing JSON data", e);
    }

    if (isNullOrEmpty(idValue)) {
        throw new ODataUnmarshallingException("The JSON object in the body has no '@odata.id' value,"
                + " or the value is empty. The JSON object in the body must have an '@odata.id' value"
                + " that refers to the entity to link to.");
    }

    return idValue;
}

From source file:com.basho.riak.client.raw.http.NamedErlangFunctionDeserializer.java

@Override
public NamedErlangFunction deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    JsonToken token = jp.getCurrentToken();

    if (JsonToken.START_OBJECT.equals(token)) {

        String mod = null;//from   ww w.j av  a 2s  .c  o  m
        String fun = null;

        while (!JsonToken.END_OBJECT.equals(token)) {
            String field = jp.getCurrentName();

            if (Constants.FL_SCHEMA_FUN_MOD.equals(field)) {
                jp.nextToken();
                mod = jp.getText();
            } else if (Constants.FL_SCHEMA_FUN_FUN.equals(field)) {
                jp.nextToken();
                fun = jp.getText();
            }
            token = jp.nextToken();
        }
        if (mod != null && fun != null) {
            return new NamedErlangFunction(mod, fun);
        } else {
            return null;
        }
    }
    throw ctxt.mappingException(NamedErlangFunction.class);
}

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

protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    final ResourceResolver resolver = request.getResourceResolver();

    UGCImportHelper.checkUserPrivileges(resolver, rrf);

    final UGCImportHelper importHelper = new UGCImportHelper();
    importHelper.setForumOperations(forumOperations);
    importHelper.setTallyService(tallyOperationsService);
    // get the forum we'll be adding new topics to
    final String path = request.getRequestParameter("path").getString();
    final Resource resource = request.getResourceResolver().getResource(path);
    if (resource == null) {
        throw new ServletException("Could not find a valid resource for import");
    }//  w ww  .j av a 2 s.  c o  m

    // finally get the uploaded file
    final RequestParameter[] fileRequestParameters = request.getRequestParameters("file");
    if (fileRequestParameters != null && fileRequestParameters.length > 0
            && !fileRequestParameters[0].isFormField()) {

        InputStream inputStream = fileRequestParameters[0].getInputStream();
        JsonParser jsonParser = new JsonFactory().createParser(inputStream);
        jsonParser.nextToken(); // get the first token

        if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
            jsonParser.nextToken();
            if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT_TYPE)) {
                jsonParser.nextToken();
                final String contentType = jsonParser.getValueAsString();
                if (contentType.equals(getContentType())) {
                    jsonParser.nextToken(); // content
                    if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT)) {
                        jsonParser.nextToken(); // startObject
                        if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
                            JsonToken token = jsonParser.nextToken(); // social:key
                            try {
                                while (!token.equals(JsonToken.END_OBJECT)) {
                                    importHelper.extractTopic(jsonParser, resource,
                                            resource.getResourceResolver(), getOperationsService());
                                    token = jsonParser.nextToken();
                                }
                            } catch (final IOException e) {
                                throw new ServletException("Encountered an IOException", e);
                            }
                        } else {
                            throw new ServletException("Start object token not found for content");
                        }
                    } else {
                        throw new ServletException("Content not found");
                    }
                } else {
                    throw new ServletException("Expected forum data");
                }
            } else {
                throw new ServletException("Content Type not specified");
            }
        } else {
            throw new ServletException("Invalid Json format");
        }
    }
}

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

protected static void getAttachments(final JsonParser jsonParser, final List attachments) throws IOException {

    JsonToken token = jsonParser.nextToken(); // skip START_ARRAY token
    String filename;// w ww.j av a 2s.c  o m
    String mimeType;
    InputStream inputStream;
    while (token.equals(JsonToken.START_OBJECT)) {
        filename = null;
        mimeType = null;
        inputStream = null;
        byte[] databytes = null;
        token = jsonParser.nextToken();
        while (!token.equals(JsonToken.END_OBJECT)) {
            final String label = jsonParser.getCurrentName();
            jsonParser.nextToken();
            if (label.equals("filename")) {
                filename = URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8");
            } else if (label.equals("jcr:mimeType")) {
                mimeType = jsonParser.getValueAsString();
            } else if (label.equals("jcr:data")) {
                databytes = Base64.decodeBase64(jsonParser.getValueAsString());
                inputStream = new ByteArrayInputStream(databytes);
            }
            token = jsonParser.nextToken();
        }
        if (filename != null && mimeType != null && inputStream != null) {
            attachments.add(
                    new UGCImportHelper.AttachmentStruct(filename, inputStream, mimeType, databytes.length));
        } else {
            // log an error
            LOG.error(
                    "We expected to import an attachment, but information was missing and nothing was imported");
        }
        token = jsonParser.nextToken();
    }
}

From source file:com.msopentech.odatajclient.engine.data.metadata.edm.v4.ActionDeserializer.java

@Override
protected Action doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final Action action = new Action();

    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        final JsonToken token = jp.getCurrentToken();
        if (token == JsonToken.FIELD_NAME) {
            if ("Name".equals(jp.getCurrentName())) {
                action.setName(jp.nextTextValue());
            } else if ("IsBound".equals(jp.getCurrentName())) {
                action.setBound(BooleanUtils.toBoolean(jp.nextTextValue()));
            } else if ("EntitySetPath".equals(jp.getCurrentName())) {
                action.setEntitySetPath(jp.nextTextValue());
            } else if ("Parameter".equals(jp.getCurrentName())) {
                jp.nextToken();//from   w ww.  ja v a2s.c o  m
                action.getParameters().add(jp.getCodec().readValue(jp, Parameter.class));
            } else if ("ReturnType".equals(jp.getCurrentName())) {
                action.setReturnType(parseReturnType(jp, "Action"));
            } else if ("Annotation".equals(jp.getCurrentName())) {
                jp.nextToken();
                action.setAnnotation(jp.getCodec().readValue(jp, Annotation.class));
            }
        }
    }

    return action;
}

From source file:com.msopentech.odatajclient.engine.data.metadata.edm.AssociationDeserializer.java

@Override
public Association deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final Association association = new Association();

    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        final JsonToken token = jp.getCurrentToken();
        if (token == JsonToken.FIELD_NAME) {
            if ("Name".equals(jp.getCurrentName())) {
                association.setName(jp.nextTextValue());
            } else if ("ReferentialConstraint".equals(jp.getCurrentName())) {
                jp.nextToken();//from  w  ww  . ja  v  a2  s  . c  o m
                association.setReferentialConstraint(jp.getCodec().readValue(jp, ReferentialConstraint.class));
            } else if ("End".equals(jp.getCurrentName())) {
                jp.nextToken();
                association.getEnds().add(jp.getCodec().readValue(jp, AssociationEnd.class));
            }
        }
    }

    return association;
}

From source file:org.messic.server.api.tagwizard.discogs.DiscogsTAGWizardPlugin.java

@Override
public List<Album> getAlbumInfo(Album albumHelpInfo, File[] files) {
    if (albumHelpInfo == null || (albumHelpInfo.name == null && albumHelpInfo.author == null)
            || ((albumHelpInfo.name != null && albumHelpInfo.name.length() <= 0)
                    && (albumHelpInfo.author != null && albumHelpInfo.author.length() <= 0))) {
        return new ArrayList<Album>();
    }/*  w w w.  ja  v a2s .  c  o m*/

    String baseURL = "http://api.discogs.com/database/search?type=release";

    try {
        if (albumHelpInfo.name != null) {
            baseURL = baseURL + "&release_title=" + URLEncoder.encode(albumHelpInfo.name, "UTF-8") + "";
        }
        if (albumHelpInfo.author != null) {
            baseURL = baseURL + "&artist=" + URLEncoder.encode(albumHelpInfo.author, "UTF-8") + "";
        }

        URL url = new URL(baseURL);
        Proxy proxy = getProxy();
        URLConnection uc = (proxy != null ? url.openConnection(proxy) : url.openConnection());
        uc.setRequestProperty("User-Agent", "Messic/1.0 +http://spheras.github.io/messic/");

        ArrayList<Album> result = new ArrayList<Album>();

        JsonFactory jsonFactory = new JsonFactory(); // or, for data binding,
        JsonParser jParser = jsonFactory.createParser(uc.getInputStream());
        while (jParser.nextToken() != null) {
            String fieldname = jParser.getCurrentName();
            if ("id".equals(fieldname)) {
                jParser.nextToken();
                String id = jParser.getText();
                // one second per petition allowed by discogs
                Thread.sleep(1000);

                Album album = getAlbum(id);

                result.add(album);
            }

        }
        return result;
    } catch (Exception e) {
        log.error("failed!", e);
    }

    return null;
}

From source file:com.redhat.red.build.koji.model.json.util.MavenGAVDeserializer.java

@Override
public SimpleProjectVersionRef deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    String g = null;/* w  w w.  j  a  va2 s .  c o m*/
    String a = null;
    String v = null;

    JsonToken token = null;
    while ((token = jp.nextToken()) != JsonToken.END_OBJECT) {
        if (token == JsonToken.VALUE_STRING) {
            String field = jp.getCurrentName();
            switch (field) {
            case ("group_id"): {
                g = jp.getText();
                break;
            }
            case ("artifact_id"): {
                a = jp.getText();
                break;
            }
            case ("version"): {
                v = jp.getText();
                break;
            }
            default: {
                Logger logger = LoggerFactory.getLogger(getClass());
                logger.debug("Ignoring unknown field: {}", field);
            }
            }
        }
    }

    if (isEmpty(g) || isEmpty(a) || isEmpty(v)) {
        throw new KojiJsonException("Invalid GAV: " + g + ":" + a + ":" + v);
    }

    return new SimpleProjectVersionRef(g, a, v);
}

From source file:com.msopentech.odatajclient.engine.data.metadata.edm.AssociationSetDeserializer.java

@Override
public AssociationSet deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final AssociationSet associationSet = new AssociationSet();

    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        final JsonToken token = jp.getCurrentToken();
        if (token == JsonToken.FIELD_NAME) {
            if ("Name".equals(jp.getCurrentName())) {
                associationSet.setName(jp.nextTextValue());
            } else if ("Association".equals(jp.getCurrentName())) {
                associationSet.setAssociation(jp.nextTextValue());
            } else if ("End".equals(jp.getCurrentName())) {
                jp.nextToken();/*from  w w  w  .  j  a  v  a  2  s.com*/
                associationSet.getEnds().add(jp.getCodec().readValue(jp, AssociationSetEnd.class));
            }
        }
    }

    return associationSet;
}

From source file:com.amazonaws.services.sns.util.SignatureChecker.java

private Map<String, String> parseJSON(String jsonmessage) {
    Map<String, String> parsed = new HashMap<String, String>();
    JsonFactory jf = new JsonFactory();
    try {/*  w  ww .  ja  v a  2s . c  o  m*/
        JsonParser parser = jf.createJsonParser(jsonmessage);
        parser.nextToken(); //shift past the START_OBJECT that begins the JSON
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String fieldname = parser.getCurrentName();
            parser.nextToken(); // move to value, or START_OBJECT/START_ARRAY
            String value;
            if (parser.getCurrentToken() == JsonToken.START_ARRAY) {
                value = "";
                boolean first = true;
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    if (!first)
                        value += ",";
                    first = false;
                    value += parser.getText();
                }
            } else {
                value = parser.getText();
            }
            parsed.put(fieldname, value);
        }
    } catch (JsonParseException e) {
        // JSON could not be parsed
        e.printStackTrace();
    } catch (IOException e) {
        // Rare exception
    }
    return parsed;
}