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:de.metas.ui.web.window.controller.WindowRestController.java

@GetMapping("/{windowId}/{documentId}/attachments/{id}")
public ResponseEntity<byte[]> getAttachmentById(@PathVariable("windowId") final int adWindowId //
        , @PathVariable("documentId") final String documentId //
        , @PathVariable("id") final int id) {
    userSession.assertLoggedIn();//from w w w.  j a va2s  .c  o  m

    final DocumentPath documentPath = DocumentPath.rootDocumentPath(DocumentType.Window, adWindowId,
            documentId);
    final Document document = documentCollection.getDocument(documentPath);

    final MAttachmentEntry entry = Services.get(IAttachmentBL.class).getEntryForModelById(document, id);
    if (entry == null) {
        throw new EntityNotFoundException("No attachment found (ID=" + id + ")");
    }

    final String entryFilename = entry.getFilename();
    final byte[] entryData = entry.getData();
    if (entryData == null || entryData.length == 0) {
        throw new EntityNotFoundException("No attachment found (ID=" + id + ")");
    }

    final String entryContentType = entry.getContentType();

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

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

@Test
public void testBytes() 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);
    domain.addRdapConformance(Domain.DEFAULT_RDAP_CONFORMANCE);
    when(domainService.getDomain(Mockito.any(DomainName.class))).thenReturn(domain);
    mockMvc.perform(get("/domain/example.com").accept(MediaType.parseMediaType("application/rdap+json")))
            .andExpect(header().string("Content-type", "application/rdap+json;charset=UTF-8"))
            .andExpect(status().isOk()).andExpect(content().string(
                    "{\"rdapConformance\":[\"rdap_level_0\"],\"objectClassName\":\"domain\",\"ldhName\":\"example.com\",\"unicodeName\":\"example.com\"}"));
}

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

@Test
public void testIDNParseException() throws Exception {
    mockMvc.perform(get("/domain/-\u2620-.be").accept(MediaType.parseMediaType("application/rdap+json")))
            .andExpect(header().string("Content-type", Controllers.CONTENT_TYPE))
            .andExpect(content().string(
                    "{\"errorCode\":400,\"title\":\"Invalid domain name\",\"description\":[\"LEADING_HYPHEN\",\"TRAILING_HYPHEN\",\"DISALLOWED\"]}"))
            .andExpect(status().isBadRequest());
}

From source file:com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

private MockMvcResponse sendRequest(HttpMethod method, String path, Object[] pathParams) {
    notNull(path, "Path");
    if (requestBody != null && !multiParts.isEmpty()) {
        throw new IllegalStateException(
                "You cannot specify a request body and a multi-part body in the same request. Perhaps you want to change the body to a multi part?");
    }/*w  ww . ja  v  a 2 s. co  m*/

    String uri;
    if (isNotBlank(basePath)) {
        uri = mergeAndRemoveDoubleSlash(basePath, path);
    } else {
        uri = path;
    }

    final MockHttpServletRequestBuilder request;
    if (multiParts.isEmpty()) {
        request = MockMvcRequestBuilders.request(method, uri, pathParams);
    } else if (method != POST) {
        throw new IllegalArgumentException("Currently multi-part file data uploading only works for " + POST);
    } else {
        request = MockMvcRequestBuilders.fileUpload(uri, pathParams);
    }

    String requestContentType = findContentType();

    if (!params.isEmpty()) {
        new ParamApplier(params) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.param(paramName, paramValues);
            }
        }.applyParams();

        if (StringUtils.isBlank(requestContentType) && method == POST && !isInMultiPartMode(request)) {
            setContentTypeToApplicationFormUrlEncoded(request);
        }
    }

    if (!queryParams.isEmpty()) {
        new ParamApplier(queryParams) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                // Spring MVC cannot distinguish query from params afaik.
                request.param(paramName, paramValues);
            }
        }.applyParams();
    }

    if (!formParams.isEmpty()) {
        if (method == GET) {
            throw new IllegalArgumentException("Cannot use form parameters in a GET request");
        }
        new ParamApplier(formParams) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.param(paramName, paramValues);
            }
        }.applyParams();

        boolean isInMultiPartMode = isInMultiPartMode(request);
        if (StringUtils.isBlank(requestContentType) && !isInMultiPartMode) {
            setContentTypeToApplicationFormUrlEncoded(request);
        }
    }

    if (!attributes.isEmpty()) {
        new ParamApplier(attributes) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.requestAttr(paramName, paramValues[0]);
            }
        }.applyParams();
    }

    if (RestDocsClassPathChecker.isSpringRestDocsInClasspath()
            && config.getMockMvcConfig().shouldAutomaticallyApplySpringRestDocsMockMvcSupport()) {
        request.requestAttr(ATTRIBUTE_NAME_URL_TEMPLATE, PathSupport.getPath(uri));
    }

    if (StringUtils.isNotBlank(requestContentType)) {
        request.contentType(MediaType.parseMediaType(requestContentType));
    }

    if (headers.exist()) {
        for (Header header : headers) {
            request.header(header.getName(), header.getValue());
        }
    }

    if (cookies.exist()) {
        for (Cookie cookie : cookies) {
            javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(),
                    cookie.getValue());
            if (cookie.hasComment()) {
                servletCookie.setComment(cookie.getComment());
            }
            if (cookie.hasDomain()) {
                servletCookie.setDomain(cookie.getDomain());
            }
            if (cookie.hasMaxAge()) {
                servletCookie.setMaxAge(cookie.getMaxAge());
            }
            if (cookie.hasPath()) {
                servletCookie.setPath(cookie.getPath());
            }
            if (cookie.hasVersion()) {
                servletCookie.setVersion(cookie.getVersion());
            }
            request.cookie(servletCookie);
        }
    }

    if (!multiParts.isEmpty()) {
        MockMultipartHttpServletRequestBuilder multiPartRequest = (MockMultipartHttpServletRequestBuilder) request;
        for (MockMvcMultiPart multiPart : multiParts) {
            MockMultipartFile multipartFile;
            String fileName = multiPart.getFileName();
            String controlName = multiPart.getControlName();
            String mimeType = multiPart.getMimeType();
            if (multiPart.isByteArray()) {
                multipartFile = new MockMultipartFile(controlName, fileName, mimeType,
                        (byte[]) multiPart.getContent());
            } else if (multiPart.isFile() || multiPart.isInputStream()) {
                InputStream inputStream;
                if (multiPart.isFile()) {
                    try {
                        inputStream = new FileInputStream((File) multiPart.getContent());
                    } catch (FileNotFoundException e) {
                        return SafeExceptionRethrower.safeRethrow(e);
                    }
                } else {
                    inputStream = (InputStream) multiPart.getContent();
                }
                try {
                    multipartFile = new MockMultipartFile(controlName, fileName, mimeType, inputStream);
                } catch (IOException e) {
                    return SafeExceptionRethrower.safeRethrow(e);
                }
            } else { // String
                multipartFile = new MockMultipartFile(controlName, fileName, mimeType,
                        ((String) multiPart.getContent()).getBytes());
            }
            multiPartRequest.file(multipartFile);
        }
    }

    if (requestBody != null) {
        if (requestBody instanceof byte[]) {
            request.content((byte[]) requestBody);
        } else if (requestBody instanceof File) {
            byte[] bytes = toByteArray((File) requestBody);
            request.content(bytes);
        } else {
            request.content(requestBody.toString());
        }
    }

    logRequestIfApplicable(method, uri, path, pathParams);

    return performRequest(request);
}

From source file:com.revolsys.ui.web.rest.interceptor.WebAnnotationMethodHandlerAdapter.java

/**
 * Sets the mapping from file extensions to media types.
 * <p>//from w ww.  j  ava  2s . c o m
 */
public void setMediaTypes(final Map<String, String> mediaTypes) {
    for (final Map.Entry<String, String> entry : mediaTypes.entrySet()) {
        final String extension = entry.getKey().toLowerCase(Locale.ENGLISH);
        final MediaType mediaType = MediaType.parseMediaType(entry.getValue());
        this.mediaTypes.put(extension, mediaType);
    }
}

From source file:com.tasktop.c2c.server.internal.wiki.server.domain.validation.AttachmentValidator.java

@Override
public void validate(Object target, Errors errors) {
    Attachment attachment = (Attachment) target;

    ValidationUtils.rejectIfEmpty(errors, "page", "field.required");
    ValidationUtils.rejectIfEmpty(errors, "name", "field.required");
    if (attachment.getName() != null && !NAME_PATTERN.matcher(attachment.getName()).matches()) {
        errors.rejectValue("name", "invalidValue", new Object[] { attachment.getName() }, "invalid name");
    }//from   w  w  w  .ja  v  a2s  .  c om
    if (attachment.getMimeType() != null) {
        MediaType mediaType = null;
        try {
            mediaType = MediaType.parseMediaType(attachment.getMimeType());
        } catch (IllegalArgumentException e) {
            errors.rejectValue("mimeType", "invalidFormat");
        }
        if (mediaType != null) {
            if (mediaType.isWildcardType() || mediaType.isWildcardSubtype()) {
                errors.rejectValue("mimeType", "mediaTypeWildcardNotAllowed");
            } else if (!mediaTypes.isSupported(mediaType)) {
                errors.rejectValue("mimeType", "mediaTypeNotPermissible",
                        new Object[] { attachment.getMimeType() }, "bad mime type");
            }
        }
    }
    if (attachment.getContent() == null || attachment.getContent().length == 0) {
        errors.rejectValue("content", "field.required");
    } else {
        int attachementSize = attachment.getContent().length;
        if (attachementSize > configuration.getMaxAttachmentSize()) {
            errors.rejectValue("content", "field.tooLarge",
                    new Object[] { FileUtils.byteCountToDisplaySize(configuration.getMaxAttachmentSize()) },
                    "Field to large");
        }
    }
}

From source file:com.viewer.controller.ViewerController.java

@RequestMapping(value = "/GetResourceForHtml")
@ResponseBody// w w  w  .  j  a  v a  2s . c  o  m
public ResponseEntity<InputStreamResource> GetResourceForHtml(@RequestParam String documentPath, int pageNumber,
        String resourceName) {
    if (!DotNetToJavaStringHelper.isNullOrEmpty(resourceName) && resourceName.indexOf("/") >= 0) {
        resourceName = resourceName.replace("/", "");
    }

    HtmlResource resource = new HtmlResource();
    resource.setResourceName(resourceName);
    resource.setResourceType(Utils.GetResourceType(resourceName));
    resource.setDocumentPageNumber(pageNumber);

    InputStream stream = _htmlHandler.getResource(documentPath, resource);

    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType(Utils.GetImageMimeTypeFromFilename(resourceName)))
            .body(new InputStreamResource(stream));

}

From source file:com.vmware.gemfire.tools.pulse.controllers.PulseControllerJUnitTest.java

@Test
public void pulseUpdateForClusterDetails() throws Exception {
    this.mockMvc/*from   ww w .ja va2  s  .  c om*/
            .perform(post("/pulseUpdate").param("pulseData", "{\"ClusterDetails\":\"{}\"}").principal(principal)
                    .accept(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE)))
            .andExpect(status().isOk()).andExpect(jsonPath("$.ClusterDetails.userName").value(PRINCIPAL_USER))
            .andExpect(jsonPath("$.ClusterDetails.totalHeap").value(0D))
            .andExpect(jsonPath("$.ClusterDetails.clusterName").value(CLUSTER_NAME));
}

From source file:com.vmware.gemfire.tools.pulse.controllers.PulseControllerJUnitTest.java

@Test
public void pulseUpdateForClusterDiskThroughput() throws Exception {
    this.mockMvc//from w  w  w  .ja va2  s  .c om
            .perform(post("/pulseUpdate").param("pulseData", "{\"ClusterDiskThroughput\":\"{}\"}")
                    .principal(principal)
                    .accept(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE)))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.ClusterDiskThroughput.currentThroughputWrites").value(0D))
            .andExpect(jsonPath("$.ClusterDiskThroughput.throughputReads", contains(1, 2, 3)))
            .andExpect(jsonPath("$.ClusterDiskThroughput.currentThroughputReads").value(0D))
            .andExpect(jsonPath("$.ClusterDiskThroughput.throughputWrites", contains(4, 5, 6)));
}

From source file:com.vmware.gemfire.tools.pulse.controllers.PulseControllerJUnitTest.java

@Test
public void pulseUpdateForClusterGCPauses() throws Exception {
    this.mockMvc.perform(post("/pulseUpdate").param("pulseData", "{\"ClusterJVMPauses\":\"{}\"}")
            .principal(principal).accept(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE)))
            .andExpect(status().isOk()).andExpect(jsonPath("$.ClusterJVMPauses.currentGCPauses").value(0))
            .andExpect(jsonPath("$.ClusterJVMPauses.gCPausesTrend").isEmpty());
}