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

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

Introduction

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

Prototype

public String getValueAsString() throws IOException, JsonParseException 

Source Link

Document

Method that will try to convert value of current token to a java.lang.String .

Usage

From source file:ch.rasc.wampspring.message.PublishMessage.java

public PublishMessage(JsonParser jp, WampSession wampSession) throws IOException {
    super(WampMessageType.PUBLISH);

    if (jp.nextToken() != JsonToken.VALUE_STRING) {
        throw new IOException();
    }/* ww  w . j a  v a2 s  .  c o  m*/
    setTopicURI(replacePrefix(jp.getValueAsString(), wampSession));

    jp.nextToken();
    this.event = jp.readValueAs(Object.class);

    if (jp.nextToken() != JsonToken.END_ARRAY) {
        if (jp.getCurrentToken() == JsonToken.VALUE_TRUE || jp.getCurrentToken() == JsonToken.VALUE_FALSE) {
            this.excludeMe = jp.getValueAsBoolean();

            this.exclude = null;

            this.eligible = null;

            if (jp.nextToken() != JsonToken.END_ARRAY) {
                // Wrong message format, excludeMe should not be followed by
                // any value
                throw new IOException();
            }
        } else {
            this.excludeMe = null;

            TypeReference<Set<String>> typRef = new TypeReference<Set<String>>() {
                // nothing here
            };

            if (jp.getCurrentToken() != JsonToken.START_ARRAY) {
                throw new IOException();
            }
            this.exclude = jp.readValueAs(typRef);

            if (jp.nextToken() == JsonToken.START_ARRAY) {
                this.eligible = jp.readValueAs(typRef);
            } else {
                this.eligible = null;
            }
        }
    } else {
        this.excludeMe = null;
        this.exclude = null;
        this.eligible = null;
    }

}

From source file:org.springframework.data.couchbase.core.convert.translation.JacksonTranslationService.java

/**
 * Helper method to decode and assign a primitive.
 *
 * @param token the type of token./*from   w  w  w  .ja  va 2  s  .  co m*/
 * @param parser the parser with the content.
 *
 * @return the decoded primitve.
 *
 * @throws IOException
 */
private Object decodePrimitive(final JsonToken token, final JsonParser parser) throws IOException {
    switch (token) {
    case VALUE_TRUE:
    case VALUE_FALSE:
        return parser.getValueAsBoolean();
    case VALUE_STRING:
        return parser.getValueAsString();
    case VALUE_NUMBER_INT:
        try {
            return parser.getValueAsInt();
        } catch (final JsonParseException e) {
            return parser.getValueAsLong();
        }
    case VALUE_NUMBER_FLOAT:
        return parser.getValueAsDouble();
    case VALUE_NULL:
        return null;
    default:
        throw new MappingException("Could not decode primitve value " + token);
    }
}

From source file:com.netflix.discovery.converters.jackson.serializer.ApplicationXmlDeserializer.java

@Override
public Application deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    String name = null;/*from w  w w .  ja v a 2s.c  o m*/
    List<InstanceInfo> instances = new ArrayList<>();
    while (jp.nextToken() == JsonToken.FIELD_NAME) {
        String fieldName = jp.getCurrentName();
        jp.nextToken(); // to point to value
        if ("name".equals(fieldName)) {
            name = jp.getValueAsString();
        } else if ("instance".equals(fieldName)) {
            instances.add(jp.readValueAs(InstanceInfo.class));
        } else {
            throw new JsonMappingException("Unexpected field " + fieldName, jp.getCurrentLocation());
        }
    }
    return new Application(name, instances);
}

From source file:automenta.knowtention.model.JSONObjectMetrics.java

public JSONObjectMetrics(JsonNode n) {

    this.when = System.currentTimeMillis();
    this.channel = null;

    JsonParser parser = n.traverse();

    error = true;/*from   w  w w  .  j av  a  2s .  c om*/
    while (!parser.isClosed()) {

        try {

            JsonToken t = parser.nextToken();
            if (t == null)
                break;

            switch (t) {
            case VALUE_STRING:
                numValues++;
                numStrings++;
                String s = parser.getValueAsString();
                if (s != null)
                    stringLengthSum += s.length();
                break;
            case VALUE_EMBEDDED_OBJECT:
                numValues++;
                numEmbeddedObjects++;
                break;
            case VALUE_FALSE:
            case VALUE_TRUE:
                numValues++;
                numBooleans++;
                break;
            case VALUE_NUMBER_FLOAT:
            case VALUE_NUMBER_INT:
                numNumbers++;
                numValues++;
                break;
            case VALUE_NULL:
                numValues++;
                numNulls++;
                break;
            }

            if (t == null)
                break;
            numTokens++;

        } catch (IOException ex) {
            break;
        }

    }

    error = false;
}

From source file:org.helm.notation2.wsadapter.MonomerWSSaver.java

/**
 * Adds or updates a single monomer to the monomer store using the URL configured in {@code MonomerStoreConfiguration}
 * .//from   ww w  .  j  a va  2s  . c  om
 * 
 * @param monomer to save
 */
public String saveMonomerToStore(Monomer monomer) {
    String res = "";
    CloseableHttpResponse response = null;

    try {
        response = WSAdapterUtils.putResource(monomer.toJSON(),
                MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesPutFullURL());
        LOG.debug(response.getStatusLine().toString());

        JsonFactory jsonf = new JsonFactory();
        InputStream instream = response.getEntity().getContent();

        JsonParser jsonParser = jsonf.createParser(instream);

        while (!jsonParser.isClosed()) {
            JsonToken jsonToken = jsonParser.nextToken();
            if (JsonToken.FIELD_NAME.equals(jsonToken)) {
                String fieldName = jsonParser.getCurrentName();
                LOG.debug("Field name: " + fieldName);
                jsonParser.nextToken();
                if (fieldName.equals("monomerShortName")) {
                    res = jsonParser.getValueAsString();
                    break;
                }
            }
        }

        EntityUtils.consume(response.getEntity());

    } catch (Exception e) {
        LOG.error("Saving monomer failed!", e);
        return "";
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            LOG.debug("Closing resources failed.", e);
            return res;
        }
    }

    return res;
}

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 w w  .  j  a va  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.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");
    }//from ww w.  j  a  v a2 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:io.syndesis.jsondb.impl.JsonRecordSupport.java

public static void jsonStreamToRecords(JsonParser jp, String path, Consumer<JsonRecord> consumer)
        throws IOException {
    boolean inArray = false;
    int arrayIndex = 0;
    while (true) {
        JsonToken nextToken = jp.nextToken();

        String currentPath = path;

        if (nextToken == FIELD_NAME) {
            if (inArray) {
                currentPath = path + toArrayIndexPath(arrayIndex) + "/";
            }//from   www. ja  v a2 s  .  c o  m
            jsonStreamToRecords(jp, currentPath + validateKey(jp.getCurrentName()) + "/", consumer);
        } else if (nextToken == VALUE_NULL) {
            if (inArray) {
                currentPath = path + toArrayIndexPath(arrayIndex) + "/";
            }
            consumer.accept(JsonRecord.of(currentPath, "", nextToken.id()));
            if (inArray) {
                arrayIndex++;
            } else {
                return;
            }
        } else if (nextToken.isScalarValue()) {
            if (inArray) {
                currentPath = path + toArrayIndexPath(arrayIndex) + "/";
            }
            consumer.accept(JsonRecord.of(currentPath, jp.getValueAsString(), nextToken.id()));
            if (inArray) {
                arrayIndex++;
            } else {
                return;
            }
        } else if (nextToken == END_OBJECT) {
            if (inArray) {
                arrayIndex++;
            } else {
                return;
            }
        } else if (nextToken == START_ARRAY) {
            inArray = true;
        } else if (nextToken == END_ARRAY) {
            return;
        }
    }
}

From source file:net.openhft.chronicle.wire.benchmarks.Data.java

public void readFrom(JsonParser parser) throws IOException {
    parser.nextToken();//from  w  w  w  .  ja v  a 2s  .c  om
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String fieldname = parser.getCurrentName();
        parser.nextToken();
        switch (fieldname) {
        case "price":
            setPrice(parser.getDoubleValue());
            break;
        case "flag":
            flag = parser.getBooleanValue();
            break;
        case "text":
            setText(parser.getValueAsString());
            break;
        case "side":
            side = Side.valueOf(parser.getValueAsString());
            break;
        case "smallInt":
            smallInt = parser.getIntValue();
            break;
        case "longInt":
            longInt = parser.getLongValue();
            break;
        }
    }
}