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.cloudfoundry.identity.uaa.integration.TokenAdminEndpointsIntegrationTests.java

@Test
@OAuth2ContextConfiguration(resource = TokenResourceOwnerPassword.class)
public void testRevokeBogusToken() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<?> request = new HttpEntity<String>(context.getAccessToken().getValue(), headers);
    ResponseEntity<Void> response = serverRunning.getRestTemplate().exchange(
            serverRunning.getUrl("/oauth/users/{user}/tokens/{token}"), HttpMethod.DELETE, request, Void.class,
            testAccounts.getUserName(), "FOO");
    assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());

}

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

/**
 * Method, where Experiment information is pushed to server in order to create user.
 * All heavy lifting is made here./*from w  ww  .  ja v a  2s  .  co m*/
 *
 * @param experiments only one Experiment object is accepted
 * @return information about created experiment
 */
@Override
protected Experiment doInBackground(Experiment... experiments) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_EXPERIMENTS + "create";

    setState(RUNNING, R.string.working_ws_create_experiment);
    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);

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

    Experiment experiment = experiments[0];

    try {
        Log.d(TAG, url);

        HttpEntity<Experiment> entity = new HttpEntity<Experiment>(experiment, requestHeaders);
        // Make the network request
        return restTemplate.postForObject(url, entity, Experiment.class);
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:com.salmon.security.xacml.demo.springmvc.rest.HTTPPopulatorsTest.java

private ResponseEntity<Integer> eraseAllData() {
    HttpHeaders headers = this.getHeaders("myusername" + ":" + "mypwd");

    RestTemplate template = new RestTemplate();

    HttpEntity<String> requestEntity = new HttpEntity<String>("{}", headers);

    ResponseEntity<Integer> entity = template.postForEntity("http://localhost:8085/xacml/populators/dvla/reset",
            requestEntity, Integer.class);

    return entity;
}

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

/**
 * Method, where digitization information is pushed to server in order to create user.
 * All heavy lifting is made here.// w w  w.  ja v  a2  s  .c om
 *
 * @param digitizations only one Digitization object is accepted
 * @return information about created digitization
 */
@Override
protected Digitization doInBackground(Digitization... digitizations) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_DIGITIZATIONS;

    setState(RUNNING, R.string.working_ws_create_digitization);
    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);

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

    Digitization digitization = digitizations[0];

    try {
        Log.d(TAG, url);

        HttpEntity<Digitization> entity = new HttpEntity<Digitization>(digitization, requestHeaders);
        // Make the network request
        return restTemplate.postForObject(url, entity, Digitization.class);
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

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

/**
 * Method, where electrode fix information is pushed to server in order to create user.
 * All heavy lifting is made here.//w ww.  j  a  va  2 s  . co  m
 *
 * @param electrodeFixes only one ElectrodeFix object is accepted
 * @return information about created electrode fix
 */
@Override
protected ElectrodeFix doInBackground(ElectrodeFix... electrodeFixes) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_ELECTRODE_FIXLIST;

    setState(RUNNING, R.string.working_ws_create_electrode_fix);
    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);

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

    ElectrodeFix fix = electrodeFixes[0];

    try {
        Log.d(TAG, url);

        HttpEntity<ElectrodeFix> entity = new HttpEntity<ElectrodeFix>(fix, requestHeaders);
        // Make the network request
        return restTemplate.postForObject(url, entity, ElectrodeFix.class);
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:io.fabric8.che.starter.client.CheRestClient.java

public Workspace createWorkspace(String cheServerURL, String name, String stack, String repo, String branch)
        throws IOException {

    // The first step is to create the workspace
    String url = generateURL(cheServerURL, CheRestEndpoints.CREATE_WORKSPACE);
    String jsonTemplate = workspaceTemplate.createRequest().setName(name).setStack(stack)
            .setDescription(workspaceHelper.getDescription(repo, branch)).getJSON();

    RestTemplate template = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(jsonTemplate, headers);

    ResponseEntity<Workspace> workspaceResponse = template.exchange(url, HttpMethod.POST, entity,
            Workspace.class);
    Workspace workspace = workspaceResponse.getBody();

    LOG.info("Workspace has been created: {}", workspace);

    workspace.setName(workspace.getConfig().getName());
    workspace.setDescription(workspace.getConfig().getDescription());

    for (WorkspaceLink link : workspace.getLinks()) {
        if (WORKSPACE_LINK_IDE_URL.equals(link.getRel())) {
            workspace.setWorkspaceIdeUrl(link.getHref());
            break;
        }/*from   ww  w .  ja  v a 2 s  . com*/
    }

    return workspace;
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
    parameters.set("username", username);
    parameters.set("password", password);

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = restTemplate.exchange(loginUrl, HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, Object>>(parameters, headers), Map.class);

    if (response.getStatusCode() == HttpStatus.OK) {
        String userFromUaa = (String) response.getBody().get("username");

        if (userFromUaa.equals(userFromUaa)) {
            logger.info("Successful authentication request for " + authentication.getName());
            return new UsernamePasswordAuthenticationToken(username, null, UaaAuthority.USER_AUTHORITIES);
        }//from   w w  w . j  av a 2  s .  c o m
    } else if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        logger.info("Failed authentication request");
        throw new BadCredentialsException("Authentication failed");
    } else if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) {
        logger.info("Internal error from UAA. Please Check the UAA logs.");
    } else {
        logger.error("Unexpected status code " + response.getStatusCode() + " from the UAA."
                + " Is a compatible version running?");
    }
    throw new RuntimeException("Could not authenticate with remote server");
}

From source file:com.github.moscaville.contactsdb.controller.BaseController.java

public String saveItem(RecordWrapper<T> recordWrapper, ID id) {

    if (OFFLINE_TEST) {
        return "";
    }// w ww .  ja  v  a2s . c  o  m
    String result = null;

    //RecordWrapper<T> recordWrapper = new RecordWrapper<>();
    //BeanUtils.copyProperties(t, recordWrapper.getFields());
    StringBuilder sUri = new StringBuilder();
    sUri.append(AIRTABLE_ENDPOINT_URL).append(getAirTableName());
    URI uri;
    if (id == null) {
        try {
            uri = new URI(sUri.toString());
            ResponseEntity<BaseResponse> response = restTemplate.postForEntity(uri, recordWrapper,
                    BaseResponse.class);
            if (response != null && response.getBody() != null) {
                result = response.getBody().getId();
            }
        } catch (URISyntaxException ex) {
            Logger.getLogger(BaseController.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        sUri.append("/").append(id.toString());
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("HeaderName", "value");
        headers.add("Content-Type", "application/json");
        ObjectMapper objectMapper = new ObjectMapper();
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        messageConverter.setObjectMapper(objectMapper);
        restTemplate.getMessageConverters().add(messageConverter);
        HttpEntity<RecordWrapper> request = new HttpEntity<>(recordWrapper, headers);
        try {
            uri = new URI(sUri.toString());
            restTemplate.put(uri, request);
            result = "";
        } catch (RestClientException e) {
            if (e instanceof HttpStatusCodeException) {
                String errorResponse = ((HttpStatusCodeException) e).getResponseBodyAsString();
                System.out.println(errorResponse);
            }
        } catch (URISyntaxException ex) {
            Logger.getLogger(BaseController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return result;
}

From source file:com.citrix.g2w.webdriver.dependencies.AccountServiceQAIImpl.java

/**
 * Method used to add user to an account.
 * //from w  ww .j a  va2s. c o  m
 * @param accountKey
 *            (user account key)
 * @param firstName
 *            (user first name)
 * @param lastName
 *            (user last name)
 * @param email
 *            (user email)
 * @param password
 *            (user password)
 * @param locale
 *            (user locale)
 * @param timezone
 *            (user timezone)
 * @return long
 */
private Long addUserToAccount(final Long accountKey, final String firstName, final String lastName,
        final String email, final String password, final String locale, final String timezone) {
    String userKey;
    try {
        JSONObject userJson = new JSONObject();
        userJson.put("email", email);
        userJson.put("firstName", firstName);
        userJson.put("lastName", lastName);
        userJson.put("password", password);
        userJson.put("locale", locale);
        userJson.put("timezone", timezone);

        HttpEntity httpEntity = new HttpEntity(userJson.toString(), this.accountSvcHeaders);
        userKey = this.restTemplate.exchange(this.accountSvcUrl + "/accounts/" + accountKey + "/users",
                HttpMethod.POST, httpEntity, String.class).getBody();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
    return Long.valueOf(userKey);
}

From source file:fi.helsinki.opintoni.service.usefullink.UsefulLinkService.java

public SearchPageTitleDto searchPageTitle(SearchPageTitleDto searchPageTitleDto) throws NotFoundException {
    try {//from w w w . j  ava 2s  .  co  m
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Lists.newArrayList(MediaType.TEXT_HTML));
        headers.add("User-Agent", "Mozilla");
        HttpEntity<String> entity = new HttpEntity<>("parameters", headers);

        ResponseEntity<String> responseEntity = linkUrlLoaderRestTemplate.exchange(searchPageTitleDto.searchUrl,
                HttpMethod.GET, entity, String.class);
        if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
            Document document = Jsoup.parse(responseEntity.getBody());
            searchPageTitleDto.searchResult = document.title();
        }
    } catch (Exception e) {
    }
    return searchPageTitleDto;
}