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.greglturnquist.springagram.fileservice.mongodb.ApplicationController.java

@RequestMapping(method = RequestMethod.GET, value = "/files/{filename}")
public ResponseEntity<?> getFile(@PathVariable String filename) {

    GridFsResource file = this.fileService.findOne(filename);

    if (file == null) {
        return ResponseEntity.notFound().build();
    }// ww w  .  ja v  a  2  s. c om

    try {
        return ResponseEntity.ok().contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType(file.getContentType()))
                .body(new InputStreamResource(file.getInputStream()));
    } catch (IOException e) {
        return ResponseEntity.badRequest().body("Couldn't process the request");
    }
}

From source file:com.appspot.potlachkk.controller.ImageSvc.java

@RequestMapping(value = ImageSvcApi.IMG_SVC_PATH_ID + "/mini", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImageByIdMini(@PathVariable("id") Long id) {
    GiftImage img = images.findOne(id);//from ww  w  . j a  v  a 2  s.c o m

    byte[] oldImageData = img.getData().getBytes();

    ImagesService imagesService = ImagesServiceFactory.getImagesService();
    Image oldImage = ImagesServiceFactory.makeImage(oldImageData);
    Transform resize = ImagesServiceFactory.makeResize(200, 300, false);

    Image newImage = imagesService.applyTransform(resize, oldImage);

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(img.getMimeType()));

    return new ResponseEntity<byte[]>(newImage.getImageData(), headers, HttpStatus.OK);
}

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/*  w w  w  . java  2  s .c  o m*/
 * @param contentType
 * @param returnAsBase64
 * @return
 * @throws java.io.IOException
 */
public static ResponseEntity<byte[]> processFile(byte[] bytes, String contentType, Boolean returnAsBase64)
        throws IOException {
    HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.parseMediaType(contentType)); //todo verify this is right.

    if (bytes instanceof byte[]) {
        if (!returnAsBase64) {
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(Base64.encodeBase64(bytes), headers, HttpStatus.OK);
        }
    }

    throw new RuntimeException("Invalid bytes");
}

From source file:bg.vitkinov.edu.services.JokeService.java

@RequestMapping(value = "/jokeImage/{id}", method = RequestMethod.GET, produces = { MediaType.IMAGE_PNG_VALUE })
public ResponseEntity<byte[]> getJokeImage(@PathVariable Long id,
        @RequestHeader(value = "Accept") String acceptType,
        @RequestParam(required = false, defaultValue = "Arial-14") String font,
        @RequestParam(required = false, defaultValue = "black") String foreColor,
        @RequestParam(required = false) String backColor) {
    Joke joke = jokeRepository.findOne(id);
    ServiceInstance instance = loadBalancerClient.choose("image-service");
    if (instance == null)
        return null;
    /*//from w  ww .  java2  s .c  om
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.set("text", Base64.getEncoder().encodeToString(joke.getContent().getBytes()));
      params.set("Accept", acceptType);
      params.set("base64", "true");
      params.set("font", font);
      params.set("foreColor", foreColor);
      params.set("foreColor", foreColor);
      params.set("backColor", backColor);
      */
    HttpHeaders params = new HttpHeaders();
    MediaType requestAcceptType = acceptType == null || "".equals(acceptType) ? MediaType.IMAGE_PNG
            : MediaType.parseMediaType(acceptType);
    params.setAccept(Arrays.asList(requestAcceptType));
    params.add("text", Base64.getEncoder().encodeToString(joke.getContent().getBytes()));
    params.add("base64", "true");
    params.add("font", font);
    params.add("foreColor", foreColor);
    params.add("backColor", backColor);

    //        URI url = URI.create(String.format("%s/img", instance.getUri().toString()))
    URI url = instance.getUri().resolve("/img");
    HttpEntity<byte[]> entity = new HttpEntity<byte[]>(null, params);
    return restTemplate.exchange(url.toString(), HttpMethod.POST, entity, byte[].class);
}

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

@Ignore
@Test/*ww  w .j  a va2  s.  c om*/
public void testEndTime() throws Exception {
    ResultActions resultActions = this.mvcMock
            .perform(get(PROJECT_BASE_URL + String.format(URL_PATTERN_END_TIME_SORTING, Sort.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[0].end_time").value(1367493780000L));
}

From source file:org.wallride.web.support.MediaHttpRequestHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    checkAndPrepare(request, response, true);

    Map<String, Object> pathVariables = (Map<String, Object>) request
            .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    String key = (String) pathVariables.get("key");

    Media media = mediaService.getMedia(key);
    int width = ServletRequestUtils.getIntParameter(request, "w", 0);
    int height = ServletRequestUtils.getIntParameter(request, "h", 0);
    int mode = ServletRequestUtils.getIntParameter(request, "m", 0);

    Resource resource = readResource(media, width, height, Media.ResizeMode.values()[mode]);

    if (resource == null) {
        logger.debug("No matching resource found - returning 404");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from  ww  w.ja  v a  2  s.  co m*/
    }
    if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
        logger.debug("Resource not modified - returning 304");
        return;
    }

    long length = resource.contentLength();
    if (length > Integer.MAX_VALUE) {
        throw new IOException("Resource content too long (beyond Integer.MAX_VALUE): " + resource);
    }

    response.setContentLength((int) length);
    response.setContentType(media.getMimeType());
    if (!"image".equals(MediaType.parseMediaType(media.getMimeType()).getType())) {
        response.setHeader("Content-Disposition",
                "attachment;filename*=utf-8''" + URLEncoder.encode(media.getOriginalName(), "UTF-8"));
    }

    FileCopyUtils.copy(resource.getInputStream(), response.getOutputStream());
}

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

@Test
public void testDefaultGet() 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/rdap+json")))
            .andExpect(status().isOk()).andExpect(jsonPath("$.ldhName", "example.com").exists());
}

From source file:com.github.ffremont.microservices.springboot.manager.nexus.NexusClientApi.java

/**
 * A METTRE EN CACHE//from   w ww . j  a  v a2 s  .c  om
 * Retourne la donne Nexus correspondant au binaire
 *
 * @param groupId
 * @param artifact
 * @param classifier
 * @param version
 * @param packaging
 * @return
 */
public NexusData getData(String groupId, String artifact, String packaging, String classifier, String version) {
    NexusData data = null;
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.parseMediaType(MediaType.APPLICATION_JSON.toString())));
    HttpEntity<NexusDataResult> entity = new HttpEntity<>(headers);

    String template = nexusProps.getBaseurl()
            + "/service/local/artifact/maven/resolve?r={r}&g={g}&a={a}&v={v}&p={p}", url;
    for (String repo : nexusProps.getRepo()) {
        url = template.replace("{r}", repo).replace("{g}", groupId).replace("{a}", artifact)
                .replace("{v}", version).replace("{p}", packaging);
        if (classifier != null) {
            url = url.concat("&c=" + classifier);
        }

        try {
            LOG.info("nexusClient url {}", url);
            ResponseEntity<NexusDataResult> response = this.nexusClient.exchange(url, HttpMethod.GET, entity,
                    NexusDataResult.class);

            data = response.getBody().getData();
            LOG.info("Rcupration avec succs de nexus");
            break;
        } catch (HttpClientErrorException hee) {
            if (!HttpStatus.NOT_FOUND.equals(hee.getStatusCode())) {
                LOG.warn("Nexus : erreur cliente", hee);
                throw hee;
            }
        }
    }

    return data;
}

From source file:net.solarnetwork.node.setup.web.NodeCertificatesController.java

/**
 * Return a node's current certificate.//  w ww  . ja va 2s  .  com
 * 
 * @return a map with the PEM encoded certificate on key {@code cert} if
 *         {@code download} is not <em>true</em>, otherwise the content is
 *         returned as a file attachment
 */
@RequestMapping(value = "/nodeCert", method = RequestMethod.GET)
@ResponseBody
public Object viewNodeCert(@RequestParam(value = "download", required = false) final Boolean download,
        @RequestParam(value = "chain", required = false) final Boolean asChain) {
    final String cert = (Boolean.TRUE.equals(asChain) ? pkiService.generateNodePKCS7CertificateChainString()
            : pkiService.generateNodePKCS7CertificateString());

    if (!Boolean.TRUE.equals(download)) {
        Map<String, Object> result = new HashMap<String, Object>(1);
        result.put("cert", cert);
        return result;
    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentLength(cert.length());
    headers.setContentType(MediaType.parseMediaType("application/x-pem-file"));
    headers.setLastModified(System.currentTimeMillis());
    headers.setCacheControl("no-cache");

    headers.set("Content-Disposition",
            "attachment; filename=solarnode-" + getIdentityService().getNodeId() + ".pem");

    return new ResponseEntity<String>(cert, headers, HttpStatus.OK);
}

From source file:spring.travel.site.controllers.LoginControllerTest.java

@Test
public void shouldReturnNotFoundIfUserNotFound() throws Exception {
    MvcResult mvcResult = this.mockMvc
            .perform(post("/login").contentType(MediaType.APPLICATION_JSON)
                    .content("{ \"username\":\"foo\", \"password\":\"bar\" }")
                    .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
            .andExpect(request().asyncStarted())
            .andExpect(request().asyncResult(instanceOf(UserNotFoundException.class))).andReturn();

    this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().is(404));
}