/** * Create a new SPARQL 1.1 query resource based on a repository. * * @param rep the repository this resources operates on */ public SPARQLQuery(SailRepository rep) { super(rep); // initialize additional result MIME-Types queryResultVariants = Variant.mediaTypes( MediaType.valueOf(RDFMediaType.SPARQL_RESULTS_JSON), MediaType.valueOf(RDFMediaType.SPARQL_RESULTS_XML), MediaType.valueOf(RDFMediaType.SPARQL_RESULTS_CSV), MediaType.valueOf(RDFMediaType.SPARQL_RESULTS_TSV) ).add().build(); booleanResultVariants = Variant.mediaTypes( MediaType.valueOf(RDFMediaType.SPARQL_RESULTS_JSON), MediaType.valueOf(RDFMediaType.SPARQL_RESULTS_XML), MediaType.valueOf(MediaType.TEXT_PLAIN) ).add().build(); // get reference to query rewriting component this.qwfactory = QueryRewriterFactory.getInstance(rep); // get query timeout from properties String sout = SPARQLExtensionProps.getProperty("query.timeout"); this.timeout = Integer.parseInt(sout); }
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; }
@Override protected Response convert(final E exception, final String id) { final Response.ResponseBuilder builder = Response.status(getStatus(exception)); final List<ValidationErrorXO> errors = getValidationErrors(exception); if (errors != null && !errors.isEmpty()) { final Variant variant = getRequest().selectVariant(variants); if (variant != null) { builder.type(variant.getMediaType()) .entity( new GenericEntity<List<ValidationErrorXO>>(errors) { @Override public String toString() { return getEntity().toString(); } } ); } } return builder.build(); }
private Variant computeVariant(@Nullable final String mimeType) throws OperationException { // Determine supported media types from supplied type or @Produces annotation MediaType[] types = null; if (mimeType != null) { types = parseMediaTypes(mimeType); } else { types = new MediaType[] { MediaType.WILDCARD_TYPE }; final Method method = this.resource.getResourceMethod(); if (method != null) { final Produces produces = method.getAnnotation(Produces.class); if (produces != null) { types = parseMediaTypes(produces.value()); } } } // Determine supported encodings from supplied encoding or using defaults final String[] encodings = new String[] { "identity", "gzip", "deflate" }; // Perform negotiation and return the result, failing if there is no acceptable variant final Variant variant = this.request.selectVariant(Variant.mediaTypes(types) .encodings(encodings).build()); check(variant != null, Outcome.Status.ERROR_NOT_ACCEPTABLE, null); return variant; }
/** * What are we willing to serve up a directory or file as? * * @param de * The reference to the object to serve. * @return The variants we can serve it as. * @throws FilesystemAccessException * If we fail to read data necessary to detection of its media * type. */ private List<Variant> getVariants(DirectoryEntry de) throws FilesystemAccessException { if (de instanceof Directory) return DIRECTORY_VARIANTS; else if (!(de instanceof File)) throw new FilesystemAccessException("not a directory or file!"); File f = (File) de; List<Variant> variants = new ArrayList<>(INITIAL_FILE_VARIANTS); String contentType = support.getEstimatedContentType(f); if (!contentType.equals(APPLICATION_OCTET_STREAM)) { String[] ct = contentType.split("/"); variants.add(0, new Variant(new MediaType(ct[0], ct[1]), (String) null, null)); } return variants; }
/** * @param baseUri * * @return * * @throws UnsupportedEncodingException * @throws UriBuilderException * @throws IllegalArgumentException */ private Invocation preparePOSTInvocationBuilder(final String mimeType, final String contentType, final String query) throws IllegalArgumentException, UriBuilderException, UnsupportedEncodingException { final UriBuilder baseBuilder = UriBuilder.fromUri(HOST).port(PORT); final URI targetUri = baseBuilder.path(QueryExecutor.ENDPOINT_NAME).build(); final Client client = ClientBuilder.newClient(); final WebTarget resourceTarget = client.target(targetUri); final Builder invocationBuilder = resourceTarget.request(mimeType); final Entity<String> entity = Entity.entity(query, Variant.mediaTypes(MediaType.valueOf(contentType)) .encodings("UTF-8") .build() .get(0), null); final Invocation invocation = invocationBuilder.buildPost(entity); return invocation; }
@Override public OperationContext checkContents() { List<Variant> supportedVariants=VariantUtils.defaultVariants(); if(entity()==null || entity().isEmpty()) { throw new MissingContentException(this); } if(headers().getMediaType()==null) { throw new MissingContentTypeException(this); } if(!VariantHelper. forVariants(supportedVariants). isSupported(contentVariant())) { throw new UnsupportedContentException(this,contentVariant()); } return this; }
@Override public Variant expectedVariant() { List<Variant> variants=VariantUtils.defaultVariants(); Variant variant=this.request.selectVariant(variants); if(variant==null) { throw new NotAcceptableException(this); } String acceptableCharset=acceptedCharset(); if(acceptableCharset==null) { throw new NotAcceptableException(this); } return Variant. encodings(variant.getEncoding()). languages(variant.getLanguage()). mediaTypes(variant.getMediaType().withCharset(acceptableCharset)). add(). build(). get(0); }
private ResponseBuilder prepareRetrievalResponse( OperationContext context, Variant variant, DataSet entity, boolean includeEntity) { String body= context.serialize( entity, NamespacesHelper. constraintReportNamespaces( context.applicationNamespaces()), variant.getMediaType()); ResponseBuilder builder=Response.ok(); EndpointControllerUtils. populateResponseBody( builder, body, variant, includeEntity); return builder; }
private Response handleRetrieval(OperationContext context, boolean includeEntity) { final Variant variant=context.expectedVariant(); context. checkOperationSupport(). checkPreconditions(); switch(RetrievalScenario.forContext(context)) { case MIXED_QUERY: throw new MixedQueryNotAllowedException(context,includeEntity); case QUERY_NOT_SUPPORTED: throw new QueryingNotSupportedException(context,includeEntity); case CONSTRAINT_REPORT_RETRIEVAL: return handleConstraintReportRetrieval(context,includeEntity,variant); default: return handleResourceRetrieval(context,includeEntity,variant); } }
protected T doProduce() { final Request request = ResteasyProviderFactory.getContextData(Request.class); final Variant variant = request.selectVariant(VARIANTS); if (variant == null) { throw new RuntimeException("Only HAL and Siren media types are supported"); } else { final UriInfo uriInfo = ResteasyProviderFactory.getContextData(UriInfo.class); if (variant.getMediaType().equals(GENERIC_HAL)) { return hal(uriInfo); } else { return siren(uriInfo); } } }
@Test public void create_gzip_compressed_request_and_response() throws Exception { final Response response = RestTest.target(getPort(), "whois/test/person?password=test") .property(ClientProperties.USE_ENCODING, "gzip") .register(EncodingFilter.class) .register(GZipEncoder.class) .request() .post(Entity.entity(map(PAULETH_PALTHEN), new Variant(MediaType.APPLICATION_XML_TYPE, (String) null, "gzip")), Response.class); assertThat(response.getHeaderString("Content-Type"), is(MediaType.APPLICATION_XML)); assertThat(response.getHeaderString("Content-Encoding"), is("gzip")); final WhoisResources whoisResources = response.readEntity(WhoisResources.class); assertThat(whoisResources.getErrorMessages(), is(empty())); final WhoisObject object = whoisResources.getWhoisObjects().get(0); assertThat(object.getAttributes(), hasItem(new Attribute("person", "Pauleth Palthen"))); }
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"); }
@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"); }
/** * Initialize result variants and save reference to repository. * @param rep reference to repository */ public AbstractSailResource(SailRepository rep) { this.rep = rep; rdfResultVariants = Variant.mediaTypes( MediaType.valueOf(RDFMediaType.RDF_TURTLE), MediaType.valueOf(RDFMediaType.RDF_YARS), MediaType.valueOf(RDFMediaType.RDF_NTRIPLES), MediaType.valueOf(RDFMediaType.RDF_XML), MediaType.valueOf(RDFMediaType.RDF_JSON) ).add().build(); }
/** * 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(); }
static Response jsonContentNegotiation(Request request, JsonResultBuilder<Object> resultBuilder) { List<Variant> variants = Variant .mediaTypes(MediaType.APPLICATION_JSON_TYPE, APPLICATION_JSON_LD_TYPE) .languages(Configuration.SUPPORTED_LOCALES) .add().build(); //TODO lang parameter Variant bestResponseVariant = request.selectVariant(variants); if (bestResponseVariant == null) { return Response.notAcceptable(variants).build(); } return Response.ok(serialize(resultBuilder.buildResult(bestResponseVariant.getLanguage())), bestResponseVariant).build(); }
@javax.ws.rs.GET public Response method() { Response.ResponseBuilder responseBuilder = Response.accepted(); responseBuilder = Response.created(URI.create("")); responseBuilder = Response.noContent(); responseBuilder = Response.notAcceptable(new LinkedList<>()); responseBuilder = Response.notModified(); responseBuilder = Response.ok(); responseBuilder = Response.ok(1L, new Variant(MediaType.TEXT_PLAIN_TYPE, Locale.ENGLISH, "UTF-8")); responseBuilder = Response.seeOther(URI.create("")); responseBuilder = Response.serverError(); responseBuilder = Response.temporaryRedirect(URI.create("")); return responseBuilder.build(); }
@javax.ws.rs.GET public Response method() { Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder.links(new Link[0]); responseBuilder.variant(new Variant(MediaType.TEXT_PLAIN_TYPE, Locale.ENGLISH, "UTF-8")); return responseBuilder.build(); }
@javax.ws.rs.GET public Response method() { Response.ResponseBuilder responseBuilder = Response.notModified(""); responseBuilder = Response.ok(1d, MediaType.APPLICATION_JSON_TYPE); responseBuilder = Response.ok(1L, new Variant(MediaType.TEXT_PLAIN_TYPE, Locale.ENGLISH, "UTF-8")); return responseBuilder.build(); }
/** How did the user want the result? */ private MediaType pickType(HttpHeaders headers, DirectoryEntry de) throws FilesystemAccessException, NegotiationFailedException { List<Variant> variants = getVariants(de); // Manual content negotiation!!! Ugh! for (MediaType mt : headers.getAcceptableMediaTypes()) for (Variant v : variants) if (matchType(mt, v.getMediaType())) return v.getMediaType(); throw new NegotiationFailedException( "Do not know what type of response to produce.", variants); }
public boolean upload(String sessionId, File file, List<String> includes, List<String> excludes, String dataspacePath, final String path) throws Exception { StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL) .append(addSlashIfMissing(restEndpointURL)) .append("data/") .append(dataspacePath) .append('/') .append(escapeUrlPathSegment(path)); ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine) .providerFactory(providerFactory) .build(); ResteasyWebTarget target = client.target(uriTmpl.toString()); Response response = null; try { response = target.request() .header("sessionid", sessionId) .put(Entity.entity(new CompressedStreamingOutput(file, includes, excludes), new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, (Locale) null, encoding(file)))); if (response.getStatus() != HttpURLConnection.HTTP_CREATED) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("File upload failed. Status code: %d", response.getStatus()), response); } } return true; } finally { if (response != null) { response.close(); } } }
public boolean upload(String sessionId, StreamingOutput output, String encoding, String dataspace, String path) throws Exception { StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL) .append(addSlashIfMissing(restEndpointURL)) .append("data/") .append(dataspace); ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine) .providerFactory(providerFactory) .build(); ResteasyWebTarget target = client.target(uriTmpl.toString()).path(path); Response response = null; try { response = target.request() .header("sessionid", sessionId) .put(Entity.entity(output, new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, (Locale) null, encoding))); if (response.getStatus() != HttpURLConnection.HTTP_CREATED) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("File upload failed. Status code: %d" + response.getStatus()), response); } } return true; } finally { if (response != null) { response.close(); } } }
public Response process(Invocation.Builder request, MediaType mediaType, boolean useCompression) { request = request.accept(MediaType.APPLICATION_JSON); if (type == Type.DELETE) { return request.delete(); } else if (useCompression) { return request.acceptEncoding("gzip").method(type.name(), Entity.entity(command, new Variant(mediaType, (String) null, "gzip"))); } else { return request.method(type.name(), Entity.entity(command, mediaType)); } }
/** * Initialize result variants and save reference to repository. * @param rep reference to repository */ public AbstractSailResource(SailRepository rep) { this.rep = rep; rdfResultVariants = Variant.mediaTypes( MediaType.valueOf(RDFMediaType.RDF_TURTLE), MediaType.valueOf(RDFMediaType.RDF_NTRIPLES), MediaType.valueOf(RDFMediaType.RDF_XML), MediaType.valueOf(RDFMediaType.RDF_JSON) ).add().build(); }
/** * Get media types for which the {@link org.glassfish.jersey.server.mvc.spi.ResolvedViewable resolved viewable} could be * produced. * * @param containerRequest request to obtain acceptable media types. * @param extendedUriInfo uri info to obtain resource method from and its producible media types. * @param varyHeaderValue Vary header reference. * @return list of producible media types. */ public static List<MediaType> getProducibleMediaTypes(final ContainerRequest containerRequest, final ExtendedUriInfo extendedUriInfo, final Ref<String> varyHeaderValue) { final List<MediaType> producedTypes = getResourceMethodProducibleTypes(extendedUriInfo); final MediaType[] mediaTypes = producedTypes.toArray(new MediaType[producedTypes.size()]); final List<Variant> variants = VariantSelector.selectVariants(containerRequest, Variant.mediaTypes(mediaTypes) .build(), varyHeaderValue == null ? Refs.emptyRef() : varyHeaderValue); return Lists.transform(variants, variant -> MediaTypes.stripQualityParams(variant.getMediaType())); }
public boolean isSupported(Variant variant) { boolean matched=false; for(Iterator<Variant> it=supportedVariants.iterator();it.hasNext() && !matched;) { matched=matches(it.next(),variant); } return matched; }
public Variant select(Collection<? extends Variant> supportedVariants) { for(Variant variant:supportedVariants) { if(isSupported(variant)) { return variant; } } return null; }
private static boolean hasMatchingEncoding(Variant supported, Variant required) { String requiredEncoding = required.getEncoding(); String supportedEncoding = supported.getEncoding(); return requiredEncoding==null || supportedEncoding==null || supportedEncoding.equals(requiredEncoding); }
private static boolean hasMatchingLanguage(Variant supported, Variant required) { Locale requiredLanguage = required.getLanguage(); Locale supportedLanguage = supported.getLanguage(); return requiredLanguage == null || supportedLanguage ==null || isLanguageMatched(supportedLanguage, requiredLanguage); }
private static boolean hasMatchingMediaType(Variant supported, Variant required) { MediaType requiredMediaType = required.getMediaType(); MediaType supportedMediaType = supported.getMediaType(); return requiredMediaType == null || supportedMediaType == null || supportedMediaType.isCompatible(requiredMediaType); }
/** * Get a list of acceptable variants. Current implementation only leverages * media type for the specification of variants. * * @param mediaTypes * The list of acceptable media types. * @return A list of acceptable variants. */ public static List<Variant> createVariants(MediaType... mediaTypes) { return Variant.VariantListBuilder. newInstance(). mediaTypes(mediaTypes). encodings(). languages(). add(). build(); }
public static String toString(Variant v) { return String.format( getTemplate(v), getMediaType(v), getEncoding(v), getLanguage(v)); }
public static String toString(List<Variant> variants) { StringBuilder builder=new StringBuilder(); for(Iterator<Variant> it=variants.iterator();it.hasNext();) { String formatedVariants = toString(it.next()); builder.append(formatedVariants); if(it.hasNext()) { builder.append(", "); } } return builder.toString(); }
private static String getLanguage(Variant v) { String language="*"; Locale locale = v.getLanguage(); if(locale!=null) { language=locale.toString(); } return language; }
private static String getEncoding(Variant v) { String encoding = v.getEncoding(); if(encoding==null) { encoding="*"; } return encoding; }
private static MediaType getMediaType(Variant v) { MediaType mediaType = v.getMediaType(); if(mediaType==null) { mediaType=new MediaType(MediaType.MEDIA_TYPE_WILDCARD,MediaType.MEDIA_TYPE_WILDCARD); } return mediaType; }
private Variant contentVariant() { List<String> requestHeader= headers(). getRequestHeader(HttpHeaders.CONTENT_ENCODING); List<Variant> variants= Variant. mediaTypes(headers().getMediaType()). encodings(requestHeader.toArray(new String[requestHeader.size()])). languages(headers().getLanguage()). add(). build(); return variants.get(0); }