Example usage for org.springframework.http HttpHeaders setAccept

List of usage examples for org.springframework.http HttpHeaders setAccept

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders setAccept.

Prototype

public void setAccept(List<MediaType> acceptableMediaTypes) 

Source Link

Document

Set the list of acceptable MediaType media types , as specified by the Accept header.

Usage

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

/**
 * Method, where electrode location information is pushed to server in order to create user.
 * All heavy lifting is made here./*from  w  ww  .  j a  va2s .  c om*/
 *
 * @param electrodeLocations only one ElectrodeLocation object is accepted
 * @return information about created electrode location
 */
@Override
protected ElectrodeLocation doInBackground(ElectrodeLocation... electrodeLocations) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_ELECTRODE_LOCATIONS;

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

    ElectrodeLocation location = electrodeLocations[0];

    try {
        Log.d(TAG, url);

        HttpEntity<ElectrodeLocation> entity = new HttpEntity<ElectrodeLocation>(location, requestHeaders);
        // Make the network request
        return restTemplate.postForObject(url, entity, ElectrodeLocation.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.CreateExperiment.java

/**
 * Method, where Experiment information is pushed to server in order to create user.
 * All heavy lifting is made here.//  ww w .j a  va 2  s  . c om
 *
 * @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:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.CreatePerson.java

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

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

    Person person = persons[0];

    try {
        Log.d(TAG, url);

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

From source file:org.cloudfoundry.identity.uaa.login.feature.ImplicitGrantIT.java

@Test
public void testDefaultScopes() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token");
    postBody.add("source", "credentials");
    postBody.add("username", testAccounts.getUserName());
    postBody.add("password", testAccounts.getPassword());

    ResponseEntity<Void> responseEntity = restOperations.exchange(baseUrl + "/oauth/authorize", HttpMethod.POST,
            new HttpEntity<>(postBody, headers), Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation())
            .build();//from   w ww .  j  av  a  2  s.c  o  m
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write",
            "cloud_controller.write", "openid", "cloud_controller.read"));

    Jwt access_token = JwtHelper.decode(params.getFirst("access_token"));

    Map<String, Object> claims = new ObjectMapper().readValue(access_token.getClaims(),
            new TypeReference<Map<String, Object>>() {
            });

    Assert.assertThat((String) claims.get("jti"), is(params.getFirst("jti")));
    Assert.assertThat((String) claims.get("client_id"), is("cf"));
    Assert.assertThat((String) claims.get("cid"), is("cf"));
    Assert.assertThat((String) claims.get("user_name"), is(testAccounts.getUserName()));

    Assert.assertThat(((List<String>) claims.get("scope")), containsInAnyOrder(scopes));

    Assert.assertThat(((List<String>) claims.get("aud")),
            containsInAnyOrder("cf", "scim", "openid", "cloud_controller", "password"));
}

From source file:com.tikinou.schedulesdirect.ClientUtils.java

/**
 * @return the requestEntity/*from   w w w . j a v a 2  s  . c  o  m*/
 */
private <T> HttpEntity<T> getRequestEntity(String userAgent, T body, String token, MediaType... mediaTypes) {

    if (null == mediaTypes || mediaTypes.length == 0) {
        mediaTypes = new MediaType[1];
        mediaTypes[0] = MediaType.APPLICATION_JSON;
    }

    if (mediaTypes.length > 1) {
        throw new IllegalArgumentException("Should only be one MediaType here");
    }

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAccept(Arrays.asList(mediaTypes));
    requestHeaders.add("Accept-Encoding", "deflate");
    requestHeaders.add("Connection", "Close");
    if (userAgent == null)
        userAgent = "tikinou-sd-api";
    requestHeaders.add("User-Agent", userAgent);
    if (token != null)
        requestHeaders.add("token", token);
    return new HttpEntity<>(body, requestHeaders);
}

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

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

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

    Weather weather = weathers[0];

    try {
        Log.d(TAG, url);

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

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);
        }// w w w.j  a v a 2 s  .  co 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:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.FetchResearchGroups.java

/**
 * Method, where all research groups are read from server.
 * All heavy lifting is made here.//from   w  ww . ja  v a 2s. c o  m
 *
 * @param params omitted here
 * @return list of fetched research groups
 */
@Override
protected List<ResearchGroup> doInBackground(Void... params) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_RESEARCH_GROUPS + qualifier;

    setState(RUNNING, R.string.working_ws_groups);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    HttpEntity<Object> entity = new HttpEntity<Object>(requestHeaders);

    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<ResearchGroupList> response = restTemplate.exchange(url, HttpMethod.GET, entity,
                ResearchGroupList.class);
        ResearchGroupList body = response.getBody();

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

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

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

/**
 * Method, where data file information is pushed to server in order to create data file record.
 * All heavy lifting is made here.//w  w  w  .  ja  v  a2s  . c  om
 *
 * @param dataFileContents must be three params in order - experiment id, description, path to file
 * @return URI of uploaded file
 */
@Override
protected URI doInBackground(String... dataFileContents) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_DATAFILE;

    setState(RUNNING, R.string.working_ws_upload_data_file);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    //so files wont buffer in memory
    factory.setBufferRequestBody(false);
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

    try {
        Log.d(TAG, url);
        FileSystemResource toBeUploadedFile = new FileSystemResource(dataFileContents[2]);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("experimentId", dataFileContents[0]);
        form.add("description", dataFileContents[1]);
        form.add("file", toBeUploadedFile);

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

From source file:com.develcom.reafolder.ClienteBajaArchivo.java

public void buscarArchivo() throws FileNotFoundException, IOException {

    CodDecodArchivos cda = new CodDecodArchivos();
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    Bufer bufer = new Bufer();
    byte[] buffer = null;
    ResponseEntity<byte[]> response;

    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    headers.setAccept(Arrays.asList(MediaType.ALL));
    HttpEntity<String> entity = new HttpEntity<>(headers);

    response = restTemplate.exchange(//  w ww.j  a va 2s. c  o  m
            "http://localhost:8080/ServicioDW4J/expediente/buscarFisicoDocumento/21593", HttpMethod.GET, entity,
            byte[].class);

    if (response.getStatusCode().equals(HttpStatus.OK)) {
        buffer = response.getBody();
        FileOutputStream output = new FileOutputStream(new File("c:/documentos/archivo.cod"));
        IOUtils.write(response.getBody(), output);
        cda.decodificar("c:/documentos/archivo.cod", "c:/documentos/archivo.pdf");
    }

}