Java Code Examples for javax.ws.rs.core.Variant#getMediaType()

The following examples show how to use javax.ws.rs.core.Variant#getMediaType() . 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: ViewResponseFilter.java    From krazo with Apache License 2.0 6 votes vote down vote up
private static MediaType selectVariant(Request request, ResourceInfo resourceInfo) {

        Produces produces = resourceInfo.getResourceMethod().getAnnotation(Produces.class);
        if (produces == null) {
            produces = getAnnotation(resourceInfo.getResourceClass(), Produces.class);
        }

        if (produces != null) {

            List<Variant> variants = Arrays.stream(produces.value())
                    .map((String mt) -> Variant.mediaTypes(MediaType.valueOf(mt)).build().get(0))
                    .collect(Collectors.toList());

            Variant variant = request.selectVariant(variants);
            if (variant != null) {
                return variant.getMediaType();
            }

        }

        return null;

    }
 
Example 2
Source File: HistoricProcessInstanceRestServiceImpl.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Response getHistoricProcessInstancesReport(UriInfo uriInfo, Request request) {
  Variant variant = request.selectVariant(VARIANTS);
  if (variant != null) {
    MediaType mediaType = variant.getMediaType();

    if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
      List<ReportResultDto> result = getReportResultAsJson(uriInfo);
      return Response.ok(result, mediaType).build();
    }
    else if (APPLICATION_CSV_TYPE.equals(mediaType) || TEXT_CSV_TYPE.equals(mediaType)) {
      String csv = getReportResultAsCsv(uriInfo);
      return Response
          .ok(csv, mediaType)
          .header("Content-Disposition", "attachment; filename=\"process-instance-report.csv\"")
          .build();
    }
  }
  throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found");
}
 
Example 3
Source File: TaskReportResourceImpl.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public Response getTaskCountByCandidateGroupReport(Request request) {
  Variant variant = request.selectVariant(VARIANTS);
  if (variant != null) {
    MediaType mediaType = variant.getMediaType();

    if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
      List<TaskCountByCandidateGroupResultDto> result = getTaskCountByCandidateGroupResultAsJson();
      return Response.ok(result, mediaType).build();
    }
    else if (APPLICATION_CSV_TYPE.equals(mediaType) || TEXT_CSV_TYPE.equals(mediaType)) {
      String csv = getReportResultAsCsv();
      return Response
        .ok(csv, mediaType)
        .header("Content-Disposition", "attachment; filename=\"task-count-by-candidate-group.csv\"")
        .build();
    }
  }
  throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found");
}
 
Example 4
Source File: VariantListBuilderImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private boolean verifyVariant(List<Variant> vs, Variant var) {
    for (Variant v : vs) {

        if (v.getLanguage() == null
            && v.getEncoding() == null
            && v.getMediaType() == null) {
            return false;
        }
        boolean encodCheck = v.getEncoding() == null && var.getEncoding() == null
                             || v.getEncoding().equals(var.getEncoding());
        boolean langCheck = v.getLanguage() == null && var.getLanguage() == null
                            || v.getLanguage().equals(var.getLanguage());
        boolean typeCheck = v.getMediaType() == null && var.getMediaType() == null
                            || v.getMediaType().equals(var.getMediaType());
        if (encodCheck && langCheck && typeCheck) {
            return true;
        }
    }

    return false;
}
 
Example 5
Source File: ViewResponseFilter.java    From ozark with Apache License 2.0 6 votes vote down vote up
private static MediaType selectVariant(Request request, ResourceInfo resourceInfo) {

        Produces produces = resourceInfo.getResourceMethod().getAnnotation(Produces.class);
        if (produces == null) {
            produces = getAnnotation(resourceInfo.getResourceClass(), Produces.class);
        }

        if (produces != null) {

            List<Variant> variants = Arrays.stream(produces.value())
                .map((String mt) -> Variant.mediaTypes(MediaType.valueOf(mt)).build().get(0))
                .collect(Collectors.toList());

            Variant variant = request.selectVariant(variants);
            if (variant != null) {
                return variant.getMediaType();
            }

        }

        return null;

    }
 
Example 6
Source File: ResponseContentTypeResolver.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public static MediaType resolve(HttpHeaders httpHeaders, String... supportedMediaTypes) {
    Objects.requireNonNull(httpHeaders, "HttpHeaders cannot be null");
    Objects.requireNonNull(supportedMediaTypes, "Supported media types array cannot be null");

    Variant bestVariant = getBestVariant(httpHeaders.getRequestHeader(ACCEPT), getMediaTypeVariants(supportedMediaTypes));

    if (bestVariant != null) {
        return bestVariant.getMediaType();
    }

    if (supportedMediaTypes.length > 0) {
        return MediaType.valueOf(supportedMediaTypes[0]);
    }

    return DEFAULT_MEDIA_TYPE;
}
 
Example 7
Source File: ApiResource.java    From tessera with Apache License 2.0 6 votes vote down vote up
@GET
@Produces({APPLICATION_JSON, TEXT_HTML})
@ApiResponses({@ApiResponse(code = 200, message = "Returns JSON or HTML OpenAPI document")})
public Response api(@Context final Request request) throws IOException {

    final Variant variant = request.selectVariant(VARIANTS);

    final URL url;
    if (variant.getMediaType() == APPLICATION_JSON_TYPE) {
        url = getClass().getResource("/swagger.json");

    } else if (variant.getMediaType() == TEXT_HTML_TYPE) {
        url = getClass().getResource("/swagger.html");

    } else {

        return Response.status(Status.BAD_REQUEST).build();
    }

    return Response.ok(url.openStream(), variant.getMediaType()).build();
}
 
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: VariantHelper.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private static boolean hasMatchingMediaType(Variant supported, Variant required) {
	MediaType requiredMediaType = required.getMediaType();
	MediaType supportedMediaType = supported.getMediaType();
	return
		requiredMediaType == null ||
		supportedMediaType == null ||
		supportedMediaType.isCompatible(requiredMediaType);
}
 
Example 10
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 11
Source File: RequestImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Variant selectVariant(List<Variant> vars) throws IllegalArgumentException {
    if (vars == null || vars.isEmpty()) {
        throw new IllegalArgumentException("List of Variants is either null or empty");
    }
    List<MediaType> acceptMediaTypes = headers.getAcceptableMediaTypes();
    List<Locale> acceptLangs = headers.getAcceptableLanguages();
    List<String> acceptEncs = parseAcceptEnc(
        headers.getRequestHeaders().getFirst(HttpHeaders.ACCEPT_ENCODING));
    List<Variant> requestVariants = sortAllCombinations(acceptMediaTypes, acceptLangs, acceptEncs);
    List<Object> varyValues = new LinkedList<>();
    for (Variant requestVar : requestVariants) {
        for (Variant var : vars) {
            MediaType mt = var.getMediaType();
            Locale lang = var.getLanguage();
            String enc = var.getEncoding();

            boolean mtMatched = mt == null || requestVar.getMediaType().isCompatible(mt);
            if (mtMatched) {
                handleVaryValues(varyValues, HttpHeaders.ACCEPT);
            }

            boolean langMatched = lang == null || isLanguageMatched(requestVar.getLanguage(), lang);
            if (langMatched) {
                handleVaryValues(varyValues, HttpHeaders.ACCEPT_LANGUAGE);
            }

            boolean encMatched = acceptEncs.isEmpty() || enc == null 
                || isEncMatached(requestVar.getEncoding(), enc);
            if (encMatched) {
                handleVaryValues(varyValues, HttpHeaders.ACCEPT_ENCODING);
            }

            if (mtMatched && encMatched && langMatched) {
                addVaryHeader(varyValues);
                return var;
            }
        }
    }
    return null;
}
 
Example 12
Source File: SPARQLService.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Runs SPARQL queries
 * 
 * @param type
 *            Result Format: N3, N-TRIPLE, RDF/XML, RDF/XML-ABBREV, TURTLE
 * @param query
 *            Sparql for the query
 * @return
 */
@GET
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response selectQuery(@QueryParam("sparql") String query,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();
	Query q = null;

	try {
		query = URLDecoder.decode(query, "UTF-8");
		q = QueryFactory.create(query);
	} catch (Exception exc) {
		logger.error("Error during the creation of the SPARQL query", exc);
		return Response.serverError().build();
	}

	QueryExecution qexec = QueryExecutionFactory.create(q, ontModel);
	Model resultModel = null;
	if (q.isSelectType()) {
		ResultSet resultSet = qexec.execSelect();
		resultModel = ResultSetFormatter.toModel(resultSet);
	} else {
		throw new WebApplicationException(Status.UNAUTHORIZED);
	}
	qexec.close();

	graphStream.setModel(resultModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example 13
Source File: SerializationService.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("/dex")
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response dexSerialization(@QueryParam("id") String uuid,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();
	String queryString;

	File file = new File(
			"../web/src/main/resources/rest/dex-serialization-query.rq");
	try {
		queryString = FileUtils.readFileToString(file);
	} catch (IOException e) {
		logger.error("File with dex serialization query could not be found ");
		return Response.serverError().build();
	}

	ParameterizedSparqlString query = new ParameterizedSparqlString(
			queryString);
	query.setLiteral("uuid", ResourceFactory.createTypedLiteral(uuid));
	QueryExecution qe = QueryExecutionFactory.create(query.asQuery(),
			ontModel);
	Model resultModel = qe.execConstruct();

	graphStream.setModel(resultModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example 14
Source File: ContextService.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("/all")
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response getAllContexts(@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();

	String queryString;
	File file = new File(QUERY_FILE_GET_ALL_CONTEXTS);
	try {
		queryString = FileUtils.readFileToString(file);
	} catch (IOException e) {
		logger.error("File with context serialization query could not be found ");
		return Response.serverError().build();
	}

	ParameterizedSparqlString query = new ParameterizedSparqlString(
			queryString);
	QueryExecution qe = QueryExecutionFactory.create(query.asQuery(),
			ontModel);
	Model resultModel = qe.execConstruct();

	graphStream.setModel(resultModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example 15
Source File: ContextService.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("/{contextid}/de")
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response getDataElements(@PathParam("contextid") String contextId,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();

	String queryString;
	File file = new File(QUERY_FILE_GET_ALL_FROM_CONTEXT);
	try {
		queryString = FileUtils.readFileToString(file);
	} catch (IOException e) {
		logger.error("File with context serialization query could not be found ");
		return Response.serverError().build();
	}

	ParameterizedSparqlString query = new ParameterizedSparqlString(
			queryString);
	query.setLiteral("uuid", ResourceFactory.createTypedLiteral(contextId));
	QueryExecution qe = QueryExecutionFactory.create(query.asQuery(),
			ontModel);
	Model resultModel = qe.execConstruct();

	graphStream.setModel(resultModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example 16
Source File: SerializationService.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 
 * @param type
 *            outputFormat "N3", "N-TRIPLE", "RDF/XML-ABBREV" or
 *            "TURTLE"default: "RDF/XML".
 * @param uuid
 * @return
 */
@GET
@Path("/graph")
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response serialize(@QueryParam("id") String uuid, @QueryParam("uri") String uri,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();
	
	String query = "";
	if(uuid != null) {
		// get the uri of the resource
		query = "prefix mdr:     <http://www.salusproject.eu/iso11179-3/mdr#> "
				+ "prefix xsd:     <http://www.w3.org/2001/XMLSchema#> "
				+ "SELECT ?resource WHERE { " + "?resource ?op ?ar . "
				+ "?ar mdr:administeredItemIdentifier ?ii . "
				+ "?ii mdr:dataIdentifier \"" + uuid + "\"^^xsd:string. " + "}";

		logger.debug("Query execution: {}", query);
		Query q = QueryFactory.create(query);
		QueryExecution qe = QueryExecutionFactory.create(q, ontModel);
		ResultSet rs = qe.execSelect();

		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			uri = qs.getResource("resource").getURI();
		}
	}

	if(uri == null) {
		throw new WebApplicationException(Response.Status.BAD_REQUEST);
	}
	
	// use the uri to construct the model and return its serialization.
	query = "CONSTRUCT WHERE { <" + uri + "> ?p ?o .}";
	Query q2 = QueryFactory.create(query);
	QueryExecution qe2 = QueryExecutionFactory.create(q2, ontModel);
	Model outModel = qe2.execConstruct();

	graphStream.setModel(outModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example 17
Source File: EndpointControllerUtils.java    From ldp4j with Apache License 2.0 3 votes vote down vote up
/**
 * Get a text/plain representation that indicates the acceptable media types
 * and charsets for the specified resource. The current implementation
 * <b>only</b> takes care of the media type, nor language, nor encodings are
 * taken into consideration for generating the acceptable content.
 *
 * @param variants
 *            The acceptable variants
 * @param resourceLocation
 *            The location of the resource
 * @param supportedCharsets
 *            The supported charsets
 * @return A content instance that outlines the acceptable media types
 *         together with the locations from where the resource contents for
 *         those media types can be retrieved, and the charsets supported.
 */
static String getAcceptableContent(
		List<Variant> variants,
		URI resourceLocation,
		List<String> supportedCharsets) {
	StringBuilder builder = new StringBuilder();
	for (Variant variant : variants) {
		MediaType mediaType = variant.getMediaType();
		builder.append(mediaType).append(" : %1$s%n");
		for(String supportedCharset:supportedCharsets) {
			builder.append(mediaType.withCharset(supportedCharset)).append(" : %1$s%n");
		}
	}
	return String.format(builder.toString(),resourceLocation);
}