Java Code Examples for javax.ws.rs.core.Variant

The following examples show how to use javax.ws.rs.core.Variant. 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 check out the related API usage on the sidebar.
Example 1
Source Project: cxf   Source File: RequestImplTest.java    License: 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 2
Source Project: quarkus   Source File: ResponseContentTypeResolver.java    License: 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 3
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 Project: redpipe   Source File: Template.java    License: 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 5
@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 6
@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 7
Source Project: cxf   Source File: ResponseBuilderImplTest.java    License: 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 8
Source Project: cxf   Source File: VariantListBuilderImplTest.java    License: 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 9
Source Project: seed   Source File: RestModule.java    License: 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 10
Source Project: ldp4j   Source File: OperationContextImpl.java    License: 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 11
Source Project: ldp4j   Source File: OperationContextImpl.java    License: 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 12
Source Project: ldp4j   Source File: ExistingEndpointController.java    License: 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 13
Source Project: ldp4j   Source File: ExistingEndpointController.java    License: 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 Project: cxf   Source File: VariantListBuilderImplTest.java    License: 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 Project: hugegraph-common   Source File: AbstractRestClient.java    License: 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);
}
 
Example 16
Source Project: camunda-bpm-platform   Source File: FilterResourceImpl.java    License: 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 17
Source Project: tessera   Source File: ApiResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetHtmlDoc() throws Exception {
    Request request = mock(Request.class);
    Variant variant = mock(Variant.class);

    when(variant.getMediaType()).thenReturn(MediaType.TEXT_HTML_TYPE);

    when(request.selectVariant(any(List.class))).thenReturn(variant);

    Response result = apiResource.api(request);

    assertThat(result.getEntity()).isNotNull();
    assertThat(result.getStatus()).isEqualTo(200);
    assertThat(result.getMediaType()).isEqualTo(MediaType.TEXT_HTML_TYPE);
}
 
Example 18
Source Project: cxf   Source File: VariantListBuilderImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildEnc() {
    VariantListBuilderImpl vb = new VariantListBuilderImpl();
    List<Variant> variants =
        vb.encodings("zip", "identity").add().build();
    assertEquals("2 variants need to be created", 2, variants.size());
    assertTrue(verifyVariant(variants, new Variant(null, (Locale)null, "zip")));
    assertTrue(verifyVariant(variants, new Variant(null, (Locale)null, "identity")));
}
 
Example 19
Source Project: cxf   Source File: ResponseBuilderImplTest.java    License: Apache License 2.0 5 votes vote down vote up
protected static List<Variant> getVariantList(List<String> encoding,
                                              MediaType... mt) {
    return Variant.VariantListBuilder.newInstance()
        .mediaTypes(mt)
        .languages(new Locale("en", "US"), new Locale("en", "GB"), new Locale("zh", "CN"))
        .encodings(encoding.toArray(new String[]{}))
        .add()
        .build();
}
 
Example 20
Source Project: everrest   Source File: ResponseBuilderImplTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void setsEmptyListOfVariants() {
    Response response = new ResponseBuilderImpl().status(200)
                                .variants(new Variant(new MediaType("text", "xml"), (String)null, null))
                                .variants(newArrayList()).build();
    assertEquals("Accept", response.getMetadata().getFirst("vary"));
}
 
Example 21
Source Project: everrest   Source File: VariantsHandler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private List<Variant> filterByMediaType(List<AcceptMediaType> acceptMediaTypes, List<Variant> variants) {
    List<Variant> filteredVariants = new ArrayList<>();
    acceptMediaTypes.forEach(acceptMediaType -> variants.forEach(
            variant -> {
                if (variant.getMediaType() != null && acceptMediaType.isCompatible(variant.getMediaType())) {
                    filteredVariants.add(variant);
                }
            }));

    filteredVariants.addAll(variants.stream().filter(variant -> variant.getMediaType() == null).collect(toList()));

    return filteredVariants;
}
 
Example 22
Source Project: semanticMDR   Source File: SPARQLService.java    License: 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 23
Source Project: redpipe   Source File: AbstractTemplate.java    License: Apache License 2.0 5 votes vote down vote up
private TemplateVariants loadVariants(FileSystem fs, String templateDir, String namePart,
		List<String> list) {
	Map<Variant, String> variants = new HashMap<>();
	String defaultTemplateExtension = "";
	for (String entry : list) {
		// classpath dir entries are expanded into temp folders which we get as absolute paths
		int lastSlash = entry.lastIndexOf('/');
		if(lastSlash != -1)
			entry = entry.substring(lastSlash+1);
		if(!entry.equals(namePart)
				&& entry.startsWith(namePart)) {
			String extensionWithDot = entry.substring(namePart.length());
			if(!extensionWithDot.startsWith("."))
				continue;
			// get rid of the template extension
			int templateExtension = extensionWithDot.indexOf('.', 1);
			if(templateExtension == -1) {
				// we have a single extension, it's probably the default template extension
				defaultTemplateExtension = extensionWithDot;
				continue;
			}
			String mediaExtension = extensionWithDot.substring(1, templateExtension);
			MediaType mediaType = AbstractTemplate.parseMediaType(mediaExtension);
			variants.put(new Variant(mediaType, (String)null, null), templateDir+"/"+entry);
		}
	}
	return new TemplateVariants(templateDir+"/"+namePart+defaultTemplateExtension, variants);
}
 
Example 24
Source Project: camunda-bpm-platform   Source File: TaskRestServiceImpl.java    License: 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 25
public ValidationExceptionMapperSupport() {
  this.variants = Variant.mediaTypes(
      VND_VALIDATION_ERRORS_V1_JSON_TYPE,
      VND_VALIDATION_ERRORS_V1_XML_TYPE,
      APPLICATION_JSON_TYPE
      ).add().build();
}
 
Example 26
Source Project: cxf   Source File: VariantListBuilderImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void handleMediaTypes() {
    for (MediaType type : mediaTypes) {
        if (!languages.isEmpty()) {
            handleLanguages(type);
        } else if (!encodings.isEmpty()) {
            for (String enc : encodings) {
                variants.add(new Variant(type, (Locale)null, enc));
            }
        } else {
            variants.add(new Variant(type, (Locale)null, null));
        }
    }
}
 
Example 27
Source Project: pay-publicapi   Source File: RateLimiterFilter.java    License: MIT License 5 votes vote down vote up
private void setTooManyRequestsError() throws IOException {
    String errorResponse = objectMapper.writeValueAsString(anApiErrorResponse(Code.TOO_MANY_REQUESTS_ERROR));
    Response.ResponseBuilder builder = Response.status(TOO_MANY_REQUESTS_STATUS_CODE)
            .entity(errorResponse)
            .encoding(UTF8_CHARACTER_ENCODING)
            .variant(new Variant(MediaType.APPLICATION_JSON_TYPE, "", UTF8_CHARACTER_ENCODING));

    throw new WebApplicationException(builder.build());
}
 
Example 28
Source Project: Processor   Source File: ExceptionMapperBase.java    License: Apache License 2.0 5 votes vote down vote up
public Response.ResponseBuilder getResponseBuilder(Model model)
{
    Variant variant = getRequest().selectVariant(getVariants(Model.class));

    Response.ResponseBuilder builder = new com.atomgraph.core.model.impl.Response(getRequest(),
            model,
            null,
            new EntityTag(Long.toHexString(ModelUtils.hashModel(model))),
            variant).
            getResponseBuilder().
        header("Link", new Link(getUriInfo().getBaseUri(), LDT.base.getURI(), null));
    if (getTemplateCall() != null) builder.header("Link", new Link(URI.create(getTemplateCall().getTemplate().getURI()), LDT.template.getURI(), null));
    
    if (getOntology() != null)
    {
        builder.header("Link", new Link(URI.create(getOntology().getURI()), LDT.ontology.getURI(), null));

        Reasoner reasoner = getOntology().getOntModel().getSpecification().getReasoner();
        if (reasoner instanceof GenericRuleReasoner)
        {
            List<Rule> rules = ((GenericRuleReasoner)reasoner).getRules();
            builder.header("Rules", RulePrinter.print(rules));
        }
    }
    
    return builder;
}
 
Example 29
Source Project: jaxrs-analyzer   Source File: TestClass19.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 30
Source Project: semanticMDR   Source File: ContextService.java    License: 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();
}