Example usage for org.springframework.http HttpHeaders HttpHeaders

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

Introduction

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

Prototype

public HttpHeaders() 

Source Link

Document

Construct a new, empty instance of the HttpHeaders object.

Usage

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

@Test
public void testDefaultScopes() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    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");
    postBody.add("source", "credentials");
    postBody.add("username", testAccounts.getUserName());
    postBody.add("password", testAccounts.getPassword());

    ResponseEntity<Void> responseEntity = restOperations.exchange(baseUrl + "/oauth/authorize", HttpMethod.POST,
            new HttpEntity<>(postBody, headers), Void.class);

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

    UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation())
            .build();//  w  ww . j  ava 2  s  . c o  m
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

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

    Jwt access_token = JwtHelper.decode(params.getFirst("access_token"));

    Map<String, Object> claims = new ObjectMapper().readValue(access_token.getClaims(),
            new TypeReference<Map<String, Object>>() {
            });

    Assert.assertThat((String) claims.get("jti"), is(params.getFirst("jti")));
    Assert.assertThat((String) claims.get("client_id"), is("cf"));
    Assert.assertThat((String) claims.get("cid"), is("cf"));
    Assert.assertThat((String) claims.get("user_name"), is(testAccounts.getUserName()));

    Assert.assertThat(((List<String>) claims.get("scope")), containsInAnyOrder(scopes));

    Assert.assertThat(((List<String>) claims.get("aud")),
            containsInAnyOrder("cf", "scim", "openid", "cloud_controller", "password"));
}

From source file:apiserver.core.common.ResponseEntityHelper.java

/**
 * return a BufferedImage as byte[] array or as a base64 version of the image bytes
 * @param image/*from   w  w w.j  a  v a  2 s.c  o m*/
 * @param contentType
 * @param returnAsBase64
 * @return
 * @throws java.io.IOException
        
public static ResponseEntity<byte[]> processImage(Object image, String contentType, Boolean returnAsBase64) throws IOException
{
HttpHeaders headers = new HttpHeaders();
        
// set content type
String convertToType = "jpg";
        
if(contentType == null )
{
    contentType = "jpg";
    contentType = contentType.toLowerCase();
}
        
        
if( contentType.contains("jpg") || contentType.contains("jpeg"))
{
    convertToType = "jpg";
    headers.setContentType(MediaType.IMAGE_JPEG);
}
else if( contentType.contains("png"))
{
    convertToType = "png";
    headers.setContentType(MediaType.IMAGE_PNG);
}
else if( contentType.contains("gif"))
{
    convertToType = "gif";
    headers.setContentType(MediaType.IMAGE_GIF);
}
else
{
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
}
        
        
        
if( image instanceof BufferedImage)
{
    //DataBufferByte bytes = (DataBufferByte)((BufferedImage) image).getRaster().getDataBuffer();
        
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write((BufferedImage) image, convertToType, baos);
    byte [] bytes = baos.toByteArray();
        
        
    if (!returnAsBase64)
    {
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
    }
    else
    {
        return new ResponseEntity<byte[]>(Base64.encode(bytes) , headers, HttpStatus.OK);
    }
}
else if(  image instanceof byte[]  )
{
    if (!returnAsBase64)
    {
        return new ResponseEntity<byte[]>( (byte[])image, headers, HttpStatus.OK);
    }
    else
    {
        return new ResponseEntity<byte[]>(Base64.encode((byte[])image) , headers, HttpStatus.OK);
    }
}
        
throw new RuntimeException("Invalid Image bytes");
}
 */

public static ResponseEntity<byte[]> processImage(BufferedImage image, String contentType,
        Boolean returnAsBase64) throws IOException {
    // set content type
    String convertToType = "png";

    if (contentType == null) {
        contentType = "application/octet-stream";
        contentType = contentType.toLowerCase();
    } else {
        convertToType = MimeType.getMimeType(contentType).getExtension();
    }

    //
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(contentType));

    if (returnAsBase64) {
        headers.set("Content-Transfer-Encoding", "base64");
    }

    if (image instanceof BufferedImage) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, convertToType, baos);
        byte[] bytes = baos.toByteArray();

        return processFile(bytes, contentType, returnAsBase64);
    }
    throw new RuntimeException("Invalid Image bytes");
}

From source file:com.tce.oauth2.spring.client.services.TodoService.java

public Todo add(String accessToken, Todo todo) {
    // Set the headers
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + accessToken);
    headers.add("Content-Type", "application/json");

    // Post request
    HttpEntity<Todo> request = new HttpEntity<Todo>(todo, headers);
    Todo todoAdded = restTemplate.postForObject(OAUTH_RESOURCE_SERVER_URL + "/rest/todos/add", request,
            Todo.class);

    return todoAdded;
}

From source file:org.trustedanalytics.metricsprovider.rest.MetricsDownloadTasks.java

private HttpEntity<String> setAuthToken(AuthTokenRetriever tokenRetriever) {
    SecurityContext context = SecurityContextHolder.getContext();
    OAuth2Authentication auth = (OAuth2Authentication) context.getAuthentication();
    String token = tokenRetriever.getAuthToken(auth);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "bearer " + token);
    return new HttpEntity<>("params", headers);
}

From source file:org.hypernovae.entapps.actuator.ui.SampleActuatorUiApplicationTests.java

@Test
public void testError() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    ResponseEntity<String> entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/error",
            HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("<html>"));
    assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("<body>"));
    assertTrue("Wrong body:\n" + entity.getBody(),
            entity.getBody().contains("Please contact the operator with the above information"));
}

From source file:org.makersoft.mvc.unit.FormatHandlerMethodReturnValueHandlerTests.java

@Test
public void testIncludes() throws Exception {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    mockMvc.perform(get("/account/user/includes/1").accept(MediaType.APPLICATION_JSON).headers(httpHeaders))
            .andDo(print()).andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().encoding("UTF-8"))
            .andExpect(jsonPath("$.id").value(1)).andExpect(jsonPath("$.password").doesNotExist())
            .andExpect(jsonPath("$.dept").doesNotExist()).andExpect(jsonPath("$.roles").doesNotExist());

}

From source file:comsat.sample.actuator.ui.SampleActuatorUiApplicationTests.java

@Test
public void testError() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    ResponseEntity<String> entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/error",
            HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
    assertThat(entity.getBody()).contains("<html>").contains("<body>")
            .contains("Please contact the operator with the above information");
}

From source file:com.demo.FakeAuthorizator.java

private void doGet(String url) {
    System.out.println("try to send to " + url);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    ResponseEntity<String> rese = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
    System.out.println("RESPONSE STRING " + rese.getBody());
}

From source file:ru.portal.controllers.RestController.java

/**
 *  ?    ? ? PortalTable/*w w w. j  a  va 2s .  c  om*/
 * @param isTable
 * @param id
 * @return
 * @throws JSONException 
 */
@RequestMapping(method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }, value = {
        "/tables" })
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ResponseEntity<String> tables(@RequestParam(value = "Table", required = false) Boolean isTable,
        @RequestParam(value = "id", required = false) String id) throws JSONException {

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-type", "application/json;charset=UTF-8");
    return new ResponseEntity<>(generateTreeJson(isTable, id), headers, HttpStatus.OK);

}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.TestCredentials.java

@Override
protected UserInfo doInBackground(Void... params) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("tmp_username", null);
    String password = credentials.getString("tmp_password", null);
    String url = credentials.getString("tmp_url", null) + Values.SERVICE_USER + "login";

    setState(RUNNING, R.string.working_ws_credentials);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    HttpEntity<Object> entity = new HttpEntity<Object>(requestHeaders);

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    try {/* www .j  av  a  2s .  c  om*/
        // Make the network request
        Log.d(TAG, url);
        ResponseEntity<UserInfo> userInfo = restTemplate.exchange(url, HttpMethod.GET, entity, UserInfo.class);
        return (Values.user = userInfo.getBody());
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
        return null;
    } finally {
        setState(DONE);
    }
}