Example usage for org.springframework.http MediaType parseMediaType

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

Introduction

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

Prototype

public static MediaType parseMediaType(String mediaType) 

Source Link

Document

Parse the given String into a single MediaType .

Usage

From source file:com.epam.ta.reportportal.ws.MultipartRequestTest.java

@Test
public void testPageableLast() throws Exception {
    Resource multipartFile = new ClassPathResource(DEMO_FILE_NAME);
    MockMultipartFile mockMultipartFile = new MockMultipartFile(DEMO_FILE_NAME, multipartFile.getInputStream());

    this.mvcMock//from  w w  w.j a  v a2s .c  o m
            .perform(fileUpload(PROJECT_BASE_URL + "/log").file(mockMultipartFile).secure(true)
                    .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
            .andExpect(status().is(400));

}

From source file:com.epam.ta.reportportal.ws.SubmittingIssueMvcTest.java

@Test
@Ignore//from w ww.ja va2  s  . co  m
public void testDesc() throws Exception {
    this.mvcMock.perform(put(PROJECT_BASE_URL + RESOURCE).secure(true).contentType(MediaType.APPLICATION_JSON)
            .content(
                    "{\"submit_new\": true,\"issues\": [{\"test_item_id\": \"44524cc1553de753b3e5bb2f\",\"issue\": {\"issue_type\": \"Automation bug\",\"comment\": \"test\"}},{\"test_item_id\": \"44524cc1553de753b3e5cc2f\",\"issue\": {\"issue_type\": \"Automation bug\",\"comment\": \"test\"}}]}")
            .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))).andExpect(status().isOk());

}

From source file:com.mycompany.testdowload.controller.DocumentFileController.java

@RequestMapping(value = "/getfile/{id}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getFile(@PathVariable("id") UploadFile uploadFile) {
    ResponseEntity<InputStreamResource> body = ResponseEntity.ok().contentLength(uploadFile.getContent().length)
            .contentType(MediaType.parseMediaType(uploadFile.getMimeType()))
            .header("Content-Disposition", "attachment; filename=\"" + uploadFile.getName() + "\"")
            .body(new InputStreamResource(new ByteArrayInputStream(uploadFile.getContent())));
    return body;//from ww  w  . j  av a2s  .com
}

From source file:io.dyn.net.Message.java

@SuppressWarnings({ "unchecked" })
public M header(String header, String val, boolean add) {
    switch (header.toLowerCase()) {
    case "content-length":
        contentLength = Integer.parseInt(val);
        break;//w  w  w .ja va  2  s  .  c o m
    case "content-type":
        contentType = MediaType.parseMediaType(val);
        break;
    }
    if (add) {
        headers.put(header.toLowerCase(), val);
    } else {
        headers.replaceValues(header.toLowerCase(), Arrays.asList(val));
    }
    return (M) this;
}

From source file:com.xyxy.platform.examples.showcase.demos.hystrix.web.HystrixExceptionHandler.java

/**
 * ?Hystrix Runtime, ://from   ww w.  ja  va 2  s . c  o m
 * Command(500).
 * Hystrix??(503).
 */
@ExceptionHandler(value = { HystrixRuntimeException.class })
public final ResponseEntity<?> handleException(HystrixRuntimeException e, WebRequest request) {
    HttpStatus status = HttpStatus.SERVICE_UNAVAILABLE;
    String message = e.getMessage();

    FailureType type = e.getFailureType();

    // ?
    if (type.equals(FailureType.COMMAND_EXCEPTION)) {
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        message = Exceptions.getErrorMessageWithNestedException(e);
    }

    logger.error(message, e);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(MediaTypes.TEXT_PLAIN_UTF_8));
    return handleExceptionInternal(e, message, headers, status, request);
}

From source file:cn.aozhi.songify.rest.RestExceptionHandler.java

/**
 * ?JSR311 Validation.//from   w w  w  . j a  v  a2  s .c  o m
 */
@ExceptionHandler(value = { ConstraintViolationException.class })
public final ResponseEntity<?> handleException(ConstraintViolationException ex, WebRequest request) {
    Map<String, String> errors = BeanValidators.extractPropertyAndMessage(ex.getConstraintViolations());
    String body = jsonMapper.toJson(errors);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(MediaTypes.TEXT_PLAIN_UTF_8));
    return handleExceptionInternal(ex, body, headers, HttpStatus.BAD_REQUEST, request);
}

From source file:de.codecentric.boot.admin.journal.web.JournalControllerTest.java

@Test
public void test_getJournal() throws Exception {
    ClientApplicationEvent emittedEvent = new ClientApplicationRegisteredEvent(
            Application.create("foo").withId("bar").withHealthUrl("http://health").build());
    journal.onClientApplicationEvent(emittedEvent);

    mvc.perform(get("/api/journal").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(jsonPath("$[0].type").value("REGISTRATION"));

    mvc.perform(get("/api/journal").accept(MediaType.parseMediaType("text/event-stream")))
            .andExpect(status().isOk());
}

From source file:io.spring.initializr.service.InitializrServiceSmokeTests.java

@Test
public void metadataCanBeSerialized() throws URISyntaxException, IOException {
    RequestEntity<Void> request = RequestEntity.get(new URI("/"))
            .accept(MediaType.parseMediaType("application/vnd.initializr.v2.1+json")).build();
    ResponseEntity<String> response = this.restTemplate.exchange(request, String.class);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    new ObjectMapper().readTree(response.getBody());
}

From source file:edu.eci.cosw.postresYa.controller.ActivityController.java

/**
 * Busca la imagen a un postre asociado por medio de un cdigo dado
 * @param code// www . java2s .co m
 * @return ResponseEntity 
 */
@RequestMapping(value = "/{code}/picture", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getPostrePicture(@PathVariable String code) {

    try {
        return ResponseEntity.ok().contentType(MediaType.parseMediaType("image/jpg"))
                .body(new InputStreamResource(stub.getPostrePicture(code)));
    } catch (Exception e) {

        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

From source file:com.iflytek.edu.cloud.frame.spring.MappingJackson2HttpMessageConverterExt.java

@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    outputMessage.getHeaders().setContentType(MediaType.parseMediaType("application/json"));
    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.getObjectMapper().getFactory().createGenerator(outputMessage.getBody(),
            encoding);//from  w  w w  .jav a 2s  . c  o  m

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.getObjectMapper().isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    String callBack = (String) RestContextHolder.getContext().getParam(Constants.SYS_PARAM_KEY_CALLBACK);
    try {
        if (StringUtils.hasText(callBack)) {
            String json = this.getObjectMapper().writeValueAsString(object);
            json = callBack + "( " + json + " )";
            outputMessage.getBody().write(json.getBytes(Charset.forName("UTF-8")));
            outputMessage.getBody().flush();
        } else {
            this.getObjectMapper().writeValue(jsonGenerator, object);
        }
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}