Example usage for org.springframework.http HttpHeaders setAccept

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

Introduction

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

Prototype

public void setAccept(List<MediaType> acceptableMediaTypes) 

Source Link

Document

Set the list of acceptable MediaType media types , as specified by the Accept header.

Usage

From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java

@Test
public void testInvalidScopeInAuthorizationRequest() throws Exception {

    HttpHeaders headers = getAuthenticatedHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));

    String scope = "bogus";
    String redirectUri = "http://anywhere?key=value";
    String clientId = "my-client-with-registered-redirect";

    UriBuilder uri = http.buildUri(authorizePath()).queryParam("response_type", "code")
            .queryParam("state", "mystateid").queryParam("scope", scope);
    if (clientId != null) {
        uri.queryParam("client_id", clientId);
    }/*from w ww  .  j a  v  a  2  s  . c o  m*/
    if (redirectUri != null) {
        uri.queryParam("redirect_uri", redirectUri);
    }
    ResponseEntity<String> response = http.getForString(uri.pattern(), headers, uri.params());
    assertEquals(HttpStatus.FOUND, response.getStatusCode());
    String location = response.getHeaders().getLocation().toString();
    assertTrue(location.startsWith("http://anywhere"));
    assertTrue(location.contains("error=invalid_scope"));
    assertFalse(location.contains("redirect_uri="));
}

From source file:de.hska.ld.core.AbstractIntegrationTest.java

private HttpEntity<String> createHeaderAndBody(Object obj, Cookie auth) {
    String json = null;//from w  ww . jav a  2 s. c  o  m
    if (obj != null) {
        try {
            json = objectMapper.writeValueAsString(obj);
            /*if (obj instanceof User) {
            // Workaround to transfer password
            json = json.substring(0, json.length() - 1);
            json += ",\"password\":\"" + PASSWORD + "\"}";
            }*/
        } catch (JsonProcessingException e) {
            // do nothing
        }
    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    if (auth != null) {
        headers.add("Cookie", "JSESSIONID=" + auth.getValue());
    }

    if (json == null) {
        return new HttpEntity<>(headers);
    } else {
        return new HttpEntity<>(json, headers);
    }
}

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));
            }//ww w .j a va 2 s . c o  m
        }
    }
    return headers;
}

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

private void doOpenIdHybridFlowIdTokenAndCode(Set<String> responseTypes, String responseTypeMatcher)
        throws Exception {

    HttpHeaders headers = new HttpHeaders();
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

    StringBuilder responseType = new StringBuilder();
    Iterator<String> rTypes = responseTypes.iterator();
    while (rTypes.hasNext()) {
        String type = rTypes.next();
        responseType.append(type);/*from ww  w  . java  2  s  .  c  o  m*/
        if (rTypes.hasNext()) {
            responseType.append(" ");
        }
    }
    String state = new RandomValueStringGenerator().generate();
    String clientId = "app";
    String clientSecret = "appclientsecret";
    String redirectUri = "http://anywhere.com";
    String uri = loginUrl + "/oauth/authorize?response_type={response_type}&"
            + "state={state}&client_id={client_id}&redirect_uri={redirect_uri}";

    ResponseEntity<Void> result = restOperations.exchange(uri, HttpMethod.GET, new HttpEntity<>(null, headers),
            Void.class, responseType, state, clientId, redirectUri);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    ResponseEntity<String> response = restOperations.exchange(location, HttpMethod.GET,
            new HttpEntity<>(null, headers), String.class);
    // should be directed to the login screen...
    assertTrue(response.getBody().contains("/login.do"));
    assertTrue(response.getBody().contains("username"));
    assertTrue(response.getBody().contains("password"));

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", user.getUserName());
    formData.add("password", "secret");

    // Should be redirected to the original URL, but now authenticated
    result = restOperations.exchange(loginUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(formData, headers), Void.class);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    if (response.getStatusCode() == HttpStatus.OK) {
        // The grant access page should be returned
        assertTrue(response.getBody().contains("You can change your approval of permissions"));

        formData.clear();
        formData.add("user_oauth_approval", "true");
        result = restOperations.exchange(loginUrl + "/oauth/authorize", HttpMethod.POST,
                new HttpEntity<>(formData, headers), Void.class);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());
        location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    } else {
        // Token cached so no need for second approval
        assertEquals(HttpStatus.FOUND, response.getStatusCode());
        location = UriUtils.decode(response.getHeaders().getLocation().toString(), "UTF-8");
    }
    assertTrue("Wrong location: " + location, location.matches(redirectUri + responseTypeMatcher.toString()));

    formData.clear();
    formData.add("client_id", clientId);
    formData.add("redirect_uri", redirectUri);
    formData.add("grant_type", "authorization_code");
    formData.add("code", location.split("code=")[1].split("&")[0]);
    HttpHeaders tokenHeaders = new HttpHeaders();
    String basicDigestHeaderValue = "Basic "
            + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes()));
    tokenHeaders.set("Authorization", basicDigestHeaderValue);

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse = restOperations.exchange(loginUrl + "/oauth/token", HttpMethod.POST,
            new HttpEntity<>(formData, tokenHeaders), Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, String> body = tokenResponse.getBody();
    Jwt token = JwtHelper.decode(body.get("access_token"));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\""));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\""));
}

From source file:com.athena.dolly.controller.module.couchbase.CouchbaseClient.java

/**
 * <pre>//from   w w w.ja va 2s . c o  m
 * HTTP Header? ??  ?.
 * </pre>
 * @return
 */
private HttpEntity<Object> setHTTPEntity(String body) {
    List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
    acceptableMediaTypes.add(MediaType.APPLICATION_JSON);

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    requestHeaders.setAccept(acceptableMediaTypes);

    if (getCredential() != null) {
        requestHeaders.set(AUTH_HEADER_KEY, getCredential());
    }

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

From source file:com.playhaven.android.req.PlayHavenRequest.java

protected HttpHeaders getHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(new MediaType("application", "json")));
    headers.setUserAgent(UserAgent.USER_AGENT);
    return headers;
}

From source file:org.cloudfoundry.identity.uaa.integration.PasswordChangeEndpointIntegrationTests.java

@Test
@OAuth2ContextConfiguration(resource = OAuth2ContextConfiguration.Implicit.class, initialize = false)
public void testUserChangesOwnPassword() throws Exception {

    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
    parameters.set("source", "credentials");
    parameters.set("username", joe.getUserName());
    parameters.set("password", "password");
    context.getAccessTokenRequest().putAll(parameters);

    PasswordChangeRequest change = new PasswordChangeRequest();
    change.setOldPassword("password");
    change.setPassword("newpassword");

    HttpHeaders headers = new HttpHeaders();
    ResponseEntity<Void> result = client.exchange(serverRunning.getUrl(userEndpoint) + "/{id}/password",
            HttpMethod.PUT, new HttpEntity<PasswordChangeRequest>(change, headers), null, joe.getId());
    assertEquals(HttpStatus.OK, result.getStatusCode());

    // Now try logging in with the new credentials
    headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    String credentials = String.format("{ \"username\":\"%s\", \"password\":\"%s\" }", joe.getUserName(),
            "newpassword");

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("credentials", credentials);
    result = serverRunning.postForResponse(implicitUrl(), headers, formData);

    assertNotNull(result.getHeaders().getLocation());
    assertTrue(result.getHeaders().getLocation().toString()
            .matches("https://uaa.cloudfoundry.com/redirect/vmc#access_token=.+"));
}