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:org.energyos.espi.thirdparty.web.custodian.AdministratorController.java

@RequestMapping(value = Routes.ROOT_SERVICE_STATUS, method = RequestMethod.GET)
public String showServiceStatus(ModelMap model) {

    ApplicationInformation applicationInformation = resourceService.findById(1L, ApplicationInformation.class);
    String statusUri = applicationInformation.getAuthorizationServerAuthorizationEndpoint()
            + "/ReadServiceStatus";
    // not sure this will work w/o the right seed information
    ////from ww w . jav  a 2  s  .  c  o m
    Authorization authorization = resourceService.findByResourceUri(statusUri, Authorization.class);
    RetailCustomer retailCustomer = authorization.getRetailCustomer();

    String accessToken = authorization.getAccessToken();
    String serviceStatus = "OK";

    try {

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.set("Authorization", "Bearer " + accessToken);
        @SuppressWarnings({ "unchecked", "rawtypes" })
        HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);

        // get the subscription
        HttpEntity<String> httpResult = restTemplate.exchange(statusUri, HttpMethod.GET, requestEntity,
                String.class);

        // import it into the repository
        ByteArrayInputStream bs = new ByteArrayInputStream(httpResult.getBody().toString().getBytes());

        importService.importData(bs, retailCustomer.getId());

        List<EntryType> entries = importService.getEntries();

        // TODO: Use-Case 1 registration - service status

    } catch (Exception e) {
        // nothing there, so log the fact and move on. It will
        // get imported later.
        e.printStackTrace();
    }
    model.put("serviceStatus", serviceStatus);

    return "/custodian/datacustodian/showservicestatus";
}

From source file:demo.AuthorizationCodeProviderCookieTests.java

@Override
protected HttpHeaders getAuthenticatedHeaders() {
    HttpHeaders headers = super.getAuthenticatedHeaders();
    if (context.getAccessTokenRequest().getCookie() != null) {
        headers.remove("Authorization");
        headers.set("Cookie", context.getAccessTokenRequest().getCookie());
    }/*from   w w  w . ja  va 2 s.com*/
    return headers;
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.xs.xss.tests.predefined.XssFilterPredefinedTests.java

@Test
public void testXssFilterInCookie() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", "safeCookie=safeCookie,riskyCookie=<script>alert(document.cookie);</script>");
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    int port = context.getEmbeddedServletContainer().getPort();
    ResponseEntity<String> response = restTemplate.exchange("http://localhost:" + port + "/test",
            HttpMethod.GET, entity, String.class);
    // Assert that: Safe cookie has been kept, Risky cookie has been skipped
    assertThat(response.getBody(), equalTo("|safeCookie|null|"));
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.xs.xss.tests.predefined.XssFilterPredefinedTests.java

@Test
public void testXssFilterInHeader() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.set("testRiskyHeader", "<script>alert(document.cookie);</script>");
    headers.set("testSafeHeader", "safeHeader");
    HttpEntity<String> entity = new HttpEntity<String>("testParamInBody1=testvalue1", headers);

    int port = context.getEmbeddedServletContainer().getPort();
    ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:" + port + "/test", entity,
            String.class);
    // Assert that Risky header has been skipped, Safe header is kept, Safe body is kept
    assertThat(response.getBody(), equalTo("||safeHeader|testParamInBody1=testvalue1|"));
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.xs.xss.tests.predefined.XssFilterPredefinedTests.java

@Test
public void testXssFilterInUrlPath() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.set("testSafeHeader", "safeHeader");
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    int port = context.getEmbeddedServletContainer().getPort();
    HttpEntity<String> response = restTemplate.exchange(
            "http://localhost:" + port + "/test/safeurlpath/document.cookie", HttpMethod.GET, entity,
            String.class);
    // Assert that: Safe header is kept, Safe url path is kept, Risky URK path is skipped
    assertThat(response.getBody(), equalTo("|safeHeader|safeurlpath|document|"));
}

From source file:com.xyxy.platform.examples.showcase.functional.rest.UserRestFT.java

/**
 * ?ShiroHttpBasic?/* w w w  .j av  a2s  .  c  o m*/
 */
@Test
public void authWithHttpBasic() {
    // Http Basic?
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set(com.google.common.net.HttpHeaders.AUTHORIZATION,
            Servlets.encodeHttpBasic("admin", "wrongpassword"));
    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);

    try {
        jdkTemplate.exchange(resourceUrl + "/{id}.xml", HttpMethod.GET, requestEntity, UserDTO.class, 1L);
        fail("Get should fail with error username/password");
    } catch (HttpStatusCodeException e) {
        assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    }
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.xs.xss.tests.predefined.XssFilterPredefinedTests.java

@Test
public void testXssFilterInUrlQueryString() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.set("testSafeHeader", "safeHeader");
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    int port = context.getEmbeddedServletContainer().getPort();
    ResponseEntity<String> response = restTemplate.exchange("http://localhost:" + port
            + "/test/safeurlpath?safeQueryStringParam=safeQueryStringParam&riskyQueryStringParam=<script>alert(document.cookie);</script>",
            HttpMethod.GET, entity, String.class);

    // Assert that: Safe header is kept, Safe url path is kept, Safe query string parameter is kept, Risky query string parameter has been skipped
    assertThat(response.getBody(), equalTo("|safeHeader|safeurlpath|safeQueryStringParam||"));
}

From source file:org.client.two.service.OAuthAuthenticationService.java

public String getAuthorizationCode(String accessTokenA, String redirectUri, String appTokenClientTwo) {
    RestOperations rest = new RestTemplate();

    HttpHeaders headersA = new HttpHeaders();
    headersA.set("Authorization", "Bearer " + accessTokenA);

    ResponseEntity<String> resAuth2 = rest
            .exchange(//from w ww  .  ja v  a  2  s  .  co m
                    MessageFormat.format(
                            "{0}/oauth/authorize?"
                                    + "client_id={1}&response_type=code&redirect_uri={2}&scope=WRITE",
                            oauthServerBaseURL, appTokenClientTwo, redirectUri),
                    HttpMethod.POST, new HttpEntity<String>(headersA), String.class);

    String sessionId = resAuth2.getHeaders().get("Set-Cookie").get(0);
    int p1 = sessionId.indexOf("=") + 1;
    int p2 = sessionId.indexOf(";");
    sessionId = sessionId.substring(p1, p2);
    headersA.add("Cookie", "JSESSIONID=" + sessionId);

    resAuth2 = rest.exchange(
            MessageFormat.format("{0}/oauth/authorize?" + "user_oauth_approval=true&authorize=Authorize",
                    oauthServerBaseURL),
            HttpMethod.POST, new HttpEntity<String>(headersA), String.class);

    String code = resAuth2.getHeaders().get("location").get(0);
    p1 = code.lastIndexOf("=") + 1;
    code = code.substring(p1);

    return code;
}

From source file:org.busko.routemanager.web.admin.community.RouteOutlineController.java

@RequestMapping(params = "gpx", value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> gpx(@PathVariable("id") Long id, Model uiModel) {
    RouteOutline routeOutline = RouteOutline.findRouteOutline(id);

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("Content-Disposition", "attachment;filename=" + routeOutline.getRouteName() + ".xml");
    responseHeaders.set("Content-Length", Integer.toString(routeOutline.getFileContent().length));
    responseHeaders.set("Content-Type", "text/xml");
    return new ResponseEntity<byte[]>(routeOutline.getFileContent(), responseHeaders, HttpStatus.OK);
}

From source file:org.cloudfoundry.identity.api.web.AppsIntegrationTests.java

/**
 * tests a happy-day flow of the native application profile.
 *//*from  w w  w.ja  va 2s.c o m*/
@Test
public void testHappyDay() throws Exception {

    RestOperations restTemplate = serverRunning.createRestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity(serverRunning.getUrl("/api/apps"),
            String.class);
    // first make sure the resource is actually protected.
    assertNotSame(HttpStatus.OK, response.getStatusCode());
    HttpHeaders approvalHeaders = new HttpHeaders();
    OAuth2AccessToken accessToken = context.getAccessToken();
    approvalHeaders.set("Authorization", "bearer " + accessToken.getValue());
    Date oneMinuteAgo = new Date(System.currentTimeMillis() - 60000);
    Date expiresAt = new Date(System.currentTimeMillis() + 60000);
    ResponseEntity<Approval[]> approvals = serverRunning.getRestTemplate().exchange(
            serverRunning.getUrl("/uaa/approvals"), HttpMethod.PUT,
            new HttpEntity<Approval[]>((new Approval[] {
                    new Approval(testAccounts.getUserName(), "app", "cloud_controller.read", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo),
                    new Approval(testAccounts.getUserName(), "app", "openid", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo),
                    new Approval(testAccounts.getUserName(), "app", "password.write", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo) }),
                    approvalHeaders),
            Approval[].class);
    assertEquals(HttpStatus.OK, approvals.getStatusCode());

    ResponseEntity<String> result = serverRunning.getForString("/api/apps");
    assertEquals(HttpStatus.OK, result.getStatusCode());
    String body = result.getBody();
    assertTrue("Wrong response: " + body, body.contains("dsyerapi.cloudfoundry.com"));

}