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:com.acc.test.ProductWebServiceTest.java

@Test()
public void testGetProductByCode_Success_XML_Options_Description() {
    final HttpEntity<String> requestEntity = new HttpEntity<String>(getXMLHeaders());
    final ResponseEntity<ProductData> response = template.exchange(URL + "/{code}?options=DESCRIPTION",
            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(5, productData.getImages().size());

    assertTrue("Description may not be null!", productData.getDescription() != null);
}

From source file:org.echocat.marquardt.example.ServiceLoginIntegrationTest.java

private void whenAccessingProtectedResourceWithSelfSignedCertificate(final byte[] attackersCertificate) {
    final RestTemplate restTemplate = new RestTemplate();
    final HttpHeaders headers = new HttpHeaders();
    headers.add(X_CERTIFICATE.getHeaderName(), new String(attackersCertificate));
    final HttpEntity<Object> requestEntity = new HttpEntity<>(headers);

    restTemplate.exchange(baseUriOfApp() + "/exampleservice/someProtectedResource", HttpMethod.POST,
            requestEntity, Void.class);
}

From source file:com.goldengekko.meetr.itest.AuthITest.java

@Test
public void testNegativeUserAccess() {
    //        final String API_URL = DomainHelper.getEndpoints(BASE_URL);

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", DomainHelper.J_BASIC_ITEST);
    HttpEntity requestEntity = new HttpEntity(headers);

    // negative test first:
    try {/*from   ww  w .  jav a  2 s. co m*/
        ResponseEntity<MeetingPage> noTokenResponse = restTemplate.exchange(API_URL + "/meeting/v10",
                HttpMethod.GET, requestEntity, MeetingPage.class);
        fail("Expected exception");
    } catch (HttpClientErrorException expected) {
        assertEquals("403 Forbidden", expected.getMessage());
    }

    // then with unregistered token:
    try {
        ResponseEntity<MeetingPage> unregisteredResponse = restTemplate.exchange(
                API_URL + "/meeting/v10?access_token=itest", HttpMethod.GET, requestEntity, MeetingPage.class);
        fail("Expected exception");
    } catch (HttpClientErrorException expected) {
        assertEquals("403 Forbidden", expected.getMessage());
    }
}

From source file:io.getlime.security.powerauth.app.server.service.behavior.CallbackUrlBehavior.java

/**
 * Tries to asynchronously notify all callbacks that are registered for given application.
 * @param applicationId Application for the callbacks to be used.
 * @param activationId Activation ID to be notified about.
 *//*ww  w .  j av  a2 s  .com*/
public void notifyCallbackListeners(Long applicationId, String activationId) {
    final Iterable<CallbackUrlEntity> callbackUrlEntities = callbackUrlRepository
            .findByApplicationIdOrderByName(applicationId);
    Map<String, String> callbackData = new HashMap<>();
    callbackData.put("activationId", activationId);
    AsyncRestTemplate template = new AsyncRestTemplate();
    for (CallbackUrlEntity callbackUrl : callbackUrlEntities) {
        HttpEntity<Map<String, String>> request = new HttpEntity<>(callbackData);
        template.postForEntity(callbackUrl.getCallbackUrl(), request, Map.class, new HashMap<>());
    }
}

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

@Test
public void simpleAuthenticationServiceTest() throws Exception {
    int port = context.getEmbeddedServletContainer().getPort();

    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);
    // When an enpoint is disabled, "405 - METHOD NOT ALLOWED" is returned
    assertEquals(HttpStatus.METHOD_NOT_ALLOWED, responseEntity.getStatusCode());
}

From source file:org.scrutmydocs.webapp.itest.api.settings.rivers.AbstractFSRiversApiTest.java

@Test
public void push_with_put() throws Exception {
    T fsRiver = buildRiverInstance("put_mydummyfs");

    // We just add the created river to be cleaned after test
    _fsRivers.add("put_mydummyfs");

    HttpEntity<T> entity = new HttpEntity<T>(fsRiver);
    restTemplate.put(buildFullApiUrl(), entity);
}

From source file:com.hatta.consumer.App.java

private static User getCustomer(int id, AuthTokenInfo tokenInfo) {
    Assert.notNull(tokenInfo, "Authenticate first please......");
    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<String> request = new HttpEntity<String>(getHeaders());
    User cust = restTemplate.getForObject(
            REST_SERVICE_URI + "/api/user/" + id + QPM_ACCESS_TOKEN + tokenInfo.getAccess_token(), User.class);
    if (cust != null) {
        System.out.println("Retrieve a customer:");
        System.out.println("Customer : id=" + cust.getId() + ", Name=" + cust.getName() + ", Address="
                + cust.getPassword() + ", Email=" + cust.getEmail());
        return cust;
    } else {/*  w  ww. j a  va 2  s.c  o  m*/
        System.out.println("No customer exist----------");
        return null;
    }
}

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

/**
 * Method, where all reservations to specified date are read from server.
 * All heavy lifting is made here.//  w  ww. j a  v  a  2  s.c o m
 *
 * @param params only one TimeContainer parameter is allowed here - specifies day, month and year
 * @return list of fetched reservations
 */
@Override
protected List<Reservation> doInBackground(TimeContainer... params) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_RESERVATION;

    if (params.length == 1) {
        TimeContainer time = params[0];
        url = url + time.getDay() + "-" + time.getMonth() + "-" + time.getYear();
    } else {
        Log.e(TAG, "Invalid params count! There must be one TimeContainer instance");
        setState(ERROR, "Invalid params count! There must be one TimeContainer instance");
        return Collections.emptyList();
    }

    setState(RUNNING, R.string.working_ws_msg);

    // Populate the HTTP Basic Authentication header with the username and
    // password
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));

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

    try {
        // Make the network request
        Log.d(TAG, url);
        ResponseEntity<ReservationList> response = restTemplate.exchange(url, HttpMethod.GET,
                new HttpEntity<Object>(requestHeaders), ReservationList.class);
        ReservationList body = response.getBody();

        if (body != null) {
            return body.getReservations();
        }

    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return Collections.emptyList();
}

From source file:org.openbaton.nse.beans.connectivitymanageragent.ConnectivityManagerRequestor.java

public HttpStatus delQos(String hypervisorName, String qosId) {

    String url = configuration.getBaseUrl() + "/qoses/" + hypervisorName + "/" + qosId;
    HttpHeaders headers = new HttpHeaders();
    HttpEntity<String> delentity = new HttpEntity<>(headers);
    ResponseEntity<String> delete = template.exchange(url, HttpMethod.DELETE, delentity, String.class);

    if (delete.getStatusCode().is5xxServerError()) {
        logger.debug("The port is still here, returned " + delete.getStatusCode() + " with body "
                + delete.getBody());//from w  ww.j a v a 2s .  c  om
        return delete.getStatusCode();
    }

    logger.debug("deleting qos " + qosId + " has returned " + delete.getStatusCode());

    return delete.getStatusCode();
}

From source file:com.bose.aem.spring.config.ConfigServicePropertySourceLocator.java

private Environment getRemoteEnvironment(RestTemplate restTemplate, String uri, String name, String profile,
        String label) {/* ww w. ja  v a2  s .c  o  m*/
    String path = "/{name}/{profile}";
    Object[] args = new String[] { name, profile };
    if (StringUtils.hasText(label)) {
        args = new String[] { name, profile, label };
        path = path + "/{label}";
    }
    ResponseEntity<Environment> response = null;

    try {
        response = restTemplate.exchange(uri + path, HttpMethod.GET, new HttpEntity<Void>((Void) null),
                Environment.class, args);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() != HttpStatus.NOT_FOUND) {
            throw e;
        }
    }

    if (response == null || response.getStatusCode() != HttpStatus.OK) {
        return null;
    }
    Environment result = response.getBody();
    return result;
}