List of usage examples for org.springframework.http MediaType parseMediaType
public static MediaType parseMediaType(String mediaType)
From source file:guru.nidi.ramltester.uc.spring.MockContextTest.java
@Test public void testGreetingWithMvcResult() throws Exception { final MvcResult mvcResult = mockMvc .perform(get("/greeting?name=hula").accept(MediaType.parseMediaType("application/json"))) .andReturn();//from w w w.j a v a2 s .c o m final RamlReport report = aggregator.addReport(api.testAgainst(mvcResult)); assertThat(report, hasNoViolations()); }
From source file:com.osc.edu.chapter4.employees.controller.EmployeesControllerTest.java
/** * Test method for {@link com.osc.edu.chapter4.employees.EmployeesController#getEmployeesList(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}. *///from w w w .j a v a 2 s . co m @Test public void testGetEmployeesList() { try { this.mockMvc .perform(get("/employees/getEmployeesList.do") .accept(MediaType.parseMediaType("text/html;charset=UTF-8"))) .andDo(print()).andExpect(status().isOk()).andExpect(model().attributeExists("employeesList")) .andExpect(view().name("employees/list")) .andExpect(forwardedUrl("/WEB-INF/jsp/employees/list.jsp")); } 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#getCustomersList(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}. * @throws Exception //from w w w .j a v a 2 s .c o m */ @Test public void testGetCustomersList() { try { this.mockMvc .perform(get("/customers/getCustomersList.do") .accept(MediaType.parseMediaType("text/html;charset=UTF-8"))) .andDo(print()).andExpect(status().isOk()).andExpect(model().attributeExists("customersList")) .andExpect(view().name("customers/list")) .andExpect(forwardedUrl("/WEB-INF/jsp/customers/list.jsp")); } catch (Exception e) { e.printStackTrace(); fail("Exception has occurred."); } }
From source file:com.appspot.potlachkk.controller.ImageSvc.java
@RequestMapping(value = ImageSvcApi.IMG_SVC_PATH_ID, method = RequestMethod.GET) public ResponseEntity<byte[]> getImageById(@PathVariable("id") Long id) { GiftImage img = images.findOne(id);/* w w w .ja v a 2 s . com*/ final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(img.getMimeType())); return new ResponseEntity<byte[]>(img.getData().getBytes(), headers, HttpStatus.OK); }
From source file:pl.maciejwalkowiak.plist.spring.PlistHttpMessageConverterTest.java
@Test public void testPlistHttpMessageConverter() throws Exception { MvcResult result = this.mockMvc .perform(get("/test").accept(MediaType.parseMediaType("application/x-plist"))) .andExpect(status().isOk()).andExpect(content().contentType("application/x-plist")).andReturn(); String xml = result.getResponse().getContentAsString(); assertThat(xml).isEqualTo("<dict><key>name</key><string>Franz Kafka</string></dict>"); }
From source file:spring.boot.hateoas.sample.SampleHdivApplication.java
@Bean public WebMvcConfigurerAdapter webConfig() { return new WebMvcConfigurerAdapter() { @Bean/*from ww w. ja v a2 s .c o m*/ public HalHttpMessageConverter halMessageConverter() { return new HalHttpMessageConverter(messageSource); } @Bean public HalFormsMessageConverter halFormsMessageConverter() { HalFormsMessageConverter converter = new HalFormsMessageConverter(objectMapper(), relProvider, curieProvider(), resourceDescriptionMessageSourceAccessor); converter.setSupportedMediaTypes( Arrays.asList(MediaType.parseMediaType("application/prs.hal-forms+json"))); return converter; } @Override public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) { converters.add(halMessageConverter()); converters.add(halFormsMessageConverter()); converters.add(new XhtmlResourceMessageConverter()); super.configureMessageConverters(converters); } }; }
From source file:io.github.autsia.crowly.controllers.DashboardController.java
@RequestMapping(value = "/campaigns/export/{campaignId}", method = RequestMethod.GET) public ResponseEntity<byte[]> export(@PathVariable("campaignId") String campaignId, ModelMap model) throws DocumentException { Document document = new Document(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PdfWriter.getInstance(document, byteArrayOutputStream); document.open();/*w w w . j a v a 2 s. c om*/ Gson gson = new Gson(); String json = gson.toJson(mentionRepository.findByCampaignId(campaignId)); document.add(new Paragraph(json)); document.close(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/pdf")); String filename = "output.pdf"; headers.setContentDispositionFormData(filename, filename); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK); return response; }
From source file:cucumber.api.spring.test.web.servlet.MockMvcStepdefs.java
@Given("^the request content type is \"(.*?)\"$") public void the_request_content_type_is(String contentType) throws Throwable { // https://jira.spring.io/browse/SPR-12405 requestBuilder.contentType(MediaType.parseMediaType(contentType)); }
From source file:apiserver.core.common.ResponseEntityHelper.java
/** * return a BufferedImage as byte[] array or as a base64 version of the image bytes * @param image//from ww w. ja v a2s .c o m * @param contentType * @param returnAsBase64 * @return * @throws java.io.IOException public static ResponseEntity<byte[]> processImage(Object image, String contentType, Boolean returnAsBase64) throws IOException { HttpHeaders headers = new HttpHeaders(); // set content type String convertToType = "jpg"; if(contentType == null ) { contentType = "jpg"; contentType = contentType.toLowerCase(); } if( contentType.contains("jpg") || contentType.contains("jpeg")) { convertToType = "jpg"; headers.setContentType(MediaType.IMAGE_JPEG); } else if( contentType.contains("png")) { convertToType = "png"; headers.setContentType(MediaType.IMAGE_PNG); } else if( contentType.contains("gif")) { convertToType = "gif"; headers.setContentType(MediaType.IMAGE_GIF); } else { headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); } if( image instanceof BufferedImage) { //DataBufferByte bytes = (DataBufferByte)((BufferedImage) image).getRaster().getDataBuffer(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write((BufferedImage) image, convertToType, baos); byte [] bytes = baos.toByteArray(); if (!returnAsBase64) { return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK); } else { return new ResponseEntity<byte[]>(Base64.encode(bytes) , headers, HttpStatus.OK); } } else if( image instanceof byte[] ) { if (!returnAsBase64) { return new ResponseEntity<byte[]>( (byte[])image, headers, HttpStatus.OK); } else { return new ResponseEntity<byte[]>(Base64.encode((byte[])image) , headers, HttpStatus.OK); } } throw new RuntimeException("Invalid Image bytes"); } */ public static ResponseEntity<byte[]> processImage(BufferedImage image, String contentType, Boolean returnAsBase64) throws IOException { // set content type String convertToType = "png"; if (contentType == null) { contentType = "application/octet-stream"; contentType = contentType.toLowerCase(); } else { convertToType = MimeType.getMimeType(contentType).getExtension(); } // HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(contentType)); if (returnAsBase64) { headers.set("Content-Transfer-Encoding", "base64"); } if (image instanceof BufferedImage) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, convertToType, baos); byte[] bytes = baos.toByteArray(); return processFile(bytes, contentType, returnAsBase64); } throw new RuntimeException("Invalid Image bytes"); }
From source file:com.alehuo.wepas2016projekti.controller.ImageController.java
/** * Hakee tietokannasta kuvan. Kuvan hakemisessa hydynnetn ETag * -otsaketta./*from www . ja va 2 s. co m*/ * * @param a Autentikointi * @param imageUuid Kuvan UUID * @param ifNoneMatch If-None-Match -headeri vlimuistia varten * @return Kuva */ @RequestMapping(value = "/{imageUuid}", method = RequestMethod.GET) @ResponseBody public ResponseEntity<byte[]> getImage(Authentication a, @PathVariable String imageUuid, @RequestHeader(required = false, value = "If-None-Match") String ifNoneMatch) { if (ifNoneMatch != null) { // LOG.log(Level.INFO, "Kuva ''{0}'' loytyy kayttajan selaimen valimuistista eika sita tarvitse ladata. Kuvaa pyysi kayttaja ''{1}''", new Object[]{imageUuid, a.getName()}); //Jos If-None-Match -headeri lytyy, niin lhet NOT MODIFIED vastaus return new ResponseEntity<>(HttpStatus.NOT_MODIFIED); } Image i = imageService.findOneImageByUuid(imageUuid); if (i != null && i.isVisible()) { //Luodaan ETag kuvalle final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(i.getContentType())); headers.setContentLength(i.getImageData().length); headers.setCacheControl("public"); headers.setExpires(Long.MAX_VALUE); headers.setETag("\"" + imageUuid + "\""); // LOG.log(Level.INFO, "Kuva ''{0}'' loytyi tietokannasta, ja sita pyysi kayttaja ''{1}''", new Object[]{imageUuid, a.getName()}); //Palautetaan kuva uutena resurssina return new ResponseEntity<>(i.getImageData(), headers, HttpStatus.CREATED); } else { //Jos kuvaa ei lydy tietokannasta LOG.log(Level.WARNING, "Kuvaa ''{0}'' ei loytynyt tietokannasta, ja sita pyysi kayttaja ''{1}''", new Object[] { imageUuid, a.getName() }); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } }