Example usage for org.springframework.http HttpEntity HttpEntity

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

Introduction

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

Prototype

public HttpEntity(MultiValueMap<String, String> headers) 

Source Link

Document

Create a new HttpEntity with the given headers and no body.

Usage

From source file:org.appverse.web.framework.backend.test.util.frontfacade.BaseAbstractAuthenticationRequiredTest.java

protected TestLoginInfo simpleLogin() throws Exception {
    CredentialsVO credentialsVO = new CredentialsVO();
    credentialsVO.setUsername(getUsername());
    credentialsVO.setPassword(getPassword());
    HttpEntity<CredentialsVO> entity = new HttpEntity<CredentialsVO>(credentialsVO);

    ResponseEntity<AuthorizationData> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + baseApiPath + simpleAuthenticationEndpointPath, HttpMethod.POST,
            entity, AuthorizationData.class);
    assertEquals(HttpStatus.OK, responseEntity.getStatusCode());

    List<String> xsrfTokenHeaders = responseEntity.getHeaders().get(DEFAULT_CSRF_HEADER_NAME);
    assertNotNull(xsrfTokenHeaders);//w  w  w .  j a  v  a2 s.  c  om
    assertEquals(xsrfTokenHeaders.size(), 1);
    assertNotNull(xsrfTokenHeaders.get(0));
    AuthorizationData authorizationData = responseEntity.getBody();
    assertNotNull(authorizationData);
    List<String> roles = authorizationData.getRoles();
    assertNotNull(roles);
    assertEquals(roles.size() > 0, true);
    assertEquals(roles.contains(getAnUserRole()), true);

    TestLoginInfo loginInfo = new TestLoginInfo();
    loginInfo.setXsrfToken(xsrfTokenHeaders.get(0));
    loginInfo.setAuthorizationData(authorizationData);
    loginInfo.setJsessionid(responseEntity.getHeaders().getFirst("Set-Cookie"));
    return loginInfo;
}

From source file:com.formulaone.controller.merchant.MerchantControllerTest.java

/**
 * Test Merchant retrieval by Id/*from  w w w  . j  ava 2s .  c o  m*/
 */
@Test
public void test_2_SuccessfulMerchantRetrievalById() {
    Map<String, Long> vars = new HashMap<String, Long>();
    vars.put("id", createdId);
    try {
        ResponseEntity<MerchantResponse> response = restTemplate.exchange(base + "/{id}", HttpMethod.GET,
                new HttpEntity<MerchantResponse>(httpHeaders), MerchantResponse.class, vars);

        MerchantResponse merchantResponse = response.getBody();
        assertThat(merchantResponse, notNullValue());
        assertThat(merchantResponse.getCompanyName(), equalTo(request.getCompany().getName()));
        assertThat(merchantResponse.getDescription(), equalTo(request.getBusinessDescription()));
        assertThat(merchantResponse.getFirstName(), equalTo(request.getOwnershipDetails().getFirstName()));
        assertThat(merchantResponse.getLastName(), equalTo(request.getOwnershipDetails().getLastName()));
        assertThat(merchantResponse.getMid(), notNullValue());
        assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));

    } catch (RestClientException e) {
        fail("Unexpected exception happened: " + e.getMessage());
    }
}

From source file:com.appglu.impl.SyncTemplate.java

/**
 * {@inheritDoc}/*  w  ww.  j  a  v  a  2 s .  c om*/
 */
public void downloadChangesForTables(final List<TableVersion> tables,
        final InputStreamCallback inputStreamCallback) throws AppGluRestClientException {
    RequestCallback requestCallback = new RequestCallback() {
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(new TableVersionBody(tables));

            HttpHeaders requestHeaders = requestEntity.getHeaders();
            if (!requestHeaders.isEmpty()) {
                request.getHeaders().putAll(requestHeaders);
            }

            jsonMessageConverter.write(requestEntity.getBody(), requestHeaders.getContentType(), request);
        }
    };

    ResponseExtractor<Object> responseExtractor = new ResponseExtractor<Object>() {
        public Object extractData(ClientHttpResponse response) throws IOException {
            inputStreamCallback.doWithInputStream(response.getBody());
            return null;
        }
    };

    try {
        this.restOperations.execute(CHANGES_FOR_TABLES_URL, HttpMethod.POST, requestCallback,
                responseExtractor);
    } catch (RestClientException e) {
        throw new AppGluRestClientException(e.getMessage(), e);
    }
}

From source file:org.zaizi.SensefyResourceApplicationTests.java

@Test
public void testRootPathAuthorized() {
    RestTemplate template = new TestRestTemplate();
    final HttpHeaders headers = new HttpHeaders();
    String accessToken = TestOAuthUtils.getDefOAuth2AccessToken();
    TestOAuthUtils.addOAuth2AccessTokenToHeader(headers, accessToken);
    HttpEntity<String> httpEntity = new HttpEntity<>(headers);
    ResponseEntity<String> response = template.exchange(baseTestServerUrl(), HttpMethod.GET, httpEntity,
            String.class);
    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
}

From source file:com.appglu.impl.UserTemplate.java

/**
 * {@inheritDoc}/*from  w ww. j  av a  2  s  .  c  o m*/
 */
public void writeData(Map<String, Object> data) throws AppGluRestClientException {
    try {
        this.restOperations.exchange(DATA_URL, HttpMethod.PUT, new HttpEntity<Map<String, Object>>(data),
                Void.class);
    } catch (AppGluHttpUserUnauthorizedException e) {
        this.userSessionPersistence.logout();
        throw e;
    } catch (RestClientException e) {
        throw new AppGluRestClientException(e.getMessage(), e);
    }
}

From source file:org.cloudfoundry.client.lib.oauth2.OauthClient.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void changePassword(String oldPassword, String newPassword) {
    HttpHeaders headers = new HttpHeaders();
    headers.add(AUTHORIZATION_HEADER_KEY, token.getTokenType() + " " + token.getValue());
    HttpEntity info = new HttpEntity(headers);
    ResponseEntity<String> response = restTemplate.exchange(authorizationUrl + "/userinfo", HttpMethod.GET,
            info, String.class);
    Map<String, Object> responseMap = JsonUtil.convertJsonToMap(response.getBody());
    String userId = (String) responseMap.get("user_id");
    Map<String, Object> body = new HashMap<String, Object>();
    body.put("schemas", new String[] { "urn:scim:schemas:core:1.0" });
    body.put("password", newPassword);
    body.put("oldPassword", oldPassword);
    HttpEntity<Map> httpEntity = new HttpEntity<Map>(body, headers);
    restTemplate.put(authorizationUrl + "/User/{id}/password", httpEntity, userId);
}

From source file:com.ge.predix.acceptance.test.ACSAcceptanceIT.java

@Test(groups = { "acsHealthCheck" })
public void testAcsHealth() {

    RestTemplate restTemplate = new RestTemplate();
    try {/*from   ww  w. jav  a 2 s.  c  om*/
        ResponseEntity<String> heartbeatResponse = restTemplate.exchange(
                this.acsBaseUrl + "/monitoring/heartbeat", HttpMethod.GET,
                new HttpEntity<>(this.headersWithZoneSubdomain), String.class);
        Assert.assertEquals(heartbeatResponse.getBody(), "alive", "ACS Heartbeat Check Failed");
    } catch (Exception e) {
        Assert.fail("Could not perform ACS Heartbeat Check: " + e.getMessage());
    }

    try {
        @SuppressWarnings("rawtypes")
        ResponseEntity<Map> healthStatus = restTemplate.exchange(this.acsBaseUrl + "/health", HttpMethod.GET,
                new HttpEntity<>(this.headersWithZoneSubdomain), Map.class);
        Assert.assertNotNull(healthStatus);
        Assert.assertEquals(healthStatus.getBody().size(), 1);
        String acsStatus = (String) healthStatus.getBody().get("status");
        Assert.assertEquals(acsStatus, "UP", "ACS Health Check Failed: " + acsStatus);
    } catch (Exception e) {
        Assert.fail("Could not perform ACS Health Check: " + e.getMessage());
    }

}

From source file:com.acc.test.ProductWebServiceTest.java

@Test()
public void testGetProductByCode_Success_XML_Options_Gallery() {
    final HttpEntity<String> requestEntity = new HttpEntity<String>(getXMLHeaders());
    final ResponseEntity<ProductData> response = template.exchange(URL + "/{code}?options=GALLERY",
            HttpMethod.GET, requestEntity, ProductData.class, TestConstants.PRODUCT_CODE);
    final ProductData productData = response.getBody();

    assertEquals(TestConstants.PRODUCT_CODE, productData.getCode());
    assertEquals("EASYSHARE V1253, Black", productData.getName());
    assertEquals(10, productData.getImages().size());

}

From source file:com.github.ffremont.microservices.springboot.node.services.MsService.java

public byte[] getContentOfProperties(String msName) {
    MasterUrlBuilder builder = new MasterUrlBuilder(cluster, node, masterhost, masterPort, masterCR);
    builder.setUri(msName + "/properties");

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN));
    HttpEntity<byte[]> entity = new HttpEntity<>(headers);

    ResponseEntity<byte[]> response = restTempate.exchange(builder.build(), HttpMethod.GET, entity,
            byte[].class);

    return HttpStatus.OK.equals(response.getStatusCode()) ? response.getBody() : null;
}

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

/**
 * ?ShiroHttpBasic?/*from   ww w .  j av  a2 s. 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);
    }
}