Example usage for org.springframework.http HttpHeaders set

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:business.services.FileService.java

public HttpEntity<InputStreamResource> downloadAccessLog(String filename,
        boolean writeContentDispositionHeader) {
    try {/*  w  w  w. java 2  s. c o m*/
        FileSystem fileSystem = FileSystems.getDefault();
        Path path = fileSystem.getPath(accessLogsPath).normalize();
        filename = filename.replace(fileSystem.getSeparator(), "_");
        filename = URLEncoder.encode(filename, "utf-8");

        Path f = fileSystem.getPath(accessLogsPath, filename).normalize();
        // filter path names that point to places outside the logs path.
        // E.g., to prevent that in cases where clients use '../' in the filename
        // arbitrary locations are reachable.
        if (!Files.isSameFile(path, f.getParent())) {
            // Path f is not in the upload path. Maybe 'name' contains '..'?
            log.error("Invalid filename: " + filename);
            throw new FileDownloadError("Invalid file name");
        }
        if (!Files.isReadable(f)) {
            log.error("File does not exist: " + filename);
            throw new FileDownloadError("File does not exist");
        }

        InputStream input = new FileInputStream(f.toFile());
        InputStreamResource resource = new InputStreamResource(input);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        if (writeContentDispositionHeader) {
            headers.set("Content-Disposition", "attachment; filename=" + filename.replace(" ", "_"));
        }
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        return response;
    } catch (IOException e) {
        log.error(e);
        throw new FileDownloadError();
    }
}

From source file:com.ge.predix.acceptance.test.zone.admin.ZoneEnforcementStepsDefinitions.java

@When("^client_two does a GET on (.*?) with (.*?) in zone (.*?)$")
public void client_two_does_a_GET_on_subject_with_subject_id__in_zone(final String api, final String identifier,
        final String subdomainSuffix) throws Throwable {

    OAuth2RestTemplate acsTemplate = this.acsZone2Template;
    String encodedIdentifier = URLEncoder.encode(identifier, "UTF-8");
    HttpHeaders zoneHeaders = new HttpHeaders();
    // differentiate between zone 1 and zone 2, which will have slightly different uris
    zoneHeaders.set(PolicyHelper.PREDIX_ZONE_ID, getZoneName(subdomainSuffix));

    URI uri = URI.create(this.acsUrl + ACS_VERSION + "/" + api + "/" + encodedIdentifier);
    try {/*from   w  w  w  . j av a  2 s .  co  m*/
        switch (api) {
        case "subject":
            this.responseEntity = acsTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<>(zoneHeaders),
                    BaseSubject.class);
            this.status = this.responseEntity.getStatusCode().value();
            break;
        case "resource":
            this.responseEntityForResource = acsTemplate.exchange(uri, HttpMethod.GET,
                    new HttpEntity<>(zoneHeaders), BaseResource.class);
            this.status = this.responseEntityForResource.getStatusCode().value();
            break;
        case "policy-set":
            this.policyset = acsTemplate.exchange(
                    this.acsUrl + PolicyHelper.ACS_POLICY_SET_API_PATH + this.testPolicyName, HttpMethod.GET,
                    new HttpEntity<>(zoneHeaders), PolicySet.class);
            this.status = this.policyset.getStatusCode().value();
            break;
        default:
            Assert.fail("Api " + api + " does not match/is not yet implemented for this test code.");
        }
    } catch (OAuth2Exception e) {
        this.status = e.getHttpErrorCode();
    }
}

From source file:org.cloudfoundry.identity.uaa.login.feature.OpenIdTokenGrantsIT.java

@Test
public void testPasswordGrant() throws Exception {
    String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64(("cf:").getBytes()));

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.set("Authorization", basicDigestHeaderValue);

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("grant_type", "password");
    postBody.add("username", user.getUserName());
    postBody.add("password", "secret");

    ResponseEntity<Map> responseEntity = restOperations.exchange(loginUrl + "/oauth/token", HttpMethod.POST,
            new HttpEntity<>(postBody, headers), Map.class);

    Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode());

    Map<String, Object> params = responseEntity.getBody();

    Assert.assertTrue(params.get("jti") != null);
    Assert.assertEquals("bearer", params.get("token_type"));
    Assert.assertThat((Integer) params.get("expires_in"), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode((String) params.get("scope"), "UTF-8").split(" ");
    Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write",
            "cloud_controller.write", "openid", "cloud_controller.read"));

    validateToken("access_token", params, scopes);
    validateToken("id_token", params, scopes);
}

From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java

private HttpHeaders getAuthenticatedHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    headers.set("Authorization", "Basic " + new String(Base64.encode("user:password".getBytes())));
    if (context.getRestTemplate() != null) {
        context.getAccessTokenRequest().setHeaders(headers);
    }/*from  w  w w .jav  a  2 s  .  co m*/
    return headers;
}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

/**
 * <pre>/*from  w  w  w .j  a v  a2s  .c  o  m*/
 * HTTP Header? ??  ?.
 * </pre>
 * @return
 */
private HttpEntity<Object> setHTTPEntity(Object body, String rootElementName) {
    List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
    acceptableMediaTypes.add(MediaType.APPLICATION_XML);

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_XML);
    requestHeaders.setAccept(acceptableMediaTypes);
    requestHeaders.set(HOST_HEADER_KEY, host);
    requestHeaders.set(AUTH_HEADER_KEY, getCredential());

    if (body != null) {
        logger.debug("Content Body => {}", marshal(body, rootElementName));
        return new HttpEntity<Object>(marshal(body, rootElementName), requestHeaders);
    } else {
        return new HttpEntity<Object>(requestHeaders);
    }
}

From source file:com.jvoid.core.controller.HomeController.java

@RequestMapping(value = "/login", method = RequestMethod.POST)
public @ResponseBody String loginToJvoid(
        @RequestParam(required = false, value = "params") JSONObject jsonParams) {
    System.out.println("Login:jsonParams=>" + jsonParams.toString());

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(ServerUris.CUSTOMER_SERVER_URI + URIConstants.GET_CUSTOMER_BY_EMAIL)
            .queryParam("params", jsonParams);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity,
            String.class);
    return returnString.getBody();
}

From source file:com.jvoid.core.controller.HomeController.java

@RequestMapping(value = "/password-reset", method = RequestMethod.POST)
public @ResponseBody String jvoidResetPAssword(
        @RequestParam(required = false, value = "params") JSONObject jsonParams) {
    System.out.println("Login:jsonParams=>" + jsonParams.toString());

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(ServerUris.CUSTOMER_SERVER_URI + URIConstants.RESET_CUSTOMER_PASSWORD)
            .queryParam("params", jsonParams);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity,
            String.class);
    return returnString.getBody();
}

From source file:com.jvoid.core.controller.HomeController.java

@RequestMapping("/cart")
public @ResponseBody String getCartById(@RequestParam("cartId") String cartId) {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

    JSONObject jsonObj = new JSONObject();
    try {//from   ww w.j a  v  a  2  s. c  om
        jsonObj.put("cartId", Integer.parseInt(cartId));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("param jsonObj=>" + jsonObj.toString());

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(ServerUris.QUOTE_SERVER_URI + URIConstants.GET_CART).queryParam("params", jsonObj);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity,
            String.class);
    return returnString.getBody();
}

From source file:com.jvoid.core.controller.HomeController.java

@RequestMapping("/remove-cart")
public @ResponseBody String removeItemsFromCartById(@RequestParam("cartId") String cartId,
        @RequestParam("prodId") String prodId) {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

    JSONObject jsonObj = new JSONObject();
    try {// w  ww.  j  av  a  2 s .  c o m
        jsonObj.put("cartId", Integer.parseInt(cartId));
        jsonObj.put("productId", Integer.parseInt(prodId));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("param jsonObj=>" + jsonObj.toString());

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(ServerUris.QUOTE_SERVER_URI + URIConstants.DELETE_CART).queryParam("params", jsonObj);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity,
            String.class);
    return returnString.getBody();
}