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:org.jodconverter.sample.springboot.ConverterController.java

@PostMapping("/converter")
public Object convert(@RequestParam("inputFile") final MultipartFile inputFile,
        @RequestParam(name = "outputFormat", required = false) final String outputFormat,
        final RedirectAttributes redirectAttributes) {

    if (inputFile.isEmpty()) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE, "Please select a file to upload.");
        return ON_ERROR_REDIRECT;
    }//from w  w w.j  av a 2  s  . c  o  m

    if (StringUtils.isBlank(outputFormat)) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE, "Please select an output format.");
        return ON_ERROR_REDIRECT;
    }

    // Here, we could have a dedicated service that would convert document
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

        final DocumentFormat targetFormat = DefaultDocumentFormatRegistry.getFormatByExtension(outputFormat);
        converter.convert(inputFile.getInputStream())
                .as(DefaultDocumentFormatRegistry
                        .getFormatByExtension(FilenameUtils.getExtension(inputFile.getOriginalFilename())))
                .to(baos).as(targetFormat).execute();

        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(targetFormat.getMediaType()));
        headers.add("Content-Disposition",
                "attachment; filename=" + FilenameUtils.getBaseName(inputFile.getOriginalFilename()) + "."
                        + targetFormat.getExtension());
        return new ResponseEntity<>(baos.toByteArray(), headers, HttpStatus.OK);

    } catch (OfficeException | IOException e) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE,
                "Unable to convert the file " + inputFile.getOriginalFilename() + ". Cause: " + e.getMessage());
    }

    return ON_ERROR_REDIRECT;
}

From source file:tds.tdsadmin.rest.TDSAdminControllerTest.java

@Test
public void getOpportunities() throws Exception {

    OpportunitySerializable opps = getOpps();
    when(_dao.getOpportunities("103", "four-3", "invalidate")).thenReturn(opps);
    opps = new OpportunitySerializable();
    when(_dao.getOpportunities("420", null, "invalidate")).thenReturn(opps);
    // test with student id and session id
    mockMvc.perform(get("/rest/getOpportunities?extSsId=103&sessionId=four-3&procedure=invalidate")
            .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))).andExpect(status().isOk())
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$", Matchers.hasSize(2)))
            .andExpect(jsonPath("$[*].name", Matchers.containsInAnyOrder("Shajib", "Khan")))
            .andExpect(jsonPath("$[*].testName", Matchers.containsInAnyOrder("english", "math")))
            .andExpect(jsonPath("$[*].altSsid", Matchers.containsInAnyOrder("777", "380")))
            .andExpect(jsonPath("$[*].status", Matchers.hasItems("paused", "expired")));

    // test with no request parameter
    mockMvc.perform(get("/rest/getOpportunities")).andExpect(status().isBadRequest());

    // test with non-existing id
    mockMvc.perform(get("/rest/getOpportunities?extSsId=420&procedure=invalidate"))
            .andExpect(jsonPath("$", Matchers.hasSize(0)));
}

From source file:be.dnsbelgium.rdap.DomainControllerTest.java

@Test
public void testAcceptRdapJson() throws Exception {
    DomainName domainName = DomainName.of("example.com");
    Domain domain = new Domain(null, null, null, null, null, null, null, null, domainName, domainName, null,
            null, null, null, null, null);
    when(domainService.getDomain(Mockito.any(DomainName.class))).thenReturn(domain);
    mockMvc.perform(get("/domain/example.com").accept(MediaType.parseMediaType("application/json")))
            .andExpect(status().isNotAcceptable());
}

From source file:de.metas.ui.web.upload.ImageRestController.java

@GetMapping("/{imageId}")
@ResponseBody//from w  w  w .  ja v  a2s  .  co  m
public ResponseEntity<byte[]> getImage(@PathVariable final int imageId) {
    userSession.assertLoggedIn();

    if (imageId <= 0) {
        throw new IllegalArgumentException("Invalid image id");
    }

    final MImage adImage = MImage.get(userSession.getCtx(), imageId);
    if (adImage == null || adImage.getAD_Image_ID() <= 0) {
        throw new EntityNotFoundException("Image id not found: " + imageId);
    }

    final boolean hasAccess = userSession.getUserRolePermissions().canView(adImage.getAD_Client_ID(),
            adImage.getAD_Org_ID(), I_AD_Image.Table_ID, adImage.getAD_Image_ID());
    if (!hasAccess) {
        throw new EntityNotFoundException("Image id not found: " + imageId);
    }

    final String imageName = adImage.getName();
    final byte[] imageData = adImage.getData();
    final String contentType = MimeType.getMimeType(imageName);

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(contentType));
    headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + imageName + "\"");
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    final ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(imageData, headers, HttpStatus.OK);
    return response;
}

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

@Test
public void testSeveralParameters() throws Exception {
    ResultActions resultActions = this.mvcMock
            .perform(get(PROJECT_BASE_URL + String.format(URL_PATTERN_NAME_DESC_SORTING, Direction.DESC))
                    .principal(AuthConstants.ADMINISTRATOR).secure(true)
                    .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
            .andExpect(status().isOk());

    resultActions.andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$.content[1].description").value("AAA-FIRST - Another Description"));
}

From source file:org.dawnsci.marketplace.controllers.PageController.java

@RequestMapping(value = "/pages/**", method = RequestMethod.GET)
@ResponseBody//from   w w  w . java  2s .c  o  m
public ResponseEntity<FileSystemResource> picture(HttpServletRequest request) {

    String resource = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE))
            .substring(1);
    Path path = fileService.getPageFile(resource).toPath();

    File file = path.toAbsolutePath().toFile();

    if (file.exists() && file.isFile()) {
        try {
            String detect = tika.detect(file);
            MediaType mediaType = MediaType.parseMediaType(detect);
            return ResponseEntity.ok().contentLength(file.length()).contentType(mediaType)
                    .body(new FileSystemResource(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        throw new ResourceNotFoundException();
    }
    return null;
}

From source file:th.co.geniustree.intenship.advisor.controller.InformationController.java

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

From source file:com.osc.edu.chapter4.employees.controller.EmployeesControllerTest.java

/**
 * Test method for {@link com.osc.edu.chapter4.employees.EmployeesController#insertEmployeesList()}.
 */// ww  w . j  a v a2 s.  c  o m
@Test
@Transactional
@Rollback(value = true)
public void insertEmployeesList() {
    try {
        this.mockMvc
                .perform(get("/employees/insertEmployeesList.do")
                        .accept(MediaType.parseMediaType("text/html;charset=UTF-8")))
                .andDo(print()).andExpect(status().isMovedTemporarily()).andExpect(redirectedUrl(
                        "/employees/getEmployeesList.do?messageList=This&messageList=is&messageList=sample&messageList=message&messageList=using&messageList=%40ModelAttribute."));
    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception has occurred.");
    }
}

From source file:com.osc.edu.chapter4.customers.controller.CustomersControllerTest.java

/**
 * Test method for {@link com.osc.edu.chapter4.customers.CustomersController#insertCustomersList()}.
 *//*from w w  w .j a  v  a 2 s  .  c o m*/
@Test
@Transactional
@Rollback(value = true)
public void insertCustomersList() {
    try {
        this.mockMvc
                .perform(post("/customers/insertCustomersList.do")
                        .accept(MediaType.parseMediaType("text/html;charset=UTF-8")))
                .andDo(print()).andExpect(status().isMovedTemporarily()).andExpect(redirectedUrl(
                        "/customers/getCustomersList.do?messageList=This&messageList=is&messageList=sample&messageList=message&messageList=using&messageList=%40ModelAttribute."));
    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception has occurred.");
    }
}

From source file:com.trenako.web.images.WebImageServiceImpl.java

private MediaType parse(String mediaType) {
    return MediaType.parseMediaType(mediaType);
}