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:de.fhg.fokus.nubomedia.paas.VNFRServiceImpl.java

/**
 * Registers a new App to the VNFR with a specific VNFR ID
 *    //from   w  ww.  j av  a  2  s .c om
 * @param externalAppId - application identifier
 * @param points - capacity
 */
public ApplicationRecord registerApplication(String externalAppId, int points)
        throws NotEnoughResourcesException {
    try {
        if (serviceProfile == null) {
            logger.info("Service Profile not set. make sure the VNFR_ID, VNFM_IP and VNFM_PORT are available ");
            return null;
        }
        String URL = serviceProfile.getServiceApiUrl();
        ApplicationRecordBody bodyObj = new ApplicationRecordBody(externalAppId, points);
        Gson mapper = new GsonBuilder().create();
        String body = mapper.toJson(bodyObj, ApplicationRecordBody.class);

        logger.info("registering new application: \nURL: " + URL + "\n + " + body);
        HttpHeaders creationHeader = new HttpHeaders();
        creationHeader.add("Accept", "application/json");
        creationHeader.add("Content-type", "application/json");

        HttpEntity<String> registerEntity = new HttpEntity<String>(body, creationHeader);
        ResponseEntity response = restTemplate.exchange(URL, HttpMethod.POST, registerEntity, String.class);

        logger.info("response from VNFM " + response);
        HttpStatus status = response.getStatusCode();
        if (status.equals(HttpStatus.CREATED) || status.equals(HttpStatus.OK)) {
            logger.info("Deployment status: " + status + " response: " + response);
            ApplicationRecord responseBody = mapper.fromJson((String) response.getBody(),
                    ApplicationRecord.class);

            logger.info("returned object " + responseBody.toString());
            return responseBody;
        } else if (status.equals(HttpStatus.UNPROCESSABLE_ENTITY)) {

            throw new NotEnoughResourcesException("Not enough resource " + response.getBody());
        }
    } catch (NotEnoughResourcesException e) {
        logger.error(e.getMessage());
    } catch (RestClientException e) {
        logger.error("Error registering application to VNFR - " + e.getMessage());
    }
    return null;
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.http.HttpCommunicationTest.java

private HttpEntity<String> createExpectedPostRequest(String body) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", "application/json");
    headers.add("Content-type", "application/x-www-form-urlencoded");

    return new HttpEntity<>(body, headers);
}

From source file:org.cloudfoundry.caldecott.client.HttpTunnel.java

private void openTunnel() {
    String initMsg = "{\"host\":\"" + host + "\",\"port\":" + port + "}";
    if (logger.isDebugEnabled()) {
        logger.debug("Initializing tunnel: " + initMsg);
    }/* w w  w. ja v  a 2s .  co m*/
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Auth-Token", auth);
    requestHeaders.set("Content-Length", initMsg.length() + "");
    HttpEntity<String> requestEntity = new HttpEntity<String>(initMsg, requestHeaders);
    String jsonResponse;
    try {
        jsonResponse = restOperations.postForObject(url + "/tunnels", requestEntity, String.class);
    } catch (RuntimeException e) {
        logger.error("Fatal error while opening tunnel: " + e.getMessage());
        close();
        throw e;
    }
    try {
        this.tunnelInfo = TunnelHelper.convertJsonToMap(jsonResponse);
    } catch (IOException ignore) {
        this.tunnelInfo = new HashMap<String, String>();
    }
}

From source file:org.jnrain.mobile.network.NewPostRequest.java

@Override
public SimpleReturnCode loadDataFromNetwork() throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.set("Content", _content);
    params.set("board", _brd);
    params.set("signature", Integer.toString(_signid));
    params.set("subject", _title);

    if (_is_new_thread) {
        params.set("ID", "");
        params.set("groupID", "");
        params.set("reID", "0");
    } else {/*from   w w  w. java2 s  .  c om*/
        params.set("ID", Long.toString(_tid));
        params.set("groupID", Long.toString(_tid));
        params.set("reID", Long.toString(_reid));
    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<MultiValueMap<String, String>>(params,
            headers);

    return getRestTemplate().postForObject(
            /* "http://rhymin.jnrain.com/api/post/new/", */
            "http://bbs.jnrain.com/rainstyle/apipost.php", req, SimpleReturnCode.class);
}

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

@RequestMapping(value = "/{repoKey}/search/{search}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<Object> repoSearch(@PathVariable String repoKey, @PathVariable String search,
        @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) {

    val result = delegate.repoSearch(ApiVersion.V1, repoKey, search, view, pageable, params);
    val resultType = result.getClass();
    if (PagedResources.class.isAssignableFrom(resultType)) {
        val pagedResources = (PagedResources) result;
        val headers = responseHeaders.buildResponseHeaders(pagedResources);
        return new HttpEntity<>(pagedResources, headers);
    } else if (Resources.class.isAssignableFrom(resultType)) {
        val resources = (Resources) result;
        return new HttpEntity<>(resources);
    } else {// ww w . j  ava2  s.com
        // We *could* just wrap the result with an HttpEntity and return it, but we're not expecting any such
        // responses, so safer to simply whitelist the result types. (That way we don't have to commit to supporting
        // them.) If later we have searches that return a single value or whatever, then we can handle those. [WLW]
        throw new UnsupportedOperationException(
                "Don't know how to handle repo search result of type " + resultType.getName());
    }
}

From source file:comsat.sample.ui.method.SampleMethodSecurityApplicationTests.java

@Test
public void testLogin() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("username", "admin");
    form.set("password", "admin");
    getCsrf(form, headers);/* w w w.j  a v  a  2s . co  m*/
    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());
    assertEquals("http://localhost:" + this.port + "/", entity.getHeaders().getLocation().toString());
}

From source file:de.zib.gndms.gndmc.AbstractClient.java

/**
 * Executes a given HTTP method on a url.
 * /*w  ww.j  a  v  a 2s. com*/
 * The request header contains a given user name and workflow id, the body of the request contains 
 * a given object of type P.
 * 
 * @param <T> The body type of the response.
 * @param <P> The body type of the request.
 * @param x The kind of HTTP method to be executed.
 * @param clazz The type of the return value.
 * @param parm The body of the request.
 * @param url The url of the request.
 * @param dn The user name.
 * @param wid The workflow id.
 * @return The response as entity.
 */
private <T, P> ResponseEntity<T> unifiedX(final HttpMethod x, final Class<T> clazz, final P parm,
        final String url, final String dn, final String wid) {
    GNDMSResponseHeader requestHeaders = new GNDMSResponseHeader();
    if (dn != null) {
        requestHeaders.setDN(dn);
    }
    if (wid != null) {
        requestHeaders.setWId(wid);
    }
    HttpEntity<P> requestEntity = new HttpEntity<P>(parm, requestHeaders);

    if (null == restTemplate)
        throw new NullPointerException("Please set RestTemplate in Client!");
    return restTemplate.exchange(url, x, requestEntity, clazz);
}

From source file:edu.fing.tagsi.db4o.business.TrackingController.java

public void RegistrarNuevoSalto(Envio envio, Recorrido recorrido, List<Tracking> list) {
    if (list.size() < recorrido.getNodos().length) {
        NodoCamino nodo = recorrido.getNodos()[list.size()];

        RestTemplate restTemplate = new RestTemplate();
        RequestTrackingAddPackage req = new RequestTrackingAddPackage(envio.getId().toString(),
                envio.getCliente().getId().toString(), nodo.getCiudad().getId().toString(), new Date(),
                list.size() + 1 == recorrido.getNodos().length);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<RequestTrackingAddPackage> entity = new HttpEntity<>(req, headers);
        restTemplate.postForObject(ConfigController.getInstance().getURLAddTracking(), entity, void.class);
    }/*from  w  w  w.  j a  v a2 s . co m*/

}

From source file:com.embedler.moon.graphql.boot.sample.test.GenericTodoSchemaParserTest.java

@Test
public void restViewerByIdTest() throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

    GraphQLServerRequest qlQuery = new GraphQLServerRequest("{viewer{ id }}");

    HttpEntity<GraphQLServerRequest> httpEntity = new HttpEntity<>(qlQuery, headers);
    ResponseEntity<GraphQLServerResult> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + "/graphql", HttpMethod.POST, httpEntity, GraphQLServerResult.class);

    GraphQLServerResult result = responseEntity.getBody();
    Assert.assertTrue(CollectionUtils.isEmpty(result.getErrors()));
    Assert.assertFalse(CollectionUtils.isEmpty(result.getData()));
    LOGGER.info(objectMapper.writeValueAsString(result.getData()));
}

From source file:org.cloudfoundry.identity.uaa.login.integration.AutologinContollerIntegrationTests.java

@Test
public void testGetCodeWithFormEncodedRequest() {
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
    request.set("username", testAccounts.getUserName());
    request.set("password", testAccounts.getPassword());
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = serverRunning.getRestTemplate().exchange(serverRunning.getUrl("/autologin"),
            HttpMethod.POST, new HttpEntity<MultiValueMap>(request, headers), Map.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, Object> result = (Map<String, Object>) entity.getBody();
    assertNotNull(result.get("code"));
}