Java Code Examples for javax.ws.rs.core.MediaType#valueOf()

The following examples show how to use javax.ws.rs.core.MediaType#valueOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GitLabApiClient.java    From gitlab4j-api with MIT License 6 votes vote down vote up
/**
 * Perform a file upload using multipart/form-data, returning
 * a ClientResponse instance with the data returned from the endpoint.
 *
 * @param name the name for the form field that contains the file name
 * @param fileToUpload a File instance pointing to the file to upload
 * @param mediaTypeString the content-type of the uploaded file, if null will be determined from fileToUpload
 * @param formData the Form containing the name/value pairs
 * @param url the fully formed path to the GitLab API endpoint
 * @return a ClientResponse instance with the data returned from the endpoint
 * @throws IOException if an error occurs while constructing the URL
 */
protected Response upload(String name, File fileToUpload, String mediaTypeString, Form formData, URL url) throws IOException {

    MediaType mediaType = (mediaTypeString != null ? MediaType.valueOf(mediaTypeString) : null);
    try (FormDataMultiPart multiPart = new FormDataMultiPart()) {

        if (formData != null) {
            MultivaluedMap<String, String> formParams = formData.asMap();
            formParams.forEach((key, values) -> {
                if (values != null) {
                    values.forEach(value -> multiPart.field(key, value));
                }
            });
        }

        FileDataBodyPart filePart = mediaType != null ?
            new FileDataBodyPart(name, fileToUpload, mediaType) :
            new FileDataBodyPart(name, fileToUpload);
        multiPart.bodyPart(filePart);
        final Entity<?> entity = Entity.entity(multiPart, Boundary.addBoundary(multiPart.getMediaType()));
        return (invocation(url, null).post(entity));
    }
}
 
Example 2
Source File: AtomPojoProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadFeedWithoutBuilders2() throws Exception {
    AtomPojoProvider provider = new AtomPojoProvider();
    final String feed =
        "<!DOCTYPE feed SYSTEM \"feed://feed\"><feed xmlns=\"http://www.w3.org/2005/Atom\">"
        + "<entry><content type=\"application/xml\"><book xmlns=\"\"><name>a</name></book></content></entry>"
        + "<entry><content type=\"application/xml\"><book xmlns=\"\"><name>b</name></book></content></entry>"
        + "</feed>";
    MediaType mt = MediaType.valueOf("application/atom+xml;type=feed");
    ByteArrayInputStream bis = new ByteArrayInputStream(feed.getBytes());
    @SuppressWarnings({"unchecked", "rawtypes" })
    Books books2 = (Books)provider.readFrom((Class)Books.class, Books.class,
                                        new Annotation[]{}, mt, null, bis);
    List<Book> list = books2.getBooks();
    assertEquals(2, list.size());
    assertTrue("a".equals(list.get(0).getName()) || "a".equals(list.get(1).getName()));
    assertTrue("b".equals(list.get(0).getName()) || "b".equals(list.get(1).getName()));
}
 
Example 3
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBookJaxbJsonProxy() throws Exception {
    String address = "http://localhost:" + PORT;
    MultipartStore client = JAXRSClientFactory.create(address, MultipartStore.class);

    Map<String, Book> map = client.getBookJaxbJson();
    List<Book> result = new ArrayList<>(map.values());
    Book jaxb = result.get(0);
    assertEquals("jaxb", jaxb.getName());
    assertEquals(1L, jaxb.getId());
    Book json = result.get(1);
    assertEquals("json", json.getName());
    assertEquals(2L, json.getId());

    String contentType =
        WebClient.client(client).getResponse().getMetadata().getFirst("Content-Type").toString();
    MediaType mt = MediaType.valueOf(contentType);
    assertEquals("multipart", mt.getType());
    assertEquals("mixed", mt.getSubtype());
}
 
Example 4
Source File: ViewableWriter.java    From ozark with Apache License 2.0 6 votes vote down vote up
/**
 * JAX-RS implementations are using different types for representing the content type.
 */
private MediaType getMediaTypeFromHeaders(MultivaluedMap<String, Object> headers) {

    Object value = headers.get(CONTENT_TYPE).get(0);

    // Jersey + RESTEasy
    if (value instanceof MediaType) {
        return (MediaType) value;
    }

    // CXF
    if (value instanceof String) {
        return MediaType.valueOf((String) value);
    }

    return null;

}
 
Example 5
Source File: HttpUtils.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * Given a list of acceptable media types, get an RDF syntax.
 *
 * @param ioService the I/O service
 * @param acceptableTypes the types from HTTP headers
 * @param mimeType an additional "default" mimeType to match
 * @return an RDFSyntax or, in the case of binaries, null
 * @throws NotAcceptableException if no acceptable syntax is available
 */
public static RDFSyntax getSyntax(final IOService ioService, final List<MediaType> acceptableTypes,
        final String mimeType) {
    if (acceptableTypes.isEmpty()) {
        return mimeType != null ? null : TURTLE;
    }
    final MediaType mt = mimeType != null ? MediaType.valueOf(mimeType) : null;
    for (final MediaType type : acceptableTypes) {
        if (type.isCompatible(mt)) {
            return null;
        }
        final RDFSyntax syntax = ioService.supportedReadSyntaxes().stream()
            .filter(s -> MediaType.valueOf(s.mediaType()).isCompatible(type))
            .findFirst().orElse(null);
        if (syntax != null) {
            return syntax;
        }
    }
    LOGGER.debug("Valid syntax not found among {} or {}", acceptableTypes, mimeType);
    throw new NotAcceptableException();
}
 
Example 6
Source File: WaveImporter.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
private void createImages(File tempBatchFolder, File original,
                          String originalFilename, LocalStorage.LocalObject foxml, ImportProfile config)
        throws IOException, DigitalObjectException, AppConfigurationException {

    long start = System.nanoTime();
    BufferedImage tiff = ImageSupport.readImage(original.toURI().toURL(), ImageMimeType.TIFF);
    long endRead = System.nanoTime() - start;
    ImageMimeType imageType = ImageMimeType.JPEG;
    MediaType mediaType = MediaType.valueOf(imageType.getMimeType());

    start = System.nanoTime();
    String targetName = String.format("%s.full.%s", originalFilename, imageType.getDefaultFileExtension());
    File f = writeImage(tiff, tempBatchFolder, targetName, imageType);
    if (!InputUtils.isJpeg(f)) {
        throw new IllegalStateException("Not a JPEG content: " + f);
    }
    long endFull = System.nanoTime() - start;

    start = System.nanoTime();
    Integer previewMaxHeight = config.getPreviewMaxHeight();
    Integer previewMaxWidth = config.getPreviewMaxWidth();
    config.checkPreviewScaleParams();
    targetName = String.format("%s.preview.%s", originalFilename, imageType.getDefaultFileExtension());
    f = writeImage(
            scale(tiff, config.getPreviewScaling(), previewMaxWidth, previewMaxHeight),
            tempBatchFolder, targetName, imageType);
    if (!InputUtils.isJpeg(f)) {
        throw new IllegalStateException("Not a JPEG content: " + f);
    }
    long endPreview = System.nanoTime() - start;
    BinaryEditor.dissemination(foxml, BinaryEditor.PREVIEW_ID, mediaType).write(f, 0, null);

    start = System.nanoTime();
    f = createThumbnail(tempBatchFolder, originalFilename, original, tiff, config);
    long endThumb = System.nanoTime() - start;
    BinaryEditor.dissemination(foxml, BinaryEditor.THUMB_ID, mediaType).write(f, 0, null);

    LOG.fine(String.format("file: %s, read: %s, full: %s, preview: %s, thumb: %s",
            originalFilename, endRead / 1000000, endFull / 1000000, endPreview / 1000000, endThumb / 1000000));
}
 
Example 7
Source File: EcsS3Storage.java    From ecs-sync with Apache License 2.0 5 votes vote down vote up
private S3ObjectMetadata s3MetaFromSyncMeta(ObjectMetadata syncMeta) {
    S3ObjectMetadata om = new S3ObjectMetadata();
    if (syncMeta.getCacheControl() != null) om.setCacheControl(syncMeta.getCacheControl());
    if (syncMeta.getContentDisposition() != null) om.setContentDisposition(syncMeta.getContentDisposition());
    if (syncMeta.getContentEncoding() != null) om.setContentEncoding(syncMeta.getContentEncoding());
    om.setContentLength(syncMeta.getContentLength());
    if (syncMeta.getChecksum() != null && syncMeta.getChecksum().getAlgorithm().equals("MD5"))
        om.setContentMd5(syncMeta.getChecksum().getValue());
    // handle invalid content-type
    if (syncMeta.getContentType() != null) {
        try {
            if (config.isResetInvalidContentType()) MediaType.valueOf(syncMeta.getContentType());
            om.setContentType(syncMeta.getContentType());
        } catch (IllegalArgumentException e) {
            log.info("Object has Invalid content-type [{}]; resetting to default", syncMeta.getContentType());
        }
    }
    if (syncMeta.getHttpExpires() != null) om.setHttpExpires(syncMeta.getHttpExpires());
    om.setUserMetadata(formatUserMetadata(syncMeta));
    if (syncMeta.getModificationTime() != null) om.setLastModified(syncMeta.getModificationTime());
    if (options.isSyncRetentionExpiration() && syncMeta.getRetentionEndDate() != null) {
        long retentionPeriod = TimeUnit.MILLISECONDS.toSeconds(syncMeta.getRetentionEndDate().getTime() - System.currentTimeMillis());
        om.setRetentionPeriod(retentionPeriod);
    }

    return om;
}
 
Example 8
Source File: MediaTypeHeaderProviderTest.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeWithExtendedParameters() {
    MediaType mt = MediaType.valueOf("multipart/related;type=application/dicom+xml");

    assertEquals("multipart", mt.getType());
    assertEquals("related", mt.getSubtype());
    ;
}
 
Example 9
Source File: SparseFieldSetFilterTest.java    From alchemy with MIT License 5 votes vote down vote up
@Test
public void testCompatibleMediaType() {
    final MediaType mediaType = MediaType.valueOf("application/json; charset=utf-8");
    doReturn(mediaType).when(response).getMediaType();

    doFilter();
    verify(response).getEntity();
}
 
Example 10
Source File: ApiResourceTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
public void shouldUploadApiMedia() {
    StreamDataBodyPart filePart = new StreamDataBodyPart("file",
            this.getClass().getResourceAsStream("/media/logo.svg"), "logo.svg", MediaType.valueOf("image/svg+xml"));
    final MultiPart multiPart = new MultiPart(MediaType.MULTIPART_FORM_DATA_TYPE);
    multiPart.bodyPart(filePart);
    final Response response = target(API + "/media/upload").request().post(entity(multiPart, multiPart.getMediaType()));
    assertEquals(OK_200, response.getStatus());
}
 
Example 11
Source File: PatchHandler.java    From trellis with Apache License 2.0 5 votes vote down vote up
static boolean supportsContentType(final RDFSyntax syntax, final String contentType) {
    if (contentType != null) {
        final MediaType mediaType = MediaType.valueOf(contentType);
        return mediaType.isCompatible(MediaType.valueOf(syntax.mediaType())) &&
            !mediaType.isWildcardSubtype() && !mediaType.isWildcardType();
    }
    return false;
}
 
Example 12
Source File: MediaTypeHeaderProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeWithExtendedAndBoundaryParameter() {
    MediaType mt = MediaType.valueOf(
        "multipart/related; type=application/dicom+xml; boundary=\"uuid:b9aecb2a-ab37-48d6-a1cd-b2f4f7fa63cb\"");
    assertEquals("multipart", mt.getType());
    assertEquals("related", mt.getSubtype());
    Map<String, String> params2 = mt.getParameters();
    assertEquals(2, params2.size());
    assertEquals("\"uuid:b9aecb2a-ab37-48d6-a1cd-b2f4f7fa63cb\"", params2.get("boundary"));
    assertEquals("application/dicom+xml", params2.get("type"));
}
 
Example 13
Source File: RequestImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleVariantsBestMatchMediaTypeQualityFactors() {
    metadata.putSingle(HttpHeaders.ACCEPT, "a/b;q=0.6, c/d;q=0.5, e/f+json");
    metadata.putSingle(HttpHeaders.ACCEPT_LANGUAGE, "en-us");
    metadata.putSingle(HttpHeaders.ACCEPT_ENCODING, "gzip;q=1.0, compress");

    List<Variant> list = new ArrayList<>();
    Variant var1 = new Variant(MediaType.valueOf("a/b"), new Locale("en"), "gzip");
    Variant var2 = new Variant(MediaType.valueOf("x/z"), new Locale("en"), "gzip");
    Variant var3 = new Variant(MediaType.valueOf("e/f+json"), new Locale("en"), "gzip");
    Variant var4 = new Variant(MediaType.valueOf("c/d"), new Locale("en"), "gzip");
    list.add(var1);
    list.add(var2);
    list.add(var3);
    list.add(var4);
    assertSame(var3, new RequestImpl(m).selectVariant(list));

    list.clear();
    list.add(var1);
    list.add(var4);
    assertSame(var1, new RequestImpl(m).selectVariant(list));

    list.clear();
    list.add(var2);
    list.add(var4);
    assertSame(var4, new RequestImpl(m).selectVariant(list));
}
 
Example 14
Source File: MediaTypeHeaderProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleType() {
    MediaType m = MediaType.valueOf("text/html");
    assertEquals("Media type was not parsed correctly",
                 m, new MediaType("text", "html"));
    assertEquals("Media type was not parsed correctly",
                 MediaType.valueOf("text/html "), new MediaType("text", "html"));
}
 
Example 15
Source File: WebResourceUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static MediaType getImageMediaTypeFromExtension(String extension) {
    com.google.common.net.MediaType mime = IMAGE_FORMAT_MIME_TYPES.get(extension.toLowerCase());
    if (mime==null) return null;
    try {
        return MediaType.valueOf(mime.toString());
    } catch (Exception e) {
        log.warn("Unparseable MIME type "+mime+"; ignoring ("+e+")");
        Exceptions.propagateIfFatal(e);
        return null;
    }
}
 
Example 16
Source File: CertificateMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public static MediaType getResponseMediaType(String acceptHeader) {
    MediaType responseMediaType;
    if (acceptHeader == null || MediaType.WILDCARD.equals(acceptHeader)) {
        responseMediaType = DEFAULT_CONTENT_TYPE;
    } else {
        responseMediaType = MediaType.valueOf(acceptHeader);
    }

    return responseMediaType;
}
 
Example 17
Source File: DataBindingMap.java    From cougar with Apache License 2.0 4 votes vote down vote up
public MediaType getPreferredMediaType() {
	return MediaType.valueOf(preferredContentType);
}
 
Example 18
Source File: MediaTypeHeaderProviderTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testNullValue() throws Exception {
    MediaType.valueOf(null);
}
 
Example 19
Source File: JaxRsContext.java    From jax-rs-pac4j with Apache License 2.0 4 votes vote down vote up
@Override
public void setResponseContentType(String content) {
    MediaType type = content == null ? null : MediaType.valueOf(content);
    getAbortBuilder().type(type);
    getResponseHolder().setResponseContentType(type);
}
 
Example 20
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testXopWebClient() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/xop";
    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setAddress(address);
    bean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED,
                                                (Object)"true"));
    WebClient client = bean.createWebClient();
    WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor());
    WebClient.getConfig(client).getOutInterceptors().add(new LoggingOutInterceptor());
    WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart",
        "true");
    client.type("multipart/related").accept("multipart/related");

    XopType xop = new XopType();
    xop.setName("xopName");
    InputStream is =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd");
    byte[] data = IOUtils.readBytesFromStream(is);
    xop.setAttachinfo(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
    xop.setAttachInfoRef(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));

    String bookXsd = IOUtils.readStringFromStream(getClass().getResourceAsStream(
        "/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
    xop.setAttachinfo2(bookXsd.getBytes());

    xop.setImage(getImage("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));

    XopType xop2 = client.post(xop, XopType.class);

    String bookXsdOriginal = IOUtils.readStringFromStream(getClass().getResourceAsStream(
            "/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
    String bookXsd2 = IOUtils.readStringFromStream(xop2.getAttachinfo().getInputStream());
    assertEquals(bookXsdOriginal, bookXsd2);
    String bookXsdRef = IOUtils.readStringFromStream(xop2.getAttachInfoRef().getInputStream());
    assertEquals(bookXsdOriginal, bookXsdRef);

    String ctString =
        client.getResponse().getMetadata().getFirst("Content-Type").toString();
    MediaType mt = MediaType.valueOf(ctString);
    Map<String, String> params = mt.getParameters();
    assertEquals(4, params.size());
    assertNotNull(params.get("boundary"));
    assertNotNull(params.get("type"));
    assertNotNull(params.get("start"));
    assertNotNull(params.get("start-info"));
}