Example usage for org.springframework.http HttpHeaders put

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

Introduction

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

Prototype

@Override
    public List<String> put(String key, List<String> value) 

Source Link

Usage

From source file:be.solidx.hot.rest.RestController.java

protected HttpHeaders buildHttpHeaders(Map headers) {
    HttpHeaders httpHeaders = new HttpHeaders();

    if (headers == null) {
        return httpHeaders;
    }/*www.j  a  v a 2  s.  com*/
    for (Object objectKey : headers.keySet()) {
        if (!(objectKey instanceof String)) {
            String error = "HTTP Headers map returned by script contains keys that are not String";
            logger.error(error);
            throw new ScriptException(error);
        }
        String key = (String) objectKey;
        Object objectValue = headers.get(objectKey);
        if (objectValue instanceof String) {
            String value = (String) objectValue;
            String[] scSplittedValues = value.split(",");
            httpHeaders.put(key, Lists.newArrayList(scSplittedValues));
        } else if (objectValue instanceof List) {
            List<?> objectValues = (List<?>) objectValue;
            List<String> values = new ArrayList<String>();
            for (Object elem : objectValues) {
                if (!(elem instanceof String)) {
                    String error = "HTTP Headers map returned by script contains values that are not String [key="
                            + key + "]";
                    logger.error(error);
                    throw new ScriptException(error);
                }
                values.add((String) elem);
            }
            httpHeaders.put(key, values);
        }
    }
    return httpHeaders;
}

From source file:com.orange.ngsi2.server.Ngsi2BaseController.java

private HttpHeaders locationHeader(String entityId) {
    HttpHeaders headers = new HttpHeaders();
    headers.put("Location", Collections.singletonList("/v2/entities/" + entityId));
    return headers;
}

From source file:com.orange.ngsi2.server.Ngsi2BaseController.java

private HttpHeaders xTotalCountHeader(int countNumber) {
    HttpHeaders headers = new HttpHeaders();
    headers.put("X-Total-Count", Collections.singletonList(Integer.toString(countNumber)));
    return headers;
}

From source file:io.github.microcks.web.RestController.java

@RequestMapping(value = "/{service}/{version}/**")
public ResponseEntity<?> execute(@PathVariable("service") String serviceName,
        @PathVariable("version") String version, @RequestParam(value = "delay", required = false) Long delay,
        @RequestBody(required = false) String body, HttpServletRequest request) {

    log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}", serviceName, version,
            request.getRequestURI(), request.getMethod());
    log.debug("Request body: " + body);

    long startTime = System.currentTimeMillis();

    // Extract resourcePath for matching with correct operation.
    String requestURI = request.getRequestURI();
    String serviceAndVersion = null;
    String resourcePath = null;//from  w  ww  .  ja  va2s.c  o m

    try {
        // Build the encoded URI fragment to retrieve simple resourcePath.
        serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version;
        resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length());
    } catch (UnsupportedEncodingException e1) {
        return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    log.info("Found resourcePath: " + resourcePath);

    Service service = serviceRepository.findByNameAndVersion(serviceName, version);
    Operation rOperation = null;
    for (Operation operation : service.getOperations()) {
        // Select operation based onto Http verb (GET, POST, PUT, etc ...)
        if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
            // ... then check is we have a matching resource path.
            if (operation.getResourcePaths().contains(resourcePath)) {
                rOperation = operation;
                break;
            }
        }
    }

    if (rOperation != null) {
        log.debug("Found a valid operation {} with rules: {}", rOperation.getName(),
                rOperation.getDispatcherRules());

        Response response = null;
        String uriPattern = getURIPattern(rOperation.getName());
        String dispatchCriteria = null;

        // Depending on dispatcher, evaluate request with rules.
        if (DispatchStyles.SEQUENCE.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) {
            ScriptEngineManager sem = new ScriptEngineManager();
            try {
                // Evaluating request with script coming from operation dispatcher rules.
                ScriptEngine se = sem.getEngineByExtension("groovy");
                SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request);
                dispatchCriteria = (String) se.eval(rOperation.getDispatcherRules());
            } catch (Exception e) {
                log.error("Error during Script evaluation", e);
            }
        }
        // New cases related to services/operations/messages coming from a postman collection file.
        else if (DispatchStyles.URI_PARAMS.equals(rOperation.getDispatcher())) {
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        } else if (DispatchStyles.URI_PARTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.URI_ELEMENTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        }

        log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
        List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(
                IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
        if (!responses.isEmpty()) {
            response = responses.get(0);
        }

        if (response != null) {
            // Setting delay to default one if not set.
            if (delay == null && rOperation.getDefaultDelay() != null) {
                delay = rOperation.getDefaultDelay();
            }

            if (delay != null && delay > -1) {
                log.debug("Mock delay is turned on, waiting if necessary...");
                long duration = System.currentTimeMillis() - startTime;
                if (duration < delay) {
                    Object semaphore = new Object();
                    synchronized (semaphore) {
                        try {
                            semaphore.wait(delay - duration);
                        } catch (Exception e) {
                            log.debug("Delay semaphore was interrupted");
                        }
                    }
                }
                log.debug("Delay now expired, releasing response !");
            }

            // Publish an invocation event before returning.
            MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version,
                    response.getName(), new Date(startTime), startTime - System.currentTimeMillis());
            applicationContext.publishEvent(event);
            log.debug("Mock invocation event has been published");

            HttpStatus status = (response.getStatus() != null
                    ? HttpStatus.valueOf(Integer.parseInt(response.getStatus()))
                    : HttpStatus.OK);

            // Deal with specific headers (content-type and redirect directive).
            HttpHeaders responseHeaders = new HttpHeaders();
            if (response.getMediaType() != null) {
                responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8"));
            }

            // Adding other generic headers (caching directives and so on...)
            if (response.getHeaders() != null) {
                for (Header header : response.getHeaders()) {
                    if ("Location".equals(header.getName())) {
                        // We should process location in order to make relative URI specified an absolute one from
                        // the client perspective.
                        String location = "http://" + request.getServerName() + ":" + request.getServerPort()
                                + request.getContextPath() + "/rest" + serviceAndVersion
                                + header.getValues().iterator().next();
                        responseHeaders.add(header.getName(), location);
                    } else {
                        if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) {
                            responseHeaders.put(header.getName(), new ArrayList<>(header.getValues()));
                        }
                    }
                }
            }
            return new ResponseEntity<Object>(response.getContent(), responseHeaders, status);
        }
        return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}

From source file:net.paslavsky.springrest.HttpHeadersHelper.java

public HttpHeaders getHttpHeaders(Map<String, Integer> headerParameters, Object[] arguments) {
    HttpHeaders headers = new HttpHeaders();
    for (String headerName : headerParameters.keySet()) {
        Object headerValue = arguments[headerParameters.get(headerName)];
        if (headerValue != null) {
            if (ACCEPT.equalsIgnoreCase(headerName)) {
                headers.setAccept(toList(headerValue, MediaType.class));
            } else if (ACCEPT_CHARSET.equalsIgnoreCase(headerName)) {
                headers.setAcceptCharset(toList(headerValue, Charset.class));
            } else if (ALLOW.equalsIgnoreCase(headerName)) {
                headers.setAllow(toSet(headerValue, HttpMethod.class));
            } else if (CONNECTION.equalsIgnoreCase(headerName)) {
                headers.setConnection(toList(headerValue, String.class));
            } else if (CONTENT_DISPOSITION.equalsIgnoreCase(headerName)) {
                setContentDisposition(headers, headerName, headerValue);
            } else if (CONTENT_LENGTH.equalsIgnoreCase(headerName)) {
                headers.setContentLength(toLong(headerValue));
            } else if (CONTENT_TYPE.equalsIgnoreCase(headerName)) {
                headers.setContentType(toMediaType(headerValue));
            } else if (DATE.equalsIgnoreCase(headerName)) {
                headers.setDate(toLong(headerValue));
            } else if (ETAG.equalsIgnoreCase(headerName)) {
                headers.setETag(toString(headerValue));
            } else if (EXPIRES.equalsIgnoreCase(headerName)) {
                headers.setExpires(toLong(headerValue));
            } else if (IF_MODIFIED_SINCE.equalsIgnoreCase(headerName)) {
                headers.setIfModifiedSince(toLong(headerValue));
            } else if (IF_NONE_MATCH.equalsIgnoreCase(headerName)) {
                headers.setIfNoneMatch(toList(headerValue, String.class));
            } else if (LAST_MODIFIED.equalsIgnoreCase(headerName)) {
                headers.setLastModified(toLong(headerValue));
            } else if (LOCATION.equalsIgnoreCase(headerName)) {
                headers.setLocation(toURI(headerValue));
            } else if (ORIGIN.equalsIgnoreCase(headerName)) {
                headers.setOrigin(toString(headerValue));
            } else if (PRAGMA.equalsIgnoreCase(headerName)) {
                headers.setPragma(toString(headerValue));
            } else if (UPGRADE.equalsIgnoreCase(headerName)) {
                headers.setUpgrade(toString(headerValue));
            } else if (headerValue instanceof String) {
                headers.set(headerName, (String) headerValue);
            } else if (headerValue instanceof String[]) {
                headers.put(headerName, Arrays.asList((String[]) headerValue));
            } else if (instanceOf(headerValue, String.class)) {
                headers.put(headerName, toList(headerValue, String.class));
            } else {
                headers.set(headerName, conversionService.convert(headerValue, String.class));
            }/*from   w  ww.ja  va2  s .com*/
        }
    }
    return headers;
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

@SuppressWarnings("unchecked")
@Override/*from  ww w.  j av a  2s  .c  o m*/
public Map<String, Object> loginForClient(String username, String password, String clientId,
        UriComponents inUrlComponents) {
    final Map<String, Object> responsePayload = new HashMap<String, Object>();

    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

    final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer());

    // login for csrf
    final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("login").build();

    ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.GET, null, headers,
            String.class);

    final List<String> cookies = new ArrayList<String>();
    cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE));

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", username);
    formData.add("password", password);
    formData.add(CSRF, getCsrf(cookies));

    headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies));
    headers.add(HttpHeaders.REFERER, loginUri.toUriString());

    // login.do
    response = exchangeForType(uriBuilder.cloneBuilder().pathSegment("login.do").build().toUriString(),
            HttpMethod.POST, formData, headers, String.class);

    if (response.getStatusCode() != HttpStatus.FOUND
            || response.getHeaders().getFirst(HttpHeaders.LOCATION).contains("login")) {
        responsePayload.put("error", "bad credentials");
        return responsePayload;
    }

    removeCookie(cookies, "X-Uaa-Csrf");
    cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE));
    removeExpiredCookies(cookies);
    headers.remove(HttpHeaders.REFERER);
    headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies));

    // authorize
    final ResponseEntity<JsonNode> authResponse = exchangeForType(
            uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize")
                    .queryParam("response_type", "code").queryParam("client_id", clientId)
                    .queryParam("redirect_uri", inUrlComponents.toUriString()).build().toUriString(),
            HttpMethod.GET, null, headers, JsonNode.class);

    if (authResponse.getStatusCode() == HttpStatus.OK) {
        removeCookie(cookies, "X-Uaa-Csrf");
        cookies.addAll(authResponse.getHeaders().get(HttpHeaders.SET_COOKIE));
        // return approval data
        final List<HttpCookie> parsedCookies = new ArrayList<HttpCookie>();

        for (final String cookie : cookies) {
            parsedCookies.add(HttpCookie.parse(cookie).get(0));
        }

        responsePayload.put(HttpHeaders.SET_COOKIE, new ArrayList<String>());

        for (final HttpCookie parsedCookie : parsedCookies) {
            if (!parsedCookie.getName().startsWith("Saved-Account")) {
                parsedCookie.setPath(inUrlComponents.getPath());
                ((List<String>) responsePayload.get(HttpHeaders.SET_COOKIE))
                        .add(httpCookieToString(parsedCookie));
            }
        }

        responsePayload.put("json", authResponse.getBody());
    } else {
        // get auth_code from Location Header
        responsePayload.put("code", authResponse.getHeaders().getLocation().getQuery().split("=")[1]);
    }

    return responsePayload;
}

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;/*  w w  w  .  j a v a2  s.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 {// w  ww. j  a  v  a 2s  .  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.j a v a  2s . 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.http.server.reactive.UndertowServerHttpRequest.java

private static HttpHeaders initHeaders(HttpServerExchange exchange) {
    HttpHeaders headers = new HttpHeaders();
    for (HeaderValues values : exchange.getRequestHeaders()) {
        headers.put(values.getHeaderName().toString(), values);
    }// w w w .jav a2s . c o m
    return headers;
}