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:org.apigw.util.OAuthTestHelper.java

private String loginAndGrabCookie() {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("j_username", username);
    formData.add("j_password", password);

    // Should be redirected to the original URL, but now authenticated
    ResponseEntity<Void> result = serverRunning.postForStatus("/apigw-auth-server-web/login.do", headers,
            formData);//from  w  w  w  . jav  a2s. c om

    assertEquals(HttpStatus.FOUND, result.getStatusCode());

    assertTrue(result.getHeaders().containsKey("Set-Cookie"));

    return result.getHeaders().getFirst("Set-Cookie");

}

From source file:org.cloudfoundry.identity.uaa.integration.NativeApplicationIntegrationTests.java

/**
 * tests that a client secret is required.
 *//*from   w  w w .  j a  v a2 s .  co  m*/
@Test
public void testSecretRequired() throws Exception {
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("grant_type", "password");
    formData.add("username", resource.getUsername());
    formData.add("password", resource.getPassword());
    formData.add("scope", "cloud_controller.read");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Basic " + new String(Base64.encode("no-such-client:".getBytes("UTF-8"))));
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    ResponseEntity<String> response = serverRunning.postForString("/oauth/token", formData, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}

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

/**
 * Method, where scenario information is pushed to server in order to new scenario.
 * All heavy lifting is made here./*  w  ww.  j  a  v a2 s .  c  om*/
 *
 * @param scenarios only one scenario is accepted - scenario to be uploaded
 * @return scenario stored
 */
@Override
protected Scenario doInBackground(Scenario... scenarios) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_SCENARIOS;

    setState(RUNNING, R.string.working_ws_create_scenario);
    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());
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    Scenario scenario = scenarios[0];

    try {
        Log.d(TAG, url);
        FileSystemResource toBeUploadedFile = new FileSystemResource(scenario.getFilePath());

        //due to multipart file, MultiValueMap is the simplest approach for performing the post request
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("scenarioName", scenario.getScenarioName());
        form.add("researchGroupId", scenario.getResearchGroupId());
        form.add("description", scenario.getDescription());
        form.add("mimeType", scenario.getMimeType());
        form.add("private", Boolean.toString(scenario.isPrivate()));
        form.add("file", toBeUploadedFile);

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

From source file:comsat.sample.actuator.SampleActuatorApplicationTests.java

private void testHtmlErrorPage(final String path) throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    HttpEntity<?> request = new HttpEntity<Void>(headers);
    ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()).exchange(
            "http://localhost:" + this.port + "/" + emptyIfNull(path) + "/foo", HttpMethod.GET, request,
            String.class);
    assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode());
    String body = entity.getBody();
    assertNotNull("Body was null", body);
    assertTrue("Wrong body: " + body, body.contains("This application has no explicit mapping for /error"));
}

From source file:org.apigw.util.OAuthTestHelper.java

public String loginAndGetConfirmationPage(String clientId, String redirectUri, String scope) {

    String cookie = loginAndGrabCookie();

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    headers.set("Cookie", cookie);

    ServerRunning.UriBuilder uri = serverRunning.buildUri("/apigw-auth-server-web/oauth/authorize")
            .queryParam("response_type", "code").queryParam("state", "gzzFqB!!!").queryParam("scope", scope);
    if (clientId != null) {
        uri.queryParam("client_id", clientId);
    }/*  w  w  w  .  j  a va  2 s  .c  o m*/
    if (redirectUri != null) {
        uri.queryParam("redirect_uri", redirectUri);
    }

    ResponseEntity<String> response = serverRunning.getForString(uri.pattern(), headers, uri.params());

    // The confirm access page should be returned

    assertTrue(response.getBody().contains("API Test"));

    return cookie;

}

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

/**
 * Method, where all experiments are read from server.
 * All heavy lifting is made here./*from ww  w. j  a v a 2s .  c  o  m*/
 *
 * @param params not used (omitted) here
 * @return list of fetched experiments
 */
@Override
protected List<Experiment> 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_EXPERIMENTS;

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

        //obtain all public records if qualifier is all
        if (Values.SERVICE_QUALIFIER_ALL.equals(qualifier)) {
            String countUrl = url + "count";
            ResponseEntity<RecordCount> count = restTemplate.exchange(countUrl, HttpMethod.GET, entity,
                    RecordCount.class);

            url += "public/" + count.getBody().getPublicRecords();
        } else
            url += qualifier;

        // Make the network request
        Log.d(TAG, url);
        ResponseEntity<ExperimentList> response = restTemplate.exchange(url, HttpMethod.GET, entity,
                ExperimentList.class);
        ExperimentList body = response.getBody();

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

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

From source file:sparklr.common.AbstractEmptyAuthorizationCodeProviderTests.java

protected HttpHeaders getAuthenticatedHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    headers.set("Authorization", getBasicAuthentication());
    if (context.getRestTemplate() != null) {
        context.getAccessTokenRequest().setHeaders(headers);
    }//from  w w  w .j  a  v a  2 s.  c om
    return headers;
}

From source file:aiai.ai.station.LaunchpadRequester.java

/**
 * this scheduler is being run at the station side
 *
 * long fixedDelay()//from ww  w. java2s  . co m
 * Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.
 */
public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;
    }
    if (!globals.isStationEnabled) {
        return;
    }

    ExchangeData data = new ExchangeData();
    String stationId = stationService.getStationId();
    if (stationId == null) {
        data.setCommand(new Protocol.RequestStationId());
    }
    data.setStationId(stationId);

    if (stationId != null) {
        // always report about current active sequences, if we have actual stationId
        data.setCommand(stationTaskService.produceStationSequenceStatus());
        data.setCommand(stationService.produceReportStationStatus());
        final boolean b = stationTaskService.isNeedNewExperimentSequence(stationId);
        if (b) {
            data.setCommand(new Protocol.RequestTask(globals.isAcceptOnlySignedSnippets));
        }
        if (System.currentTimeMillis() - lastRequestForMissingResources > 15_000) {
            data.setCommand(new Protocol.CheckForMissingOutputResources());
            lastRequestForMissingResources = System.currentTimeMillis();
        }
    }

    reportSequenceProcessingResult(data);

    List<Command> cmds;
    synchronized (commands) {
        cmds = new ArrayList<>(commands);
        commands.clear();
    }
    data.setCommands(cmds);

    // !!! always use data.setCommand() for correct initializing stationId !!!

    // we have to pull new tasks from server constantly
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (globals.isSecureRestUrl) {
            String auth = globals.restUsername + '=' + globals.restToken + ':' + globals.stationRestPassword;
            byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.US_ASCII));
            String authHeader = "Basic " + new String(encodedAuth);
            headers.set("Authorization", authHeader);
        }

        HttpEntity<ExchangeData> request = new HttpEntity<>(data, headers);

        ResponseEntity<ExchangeData> response = restTemplate.exchange(globals.serverRestUrl, HttpMethod.POST,
                request, ExchangeData.class);
        ExchangeData result = response.getBody();

        addCommands(commandProcessor.processExchangeData(result).getCommands());
        log.debug("fixedDelay(), {}", result);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            log.error("Error 401 accessing url {}, globals.isSecureRestUrl: {}", globals.serverRestUrl,
                    globals.isSecureRestUrl);
        } else {
            throw e;
        }
    } catch (RestClientException e) {
        log.error("Error accessing url: {}", globals.serverRestUrl);
        log.error("Stacktrace", e);
    }
}

From source file:org.cloudfoundry.identity.uaa.integration.NativeApplicationIntegrationTests.java

/**
 * tests that an error occurs if you attempt to use bad client credentials.
 *//*ww  w  .j a  va 2  s. co  m*/
@Test
// Need a custom auth entry point to get the correct JSON response here.
public void testInvalidClient() throws Exception {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("grant_type", "password");
    formData.add("username", resource.getUsername());
    formData.add("password", resource.getPassword());
    formData.add("scope", "cloud_controller.read");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Basic " + new String(Base64.encode("no-such-client:".getBytes("UTF-8"))));
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap("/oauth/token", formData, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    List<String> newCookies = response.getHeaders().get("Set-Cookie");
    if (newCookies != null && !newCookies.isEmpty()) {
        fail("No cookies should be set. Found: " + newCookies.get(0) + ".");
    }
    assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));

    @SuppressWarnings("unchecked")
    OAuth2Exception error = OAuth2Exception.valueOf(response.getBody());
    assertEquals("invalid_client", error.getOAuth2ErrorCode());
}