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

The following examples show how to use javax.ws.rs.core.MediaType#getSubtype() . 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: BasedModelProvider.java    From Processor with Apache License 2.0 6 votes vote down vote up
@Override
public Model readFrom(Class<Model> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException
{
    if (log.isTraceEnabled()) log.trace("Reading Model with HTTP headers: {} MediaType: {}", httpHeaders, mediaType);
    
    Model model = ModelFactory.createDefaultModel();

    MediaType formatType = new MediaType(mediaType.getType(), mediaType.getSubtype()); // discard charset param
    Lang lang = RDFLanguages.contentTypeToLang(formatType.toString());
    if (lang == null)
    {
        if (log.isErrorEnabled()) log.error("MediaType '{}' not supported by Jena", formatType);
        throw new NoReaderForLangException("MediaType not supported: " + formatType);
    }
    if (log.isDebugEnabled()) log.debug("RDF language used to read Model: {}", lang);
    
    return read(model, entityStream, lang, getUriInfo().getBaseUri().toString());
}
 
Example 2
Source File: BasedModelProvider.java    From Processor with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(Model model, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException
{
    if (log.isTraceEnabled()) log.trace("Writing Model with HTTP headers: {} MediaType: {}", httpHeaders, mediaType);

    MediaType formatType = new MediaType(mediaType.getType(), mediaType.getSubtype()); // discard charset param
    Lang lang = RDFLanguages.contentTypeToLang(formatType.toString());
    if (lang == null)
    {
        if (log.isErrorEnabled()) log.error("MediaType '{}' not supported by Jena", formatType);
        throw new NoWriterForLangException("MediaType not supported: " + formatType);
    }
    if (log.isDebugEnabled()) log.debug("RDF language used to read Model: {}", lang);
    
    write(model, entityStream, lang, getUriInfo().getBaseUri().toString());
}
 
Example 3
Source File: TextJacksonJsonProvider.java    From components with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean hasMatchingMediaType(MediaType mediaType) {
    /*
     * As suggested by Stephen D, there are 2 ways to check: either being as inclusive as possible (if subtype is "json"),
     * or exclusive (major type "application", minor type "json"). Let's start with inclusive one, hard to know which major
     * types we should cover aside from "application".
     */
    if (mediaType != null) {
        // Ok: there are also "xxx+json" subtypes, which count as well
        String subtype = mediaType.getSubtype();
        return "json".equalsIgnoreCase(subtype) || subtype.endsWith("+json") || mediaType.equals(MediaType.TEXT_PLAIN_TYPE) || "plain".equalsIgnoreCase(subtype);
    }
    /*
     * Not sure if this can happen; but it seems reasonable that we can at least produce json without media type?
     */
    return true;
}
 
Example 4
Source File: InputStreamMessageBodyWriter.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(DataInputStream in, Class<?> type, Type genericType,
                    Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException, WebApplicationException {
    String subtype = mediaType.getSubtype();
    logger.debug("Trying write DataInputStream into servlet OutputStream. Output subtype:{}", subtype);
    IOUtils.copy(in, entityStream);
    in.close();
    entityStream.close();
}
 
Example 5
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 6
Source File: EndpointControllerUtils.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
static void populateResponseBody(ResponseBuilder builder, String entity, Variant variant, boolean includeEntity) {
	MediaType mediaType = variant.getMediaType();

	String charsetName=mediaType.getParameters().get(MediaType.CHARSET_PARAMETER);
	Charset charset=StandardCharsets.UTF_8;
	if(charsetName!=null && !charsetName.isEmpty() && Charset.isSupported(charsetName)) {
		charset=Charset.forName(charsetName);
	} else {
		LOGGER.error("Missing of invalid charset information {}",mediaType);
		charsetName=charset.name();
	}

	MediaType target=
		Configuration.includeCharsetInformation()?
			mediaType.withCharset(charsetName):
			new MediaType(mediaType.getType(),mediaType.getSubtype());

	byte[] bytes = entity.getBytes(charset);
	builder.
		type(target).
		header(MoreHttp.CONTENT_LENGTH_HEADER,bytes.length);

	if(variant.getLanguage()!=null) {
		builder.language(variant.getLanguage());
	}

	if(includeEntity) {
		builder.entity(new ByteArrayInputStream(bytes));
	}
}
 
Example 7
Source File: FastJsonProvider.java    From fastjson-jaxrs-json-provider with Apache License 2.0 5 votes vote down vote up
/**
 * Check media type like "application/json".
 * 
 * @param mediaType
 *            media type
 * @return true if the media type is valid
 */
protected boolean hasMatchingMediaType(MediaType mediaType) {
	if (mediaType != null) {
		String subtype = mediaType.getSubtype();
		return "json".equalsIgnoreCase(subtype) || subtype.endsWith("+json") || "javascript".equals(subtype) || "x-javascript".equals(subtype);
	}
	return true;
}
 
Example 8
Source File: GraphStore.java    From neo4j-sparql-extension with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns RDF data from a graph in the repository.
 *
 * @see RDFStreamingOutput
 * @param req JAX-RS {@link Request} object
 * @param def the "default" query parameter
 * @param graphString the "graph" query parameter
 * @return RDF data as HTTP response
 */
private Response handleGet(
		Request req,
		String def,
		String graphString) {
	// select matching MIME-Type for response based on HTTP headers
	final Variant variant = req.selectVariant(rdfResultVariants);
	final MediaType mt = variant.getMediaType();
	final String mtstr = mt.getType() + "/" + mt.getSubtype();
	final RDFFormat format = getRDFFormat(mtstr);
	StreamingOutput stream;
	RepositoryConnection conn = null;
	try {
		// return data as RDF stream
		conn = getConnection();
		if (graphString != null) {
			Resource ctx = vf.createURI(graphString);
			if (conn.size(ctx) == 0) {
				return Response.status(Response.Status.NOT_FOUND).build();
			}
			stream = new RDFStreamingOutput(conn, format, ctx);
		} else {
			stream = new RDFStreamingOutput(conn, format);
		}
	} catch (RepositoryException ex) {
		// server error
		close(conn, ex);
		throw new WebApplicationException(ex);
	}
	return Response.ok(stream).build();
}
 
Example 9
Source File: GsonUtil.java    From tajo with Apache License 2.0 5 votes vote down vote up
public static boolean isJsonType(MediaType mediaType) {
  if (mediaType != null) {
    String subType = mediaType.getSubtype();
    return "json".equalsIgnoreCase(subType) || subType.endsWith("+json");
  }
  return false;
}
 
Example 10
Source File: MediaTypeHeaderProvider.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a media type object to a string.
 *
 * @param type MediaType object
 * @return string media type
 */
public String toString(MediaType type) {
    if (type == null) {
        throw new IllegalArgumentException("MediaType can not be null");
    }
    return type.getType() + '/' + type.getSubtype();
}
 
Example 11
Source File: HttpCallOperatorFactory.java    From digdag with Apache License 2.0 5 votes vote down vote up
private String reformatDigFile(String content, String mediaTypeString, String mediaTypeOverride)
{
    MediaType mediaType;
    if (Strings.isNullOrEmpty(mediaTypeOverride)) {
        if (Strings.isNullOrEmpty(mediaTypeString)) {
            throw new TaskExecutionException("Content-Type must be set in the HTTP response but not set");
        }
        mediaType = MediaType.valueOf(mediaTypeString);
    }
    else {
        mediaType = MediaType.valueOf(mediaTypeOverride);
    }

    String t = mediaType.getType() + "/" + mediaType.getSubtype();  // without ;charset= or other params
    switch (t) {
    case MediaType.APPLICATION_JSON:
        try {
            // parse as json
            Config sourceConfig = cf.fromJsonString(content);
            // reformat as yaml
            return formatYaml(sourceConfig);
        }
        catch (ConfigException ex) {
            throw new RuntimeException("Failed to parse response as JSON: " + ex.getMessage(), ex);
        }

    case "application/x-yaml":
        // use as-is; let projectLoader.loadWorkflowFileFromPath handle parse errors
        return content;

    //case MediaType.TEXT_PLAIN:
    //case MediaType.APPLICATION_OCTET_STREAM:

    default:
        throw new TaskExecutionException("Unsupported Content-Type (expected application/json or application/x-yaml): " + mediaTypeString);
    }
}
 
Example 12
Source File: ContentTypeNormaliserImpl.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public MediaType getNormalisedRequestMediaType(HttpServletRequest request) {
    String contentType = request.getContentType();
    if (request.getMethod().equals("POST")) {
        if (contentType == null) {
            throw new CougarValidationException(ServerFaultCode.ContentTypeNotValid, "Input content type was not specified for deserialisable response");
        }
        MediaType requestMT;
        try {
            requestMT = MediaType.valueOf(contentType);
        } catch (Exception e) {
            throw new CougarValidationException(ServerFaultCode.MediaTypeParseFailure, "Input content type cannot be parsed: " + contentType,e);
        }
        if (requestMT.isWildcardType() || requestMT.isWildcardSubtype()) {
            throw new CougarValidationException(ServerFaultCode.InvalidInputMediaType, "Input content type may not be wildcard: " + requestMT);
        }
        if (!MediaTypeUtils.isValid(allContentTypes, requestMT)) {
            throw new CougarValidationException(ServerFaultCode.ContentTypeNotValid, "Input content type is not valid: " + requestMT);
        }
        String candidateContentType = requestMT.getType() + "/" + requestMT.getSubtype();
        MediaType normalizedMediaType = validContentTypes.get(candidateContentType);
        if (normalizedMediaType == null) {
            throw new CougarValidationException(ServerFaultCode.FrameworkError, "Input content type " + contentType + " failed to find a normalized type using key " + candidateContentType);
        }
        return normalizedMediaType;
    }
    return null;
}
 
Example 13
Source File: MediaTypeHelper.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
public static String getKey(MediaType mediaType) {

        if (mediaType == null) {
            return MediaType.WILDCARD;
        }

        return mediaType.getType() + "/" + mediaType.getSubtype(); // key does not contain any charset
    }
 
Example 14
Source File: FastJsonProvider.java    From metrics with Apache License 2.0 5 votes vote down vote up
/**
 * Check media type like "application/json".
 *
 * @param mediaType media type
 * @return true if the media type is valid
 */
protected boolean hasMatchingMediaType(MediaType mediaType) {
    if (mediaType != null) {
        String subtype = mediaType.getSubtype();
        return "json".equalsIgnoreCase(subtype) || subtype.endsWith("+json") ||
                "javascript".equalsIgnoreCase(subtype) || "x-javascript".equalsIgnoreCase(subtype);
    }
    return true;
}
 
Example 15
Source File: RescriptOperationBinding.java    From cougar with Apache License 2.0 4 votes vote down vote up
public Object[] resolveArgs(HttpServletRequest request, InputStream inputStream, MediaType mediaType, String encoding) {
    Object[] args = new Object[paramBindings.length];

    String format = mediaType == null || mediaType.getSubtype() == null ? "unknown" : mediaType.getSubtype();
    RescriptBody body = null;
    if (bindingDescriptor.containsBodyData()) {
        //If the request contains body data, then it must be a post request
        if (!request.getMethod().equals("POST")) {
            throw CougarMarshallingException.unmarshallingException(format, "Bad body data", false);
        }
        body = resolveBody(inputStream, mediaType, encoding);
    }

    // jetty 9 handily gives back null when you specify a header with no value, whereas jetty 7 treated this as an empty string.. which we rely on
    // so, we're going to list all the header names, and for each on if the value is null, add them to a set so we can query later..
    Set<String> headersWithNullValues = new HashSet<>();
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String header = headerNames.nextElement();
        if (request.getHeader(header) == null) {
            headersWithNullValues.add(header.toLowerCase());
        }
    }
    try {
        for (int i = 0; i < args.length; ++i) {
            RescriptParamBindingDescriptor descriptor = paramBindings[i];
            Parameter param = operationDefinition.getParameters()[i];
            switch (descriptor.getSource()) {
                case HEADER :
                    String key = descriptor.getName();
                    args[i] = resolveArgument(headersWithNullValues.contains(key.toLowerCase()) ? "" : request.getHeader(key), param, descriptor, format);
                    break;
                case QUERY :
                    args[i] = resolveArgument(request.getParameter(descriptor.getName()), param, descriptor, format);
                    break;
                case BODY :
                    if (body != null) {
                        args[i] = body.getValue(descriptor.getName());
                        // non-null enums get stored as their raw string value so need converting to the true enum value
                        if (param.getParameterType().getType() == ParameterType.Type.ENUM) {
                            if (args[i] != null) {
                                args[i] = EnumUtils.readEnum(param.getParameterType().getImplementationClass(), (String) args[i]);
                            }
                        }
                    }
                    break;
                default :
                    throw new PanicInTheCougar("Unsupported argument annotation "+ descriptor.getSource());
            }
            //request.trace("Deserialised argument {} from {} to value {}", i, param.getSource(), args[i]);
        }
    }
    catch (EnumDerialisationException ede) {
        throw CougarMarshallingException.unmarshallingException(format, ede.getMessage(), ede.getCause(), false);
    }
    return args;
}
 
Example 16
Source File: JweWriterInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException {
    if (ctx.getEntity() == null) {
        ctx.proceed();
        return;
    }
    OutputStream actualOs = ctx.getOutputStream();
    JweHeaders jweHeaders = new JweHeaders();
    JweEncryptionProvider theEncryptionProvider = getInitializedEncryptionProvider(jweHeaders);

    String ctString = null;
    MediaType contentMediaType = ctx.getMediaType();
    if (contentTypeRequired && contentMediaType != null) {
        if ("application".equals(contentMediaType.getType())) {
            ctString = contentMediaType.getSubtype();
        } else {
            ctString = JAXRSUtils.mediaTypeToString(contentMediaType);
        }
    }
    if (ctString != null) {
        jweHeaders.setContentType(ctString);
    }
    protectHttpHeadersIfNeeded(ctx, jweHeaders);
    if (useJweOutputStream) {
        JweEncryptionOutput encryption =
            theEncryptionProvider.getEncryptionOutput(new JweEncryptionInput(jweHeaders));
        JoseUtils.traceHeaders(encryption.getHeaders());
        try {
            JweCompactBuilder.startJweContent(actualOs,
                                               encryption.getHeaders(),
                                               encryption.getEncryptedContentEncryptionKey(),
                                               encryption.getIv());
        } catch (IOException ex) {
            LOG.warning("JWE encryption error");
            throw new JweException(JweException.Error.CONTENT_ENCRYPTION_FAILURE, ex);
        }
        OutputStream wrappedStream = null;
        JweOutputStream jweOutputStream = new JweOutputStream(actualOs, encryption.getCipher(),
                                                     encryption.getAuthTagProducer());
        wrappedStream = jweOutputStream;
        if (encryption.isCompressionSupported()) {
            wrappedStream = new DeflaterOutputStream(jweOutputStream);
        }

        ctx.setOutputStream(wrappedStream);
        ctx.proceed();
        setJoseMediaType(ctx);
        jweOutputStream.finalFlush();
    } else {
        CachedOutputStream cos = new CachedOutputStream();
        ctx.setOutputStream(cos);
        ctx.proceed();
        String jweContent = theEncryptionProvider.encrypt(cos.getBytes(), jweHeaders);
        JoseUtils.traceHeaders(jweHeaders);
        setJoseMediaType(ctx);
        IOUtils.copy(new ByteArrayInputStream(StringUtils.toBytesUTF8(jweContent)),
                     actualOs);
        actualOs.flush();
    }
}
 
Example 17
Source File: JweJsonWriterInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException {
    if (ctx.getEntity() == null) {
        ctx.proceed();
        return;
    }
    OutputStream actualOs = ctx.getOutputStream();
    JweHeaders sharedProtectedHeaders = new JweHeaders();
    List<String> propLocs = getPropertyLocations();
    List<JweHeaders> perRecipientUnprotectedHeaders = new ArrayList<>(propLocs.size());
    for (int i = 0; i < propLocs.size(); i++) {
        perRecipientUnprotectedHeaders.add(new JweHeaders());
    }
    List<JweEncryptionProvider> providers = getInitializedEncryptionProviders(propLocs,
                                                                              sharedProtectedHeaders,
                                                                              perRecipientUnprotectedHeaders);

    String ctString = null;
    MediaType contentMediaType = ctx.getMediaType();
    if (contentTypeRequired && contentMediaType != null) {
        if ("application".equals(contentMediaType.getType())) {
            ctString = contentMediaType.getSubtype();
        } else {
            ctString = JAXRSUtils.mediaTypeToString(contentMediaType);
        }
    }
    if (ctString != null) {
        sharedProtectedHeaders.setContentType(ctString);
    }
    protectHttpHeadersIfNeeded(ctx, sharedProtectedHeaders);
    if (useJweOutputStream) {
        //TODO
    } else {
        CachedOutputStream cos = new CachedOutputStream();
        ctx.setOutputStream(cos);
        ctx.proceed();



        JweJsonProducer producer = new JweJsonProducer(sharedProtectedHeaders, cos.getBytes());
        String jweContent = producer.encryptWith(providers, perRecipientUnprotectedHeaders);

        setJoseMediaType(ctx);
        IOUtils.copy(new ByteArrayInputStream(StringUtils.toBytesUTF8(jweContent)),
                     actualOs);
        actualOs.flush();
    }
}
 
Example 18
Source File: MediaTypeComparator.java    From everrest with Eclipse Public License 2.0 4 votes vote down vote up
private String toString(MediaType mime) {
    return mime.getType() + "/" + mime.getSubtype();
}
 
Example 19
Source File: CollectionMultipartFormDataMessageBodyWriter.java    From everrest with Eclipse Public License 2.0 4 votes vote down vote up
private MediaType createMediaTypeWithBoundary(MediaType mediaType, String boundary) {
    Map<String, String> parameters = newHashMap(mediaType.getParameters());
    parameters.put("boundary", boundary);
    return new MediaType(mediaType.getType(), mediaType.getSubtype(), parameters);
}
 
Example 20
Source File: ResteasyCommonProcessor.java    From quarkus with Apache License 2.0 3 votes vote down vote up
/**
 * Compares the {@link MediaType#getType() type} and the {@link MediaType#getSubtype() subtype} to see if they are
 * equal (case insensitive). If they are equal, then this method returns {@code true}, else returns {@code false}.
 * Unlike the {@link MediaType#equals(Object)}, this method doesn't take into account the {@link MediaType#getParameters()
 * parameters} during the equality check
 *
 * @param m1 one of the MediaType
 * @param m2 the other MediaType
 * @return
 */
private static boolean matches(final MediaType m1, final MediaType m2) {
    if (m1 == null || m2 == null) {
        return false;
    }
    if (m1.getType() == null || m1.getSubtype() == null) {
        return false;
    }
    return m1.getType().equalsIgnoreCase(m2.getType()) && m1.getSubtype().equalsIgnoreCase(m2.getSubtype());
}