Example usage for com.fasterxml.jackson.databind JsonNode textValue

List of usage examples for com.fasterxml.jackson.databind JsonNode textValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode textValue.

Prototype

public String textValue() 

Source Link

Usage

From source file:com.neovisionaries.security.JsonDigestUpdater.java

private boolean shouldIgnore(JsonNode value) {
    if (ignoreNull && value.isNull()) {
        // The value of the field is null. Ignore this entry.
        return true;
    }// w  w w  .  java  2 s.co  m

    if (ignoreFalse && value.isBoolean()) {
        // Ignore this entry if its value is false.
        return value.asBoolean() == false;
    }

    if (ignoreZero && value.isNumber()) {
        // Ignore this entry if its value is zero.
        return isZero(value);
    }

    if (ignoreEmptyString && value.isTextual()) {
        // Ignore this entry if its value is an empty string.
        return value.textValue().length() == 0;
    }

    if (ignoreEmptyArray && value.isArray()) {
        // Ignore this entry if its value is an empty array.
        return value.size() == 0;
    }

    if (ignoreEmptyObject && value.isObject()) {
        // Ignore this entry if its value is an empty object.
        return value.size() == 0;
    }

    // Should not ignore.
    return false;
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManager.java

@Override
public MantaMultipartStatus getStatus(final ServerSideMultipartUpload upload) throws IOException {
    Validate.notNull(upload, "Upload state object must not be null");

    final String partsDirectory;

    if (upload.getPartsDirectory() == null) {
        partsDirectory = uuidPrefixedPath(upload.getId());
    } else {// ww w.  j  a v a2s  .  co m
        partsDirectory = upload.getPartsDirectory();
    }

    final String getPath = partsDirectory + SEPARATOR + "state";
    final HttpGet get = httpHelper.getRequestFactory().get(getPath);

    final int expectedStatusCode = HttpStatus.SC_OK;
    final CloseableHttpClient httpClient = httpHelper.getConnectionContext().getHttpClient();

    try (CloseableHttpResponse response = httpClient.execute(get)) {
        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            return MantaMultipartStatus.UNKNOWN;
        }

        validateStatusCode(expectedStatusCode, statusLine.getStatusCode(),
                "Unable to get status for multipart upload", get, response, null, null);
        validateEntityIsPresent(get, response, null, null);

        try (InputStream in = response.getEntity().getContent()) {
            ObjectNode objectNode = MantaObjectMapper.INSTANCE.readValue(in, ObjectNode.class);

            JsonNode stateNode = objectNode.get("state");
            Validate.notNull(stateNode, "Unable to get state from response");
            String state = stateNode.textValue();
            Validate.notBlank(state, "State field was blank in response");

            if (state.equalsIgnoreCase("created")) {
                return MantaMultipartStatus.CREATED;
            }
            if (state.equalsIgnoreCase("finalizing")) {
                return extractMultipartStatusResult(objectNode);
            }
            if (state.equalsIgnoreCase("done")) {
                return extractMultipartStatusResult(objectNode);
            }

            return MantaMultipartStatus.UNKNOWN;
        } catch (JsonParseException e) {
            String msg = "Response body was not JSON";
            MantaMultipartException me = new MantaMultipartException(msg, e);
            annotateException(me, get, response, null, null);
            throw me;
        } catch (NullPointerException | IllegalArgumentException e) {
            String msg = "Expected response field was missing or malformed";
            MantaMultipartException me = new MantaMultipartException(msg, e);
            annotateException(me, get, response, null, null);
            throw me;
        }
    }
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManager.java

@Override
public ServerSideMultipartUpload initiateUpload(final String path, final Long contentLength,
        final MantaMetadata mantaMetadata, final MantaHttpHeaders httpHeaders) throws IOException {
    Validate.notBlank(path, "Path to object must not be blank");

    final MantaMetadata metadata;

    if (mantaMetadata == null) {
        metadata = new MantaMetadata();
    } else {/*from   www. j a  v  a  2 s  .  co  m*/
        metadata = mantaMetadata;
    }

    final MantaHttpHeaders headers;

    if (httpHeaders == null) {
        headers = new MantaHttpHeaders();
    } else {
        headers = httpHeaders;
    }

    /* We explicitly set the content-length header if it is passed as a method parameter
     * so that the server will validate the size of the upload when it is committed. */
    if (contentLength != null && headers.getContentLength() == null) {
        headers.setContentLength(contentLength);
    }

    final String postPath = uploadsPath();
    final HttpPost post = httpHelper.getRequestFactory().post(postPath);

    final byte[] jsonRequest = createMpuRequestBody(path, metadata, headers);
    final HttpEntity entity = new ExposedByteArrayEntity(jsonRequest, ContentType.APPLICATION_JSON);
    post.setEntity(entity);

    final int expectedStatusCode = HttpStatus.SC_CREATED;
    final CloseableHttpClient httpClient = httpHelper.getConnectionContext().getHttpClient();

    try (CloseableHttpResponse response = httpClient.execute(post)) {
        StatusLine statusLine = response.getStatusLine();

        validateStatusCode(expectedStatusCode, statusLine.getStatusCode(), "Unable to create multipart upload",
                post, response, path, jsonRequest);
        validateEntityIsPresent(post, response, path, jsonRequest);

        try (InputStream in = response.getEntity().getContent()) {
            ObjectNode mpu = MantaObjectMapper.INSTANCE.readValue(in, ObjectNode.class);

            JsonNode idNode = mpu.get("id");
            Validate.notNull(idNode, "No multipart id returned in response");
            UUID uploadId = UUID.fromString(idNode.textValue());

            JsonNode partsDirectoryNode = mpu.get("partsDirectory");
            Validate.notNull(partsDirectoryNode, "No parts directory returned in response");
            String partsDirectory = partsDirectoryNode.textValue();

            return new ServerSideMultipartUpload(uploadId, path, partsDirectory);
        } catch (NullPointerException | IllegalArgumentException e) {
            String msg = "Expected response field was missing or malformed";
            MantaMultipartException me = new MantaMultipartException(msg, e);
            annotateException(me, post, response, path, jsonRequest);
            throw me;
        } catch (JsonParseException e) {
            String msg = "Response body was not JSON";
            MantaMultipartException me = new MantaMultipartException(msg, e);
            annotateException(me, post, response, path, jsonRequest);
            throw me;
        }
    }
}

From source file:com.arpnetworking.tsdaggregator.parsers.QueryLogParser.java

/**
 * {@inheritDoc}/*ww w . java 2s  . co  m*/
 */
@Override
public Record parse(final byte[] data) throws ParsingException {
    // Attempt to parse the data as JSON to distinguish between the legacy 
    // format and the current JSON format
    final JsonNode jsonNode;
    try {
        jsonNode = OBJECT_MAPPER.readTree(data);
    } catch (final IOException ex) {
        // CHECKSTYLE.OFF: IllegalInstantiation - Approved for byte[] to String
        throw new ParsingException(
                String.format("Unsupported non-json format; data=%s", new String(data, Charsets.UTF_8)));
        // CHECKSTYLE.ON: IllegalInstantiation
    }

    // If it's JSON extract the version and parse accordingly
    final JsonNode dataNode = jsonNode.get(DATA_KEY);
    JsonNode versionNode = jsonNode.get(VERSION_KEY);
    if (dataNode != null) {
        final JsonNode dataVersionNode = dataNode.get(VERSION_KEY);
        if (dataVersionNode != null) {
            versionNode = dataVersionNode;
        }
    }
    if (versionNode == null) {
        throw new ParsingException(String.format("Unable to determine version; jsonNode=%s", jsonNode));
    }
    final String version = versionNode.textValue().toLowerCase();
    switch (version) {
    case "2c":
        return parseV2cLogLine(jsonNode);
    case "2d":
        return parseV2dLogLine(jsonNode);
    case "2e":
        return parseV2eLogLine(jsonNode);
    default:
        throw new ParsingException(String.format("Unsupported version; version=%s", version));
    }
}

From source file:com.alliander.osgp.shared.usermanagement.KeycloakClient.java

/**
 * Performs a user lookup by username.//from  w  w w. ja v a  2  s  .c  om
 * <p>
 * This method assumes an existing unique username is provided, so a exactly
 * one user will be found in the lookup.
 *
 * @param username
 *            an existing Keycloak username for the configured realm.
 * @return the user ID for the user with the given username.
 * @throws KeycloakClientException
 *             if retrieving a single user ID for the given username does
 *             not succeed.
 */
public String getUserId(final String username) throws KeycloakClientException {

    LOGGER.info("Retrieving Keycloak user ID for user '{}' and realm '{}'.", username, this.realm);

    final WebClient getUserIdWebClient = this.getWebClientInstance().path(this.usersPath).query("username",
            username);

    Response response = this.withBearerToken(getUserIdWebClient).get();

    JsonNode jsonNode;
    try {
        jsonNode = this.getJsonResponseBody(response);
    } catch (final KeycloakBearerException e) {
        LOGGER.debug("It looks like the bearer token expired, retry API call to the user lookup.", e);
        this.refreshToken();
        response = this.withBearerToken(getUserIdWebClient).get();
        jsonNode = this.getJsonResponseBody(response);
    }

    if (!jsonNode.isArray()) {
        throw new KeycloakClientException(
                "Expected array result from Keycloak API user lookup, got: " + jsonNode.getNodeType().name());
    }
    final ArrayNode jsonArray = (ArrayNode) jsonNode;

    if (jsonArray.size() != 1) {
        throw new KeycloakClientException("Expected 1 array result from Keycloak API user lookup for username '"
                + username + "', got: " + jsonArray.size());
    }

    final JsonNode userRepresentation = jsonArray.get(0);

    final JsonNode userId = userRepresentation.get("id");

    if (userId == null || !userId.isTextual()) {
        throw new KeycloakClientException(
                "Keycloak API user representation does not contain a JSON text field 'id'.");
    }

    return userId.textValue();
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManager.java

@Override
public MantaMultipartUploadPart getPart(final ServerSideMultipartUpload upload, final int partNumber)
        throws IOException {
    Validate.notNull(upload, "Upload state object must not be null");
    validatePartNumber(partNumber);/*from ww  w.j  a  va 2 s. co m*/

    final int adjustedPartNumber = partNumber - 1;

    final String getPath = upload.getPartsDirectory() + SEPARATOR + "state";
    final HttpGet get = httpHelper.getRequestFactory().get(getPath);

    final String objectPath;

    final int expectedStatusCode = HttpStatus.SC_OK;
    final CloseableHttpClient httpClient = httpHelper.getConnectionContext().getHttpClient();

    try (CloseableHttpResponse response = httpClient.execute(get)) {
        StatusLine statusLine = response.getStatusLine();
        validateStatusCode(expectedStatusCode, statusLine.getStatusCode(),
                "Unable to get status for multipart upload", get, response, null, null);
        validateEntityIsPresent(get, response, null, null);

        try (InputStream in = response.getEntity().getContent()) {
            ObjectNode objectNode = MantaObjectMapper.INSTANCE.readValue(in, ObjectNode.class);

            JsonNode objectPathNode = objectNode.get("targetObject");
            Validate.notNull(objectPathNode, "Unable to read object path from response");
            objectPath = objectPathNode.textValue();
            Validate.notBlank(objectPath, "Object path field was blank in response");
        } catch (JsonParseException e) {
            String msg = "Response body was not JSON";
            MantaMultipartException me = new MantaMultipartException(msg, e);
            annotateException(me, get, response, null, null);
            throw me;
        } catch (NullPointerException | IllegalArgumentException e) {
            String msg = "Expected response field was missing or malformed";
            MantaMultipartException me = new MantaMultipartException(msg, e);
            annotateException(me, get, response, null, null);
            throw me;
        }
    }

    final String headPath = upload.getPartsDirectory() + SEPARATOR + adjustedPartNumber;
    final HttpHead head = httpHelper.getRequestFactory().head(headPath);

    final String etag;

    try (CloseableHttpResponse response = httpClient.execute(head)) {
        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            return null;
        }

        validateStatusCode(expectedStatusCode, statusLine.getStatusCode(),
                "Unable to get status for multipart upload part", get, response, null, null);

        try {
            final Header etagHeader = response.getFirstHeader(HttpHeaders.ETAG);
            Validate.notNull(etagHeader, "ETag header was not returned");
            etag = etagHeader.getValue();
            Validate.notBlank(etag, "ETag is blank");
        } catch (NullPointerException | IllegalArgumentException e) {
            String msg = "Expected header was missing or malformed";
            MantaMultipartException me = new MantaMultipartException(msg, e);
            annotateException(me, get, response, null, null);
            throw me;
        }
    }

    return new MantaMultipartUploadPart(partNumber, objectPath, etag);
}

From source file:org.dd4t.databind.builder.json.JsonModelConverter.java

private <T extends BaseViewModel> void buildMultimediaField(final T model, final String fieldName,
        final JsonNode currentField, final ModelFieldMapping modelFieldMapping) throws IllegalAccessException {
    final Field modelField = modelFieldMapping.getField();
    modelField.setAccessible(true);//from  ww w .ja  v a2s . c om
    setXPathForXpm(model, fieldName, currentField, modelField);

    Class<?> fieldTypeOfFieldToSet = TypeUtils.determineTypeOfField(modelField);

    if (fieldTypeOfFieldToSet == String.class) {
        modelField.set(model, currentField.textValue());
    } else if (fieldTypeOfFieldToSet == int.class || fieldTypeOfFieldToSet == Integer.class) {
        modelField.set(model, currentField.intValue());
    }
}

From source file:org.sead.repositories.reference.RefRepository.java

private ObjectNode getChildren(ObjectNode resultNode, File indexFile, CountingInputStream cis, Long oreFileSize,
        long curPos, ArrayList<String> entries, ArrayList<Long> offsets)
        throws JsonParseException, JsonMappingException, IOException {

    ArrayList<String> childIds = new ArrayList<String>();
    JsonNode children = resultNode.get("Has Part");
    if (children.isArray()) {
        for (JsonNode child : children) {
            childIds.add(child.textValue());
        }// w ww .  ja  v  a2s. c  om
    } else {
        System.out.println("Has Part not an array");
        childIds.add(children.textValue());
    }
    ArrayNode aggregates = mapper.createArrayNode();
    for (String name : childIds) {
        aggregates.add(getItem(name, indexFile, cis, false, oreFileSize, curPos, entries, offsets));
        curPos = cis.getByteCount();
        log.trace("curPos updated to " + curPos + " after reading: " + name);

    }
    log.trace("Child Ids: " + childIds.toString());
    resultNode.set("aggregates", aggregates);
    return resultNode;

}

From source file:com.alliander.osgp.shared.usermanagement.KeycloakClient.java

private void initializeToken() throws KeycloakClientException {

    final Form form = new Form().param("grant_type", "password").param("username", this.apiUser)
            .param("password", this.apiPassword).param("client_id", this.apiClient)
            .param("client_secret", this.apiClientSecret);

    LOGGER.info("Initializing Keycloak API bearer token for client '{}' and realm '{}'.", this.apiClient,
            this.realm);

    final Response response = this.getWebClientInstance().path(this.tokenPath).form(form);
    final JsonNode jsonNode = this.getJsonResponseBody(response);

    final JsonNode accessToken = jsonNode.get("access_token");

    if (accessToken == null || !accessToken.isTextual()) {
        throw new KeycloakClientException(
                "Keycloak API access token response does not contain a JSON text field 'access_token'.");
    }/*from  ww w  .j ava2s.c om*/

    this.currentToken = accessToken.textValue();
}

From source file:com.alliander.osgp.shared.usermanagement.KeycloakClient.java

private void checkForError(final JsonNode jsonNode) throws KeycloakClientException {

    final JsonNode error = jsonNode.get("error");
    final JsonNode errorDescription = jsonNode.get("error_description");

    if (error != null || errorDescription != null) {
        final StringBuilder errorBuilder = new StringBuilder();
        if (error != null && error.isTextual()) {
            errorBuilder.append("error: ").append(error.textValue());
        }//from ww w  .j ava  2  s.c  om
        if (errorDescription != null && errorDescription.isTextual()) {
            if (errorBuilder.length() != 0) {
                errorBuilder.append(", ");
            }
            errorBuilder.append("description: ").append(errorDescription.textValue());
        }
        throw new KeycloakClientException(
                "Keycloak API call returned " + (errorBuilder.length() == 0 ? "error" : errorBuilder));
    }
}