javax.ws.rs.core.Variant Java Examples

The following examples show how to use javax.ws.rs.core.Variant. 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: ExistingEndpointController.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
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;
}
 
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: ValidationExceptionMapperSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@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();
}
 
Example #4
Source File: ResponseBuilderImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testVariantsList() throws Exception {
    MetadataMap<String, Object> m = new MetadataMap<>();
    m.add("Content-Type", MediaType.TEXT_XML_TYPE);
    m.add("Content-Language", new Locale("en", "UK"));
    m.add("Content-Language", new Locale("en", "GB"));
    m.add("Content-Encoding", "compress");
    m.add("Content-Encoding", "gzip");
    m.add("Vary", "Accept");
    m.add("Vary", "Accept-Language");
    m.add("Vary", "Accept-Encoding");

    List<Variant> vts = Variant.VariantListBuilder.newInstance()
        .mediaTypes(MediaType.TEXT_XML_TYPE).
        languages(new Locale("en", "UK"), new Locale("en", "GB")).encodings("compress", "gzip").
                  add().build();

    checkBuild(Response.ok().variants(vts).build(),
               200, null, m);
}
 
Example #5
Source File: Template.java    From redpipe with Apache License 2.0 6 votes vote down vote up
public Single<String> selectVariant(Request request){
	return loadVariants()
			.flatMap(variants -> {
				// no variant
				if(variants.variants.isEmpty())
					return Single.just(variants.defaultTemplate);
				Variant selectedVariant = request.selectVariant(new ArrayList<>(variants.variants.keySet()));
				// no acceptable variant
				if(selectedVariant == null) {
					// if it does not exist, that's special
					String template = variants.defaultTemplate;
					FileSystem fs = AppGlobals.get().getVertx().fileSystem();
					return fs.rxExists(template)
							.map(exists -> {
								if(exists)
									return template;
								throw new WebApplicationException(Status.NOT_ACCEPTABLE);
							});
				}
				return Single.just(variants.variants.get(selectedVariant));
			});
}
 
Example #6
Source File: OperationContextImpl.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: OperationContextImpl.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #8
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 #9
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 #10
Source File: RequestImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleVariantsBestMatch() {
    metadata.putSingle(HttpHeaders.ACCEPT, "application/xml");
    metadata.putSingle(HttpHeaders.ACCEPT_LANGUAGE, "en-us");
    metadata.putSingle(HttpHeaders.ACCEPT_ENCODING, "gzip;q=1.0, compress");

    List<Variant> list = new ArrayList<>();
    list.add(new Variant(MediaType.APPLICATION_JSON_TYPE, new Locale("en"), "gzip"));
    Variant var2 = new Variant(MediaType.APPLICATION_XML_TYPE, new Locale("en"), "gzip");
    list.add(var2);
    Variant var3 = new Variant(MediaType.APPLICATION_XML_TYPE, new Locale("en"), null);
    list.add(var3);
    assertSame(var2, new RequestImpl(m).selectVariant(list));
    list.clear();
    list.add(var3);
    assertSame(var3, new RequestImpl(m).selectVariant(list));
}
 
Example #11
Source File: VariantListBuilderImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildAllWithoutAdd() {
    VariantListBuilderImpl vb = new VariantListBuilderImpl();
    MediaType mt1 = new MediaType("*", "*");
    MediaType mt2 = new MediaType("text", "xml");
    List<Variant> variants = vb.mediaTypes(mt1, mt2)
        .languages(new Locale("en"), new Locale("fr")).encodings("zip", "identity").build();
    assertEquals("8 variants need to be created", 8, variants.size());
    assertTrue(verifyVariant(variants, new Variant(mt1, new Locale("en"), "zip")));
    assertTrue(verifyVariant(variants, new Variant(mt1, new Locale("en"), "identity")));
    assertTrue(verifyVariant(variants, new Variant(mt1, new Locale("fr"), "zip")));
    assertTrue(verifyVariant(variants, new Variant(mt1, new Locale("fr"), "identity")));
    assertTrue(verifyVariant(variants, new Variant(mt2, new Locale("en"), "zip")));
    assertTrue(verifyVariant(variants, new Variant(mt2, new Locale("en"), "identity")));
    assertTrue(verifyVariant(variants, new Variant(mt2, new Locale("fr"), "zip")));
    assertTrue(verifyVariant(variants, new Variant(mt2, new Locale("fr"), "identity")));
}
 
Example #12
Source File: RestModule.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    for (Class<?> resource : resources) {
        bind(resource);
    }
    for (Class<?> provider : providers) {
        bind(provider).in(Scopes.SINGLETON);
    }
    if (!rootResourcesByVariant.isEmpty()) {
        MapBinder<Variant, RootResource> multiBinder = MapBinder.newMapBinder(binder(), Variant.class,
                RootResource.class);
        for (Map.Entry<Variant, Class<? extends RootResource>> rootResourceClassEntry : rootResourcesByVariant
                .entrySet()) {
            multiBinder.addBinding(rootResourceClassEntry.getKey()).to(rootResourceClassEntry.getValue());
        }
    }
}
 
Example #13
Source File: ExistingEndpointController.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
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);
	}
}
 
Example #14
Source File: VariantListBuilderImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildAll() {
    VariantListBuilderImpl vb = new VariantListBuilderImpl();
    MediaType mt1 = new MediaType("*", "*");
    MediaType mt2 = new MediaType("text", "xml");
    List<Variant> variants = vb.mediaTypes(mt1, mt2)
        .languages(new Locale("en"), new Locale("fr")).encodings("zip", "identity").add().build();
    assertEquals("8 variants need to be created", 8, variants.size());
    assertTrue(verifyVariant(variants, new Variant(mt1, new Locale("en"), "zip")));
    assertTrue(verifyVariant(variants, new Variant(mt1, new Locale("en"), "identity")));
    assertTrue(verifyVariant(variants, new Variant(mt1, new Locale("fr"), "zip")));
    assertTrue(verifyVariant(variants, new Variant(mt1, new Locale("fr"), "identity")));
    assertTrue(verifyVariant(variants, new Variant(mt2, new Locale("en"), "zip")));
    assertTrue(verifyVariant(variants, new Variant(mt2, new Locale("en"), "identity")));
    assertTrue(verifyVariant(variants, new Variant(mt2, new Locale("fr"), "zip")));
    assertTrue(verifyVariant(variants, new Variant(mt2, new Locale("fr"), "identity")));
}
 
Example #15
Source File: VariantHelper.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
public Variant select(Collection<? extends Variant> supportedVariants) {
	for(Variant variant:supportedVariants) {
		if(isSupported(variant)) {
			return variant;
		}
	}
	return null;
}
 
Example #16
Source File: OperationContextImpl.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private CharsetSelector charsetSelector() {
	if(this.charsetSelector==null) {
		final List<Variant> variants=VariantUtils.defaultVariants();
		final Variant variant = this.request.selectVariant(variants);
		this.charsetSelector=
			CharsetSelector.
				newInstance().
					mediaType(variant==null?null:variant.getMediaType()).
					acceptableCharsets(this.headers.getRequestHeader(HttpHeaders.ACCEPT_CHARSET)).
					supportedCharsets(supportedCharsets());
	}
	return this.charsetSelector;
}
 
Example #17
Source File: ContentProcessingException.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
static String getFailureMessage(String message, List<Variant> variants) {
	return
		new StringBuilder().
			append(message).
			append(variants.size()==1?"":"one of: ").
			append(VariantUtils.toString(variants)).
			toString();
}
 
Example #18
Source File: ExistingEndpointController.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private Response prepareResourceRetrievalResponse(
		OperationContext context,
		Variant variant,
		DataSet entity,
		boolean includeEntity) {
	ResponseBuilder builder=prepareRetrievalResponse(context, variant, entity, includeEntity);
	addOptionsMandatoryHeaders(context, builder);

	ContentPreferences preferences = context.contentPreferences();
	if(preferences!=null) {
		builder.
			header(
				ContentPreferencesUtils.PREFERENCE_APPLIED_HEADER,
				ContentPreferencesUtils.asPreferenceAppliedHeader(preferences));
	}

	Query query=context.getQuery();
	if(!query.isEmpty()) {
		builder.
			header(
				HttpHeaders.LINK,
				EndpointControllerUtils.
					createQueryOfLink(
						context.base().resolve(context.path()),
						query));
	}
	return builder.build();
}
 
Example #19
Source File: RequestImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleNonMatchingVariant() {
    metadata.putSingle(HttpHeaders.ACCEPT, "application/xml");
    metadata.putSingle(HttpHeaders.ACCEPT_LANGUAGE, "en");
    metadata.putSingle(HttpHeaders.ACCEPT_ENCODING, "utf-8");

    List<Variant> list = new ArrayList<>();
    list.add(new Variant(MediaType.APPLICATION_JSON_TYPE, new Locale("en"), "utf-8"));
    assertNull(new RequestImpl(m).selectVariant(list));

}
 
Example #20
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 #21
Source File: ExistingEndpointController.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private Response prepareConstraintReportRetrievalResponse(
		OperationContext context,
		Variant variant,
		DataSet report,
		boolean includeEntity) {
	return
		prepareRetrievalResponse(context,variant,report,includeEntity).
			build();
}
 
Example #22
Source File: RequestImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public int compare(Variant v1, Variant v2) {
    int result = compareMediaTypes(v1.getMediaType(), v2.getMediaType());

    if (result != 0) {
        return result;
    }

    result = compareLanguages(v1.getLanguage(), v2.getLanguage());

    if (result == 0) {
        result = compareEncodings(v1.getEncoding(), v2.getEncoding());
    }

    return result;
}
 
Example #23
Source File: ResponseBuilderImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testVariant2() throws Exception {
    List<String> encoding = Arrays.asList("gzip", "compress");
    MediaType mt = MediaType.APPLICATION_JSON_TYPE;
    ResponseBuilder rb = Response.ok();
    rb = rb.variants(getVariantList(encoding, mt).toArray(new Variant[0]));
    Response response = rb.build();
    List<Object> enc = response.getHeaders().get(HttpHeaders.CONTENT_ENCODING);
    assertTrue(encoding.containsAll(enc));
    List<Object> ct = response.getHeaders().get(HttpHeaders.CONTENT_TYPE);
    assertTrue(ct.contains(mt));
}
 
Example #24
Source File: VariantHelper.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private static boolean hasMatchingEncoding(Variant supported, Variant required) {
	String requiredEncoding = required.getEncoding();
	String supportedEncoding = supported.getEncoding();
	return
		requiredEncoding==null ||
		supportedEncoding==null ||
		supportedEncoding.equals(requiredEncoding);
}
 
Example #25
Source File: ResponseBuilderImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void setsListOfVariants() {
    List<Variant> variants = new ArrayList<>(3);
    variants.add(new Variant(new MediaType("text", "xml"), (String)null, null));
    variants.add(new Variant(null, (String)null, "KOI8-R"));
    variants.add(new Variant(null, new Locale("ru", "RU"), null));
    Response response = new ResponseBuilderImpl().status(200).variants(variants).build();
    assertEquals("Accept,Accept-Language,Accept-Encoding", response.getMetadata().getFirst("vary"));
    variants.remove(1);
    response = new ResponseBuilderImpl().status(200).variants(variants).build();
    assertEquals("Accept,Accept-Language", response.getMetadata().getFirst("vary"));
    variants.remove(0);
    response = new ResponseBuilderImpl().status(200).variants(variants).build();
    assertEquals("Accept-Language", response.getMetadata().getFirst("vary"));
}
 
Example #26
Source File: VariantUtils.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private static String getLanguage(Variant v) {
	String language="*";
	Locale locale = v.getLanguage();
	if(locale!=null) {
		language=locale.toString();
	}
	return language;
}
 
Example #27
Source File: VariantHelper.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
public boolean isSupported(Variant variant) {
	boolean matched=false;
	for(Iterator<Variant> it=supportedVariants.iterator();it.hasNext() && !matched;) {
		matched=matches(it.next(),variant);
	}
	return matched;
}
 
Example #28
Source File: RestPlugin.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public InitState initialize(InitContext initContext) {
    ServletContext servletContext = seedRuntime.contextAs(ServletContext.class);
    Map<Predicate<Class<?>>, Collection<Class<?>>> scannedClasses = initContext.scannedTypesByPredicate();

    restConfig = getConfiguration(RestConfig.class);
    resources = scannedClasses.get(JaxRsResourcePredicate.INSTANCE);
    providers = scannedClasses.get(JaxRsProviderPredicate.INSTANCE);

    if (servletContext != null) {
        addJacksonProviders(providers);

        configureExceptionMappers();
        configureStreamSupport();

        initializeHypermedia(servletContext.getContextPath());

        if (restConfig.isJsonHome()) {
            // The typed locale parameter resolves constructor ambiguity when the JAX-RS 2.0 spec is in the
            // classpath
            addRootResourceVariant(new Variant(new MediaType("application", "json"), (Locale) null, null),
                    JsonHomeRootResource.class);
        }

        seedRuntime.registerConfigurationProvider(
                new RestRuntimeConfigurationProvider(restConfig),
                ConfigurationPriority.RUNTIME_INFO
        );

        enabled = true;
    } else {
        initializeHypermedia("");
    }

    return InitState.INITIALIZED;
}
 
Example #29
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 #30
Source File: AbstractRestClient.java    From hugegraph-common with Apache License 2.0 5 votes vote down vote up
private Pair<Builder, Entity<?>> buildRequest(
                                 String path, String id, Object object,
                                 MultivaluedMap<String, Object> headers,
                                 Map<String, Object> params) {
    WebTarget target = this.target;
    if (params != null && !params.isEmpty()) {
        for (Map.Entry<String, Object> param : params.entrySet()) {
            target = target.queryParam(param.getKey(), param.getValue());
        }
    }

    Builder builder = id == null ? target.path(path).request() :
                      target.path(path).path(encode(id)).request();

    String encoding = null;
    if (headers != null && !headers.isEmpty()) {
        // Add headers
        builder = builder.headers(headers);
        encoding = (String) headers.getFirst("Content-Encoding");
    }

    /*
     * We should specify the encoding of the entity object manually,
     * because Entity.json() method will reset "content encoding =
     * null" that has been set up by headers before.
     */
    Entity<?> entity;
    if (encoding == null) {
        entity = Entity.json(object);
    } else {
        Variant variant = new Variant(MediaType.APPLICATION_JSON_TYPE,
                                      (String) null, encoding);
        entity = Entity.entity(object, variant);
    }
    return Pair.of(builder, entity);
}