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

The following examples show how to use javax.ws.rs.core.MediaType#getType() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Processor   File: BasedModelProvider.java    License: 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 Project: Processor   File: BasedModelProvider.java    License: 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 Project: rest.vertx   File: MediaTypeHelper.java    License: 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 4
Source Project: digdag   File: HttpCallOperatorFactory.java    License: 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 5
Source Project: msf4j   File: MediaTypeHeaderProvider.java    License: 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 6
/**
 * 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 7
Source Project: ldp4j   File: EndpointControllerUtils.java    License: 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 8
Source Project: cxf   File: AccumulatingIntersector.java    License: 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
@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 10
private static String mediaTypeWithoutParams(final MediaType mediaType) {
    return mediaType.getType() + "/" + mediaType.getSubtype();
}
 
Example 11
private String toString(MediaType mime) {
    return mime.getType() + "/" + mime.getSubtype();
}
 
Example 12
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 13
Source Project: quarkus   File: ResteasyCommonProcessor.java    License: 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());
}
 
Example 14
Source Project: enkan   File: CodecUtils.java    License: Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Convert media type to a String represents the MediaType.
 *
 * MediaType#toString requires a JAX-RS implementation.
 * To avoid that enkan requires a JAX-RS implementation, Use this method.
 *
 * @param mediaType MediaType
 * @return a String represents the MediaType
 */
public static String printMediaType(MediaType mediaType) {
    return mediaType.getType() + "/" + mediaType.getSubtype();
}