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(@Nullable T body, @Nullable MultiValueMap<String, String> headers) 

Source Link

Document

Create a new HttpEntity with the given body and headers.

Usage

From source file:org.zlogic.vogon.web.controller.DataController.java

/**
 * Returns all data// w  ww. j  ava 2  s.  co m
 *
 * @param userPrincipal the authenticated user
 * @return the HTTPEntity for the file download
 */
@RequestMapping(value = "/export/xml", method = { RequestMethod.GET, RequestMethod.POST })
public HttpEntity<byte[]> exportDataXML(@AuthenticationPrincipal VogonSecurityUser userPrincipal)
        throws RuntimeException {
    VogonUser user = userRepository.findByUsernameIgnoreCase(userPrincipal.getUsername());
    try {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        XmlExporter exporter = new XmlExporter(outStream);
        Sort accountSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N
        Sort transactionSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N
        exporter.exportData(user, accountRepository.findByOwner(user, accountSort),
                transactionRepository.findByOwner(user, transactionSort), null);

        String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()); //NOI18N

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        headers.setContentLength(outStream.size());
        headers.setContentDispositionFormData("attachment", "vogon-" + date + ".xml"); //NOI18N //NOI18N

        return new HttpEntity<>(outStream.toByteArray(), headers);
    } catch (VogonExportException ex) {
        throw new RuntimeException(ex);
    }
}

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

public boolean updateCurrentUserProfile(String token, Profile profile)
        throws JsonGenerationException, JsonMappingException, IOException, JSONException {
    RestOperations rest = new RestTemplate();

    HttpHeaders headersA = new HttpHeaders();
    headersA.set("Authorization", "Bearer " + token);
    headersA.setContentType(MediaType.TEXT_PLAIN);

    ObjectMapper mapper = new ObjectMapper();
    HttpEntity<String> request = new HttpEntity<String>(mapper.writeValueAsString(profile), headersA);

    ResponseEntity<String> responseUpdate = rest.exchange(oauthServerBaseURL + "/resources/profile/update",
            HttpMethod.POST, request, String.class);

    JSONObject responseUpdateJSON = new JSONObject(responseUpdate.getBody());

    return responseUpdateJSON.getBoolean("success");
}

From source file:com.auditbucket.client.AbRestClient.java

public int flushXReferences(List<CrossReferenceInputBean> referenceInputBeans) {
    logger.info("Processing [{}] cross references - simulate [{}]", referenceInputBeans.size(), simulateOnly);
    if (simulateOnly)
        return 0;
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    HttpHeaders httpHeaders = getHeaders(userName, password);
    HttpEntity<List<CrossReferenceInputBean>> requestEntity = new HttpEntity<>(referenceInputBeans,
            httpHeaders);/*from  w  ww . ja va  2  s . c om*/
    try {
        ResponseEntity<ArrayList> response = restTemplate.exchange(CROSS_REFERENCES, HttpMethod.POST,
                requestEntity, ArrayList.class);
        logServerMessages(response);
        return referenceInputBeans.size();
    } catch (HttpClientErrorException e) {
        // ToDo: Rest error handling pretty useless. need to know why it's failing
        logger.error("AB Client Audit error {}", getErrorMessage(e));
        return 0;
    } catch (HttpServerErrorException e) {
        logger.error("AB Server Audit error {}", getErrorMessage(e));
        return 0;

    }

}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void basicAuthenticationRemoteLogServiceEnabledWithoutCsrfTokenTest() throws Exception {
    RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO();
    logRequestVO.setMessage("Test mesage!");
    logRequestVO.setLogLevel("DEBUG");

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization",
            "Basic " + new String(Base64.encode((getUsername() + ":" + getPassword()).getBytes("UTF-8"))));
    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath);
    ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entity, String.class);
    assertEquals(HttpStatus.FORBIDDEN, responseEntity.getStatusCode());
}

From source file:com.ge.predix.integration.test.ACSMeteringIT.java

@Test(enabled = false)
public void testACSMetering() throws Exception {
    String testPolicyName = null;
    PolicyEvaluationRequestV1 policyEvaluationRequest = this.policyHelper
            .createEvalRequest(MARISSA_V1.getSubjectIdentifier(), "sanramon");
    OAuth2RestTemplate acsRestTemplate = this.acsRestTemplateFactory.getACSTemplateWithPolicyScope();
    try {/* w w w.  ja va2 s  .c  o  m*/
        // Get meter readings before
        Double beforePolicyUpdateMeterCount = getEntitlementUsageByFeatureId(POLICY_UPDATE_FEATURE_ID,
                this.zoneId);
        Double beforePolicyEvalMeterCount = getEntitlementUsageByFeatureId(POLICY_EVAL_FEATURE_ID, this.zoneId);

        LOGGER.info("POLICY UPDATE USAGE BEFORE:" + beforePolicyUpdateMeterCount);
        LOGGER.info("POLICY EVAL USAGE BEFORE:" + beforePolicyEvalMeterCount);

        String policyFile = "src/test/resources/single-site-based-policy-set.json";
        testPolicyName = this.policyHelper.setTestPolicy(acsRestTemplate, getZoneHeaders(), this.acsUrl,
                policyFile);
        ResponseEntity<PolicyEvaluationResult> evalResponse = acsRestTemplate.postForEntity(
                this.acsUrl + PolicyHelper.ACS_POLICY_EVAL_API_PATH,
                new HttpEntity<>(policyEvaluationRequest, getZoneHeaders()), PolicyEvaluationResult.class);

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

        // Nurego server seems to have a lag before the counts are updated
        // Wait for Nurego to be updated before proceeding with assertion
        Double afterPolicyUpdateMeterCount = 0.0;
        Double afterPolicyEvalMeterCount = 0.0;
        Double updateMeterCount = 0.0;
        Double evalMeterCount = 0.0;
        for (int i = 0; i < MAX_ITERATIONS; i++) {
            Thread.sleep(NUREGO_UPDATE_SLEEP_MS);
            afterPolicyUpdateMeterCount = getEntitlementUsageByFeatureId(POLICY_UPDATE_FEATURE_ID, this.zoneId);
            afterPolicyEvalMeterCount = getEntitlementUsageByFeatureId(POLICY_EVAL_FEATURE_ID, this.zoneId);

            if (isMeterUpdated(beforePolicyUpdateMeterCount, afterPolicyUpdateMeterCount)
                    && isMeterUpdated(beforePolicyEvalMeterCount, afterPolicyEvalMeterCount)) {
                LOGGER.debug("POLICY UPDATE USAGE AFTER: " + afterPolicyUpdateMeterCount);
                LOGGER.debug("POLICY EVAL USAGE AFTER: " + afterPolicyEvalMeterCount);
                break;
            }
        }

        // Assert metering counts incremented by 1
        updateMeterCount = afterPolicyUpdateMeterCount - beforePolicyUpdateMeterCount;
        evalMeterCount = afterPolicyEvalMeterCount - beforePolicyEvalMeterCount;
        Assert.assertEquals(updateMeterCount, 1.0);
        Assert.assertEquals(evalMeterCount, 1.0);
    } finally {
        if (testPolicyName != null) {
            this.policyHelper.deletePolicySet(acsRestTemplate, this.acsUrl, testPolicyName, getZoneHeaders());
        }
    }
}

From source file:com.garyclayburg.UserRestSmokeTest.java

@Ignore
@Test//from  w  ww.  j a va 2 s  . c o m
public void testJsonutf8Apache() throws Exception {
    RestTemplate rest = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    SimpleUser user1 = new SimpleUser();
    user1.setFirstname("Tommy");
    user1.setLastname("Deleteme");
    user1.setId("112" + (int) (Math.floor(Math.random() * 10000)));

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Content-Type", "application/json;charset=UTF-8");
    //        HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    HttpEntity<?> requestEntity = new HttpEntity(user1, requestHeaders);

    ResponseEntity<SimpleUser> simpleUserResponseEntity = rest.exchange(
            "http://" + endpoint + "/audited-users/auditedsave", HttpMethod.POST, requestEntity,
            SimpleUser.class);

    //        ResponseEntity<SimpleUser> userResponseEntity =
    //            rest.postForEntity("http://" + endpoint + "/audited-users/auditedsave",user1,SimpleUser.class);
    log.info("got a response");
    MatcherAssertionErrors.assertThat(simpleUserResponseEntity.getStatusCode(),
            Matchers.equalTo(HttpStatus.OK));

}

From source file:com.ge.predix.test.utils.PrivilegeHelper.java

public ResponseEntity<Object> postSubjects(final OAuth2RestTemplate acsTemplate, final String endpoint,
        final HttpHeaders headers, final BaseSubject... subjects) {
    List<BaseSubject> subjectsArray = new ArrayList<>();
    for (BaseSubject s : subjects) {
        subjectsArray.add(s);//  w  w w .ja v a 2 s  .  co m
    }
    URI subjectUri = URI.create(endpoint + ACS_SUBJECT_API_PATH);
    ResponseEntity<Object> responseEntity = acsTemplate.postForEntity(subjectUri,
            new HttpEntity<>(subjectsArray, headers), Object.class);
    return responseEntity;
}

From source file:org.callistasoftware.netcare.core.spi.impl.PushNotificationServiceImpl.java

void sendApnsNotification(final String registrationId, final String message) {
    getLog().info("Preparing to send APNS message: {}", apnsCount);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("token", registrationId);
    params.add("message", message);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params,
            headers);/* ww w  .  j a  v  a  2  s  . co m*/

    String result = new RestTemplate().postForObject(apnsServiceUrl, request, String.class);

    if (result.equals("success")) {
        getLog().debug("Push notification " + apnsCount + " sent. Result: " + result);
        apnsCount++;
    } else {
        getLog().error("Push notification could not be sent. Server result:\n" + result);
    }
}

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

@Test
public void implicitGrantClientWithoutSecretIsOk() throws Exception {
    BaseClientDetails client = new BaseClientDetails(new RandomValueStringGenerator().generate(), "", "foo,bar",
            "implicit", "uaa.none");
    ResponseEntity<Void> result = serverRunning.getRestTemplate().exchange(
            serverRunning.getUrl("/oauth/clients"), HttpMethod.POST,
            new HttpEntity<BaseClientDetails>(client, headers), Void.class);

    assertEquals(HttpStatus.CREATED, result.getStatusCode());
}