Example usage for org.springframework.http HttpHeaders add

List of usage examples for org.springframework.http HttpHeaders add

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders add.

Prototype

@Override
public void add(String headerName, @Nullable String headerValue) 

Source Link

Document

Add the given, single header value under the given name.

Usage

From source file:org.springframework.cloud.config.client.ConfigServicePropertySourceLocator.java

private Environment getRemoteEnvironment(RestTemplate restTemplate, ConfigClientProperties properties,
        String label, String state) {
    String path = "/{name}/{profile}";
    String name = properties.getName();
    String profile = properties.getProfile();
    String token = properties.getToken();
    String uri = properties.getRawUri();

    Object[] args = new String[] { name, profile };
    if (StringUtils.hasText(label)) {
        args = new String[] { name, profile, label };
        path = path + "/{label}";
    }//from  w w w.  ja  va  2 s  .  co  m
    ResponseEntity<Environment> response = null;

    try {
        HttpHeaders headers = new HttpHeaders();
        if (StringUtils.hasText(token)) {
            headers.add(TOKEN_HEADER, token);
        }
        if (StringUtils.hasText(state)) { //TODO: opt in to sending state?
            headers.add(STATE_HEADER, state);
        }
        final HttpEntity<Void> entity = new HttpEntity<>((Void) null, headers);
        response = restTemplate.exchange(uri + path, HttpMethod.GET, entity, Environment.class, args);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() != HttpStatus.NOT_FOUND) {
            throw e;
        }
    }

    if (response == null || response.getStatusCode() != HttpStatus.OK) {
        return null;
    }
    Environment result = response.getBody();
    return result;
}

From source file:org.springframework.cloud.config.server.environment.VaultEnvironmentRepository.java

String read(String key) {
    String url = String.format("%s://%s:%s/v1/{backend}/{key}", this.scheme, this.host, this.port);

    HttpHeaders headers = new HttpHeaders();

    String token = request.getHeader(TOKEN_HEADER);
    if (!StringUtils.hasLength(token)) {
        throw new IllegalArgumentException("Missing required header: " + TOKEN_HEADER);
    }/*from  www.  j  a  v a2  s.c  o  m*/
    headers.add(VAULT_TOKEN, token);
    try {
        ResponseEntity<VaultResponse> response = this.rest.exchange(url, HttpMethod.GET,
                new HttpEntity<>(headers), VaultResponse.class, this.backend, key);

        HttpStatus status = response.getStatusCode();
        if (status == HttpStatus.OK) {
            return response.getBody().getData();
        }
    } catch (HttpStatusCodeException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            return null;
        }
        throw e;
    }

    return null;
}

From source file:org.springframework.cloud.dataflow.server.service.impl.validation.DockerRegistryValidator.java

/**
 * Verifies that the image is present./*w  ww  .jav  a 2s.c  o m*/
 *JobDependencies.java
 * @return true if image is present.
 */
public boolean isImagePresent() {
    boolean result = false;
    try {
        String resourceTag = this.appResourceCommon.getResourceVersion(this.dockerResource);
        HttpHeaders headers = new HttpHeaders();
        if (this.dockerAuth != null) {
            headers.add(HttpHeaders.AUTHORIZATION,
                    DOCKER_REGISTRY_AUTH_TYPE + " " + this.dockerAuth.getToken());
        }
        HttpEntity<String> httpEntity = new HttpEntity<>(headers);
        String endpointUrl = getDockerTagsEndpointUrl();
        do {
            ResponseEntity tags = this.restTemplate.exchange(endpointUrl, HttpMethod.GET, httpEntity,
                    DockerResult.class);
            DockerResult dockerResult = (DockerResult) tags.getBody();
            for (DockerTag dockerTag : dockerResult.getResults()) {
                if (dockerTag.getName().equals(resourceTag)) {
                    result = true;
                    break;
                }
            }
            endpointUrl = dockerResult.getNext();
        } while (result == false && endpointUrl != null);
    } catch (HttpClientErrorException hcee) {
        //when attempting to access an invalid docker image or if you
        //don't have proper credentials docker returns a 404.
        logger.info("Unable to find image because of the following exception:", hcee);
        result = false;
    }
    return result;
}

From source file:org.springframework.cloud.gateway.test.websocket.WebSocketIntegrationTests.java

@Test
public void customHeader() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.add("my-header", "my-value");
    MonoProcessor<Object> output = MonoProcessor.create();

    client.execute(getUrl("/custom-header"), headers,
            session -> session.receive().map(WebSocketMessage::getPayloadAsText).subscribeWith(output).then())
            .block(Duration.ofMillis(5000));

    assertThat(output.block(Duration.ofMillis(5000))).isEqualTo("my-header:my-value");
}

From source file:org.springframework.cloud.netflix.eureka.http.RestTemplateEurekaHttpClient.java

@Override
public EurekaHttpResponse<Void> register(InstanceInfo info) {
    String urlPath = serviceUrl + "apps/" + info.getAppName();

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.ACCEPT_ENCODING, "gzip");
    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

    ResponseEntity<Void> response = restTemplate.exchange(urlPath, HttpMethod.POST,
            new HttpEntity<InstanceInfo>(info, headers), Void.class);

    return anEurekaHttpResponse(response.getStatusCodeValue()).headers(headersOf(response)).build();
}

From source file:org.springframework.cloud.stream.app.http.source.DefaultMixedCaseContentTypeHttpHeaderMapper.java

private void setHttpHeader(HttpHeaders target, String name, Object value) {
    if (ACCEPT.equalsIgnoreCase(name)) {
        if (value instanceof Collection<?>) {
            Collection<?> values = (Collection<?>) value;
            if (!CollectionUtils.isEmpty(values)) {
                List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
                for (Object type : values) {
                    if (type instanceof MediaType) {
                        acceptableMediaTypes.add((MediaType) type);
                    } else if (type instanceof String) {
                        acceptableMediaTypes.addAll(MediaType.parseMediaTypes((String) type));
                    } else {
                        Class<?> clazz = (type != null) ? type.getClass() : null;
                        throw new IllegalArgumentException(
                                "Expected MediaType or String value for 'Accept' header value, but received: "
                                        + clazz);
                    }//from www  .  ja va2  s. c o  m
                }
                target.setAccept(acceptableMediaTypes);
            }
        } else if (value instanceof MediaType) {
            target.setAccept(Collections.singletonList((MediaType) value));
        } else if (value instanceof String[]) {
            List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
            for (String next : (String[]) value) {
                acceptableMediaTypes.add(MediaType.parseMediaType(next));
            }
            target.setAccept(acceptableMediaTypes);
        } else if (value instanceof String) {
            target.setAccept(MediaType.parseMediaTypes((String) value));
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected MediaType or String value for 'Accept' header value, but received: " + clazz);
        }
    } else if (ACCEPT_CHARSET.equalsIgnoreCase(name)) {
        if (value instanceof Collection<?>) {
            Collection<?> values = (Collection<?>) value;
            if (!CollectionUtils.isEmpty(values)) {
                List<Charset> acceptableCharsets = new ArrayList<Charset>();
                for (Object charset : values) {
                    if (charset instanceof Charset) {
                        acceptableCharsets.add((Charset) charset);
                    } else if (charset instanceof String) {
                        acceptableCharsets.add(Charset.forName((String) charset));
                    } else {
                        Class<?> clazz = (charset != null) ? charset.getClass() : null;
                        throw new IllegalArgumentException(
                                "Expected Charset or String value for 'Accept-Charset' header value, but received: "
                                        + clazz);
                    }
                }
                target.setAcceptCharset(acceptableCharsets);
            }
        } else if (value instanceof Charset[] || value instanceof String[]) {
            List<Charset> acceptableCharsets = new ArrayList<Charset>();
            Object[] values = ObjectUtils.toObjectArray(value);
            for (Object charset : values) {
                if (charset instanceof Charset) {
                    acceptableCharsets.add((Charset) charset);
                } else if (charset instanceof String) {
                    acceptableCharsets.add(Charset.forName((String) charset));
                }
            }
            target.setAcceptCharset(acceptableCharsets);
        } else if (value instanceof Charset) {
            target.setAcceptCharset(Collections.singletonList((Charset) value));
        } else if (value instanceof String) {
            String[] charsets = StringUtils.commaDelimitedListToStringArray((String) value);
            List<Charset> acceptableCharsets = new ArrayList<Charset>();
            for (String charset : charsets) {
                acceptableCharsets.add(Charset.forName(charset.trim()));
            }
            target.setAcceptCharset(acceptableCharsets);
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Charset or String value for 'Accept-Charset' header value, but received: "
                            + clazz);
        }
    } else if (ALLOW.equalsIgnoreCase(name)) {
        if (value instanceof Collection<?>) {
            Collection<?> values = (Collection<?>) value;
            if (!CollectionUtils.isEmpty(values)) {
                Set<HttpMethod> allowedMethods = new HashSet<HttpMethod>();
                for (Object method : values) {
                    if (method instanceof HttpMethod) {
                        allowedMethods.add((HttpMethod) method);
                    } else if (method instanceof String) {
                        allowedMethods.add(HttpMethod.valueOf((String) method));
                    } else {
                        Class<?> clazz = (method != null) ? method.getClass() : null;
                        throw new IllegalArgumentException(
                                "Expected HttpMethod or String value for 'Allow' header value, but received: "
                                        + clazz);
                    }
                }
                target.setAllow(allowedMethods);
            }
        } else {
            if (value instanceof HttpMethod) {
                target.setAllow(Collections.singleton((HttpMethod) value));
            } else if (value instanceof HttpMethod[]) {
                Set<HttpMethod> allowedMethods = new HashSet<HttpMethod>();
                Collections.addAll(allowedMethods, (HttpMethod[]) value);
                target.setAllow(allowedMethods);
            } else if (value instanceof String || value instanceof String[]) {
                String[] values = (value instanceof String[]) ? (String[]) value
                        : StringUtils.commaDelimitedListToStringArray((String) value);
                Set<HttpMethod> allowedMethods = new HashSet<HttpMethod>();
                for (String next : values) {
                    allowedMethods.add(HttpMethod.valueOf(next.trim()));
                }
                target.setAllow(allowedMethods);
            } else {
                Class<?> clazz = (value != null) ? value.getClass() : null;
                throw new IllegalArgumentException(
                        "Expected HttpMethod or String value for 'Allow' header value, but received: " + clazz);
            }
        }
    } else if (CACHE_CONTROL.equalsIgnoreCase(name)) {
        if (value instanceof String) {
            target.setCacheControl((String) value);
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected String value for 'Cache-Control' header value, but received: " + clazz);
        }
    } else if (CONTENT_LENGTH.equalsIgnoreCase(name)) {
        if (value instanceof Number) {
            target.setContentLength(((Number) value).longValue());
        } else if (value instanceof String) {
            target.setContentLength(Long.parseLong((String) value));
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Number or String value for 'Content-Length' header value, but received: "
                            + clazz);
        }
    } else if (MessageHeaders.CONTENT_TYPE.equalsIgnoreCase(name)) {
        if (value instanceof MediaType) {
            target.setContentType((MediaType) value);
        } else if (value instanceof String) {
            target.setContentType(MediaType.parseMediaType((String) value));
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected MediaType or String value for 'Content-Type' header value, but received: "
                            + clazz);
        }
    } else if (DATE.equalsIgnoreCase(name)) {
        if (value instanceof Date) {
            target.setDate(((Date) value).getTime());
        } else if (value instanceof Number) {
            target.setDate(((Number) value).longValue());
        } else if (value instanceof String) {
            try {
                target.setDate(Long.parseLong((String) value));
            } catch (NumberFormatException e) {
                target.setDate(this.getFirstDate((String) value, DATE));
            }
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Date, Number, or String value for 'Date' header value, but received: " + clazz);
        }
    } else if (ETAG.equalsIgnoreCase(name)) {
        if (value instanceof String) {
            target.setETag((String) value);
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected String value for 'ETag' header value, but received: " + clazz);
        }
    } else if (EXPIRES.equalsIgnoreCase(name)) {
        if (value instanceof Date) {
            target.setExpires(((Date) value).getTime());
        } else if (value instanceof Number) {
            target.setExpires(((Number) value).longValue());
        } else if (value instanceof String) {
            try {
                target.setExpires(Long.parseLong((String) value));
            } catch (NumberFormatException e) {
                target.setExpires(this.getFirstDate((String) value, EXPIRES));
            }
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Date, Number, or String value for 'Expires' header value, but received: "
                            + clazz);
        }
    } else if (IF_MODIFIED_SINCE.equalsIgnoreCase(name)) {
        if (value instanceof Date) {
            target.setIfModifiedSince(((Date) value).getTime());
        } else if (value instanceof Number) {
            target.setIfModifiedSince(((Number) value).longValue());
        } else if (value instanceof String) {
            try {
                target.setIfModifiedSince(Long.parseLong((String) value));
            } catch (NumberFormatException e) {
                target.setIfModifiedSince(this.getFirstDate((String) value, IF_MODIFIED_SINCE));
            }
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Date, Number, or String value for 'If-Modified-Since' header value, but received: "
                            + clazz);
        }
    } else if (IF_UNMODIFIED_SINCE.equalsIgnoreCase(name)) {
        String ifUnmodifiedSinceValue = null;
        if (value instanceof Date) {
            ifUnmodifiedSinceValue = this.formatDate(((Date) value).getTime());
        } else if (value instanceof Number) {
            ifUnmodifiedSinceValue = this.formatDate(((Number) value).longValue());
        } else if (value instanceof String) {
            try {
                ifUnmodifiedSinceValue = this.formatDate(Long.parseLong((String) value));
            } catch (NumberFormatException e) {
                long longValue = this.getFirstDate((String) value, IF_UNMODIFIED_SINCE);
                ifUnmodifiedSinceValue = this.formatDate(longValue);
            }
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Date, Number, or String value for 'If-Unmodified-Since' header value, but received: "
                            + clazz);
        }
        target.set(IF_UNMODIFIED_SINCE, ifUnmodifiedSinceValue);
    } else if (IF_NONE_MATCH.equalsIgnoreCase(name)) {
        if (value instanceof String) {
            target.setIfNoneMatch((String) value);
        } else if (value instanceof String[]) {
            String delmitedString = StringUtils.arrayToCommaDelimitedString((String[]) value);
            target.setIfNoneMatch(delmitedString);
        } else if (value instanceof Collection) {
            Collection<?> values = (Collection<?>) value;
            if (!CollectionUtils.isEmpty(values)) {
                List<String> ifNoneMatchList = new ArrayList<String>();
                for (Object next : values) {
                    if (next instanceof String) {
                        ifNoneMatchList.add((String) next);
                    } else {
                        Class<?> clazz = (next != null) ? next.getClass() : null;
                        throw new IllegalArgumentException(
                                "Expected String value for 'If-None-Match' header value, but received: "
                                        + clazz);
                    }
                }
                target.setIfNoneMatch(ifNoneMatchList);
            }
        }
    } else if (LAST_MODIFIED.equalsIgnoreCase(name)) {
        if (value instanceof Date) {
            target.setLastModified(((Date) value).getTime());
        } else if (value instanceof Number) {
            target.setLastModified(((Number) value).longValue());
        } else if (value instanceof String) {
            try {
                target.setLastModified(Long.parseLong((String) value));
            } catch (NumberFormatException e) {
                target.setLastModified(this.getFirstDate((String) value, LAST_MODIFIED));
            }
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Date, Number, or String value for 'Last-Modified' header value, but received: "
                            + clazz);
        }
    } else if (LOCATION.equalsIgnoreCase(name)) {
        if (value instanceof URI) {
            target.setLocation((URI) value);
        } else if (value instanceof String) {
            try {
                target.setLocation(new URI((String) value));
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException(e);
            }
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected URI or String value for 'Location' header value, but received: " + clazz);
        }
    } else if (PRAGMA.equalsIgnoreCase(name)) {
        if (value instanceof String) {
            target.setPragma((String) value);
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected String value for 'Pragma' header value, but received: " + clazz);
        }
    } else if (value instanceof String) {
        target.set(name, (String) value);
    } else if (value instanceof String[]) {
        for (String next : (String[]) value) {
            target.add(name, next);
        }
    } else if (value instanceof Iterable<?>) {
        for (Object next : (Iterable<?>) value) {
            String convertedValue = null;
            if (next instanceof String) {
                convertedValue = (String) next;
            } else {
                convertedValue = this.convertToString(value);
            }
            if (StringUtils.hasText(convertedValue)) {
                target.add(name, convertedValue);
            } else {
                logger.warn("Element of the header '" + name + "' with value '" + value
                        + "' will not be set since it is not a String and no Converter is available. "
                        + "Consider registering a Converter with ConversionService (e.g., <int:converter>)");
            }
        }
    } else {
        String convertedValue = this.convertToString(value);
        if (StringUtils.hasText(convertedValue)) {
            target.set(name, convertedValue);
        } else {
            logger.warn("Header '" + name + "' with value '" + value
                    + "' will not be set since it is not a String and no Converter is available. "
                    + "Consider registering a Converter with ConversionService (e.g., <int:converter>)");
        }
    }
}

From source file:org.springframework.cloud.stream.schema.client.ConfluentSchemaRegistryClient.java

@Override
public SchemaRegistrationResponse register(String subject, String format, String schema) {
    Assert.isTrue("avro".equals(format), "Only Avro is supported");
    String path = String.format("/subjects/%s", subject);
    HttpHeaders headers = new HttpHeaders();
    headers.put("Accept", Arrays.asList("application/vnd.schemaregistry.v1+json",
            "application/vnd.schemaregistry+json", "application/json"));
    headers.add("Content-Type", "application/json");
    Integer version = null;//from   www  .  j a  va 2s  .  c  om
    try {
        String payload = this.mapper.writeValueAsString(Collections.singletonMap("schema", schema));
        HttpEntity<String> request = new HttpEntity<>(payload, headers);
        ResponseEntity<Map> response = this.template.exchange(this.endpoint + path, HttpMethod.POST, request,
                Map.class);
        version = (Integer) response.getBody().get("version");
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    SchemaRegistrationResponse schemaRegistrationResponse = new SchemaRegistrationResponse();
    schemaRegistrationResponse.setId(version);
    schemaRegistrationResponse.setSchemaReference(new SchemaReference(subject, version, "avro"));
    return schemaRegistrationResponse;
}

From source file:org.springframework.cloud.stream.schema.client.ConfluentSchemaRegistryClient.java

@Override
public String fetch(SchemaReference schemaReference) {
    String path = String.format("/subjects/%s/versions/%d", schemaReference.getSubject(),
            schemaReference.getVersion());
    HttpHeaders headers = new HttpHeaders();
    headers.put("Accept", Arrays.asList("application/vnd.schemaregistry.v1+json",
            "application/vnd.schemaregistry+json", "application/json"));
    headers.add("Content-Type", "application/vnd.schemaregistry.v1+json");
    HttpEntity<String> request = new HttpEntity<>("", headers);
    try {//from w ww  .  j  a v  a 2  s  . c  o m
        ResponseEntity<Map> response = this.template.exchange(this.endpoint + path, HttpMethod.GET, request,
                Map.class);
        return (String) response.getBody().get("schema");
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            throw new SchemaNotFoundException(
                    String.format("Could not find schema for reference: %s", schemaReference));
        } else {
            throw e;
        }
    }
}

From source file:org.springframework.cloud.stream.schema.client.ConfluentSchemaRegistryClient.java

@Override
public String fetch(int id) {
    String path = String.format("/schemas/ids/%d", id);
    HttpHeaders headers = new HttpHeaders();
    headers.put("Accept", Arrays.asList("application/vnd.schemaregistry.v1+json",
            "application/vnd.schemaregistry+json", "application/json"));
    headers.add("Content-Type", "application/vnd.schemaregistry.v1+json");
    HttpEntity<String> request = new HttpEntity<>("", headers);
    try {//  w w w.ja  v a2 s  .  co m
        ResponseEntity<Map> response = this.template.exchange(this.endpoint + path, HttpMethod.GET, request,
                Map.class);
        return (String) response.getBody().get("schema");
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            throw new SchemaNotFoundException(String.format("Could not find schema with id: %s", id));
        } else {
            throw e;
        }
    }
}

From source file:org.springframework.cloud.vault.util.PrepareVault.java

private HttpHeaders authenticatedHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.add(VaultClient.VAULT_TOKEN, rootToken.getToken());
    return headers;
}