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

The following examples show how to use javax.ws.rs.core.MediaType#getParameters() . 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: ContentMappingServiceForToDoItem.java    From isis-app-todoapp with Apache License 2.0 6 votes vote down vote up
@Programmatic
@Override
public Object map(
        final Object object,
        final List<MediaType> acceptableMediaTypes) {

    if(object instanceof ToDoItem) {
        for (MediaType acceptableMediaType : acceptableMediaTypes) {
            final Map<String, String> parameters = acceptableMediaType.getParameters();
            final String className = parameters.get("x-ro-domain-type");
            if( matches(className, ToDoItemV1_1.class)) {
                return newToDoItemV1_1((ToDoItem) object);
            }
        }
    }

    return null;
}
 
Example 2
Source File: MediaTypeHeaderProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static String typeToString(MediaType type, List<String> ignoreParams) {
    if (type == null) {
        throw new IllegalArgumentException("MediaType parameter is null");
    }
    StringBuilder sb = new StringBuilder();
    sb.append(type.getType()).append('/').append(type.getSubtype());

    Map<String, String> params = type.getParameters();
    if (params != null) {
        for (Iterator<Map.Entry<String, String>> iter = params.entrySet().iterator();
            iter.hasNext();) {
            Map.Entry<String, String> entry = iter.next();
            if (ignoreParams != null && ignoreParams.contains(entry.getKey())) {
                continue;
            }
            sb.append(';').append(entry.getKey()).append('=').append(entry.getValue());
        }
    }

    return sb.toString();
}
 
Example 3
Source File: MediaTypeHeaderProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testHeaderFileName() {

    String fileName = "version_2006&#65288;3&#65289;.pdf";
    String header = "application/octet-stream; name=\"%s\"";
    String value = String.format(header, fileName);

    MediaTypeHeaderProvider provider = new MediaTypeHeaderProvider();
    MediaType mt = provider.fromString(value);
    assertEquals("application", mt.getType());
    assertEquals("octet-stream", mt.getSubtype());
    Map<String, String> params = mt.getParameters();
    assertEquals(1, params.size());
    assertEquals("\"version_2006&#65288;3&#65289;.pdf\"", params.get("name"));

}
 
Example 4
Source File: MediaTypeHeaderProvider.java    From cougar with Apache License 2.0 6 votes vote down vote up
public String toString(final MediaType type) {
	String mType = cacheFormat.get(type);
	if (mType == null) {
     StringBuilder sb = new StringBuilder();
     sb.append(type.getType()).append('/').append(type.getSubtype());

     Map<String, String> params = type.getParameters();
     for (Map.Entry<String, String> entry : params.entrySet()) {
         sb.append(';').append(entry.getKey()).append('=').append(entry.getValue());
     }

     mType = sb.toString().toLowerCase();
     cacheFormat.put(type, mType);
	}
	return mType;
}
 
Example 5
Source File: FHIRProviderUtil.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static MediaType getMediaType(String acceptHeader) {
    MediaType mediaType = null;
    try {
        mediaType = FHIRMediaType.valueOf(acceptHeader);
    } catch (IllegalArgumentException e) {
        // ignore
    }
    if (mediaType != null) {
        MediaType outMediaType = null;
        if (mediaType.isCompatible(FHIRMediaType.APPLICATION_FHIR_JSON_TYPE)) {               
            outMediaType = FHIRMediaType.APPLICATION_FHIR_JSON_TYPE;
        } else if (mediaType.isCompatible(FHIRMediaType.APPLICATION_JSON_TYPE)) {
            outMediaType = MediaType.APPLICATION_JSON_TYPE;
        } else if (mediaType.isCompatible(FHIRMediaType.APPLICATION_FHIR_XML_TYPE)) {
            outMediaType = FHIRMediaType.APPLICATION_FHIR_XML_TYPE;
        } else if (mediaType.isCompatible(FHIRMediaType.APPLICATION_XML_TYPE)) {
            outMediaType = MediaType.APPLICATION_XML_TYPE;
        } else {
            outMediaType = FHIRMediaType.APPLICATION_FHIR_JSON_TYPE;
        }
        // Need to get the charset setting from the acceptHeader if there
        if (mediaType.getParameters() != null
                && mediaType.getParameters().get("charset") != null) {
            outMediaType = outMediaType.withCharset(mediaType.getParameters().get("charset"));
        }
        return outMediaType;
    }
    // default
    return FHIRMediaType.APPLICATION_FHIR_JSON_TYPE;
}
 
Example 6
Source File: ResteasyCommonProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a collection of providers that are "inferred" based on certain rules applied to the passed
 * {@code mediaType}. Returns an empty collection if no providers were inferred.
 *
 * @param mediaType The MediaType to process
 * @param categorizedProviders Available providers that are categorized based on their media type. This map
 *        will be used to find possible providers that can be used for the passed
 *        {@code mediaType}
 * @return
 */
private static Collection<String> collectInferredProviders(final MediaType mediaType,
        final MediaTypeMap<String> categorizedProviders, final MethodInfo targetMethod) {

    // for SERVER_SENT_EVENTS media type, we do certain things:
    // - check if the @SseElementType (RestEasy) specific annotation is specified on the target.
    //   if it is, then include a provider which can handle that element type.
    // - if no @SseElementType is present, check if the media type has the "element-type" parameter
    //   and if it does then include the provider which can handle that element-type
    // - if neither of the above specifies an element-type then we by fallback to including text/plain
    //   provider as a default
    if (matches(MediaType.SERVER_SENT_EVENTS_TYPE, mediaType)) {
        final Set<String> additionalProvidersToRegister = new HashSet<>();
        // first check for @SseElementType
        final AnnotationInstance sseElementTypeAnnInst = targetMethod
                .annotation(ResteasyDotNames.RESTEASY_SSE_ELEMENT_TYPE);
        String elementType = null;
        if (sseElementTypeAnnInst != null) {
            elementType = sseElementTypeAnnInst.value().asString();
        } else if (mediaType.getParameters() != null
                && mediaType.getParameters().containsKey(SseConstants.SSE_ELEMENT_MEDIA_TYPE)) {
            // fallback on the MediaType parameter
            elementType = mediaType.getParameters().get(SseConstants.SSE_ELEMENT_MEDIA_TYPE);
        }
        if (elementType != null) {
            additionalProvidersToRegister.addAll(categorizedProviders.getPossible(MediaType.valueOf(elementType)));
        } else {
            // add text/plain provider as a fallback default for SSE mediatype
            additionalProvidersToRegister.addAll(categorizedProviders.getPossible(MediaType.TEXT_PLAIN_TYPE));
        }
        return additionalProvidersToRegister;
    }
    return Collections.emptySet();
}
 
Example 7
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Map<String, String> doTestAddBookJaxbJsonImageWebClient(String multipartType) throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/books/jaxbjsonimage";
    WebClient client = WebClient.create(address);
    WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor());
    client.type(multipartType).accept(multipartType);

    Book jaxb = new Book("jaxb", 1L);
    Book json = new Book("json", 2L);
    InputStream is1 =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
    Map<String, Object> objects = new LinkedHashMap<>();
    objects.put(MediaType.APPLICATION_XML, jaxb);
    objects.put(MediaType.APPLICATION_JSON, json);
    objects.put(MediaType.APPLICATION_OCTET_STREAM, is1);
    Collection<? extends Attachment> coll = client.postAndGetCollection(objects, Attachment.class);
    List<Attachment> result = new ArrayList<>(coll);
    Book jaxb2 = readBookFromInputStream(result.get(0).getDataHandler().getInputStream());
    assertEquals("jaxb", jaxb2.getName());
    assertEquals(1L, jaxb2.getId());
    Book json2 = readJSONBookFromInputStream(result.get(1).getDataHandler().getInputStream());
    assertEquals("json", json2.getName());
    assertEquals(2L, json2.getId());
    InputStream is2 = result.get(2).getDataHandler().getInputStream();
    byte[] image1 = IOUtils.readBytesFromStream(
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
    byte[] image2 = IOUtils.readBytesFromStream(is2);
    assertArrayEquals(image1, image2);

    String ctString =
        client.getResponse().getMetadata().getFirst("Content-Type").toString();
    MediaType mt = MediaType.valueOf(ctString);
    return mt.getParameters();
}
 
Example 8
Source File: AccumulatingIntersector.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public boolean intersect(MediaType requiredType, MediaType userType) {
    boolean requiredTypeWildcard = requiredType.getType().equals(MediaType.MEDIA_TYPE_WILDCARD);
    boolean requiredSubTypeWildcard = requiredType.getSubtype().contains(MediaType.MEDIA_TYPE_WILDCARD);

    String type = requiredTypeWildcard ? userType.getType() : requiredType.getType();
    String subtype = requiredSubTypeWildcard ? userType.getSubtype() : requiredType.getSubtype();

    Map<String, String> parameters = userType.getParameters();
    if (addRequiredParamsIfPossible) {
        parameters = new LinkedHashMap<>(parameters);
        for (Map.Entry<String, String> entry : requiredType.getParameters().entrySet()) {
            if (!parameters.containsKey(entry.getKey())) {
                parameters.put(entry.getKey(), entry.getValue());
            }
        }
    }
    if (addDistanceParameter) {
        int distance = 0;
        if (requiredTypeWildcard) {
            distance++;
        }
        if (requiredSubTypeWildcard) {
            distance++;
        }
        parameters.put(MEDIA_TYPE_DISTANCE_PARAM, Integer.toString(distance));
    }
    getSupportedMimeTypeList().add(new MediaType(type, subtype, parameters));
    return true;
}
 
Example 9
Source File: MediaTypeHeaderProviderTest.java    From cxf 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());
    Map<String, String> params2 = mt.getParameters();
    assertEquals(1, params2.size());
    assertEquals("application/dicom+xml", params2.get("type"));
}
 
Example 10
Source File: MediaTypeHeaderProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeWithExtendedParametersQuote() {
    MediaType mt = MediaType.valueOf("multipart/related;type=\"application/dicom+xml\"");

    assertEquals("multipart", mt.getType());
    assertEquals("related", mt.getSubtype());
    Map<String, String> params2 = mt.getParameters();
    assertEquals(1, params2.size());
    assertEquals("\"application/dicom+xml\"", params2.get("type"));
}
 
Example 11
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 12
Source File: MediaTypeHeaderProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeWithParameters() {
    MediaType mt = MediaType.valueOf("text/html;q=1234;b=4321");

    assertEquals("text", mt.getType());
    assertEquals("html", mt.getSubtype());
    Map<String, String> params2 = mt.getParameters();
    assertEquals(2, params2.size());
    assertEquals("1234", params2.get("q"));
    assertEquals("4321", params2.get("b"));
}
 
Example 13
Source File: AcceptMediaType.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
public AcceptMediaType(MediaType mediaType) {
    this.mediaType = mediaType;
    if (mediaType.getParameters() != null && mediaType.getParameters().get(QVALUE) != null) {
        this.qValue = parseQualityValue(mediaType.getParameters().get(QVALUE));
    } else {
        this.qValue = DEFAULT_QUALITY_VALUE;
    }
}
 
Example 14
Source File: DtoFactoryAbstract.java    From estatio with Apache License 2.0 5 votes vote down vote up
private static String xRoDomainTypeFrom(final List<MediaType> acceptableMediaTypes) {
    for (MediaType acceptableMediaType : acceptableMediaTypes) {
        final Map<String, String> parameters = acceptableMediaType.getParameters();
        final String domainType = parameters.get("x-ro-domain-type");
        if(domainType != null) {
            return domainType;
        }
    }
    throw new IllegalArgumentException(String.format(
            "Could not locate x-ro-domain-type parameter in any of the provided media types; got: %s",
            Joiner.on(", ").join(acceptableMediaTypes)));
}
 
Example 15
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"));
}
 
Example 16
Source File: TableProvider.java    From openscoring with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public TableEvaluationRequest readFrom(Class<TableEvaluationRequest> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
	MultivaluedMap<String, String> queryParameters = this.uriInfo.getQueryParameters();

	String delimiterChar = queryParameters.getFirst("delimiterChar");
	String quoteChar = queryParameters.getFirst("quoteChar");

	Map<String, String> parameters = mediaType.getParameters();

	String charset = parameters.get(MediaType.CHARSET_PARAMETER);
	if(charset == null){
		charset = "UTF-8";
	}

	BufferedReader reader = new BufferedReader(new InputStreamReader(entityStream, charset)){

		@Override
		public void close(){
			// The closing of the underlying java.io.InputStream is handled elsewhere
		}
	};

	TableEvaluationRequest tableRequest;

	try {
		CsvPreference format;

		if(delimiterChar != null){
			format = CsvUtil.getFormat(delimiterChar, quoteChar);
		} else

		{
			format = CsvUtil.getFormat(reader);
		}

		tableRequest = CsvUtil.readTable(reader, format);

		TableFormat tableFormat = new TableFormat()
			.setCharset(charset)
			.setDelimiterChar((char)format.getDelimiterChar())
			.setQuoteChar(format.getQuoteChar());

		tableRequest.setFormat(tableFormat);
	} catch(Exception e){
		logger.error("Failed to load the CSV document", e);

		throw new BadRequestException(e);
	} finally {
		reader.close();
	}

	return tableRequest;
}