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.esupportail.filex.web.WebController.java

@RequestMapping("VIEW")
protected ModelAndView renderView(RenderRequest request, RenderResponse response) throws Exception {

    ModelMap model = new ModelMap();

    final PortletPreferences prefs = request.getPreferences();
    String eppnAttr = prefs.getValue(PREF_EPPN_ATTR, null);
    String restUrl = prefs.getValue(PREF_REST_URL, null);

    Map userInfos = (Map) request.getAttribute(PortletRequest.USER_INFO);
    String eppn = (String) userInfos.get(eppnAttr);

    log.info("Try to get FileX info for " + eppn);

    try {/*  w  w  w.  j  a va  2s.co m*/

        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        headers.add("eppn", eppn);

        HttpEntity<MultiValueMap<String, String>> httpRequest = new HttpEntity<MultiValueMap<String, String>>(
                null, headers);

        ResponseEntity<Filex> filexEntity = restTemplate.exchange(restUrl, HttpMethod.GET, httpRequest,
                Filex.class);
        log.debug("FileX info for " + eppn + " : " + filexEntity.getBody().toString());

        model.put("filex", filexEntity.getBody());
    } catch (HttpClientErrorException e) {
        return new ModelAndView("error", model);
    }

    model.put("serviceUrl", prefs.getValue(PREF_SERVICE_URL, null));
    return new ModelAndView("view", model);
}

From source file:web.rufer.swisscom.sms.api.client.SwisscomSmsSender.java

/**
 * Send a sms to one or more receivers/*  ww  w .  jav a2 s  .  co m*/
 *
 * @param message the message text
 * @param receiverNumbers the numbers of the receivers (i.e. +41791234567)
 */
public CommunicationWrapper sendSms(String message, String... receiverNumbers) {
    validationChain.executeValidation(receiverNumbers);
    CommunicationWrapper communicationWrapper = new CommunicationWrapper();
    communicationWrapper
            .setOutboundSMSMessageRequest(createOutboundSMSMessageRequest(message, receiverNumbers));
    return restTemplate.postForObject(createRequestUri(),
            new HttpEntity(communicationWrapper, HeaderFactory.createHeaders(apiKey)),
            CommunicationWrapper.class);
}

From source file:com.interop.webapp.WebAppTests.java

@Test
public void testLogin() throws Exception {
    HttpHeaders headers = getHeaders();/*from   ww  w  .j a  va  2s .c o m*/
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("username", "user");
    form.set("password", "user");
    ResponseEntity<String> entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/login",
            HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class);
    assertEquals(HttpStatus.FOUND, entity.getStatusCode());
    assertTrue("Wrong location:\n" + entity.getHeaders(),
            entity.getHeaders().getLocation().toString().endsWith(port + "/"));
    assertNotNull("Missing cookie:\n" + entity.getHeaders(), entity.getHeaders().get("Set-Cookie"));
}

From source file:com.expedia.seiso.web.controller.v1.ItemControllerV1.java

/**
 * @param repoKey/*from  w  ww  .  j  a  v  a2  s  .com*/
 * @param view
 * @param pageable
 * @param params
 * @return either {@link Resources} or {@link PagedResources} depending on the repo type
 */
@RequestMapping(value = "/{repoKey}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<?> getAll(@PathVariable String repoKey,
        @RequestParam(defaultValue = Projection.DEFAULT) String view,
        @PageableDefault(page = C.DEFAULT_PAGE_NUMBER, size = C.DEFAULT_PAGE_SIZE, direction = Direction.ASC) Pageable pageable,
        @RequestParam MultiValueMap<String, String> params) {

    log.trace("Getting all items: repoKey={}", repoKey);

    val result = delegate.getAll(ApiVersion.V1, repoKey, view, pageable, params);
    val resultClass = result.getClass();

    if (PagedResources.class.isAssignableFrom(resultClass)) {
        val baseResourcePage = (PagedResources) result;
        val headers = responseHeaders.buildResponseHeaders(baseResourcePage);
        return new HttpEntity<PagedResources>(baseResourcePage, headers);
    } else if (Resources.class.isAssignableFrom(resultClass)) {
        return new HttpEntity<Resources>((Resources) result);
    } else {
        throw new RuntimeException("Unknown result type: " + resultClass);
    }
}

From source file:eu.falcon.semantic.client.DenaClient.java

public static JSONObject getClassAttributes(String classURI) {

    final String uri = "http://falconsemanticmanager.euprojects.net/api/v1/ontology/class/attributes";
    //final String uri = "http://localhost:8090/api/v1/ontology/class/attributes";

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

    RestTemplate restTemplate = new RestTemplate();

    HttpEntity<String> entity = new HttpEntity<>(classURI, headers);

    String result = restTemplate.postForObject(uri, entity, String.class);

    return new JSONObject(result);
}

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

/**
 * Method, where reservation information is pushed to server in order to create reservation record.
 * All heavy lifting is made here./*from   w w w  .  ja  v a  2s  .  co  m*/
 *
 * @param params only one reservation instance is allowed here - reservation to be created
 * @return object of created reservation if any
 */
@Override
protected Reservation doInBackground(Reservation... params) {

    Reservation data = params[0];
    try {

        setState(RUNNING, R.string.working_ws_create);

        SharedPreferences credentials = getCredentials();
        String username = credentials.getString("username", null);
        String password = credentials.getString("password", null);
        String url = credentials.getString("url", null) + Values.SERVICE_RESERVATION;

        //set HTTP connection
        HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAuthorization(authHeader);
        requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
        requestHeaders.setContentType(MediaType.APPLICATION_XML);
        HttpEntity<Reservation> entity = new HttpEntity<Reservation>(data, requestHeaders);

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

        Log.d(TAG, url);
        ResponseEntity<Reservation> dataEntity = restTemplate.postForEntity(url, entity, Reservation.class);
        return dataEntity.getBody();
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage());
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:de.loercher.localpress.core.api.LocalPressController.java

@RequestMapping(value = "/articles", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> addArticleEntry(@RequestBody LocalPressArticleEntity entity,
        @RequestHeader HttpHeaders headers)
        throws UnauthorizedException, GeneralLocalPressException, JsonProcessingException {
    AddArticleEntityDTO geoDTO = new AddArticleEntityDTO(entity.getRelease());

    List<String> userHeader = headers.get("UserID");
    if (userHeader == null || userHeader.isEmpty()) {
        throw new UnauthorizedException("There needs to be set a UserID-Header!", "", "");
    }//  www .j  a  va  2 s.  c  om

    MultiValueMap<String, String> geoHeaders = new LinkedMultiValueMap<>();
    geoHeaders.add("UserID", userHeader.get(0));

    HttpEntity<AddArticleEntityDTO> request = new HttpEntity<>(geoDTO, geoHeaders);

    RestTemplate template = new RestTemplate();
    String ratingURL = RATING_URL + "feedback";
    ResponseEntity<Map> result;
    try {
        result = template.postForEntity(ratingURL, request, Map.class);
    } catch (RestClientException e) {
        GeneralLocalPressException ex = new GeneralLocalPressException(
                "There happened an error by trying to invoke the geo API!", e);
        log.error(ex.getLoggingString());
        throw ex;
    }

    if (!result.getStatusCode().equals(HttpStatus.CREATED)) {
        GeneralLocalPressException e = new GeneralLocalPressException(result.getStatusCode().getReasonPhrase());
        log.error(e.getLoggingString());
        throw e;
    }

    String articleID = (String) result.getBody().get("articleID");
    if (articleID == null) {
        GeneralLocalPressException e = new GeneralLocalPressException(
                "No articleID found in response from rating module by trying to add new article!");
        log.error(e.getLoggingString());
        throw e;
    }

    HttpEntity<LocalPressArticleEntity> second = new HttpEntity<>(entity, geoHeaders);

    template.put(GEO_URL + articleID, second);

    String url = (String) result.getBody().get("feedbackURL");

    Map<String, Object> returnMap = new LinkedHashMap<>();
    returnMap.put("articleID", articleID);
    returnMap.put("userID", userHeader.get(0));

    Timestamp now = new Timestamp(new Date().getTime());
    returnMap.put("timestamp", now);
    returnMap.put("status", 201);
    returnMap.put("message", "Created.");

    returnMap.put("feedbackURL", url);

    return new ResponseEntity<>(objectMapper.writeValueAsString(returnMap), HttpStatus.CREATED);
}

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

protected TestLoginInfo login() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization",
            "Basic " + new String(Base64.encode((getUsername() + ":" + getPassword()).getBytes("UTF-8"))));
    HttpEntity<String> entity = new HttpEntity<String>("headers", headers);

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

    List<String> xsrfTokenHeaders = responseEntity.getHeaders().get(DEFAULT_CSRF_HEADER_NAME);
    assertNotNull(xsrfTokenHeaders);//from  w  w w .  j  a v a 2s  . c  o  m
    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:org.cloudfoundry.identity.uaa.integration.VmcUserIdTranslationEndpointIntegrationTests.java

@BeforeOAuth2Context
@OAuth2ContextConfiguration(OAuth2ContextConfiguration.ClientCredentials.class)
public void setUpUserAccounts() {

    // If running against vcap we don't want to run these tests because they create new user accounts
    // Assume.assumeTrue(!testAccounts.isProfileActive("vcap"));

    RestOperations client = serverRunning.getRestTemplate();

    ScimUser user = new ScimUser();
    user.setUserName(JOE);/*w  w  w . jav  a  2s.c  o m*/
    user.setName(new ScimUser.Name("Joe", "User"));
    user.addEmail("joe@blah.com");
    user.setGroups(Arrays.asList(new Group(null, "uaa.user"), new Group(null, "orgs.foo")));

    ResponseEntity<ScimUser> newuser = client.postForEntity(serverRunning.getUrl(userEndpoint), user,
            ScimUser.class);

    joe = newuser.getBody();
    assertEquals(JOE, joe.getUserName());

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

    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());

    // The implicit grant for vmc requires extra parameters in the authorization request
    context.setParameters(Collections.singletonMap("credentials",
            testAccounts.getJsonCredentials(joe.getUserName(), "password")));

}

From source file:bibibi.controllers.CitationsController.java

@RequestMapping(value = "/export", method = RequestMethod.GET)
public HttpEntity<FileSystemResource> getFile() throws IOException {
    BibWriter bw = new BibWriter("export", this.citationRepository.findAll());
    bw.writeFile();//from ww  w. j  ava 2  s .c o m

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + bw.getFile().getName());
    header.setContentLength(bw.getFile().length());

    return new HttpEntity<>(new FileSystemResource(bw.getFile()), header);
}