Java Code Examples for javax.ws.rs.core.Request#selectVariant()

The following examples show how to use javax.ws.rs.core.Request#selectVariant() . 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: 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 5
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 6
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 7
Source File: RootResourceDispatcher.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@GET
public Response lookup(@Context Request request, @Context HttpServletRequest httpServletRequest,
        @Context UriInfo uriInfo) {
    ArrayList<Variant> variants = new ArrayList<>(rootResources.keySet());

    if (!variants.isEmpty()) {
        Variant v = request.selectVariant(variants);
        if (v != null) {
            return rootResources.get(v).buildResponse(httpServletRequest, uriInfo);
        }
    }
    return Response.status(Response.Status.NOT_FOUND).build();
}
 
Example 8
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 9
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 10
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 11
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 12
Source File: FilterResourceImpl.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public Object executeSingleResult(Request request) {
  Variant variant = request.selectVariant(VARIANTS);
  if (variant != null) {
    if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) {
      return executeJsonSingleResult();
    }
    else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) {
      return executeHalSingleResult();
    }
  }
  throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found");
}
 
Example 13
Source File: FilterResourceImpl.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public Object querySingleResult(Request request, String extendingQuery) {
  Variant variant = request.selectVariant(VARIANTS);
  if (variant != null) {
    if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) {
      return queryJsonSingleResult(extendingQuery);
    }
    else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) {
      return queryHalSingleResult(extendingQuery);
    }
  }
  throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found");
}
 
Example 14
Source File: FilterResourceImpl.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public Object executeList(Request request, Integer firstResult, Integer maxResults) {
  Variant variant = request.selectVariant(VARIANTS);
  if (variant != null) {
    if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) {
      return executeJsonList(firstResult, maxResults);
    }
    else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) {
      return executeHalList(firstResult, maxResults);
    }
  }
  throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found");
}
 
Example 15
Source File: FilterResourceImpl.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public Object queryList(Request request, String extendingQuery, Integer firstResult, Integer maxResults) {
  Variant variant = request.selectVariant(VARIANTS);
  if (variant != null) {
    if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) {
      return queryJsonList(extendingQuery, firstResult ,maxResults);
    }
    else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) {
      return queryHalList(extendingQuery, firstResult, maxResults);
    }
  }
  throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found");
}
 
Example 16
Source File: TaskResourceImpl.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public Object getTask(Request request) {
  Variant variant = request.selectVariant(VARIANTS);
  if (variant != null) {
    if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) {
      return getJsonTask();
    }
    else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) {
      return getHalTask();
    }
  }
  throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found");
}
 
Example 17
Source File: TaskRestServiceImpl.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public Object getTasks(Request request, UriInfo uriInfo, Integer firstResult, Integer maxResults) {
  Variant variant = request.selectVariant(VARIANTS);
  if (variant != null) {
    if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) {
      return getJsonTasks(uriInfo, firstResult, maxResults);
    }
    else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) {
      return getHalTasks(uriInfo, firstResult, maxResults);
    }
  }
  throw new InvalidRequestException(Response.Status.NOT_ACCEPTABLE, "No acceptable content-type found");
}
 
Example 18
Source File: JaxRsUtil.java    From SciGraph with Apache License 2.0 4 votes vote down vote up
public static Variant getVariant(Request request) {
  return request.selectVariant(VARIANTS);
}
 
Example 19
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();
}