Example usage for org.springframework.http MediaType ALL

List of usage examples for org.springframework.http MediaType ALL

Introduction

In this page you can find the example usage for org.springframework.http MediaType ALL.

Prototype

MediaType ALL

To view the source code for org.springframework.http MediaType ALL.

Click Source Link

Document

Public constant media type that includes all media ranges (i.e.

Usage

From source file:ch.ralscha.extdirectspring.controller.RouterControllerFormPostTest.java

@SuppressWarnings("unchecked")
@Test/*from  ww  w . j  a va 2  s  .  c  o m*/
public void testUpload() throws Exception {
    MockMultipartHttpServletRequestBuilder request = fileUpload("/router");
    request.accept(MediaType.ALL).characterEncoding("UTF-8").session(new MockHttpSession());

    request.param("extTID", "1");
    request.param("extAction", "uploadService");
    request.param("extMethod", "upload");
    request.param("extType", "rpc");
    request.param("name", "Ralph");
    request.param("age", "20");
    request.param("admin", "true");
    request.param("salary", "12.3");
    request.param("result", "theResult");

    request.file("fileUpload", "the content of the file".getBytes());

    MvcResult resultMvc = mockMvc.perform(request).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8")).andExpect(content().encoding("UTF-8"))
            .andReturn();

    String response = resultMvc.getResponse().getContentAsString();
    String prefix = "<html><body><textarea>";
    String suffix = "</textarea></body></html>";
    assertThat(response).startsWith(prefix).endsWith(suffix);
    String json = response.substring(prefix.length(), response.indexOf(suffix));

    ExtDirectResponse edsResponse = ControllerUtil
            .readDirectResponse(json.getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

    assertThat(edsResponse.getType()).isEqualTo("rpc");
    assertThat(edsResponse.getMessage()).isNull();
    assertThat(edsResponse.getWhere()).isNull();
    assertThat(edsResponse.getTid()).isEqualTo(1);
    assertThat(edsResponse.getAction()).isEqualTo("uploadService");
    assertThat(edsResponse.getMethod()).isEqualTo("upload");

    Map<String, Object> result = (Map<String, Object>) edsResponse.getResult();
    assertThat(result).hasSize(8);
    assertThat(result).contains(entry("e-mail", null), entry("age", 20), entry("name", "Ralph"),
            entry("fileName", ""), entry("fileContents", "the content of the file"), entry("firstName", null),
            entry("success", Boolean.TRUE));
    Map<String, Object> error = (Map<String, Object>) result.get("errors");
    assertThat(error).containsKey("email");
    assertThat((List<String>) error.get("email")).containsExactly("may not be empty");
}

From source file:it.unitn.disi.smatch.web.server.api.handlers.ExceptionDetailsExceptionResolver.java

@SuppressWarnings("unchecked")
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {
    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }/*from  w w  w  .j  av a2s .c o m*/

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    //return empty model and view to short circuit the iteration and to let
                    //Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}

From source file:ch.ralscha.extdirectspring.controller.ApiControllerWithDocumentationTest.java

private void doRequestWithoutDocs(String url) throws Exception {
    ApiRequestParams params = ApiRequestParams.builder().apiNs("Ext.ns").actionNs("actionns").group("doc")
            .configuration(configurationService.getConfiguration()).build();
    MockHttpServletRequestBuilder request = get(url).accept(MediaType.ALL).characterEncoding("UTF-8");
    request.param("apiNs", params.getApiNs());
    request.param("actionNs", params.getActionNs());
    request.param("group", params.getGroup());

    MvcResult result = mockMvc.perform(request).andExpect(status().isOk())
            .andExpect(content().contentType("application/javascript")).andReturn();

    ApiControllerTest.compare(result, ApiControllerTest.groupApisWithDoc("actionns"), params);
    Assert.doesNotContain("/**", result.getResponse().getContentAsString(),
            "generation of api.js should not contain method documentation");
}

From source file:com.oolong.platform.web.error.RestExceptionHandler.java

@SuppressWarnings("unchecked")
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }//from  ww  w  .  j  av a  2 s.c o  m

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    // return empty model and view to short circuit the
                    // iteration and to let
                    // Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}

From source file:com.novation.eligibility.rest.spring.web.servlet.handler.RestExceptionHandler.java

@SuppressWarnings("unchecked")
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }/*from   w  ww  .ja v a2s. com*/

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    //return empty model and view to short circuit the iteration and to let
                    //Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}

From source file:com.yang.oa.commons.exception.RestExceptionHandler.java

@SuppressWarnings("unchecked")
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }/*from   w ww. j  av  a 2  s.  c o m*/

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    //return empty model and view to short circuit the iteration and to let
                    //Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    return null;
}

From source file:org.jlot.web.api.error.RestExceptionHandler.java

@SuppressWarnings({ "unchecked", "rawtypes", "resource" })
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }//w  ww  . j  ava 2s .com

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    // return empty model and view to short circuit the
                    // iteration and to let
                    // Spring know that we've rendered the view ourselves:

                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}

From source file:ch.ralscha.extdirectspring.controller.ApiControllerWithDocumentationTest.java

private ActionDoc callApi(String method) throws Exception {
    ApiRequestParams params = ApiRequestParams.builder().apiNs("Ext.ns").actionNs("actionns").group("doc")
            .configuration(configurationService.getConfiguration()).build();
    MockHttpServletRequestBuilder request = get("/api-debug-doc.js").accept(MediaType.ALL)
            .characterEncoding("UTF-8");
    request.param("apiNs", params.getApiNs());
    request.param("actionNs", params.getActionNs());
    request.param("group", params.getGroup());

    MvcResult result = mockMvc.perform(request).andExpect(status().isOk())
            .andExpect(content().contentType("application/javascript")).andReturn();

    ApiControllerTest.compare(result, ApiControllerTest.groupApisWithDoc("actionns"), params);
    ActionDoc doc = getCommentForMethod(result.getResponse().getContentAsString(), method);
    return doc;//w  ww  . j  a  v a  2  s  .c o m
}

From source file:com.cloud.baremetal.networkservice.Force10BaremetalSwitchBackend.java

private HttpHeaders createBasicAuthenticationHeader(BaremetalVlanStruct struct) {
    String plainCreds = String.format("%s:%s", struct.getSwitchUsername(), struct.getSwitchPassword());
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);
    headers.setAccept(Arrays.asList(MediaType.ALL));
    headers.setContentType(MediaType.valueOf("application/vnd.yang.data+xml"));
    return headers;
}

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

private void doOpenIdHybridFlowIdTokenAndCode(Set<String> responseTypes, String responseTypeMatcher)
        throws Exception {

    HttpHeaders headers = new HttpHeaders();
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

    StringBuilder responseType = new StringBuilder();
    Iterator<String> rTypes = responseTypes.iterator();
    while (rTypes.hasNext()) {
        String type = rTypes.next();
        responseType.append(type);/*from  www  . j a v  a 2 s  .  c o  m*/
        if (rTypes.hasNext()) {
            responseType.append(" ");
        }
    }
    String state = new RandomValueStringGenerator().generate();
    String clientId = "app";
    String clientSecret = "appclientsecret";
    String redirectUri = "http://anywhere.com";
    String uri = loginUrl + "/oauth/authorize?response_type={response_type}&"
            + "state={state}&client_id={client_id}&redirect_uri={redirect_uri}";

    ResponseEntity<Void> result = restOperations.exchange(uri, HttpMethod.GET, new HttpEntity<>(null, headers),
            Void.class, responseType, state, clientId, redirectUri);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    ResponseEntity<String> response = restOperations.exchange(location, HttpMethod.GET,
            new HttpEntity<>(null, headers), String.class);
    // should be directed to the login screen...
    assertTrue(response.getBody().contains("/login.do"));
    assertTrue(response.getBody().contains("username"));
    assertTrue(response.getBody().contains("password"));

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", user.getUserName());
    formData.add("password", "secret");

    // Should be redirected to the original URL, but now authenticated
    result = restOperations.exchange(loginUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(formData, headers), Void.class);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    if (response.getStatusCode() == HttpStatus.OK) {
        // The grant access page should be returned
        assertTrue(response.getBody().contains("You can change your approval of permissions"));

        formData.clear();
        formData.add("user_oauth_approval", "true");
        result = restOperations.exchange(loginUrl + "/oauth/authorize", HttpMethod.POST,
                new HttpEntity<>(formData, headers), Void.class);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());
        location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    } else {
        // Token cached so no need for second approval
        assertEquals(HttpStatus.FOUND, response.getStatusCode());
        location = UriUtils.decode(response.getHeaders().getLocation().toString(), "UTF-8");
    }
    assertTrue("Wrong location: " + location, location.matches(redirectUri + responseTypeMatcher.toString()));

    formData.clear();
    formData.add("client_id", clientId);
    formData.add("redirect_uri", redirectUri);
    formData.add("grant_type", "authorization_code");
    formData.add("code", location.split("code=")[1].split("&")[0]);
    HttpHeaders tokenHeaders = new HttpHeaders();
    String basicDigestHeaderValue = "Basic "
            + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes()));
    tokenHeaders.set("Authorization", basicDigestHeaderValue);

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse = restOperations.exchange(loginUrl + "/oauth/token", HttpMethod.POST,
            new HttpEntity<>(formData, tokenHeaders), Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, String> body = tokenResponse.getBody();
    Jwt token = JwtHelper.decode(body.get("access_token"));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\""));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\""));
}