javax.ws.rs.core.Link Java Examples

The following examples show how to use javax.ws.rs.core.Link. 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: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getRecordsWithLinksTest() {
    // Setup:
    when(results.getPageNumber()).thenReturn(1);

    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records")
            .queryParam("offset", 1)
            .queryParam("limit", 1).request().get();
    assertEquals(response.getStatus(), 200);
    verify(catalogManager).findRecord(eq(vf.createIRI(LOCAL_IRI)), any(PaginatedSearchParams.class));
    Set<Link> links = response.getLinks();
    assertEquals(links.size(), 2);
    links.forEach(link -> {
        assertTrue(link.getUri().getRawPath().contains("catalogs/" + encode(LOCAL_IRI) + "/records"));
        assertTrue(link.getRel().equals("prev") || link.getRel().equals("next"));
    });
}
 
Example #2
Source File: JsonHyperSchema.java    From rest-schemagen with Apache License 2.0 6 votes vote down vote up
@Override
public Link unmarshal(JsonLink v) {
	Link.Builder lb = Link.fromUri(v.getHref());
	if (v.getMap() != null) {
		for (Entry<String, String> en : v.getMap().entrySet()) {
			lb.param(en.getKey(), en.getValue());
		}
	}
	if (v.getSchema() != null) {
		lb.param(LinkCreator.SCHEMA_PARAM_KEY, v.getSchema().toString());
	}

	if (v.getTargetSchema() != null) {
		lb.param(LinkCreator.TARGET_SCHEMA_PARAM_KEY, v.getTargetSchema().toString());
	}
	return lb.build();
}
 
Example #3
Source File: ResponseImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetLinksNoRel() {
    try (ResponseImpl ri = new ResponseImpl(200)) {
        MetadataMap<String, Object> meta = new MetadataMap<>();
        ri.addMetadata(meta);

        Set<Link> links = ri.getLinks();
        assertTrue(links.isEmpty());

        meta.add(HttpHeaders.LINK, "<http://next>");
        meta.add(HttpHeaders.LINK, "<http://prev>");

        assertFalse(ri.hasLink("next"));
        Link next = ri.getLink("next");
        assertNull(next);
        assertFalse(ri.hasLink("prev"));
        Link prev = ri.getLink("prev");
        assertNull(prev);

        links = ri.getLinks();
        assertTrue(links.contains(Link.fromUri("http://next").build()));
        assertTrue(links.contains(Link.fromUri("http://prev").build()));
    }
}
 
Example #4
Source File: RestUtilsTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void createPaginatedResponseWithJsonTest() {
    JSONArray array = JSONArray.fromObject("[{'@graph':[" + expectedTypedJsonld + "]}]");

    Response response = RestUtils.createPaginatedResponseWithJson(uriInfo, array, 3, 1, 0);
    assertEquals(response.getLinks().size(), 1);
    Link link = response.getLinks().iterator().next();
    assertEquals(link.getRel(), "next");
    assertTrue(link.getUri().getRawPath().equals("/rest/tests"));

    response = RestUtils.createPaginatedResponseWithJson(uriInfo, array, 3, 1, 1);
    assertEquals(response.getLinks().size(), 2);
    assertTrue(response.getLinks().stream()
            .allMatch(lnk -> (lnk.getRel().equals("prev") || lnk.getRel().equals("next"))
                    && lnk.getUri().getRawPath().equals("/rest/tests")));

    response = RestUtils.createPaginatedResponseWithJson(uriInfo, array, 3, 1, 2);
    assertEquals(response.getLinks().size(), 1);
    link = response.getLinks().iterator().next();
    assertEquals(link.getRel(), "prev");
    assertTrue(link.getUri().getRawPath().equals("/rest/tests"));

    response = RestUtils.createPaginatedResponseWithJson(uriInfo, array, 3, 3, 0);
    assertEquals(response.getLinks().size(), 0);
}
 
Example #5
Source File: AbstractTrellisHttpResourceTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
private Stream<Executable> checkMementoHeaders(final Response res, final String path) {
    final List<Link> links = getLinks(res);
    return Stream.of(
            () -> assertTrue(links.stream().anyMatch(l -> l.getRels().contains("first") &&
                RFC_1123_DATE_TIME.withZone(UTC).format(ofEpochSecond(timestamp - 2000))
                    .equals(l.getParams().get("datetime")) &&
                l.getUri().toString().equals(getBaseUrl() + path + "?version=1496260729")),
                             "Missing expected first rel=memento Link!"),
            () -> assertTrue(links.stream().anyMatch(l -> l.getRels().contains("last") &&
                RFC_1123_DATE_TIME.withZone(UTC).format(time).equals(l.getParams().get("datetime")) &&
                l.getUri().toString().equals(getBaseUrl() + path + VERSION_PARAM)),
                             "Missing expected last rel=memento Link!"),
            () -> assertTrue(links.stream().anyMatch(l -> l.getRels().contains("timemap") &&
                RFC_1123_DATE_TIME.withZone(UTC).format(ofEpochSecond(timestamp - 2000))
                    .equals(l.getParams().get("from")) &&
                RFC_1123_DATE_TIME.withZone(UTC).format(ofEpochSecond(timestamp))
                    .equals(l.getParams().get("until")) &&
                APPLICATION_LINK_FORMAT.equals(l.getType()) &&
                l.getUri().toString().equals(getBaseUrl() + path + "?ext=timemap")), "Missing valid timemap link!"),
            () -> assertTrue(hasTimeGateLink(res, path), "No rel=timegate Link!"),
            () -> assertTrue(hasOriginalLink(res, path), "No rel=original Link!"));
}
 
Example #6
Source File: PatchHandler.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * Update the resource in the persistence layer.
 *
 * @param builder the Trellis response builder
 * @return a response builder promise
 */
public CompletionStage<ResponseBuilder> updateResource(final ResponseBuilder builder) {
    LOGGER.debug("Updating {} via PATCH", getIdentifier());

    // Add the LDP link types
    if (getExtensionGraphName() != null) {
        getLinkTypes(LDP.RDFSource).forEach(type -> builder.link(type, Link.TYPE));
    } else {
        getLinkTypes(getLdpType()).forEach(type -> builder.link(type, Link.TYPE));
    }

    final Dataset mutable = rdf.createDataset();
    final Dataset immutable = rdf.createDataset();

    return assembleResponse(mutable, immutable, builder)
        .whenComplete((a, b) -> closeDataset(mutable))
        .whenComplete((a, b) -> closeDataset(immutable));
}
 
Example #7
Source File: ResponseImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetMultipleWithSingleLink() {
    try (ResponseImpl ri = new ResponseImpl(200)) {
        MetadataMap<String, Object> meta = new MetadataMap<>();
        ri.addMetadata(meta);

        Set<Link> links = ri.getLinks();
        assertTrue(links.isEmpty());

        meta.add(HttpHeaders.LINK, "<http://next>;rel=\"next\",");

        assertTrue(ri.hasLink("next"));
        Link next = ri.getLink("next");
        assertNotNull(next);

        links = ri.getLinks();
        assertTrue(links.contains(Link.fromUri("http://next").rel("next").build()));
    }
}
 
Example #8
Source File: LinkCreatorTest.java    From rest-schemagen with Apache License 2.0 6 votes vote down vote up
@Test
public void testTargetSchemaPresentOnMatchingMediaTypeAtMethodLevel()
        throws NoSuchMethodException, SecurityException {
    @Path("test")
    class TestResource {
        @GET
        @Produces("application/json")
        public String get() {
            return "test";
        }
    }

    Scope scope = new CallScope(TestResource.class, TestResource.class.getMethod("get"),
            new String[] {}, null);

    Link link = createFor(scope, Relation.of(Rel.SELF));

    assertEquals("http://host/base/test", link.getUri().toString());
    assertEquals("GET", link.getParams().get("method"));
    assertEquals("application/json", link.getParams().get("mediaType"));
    assertEquals(testSchema, link.getParams().get(LinkCreator.TARGET_SCHEMA_PARAM_KEY));
}
 
Example #9
Source File: ResponseImpl.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Set<Link> getLinks() {
    List<Object> links = getMetadata().get(LINK);
    if (links == null) {
        return Collections.emptySet();
    }
    Set<Link> linkSet = new LinkedHashSet<>();
    for (Object value : links) {
        if (value instanceof Link) {
            linkSet.add((Link)value);
        } else {
            linkSet.add(Link.valueOf(value instanceof String ? (String)value : getHeaderAsString(value)));
        }
    }
    return linkSet;
}
 
Example #10
Source File: WebAcFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testFilterResponseWithControl() {
    final MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    final MultivaluedMap<String, String> stringHeaders = new MultivaluedHashMap<>();
    stringHeaders.putSingle("Link", "<http://www.w3.org/ns/ldp#BasicContainer>; rel=\"type\"");
    when(mockResponseContext.getStatusInfo()).thenReturn(OK);
    when(mockResponseContext.getHeaders()).thenReturn(headers);
    when(mockResponseContext.getStringHeaders()).thenReturn(stringHeaders);
    when(mockContext.getProperty(eq(WebAcFilter.SESSION_WEBAC_MODES)))
        .thenReturn(new AuthorizedModes(effectiveAcl, allModes));

    final WebAcFilter filter = new WebAcFilter();
    filter.setAccessService(mockWebAcService);

    assertTrue(headers.isEmpty());
    filter.filter(mockContext, mockResponseContext);
    assertFalse(headers.isEmpty());

    final List<Object> links = headers.get("Link");
    assertTrue(links.stream().map(Link.class::cast).anyMatch(link ->
                link.getRels().contains("acl") && "/?ext=acl".equals(link.getUri().toString())));
    assertTrue(links.stream().map(Link.class::cast).anyMatch(link ->
                "/?ext=acl".equals(link.getUri().toString()) &&
                link.getRels().contains(Trellis.effectiveAcl.getIRIString())));
}
 
Example #11
Source File: JsonLinkTest.java    From rest-schemagen with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
	uriString = "https://localhost:1234/base?parm1=val1&parm2=val2#test";
	jsonLink = new JsonLink(Link //
			.fromUri(uriString) //
			.param(LinkCreator.SCHEMA_PARAM_KEY, SCHEMA_VALUE) //
			.param(LinkCreator.TARGET_SCHEMA_PARAM_KEY, TARGET_SCHEMA_VALUE) //
			.param("foo", "bar") //
			.build());

	uriStringTemplate = "https://localhost:1234/{id}/base?parm1=val1&parm2=val2#test";
			jsonLinkTemplate = new JsonLink(Link //
							.fromUri(uriStringTemplate) //
							.param(LinkCreator.SCHEMA_PARAM_KEY, SCHEMA_VALUE) //
							.param(LinkCreator.TARGET_SCHEMA_PARAM_KEY, TARGET_SCHEMA_VALUE) //
							.param("foo", "bar") //
							.build("{id}"));
}
 
Example #12
Source File: MementoResourceTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testFilteredMementoLink() {
    final Link link = fromUri("http://example.com/resource/memento/1").rel(MEMENTO)
        .param(DATETIME, ofInstant(now(), UTC).format(RFC_1123_DATE_TIME)).build();
    assertTrue(MementoResource.filterLinkParams(link, false).getParams().containsKey(DATETIME));
    assertFalse(MementoResource.filterLinkParams(link, true).getParams().containsKey(DATETIME));
}
 
Example #13
Source File: Orders.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@XmlTransient
public URI getNext()
{
   if (links == null) return null;
   for (Link link : links)
   {
      if ("next".equals(link.getRel())) return link.getUri();
   }
   return null;
}
 
Example #14
Source File: MementoResourceTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testFilteredTimemapLink() {
    final Link link = fromUri("http://example.com/resource/timemap").rel(TIMEMAP)
        .param(FROM, ofInstant(now().minusSeconds(1000), UTC).format(RFC_1123_DATE_TIME))
        .param(UNTIL, ofInstant(now(), UTC).format(RFC_1123_DATE_TIME)).build();
    assertTrue(MementoResource.filterLinkParams(link, false).getParams().containsKey(FROM));
    assertFalse(MementoResource.filterLinkParams(link, true).getParams().containsKey(FROM));
    assertTrue(MementoResource.filterLinkParams(link, false).getParams().containsKey(UNTIL));
    assertFalse(MementoResource.filterLinkParams(link, true).getParams().containsKey(UNTIL));
}
 
Example #15
Source File: HyperSchemaCreator.java    From rest-schemagen with Apache License 2.0 5 votes vote down vote up
@SafeVarargs
public final <T> ObjectWithSchema<T> create(T object, List<Link>... linkArray) {
    ArrayList<Link> links = new ArrayList<>();
    Arrays.stream(linkArray).forEach(links::addAll);

    JsonHyperSchema hyperSchema = jsonHyperSchemaCreator.from(links);
    return objectWithSchemaCreator.create(object, hyperSchema);
}
 
Example #16
Source File: RootController.java    From container with Apache License 2.0 5 votes vote down vote up
@GET
@Produces( {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getRoot() {
    final ResourceSupport links = new ResourceSupport();
    links.add(Link.fromResource(RootController.class).rel("self").baseUri(this.uriInfo.getBaseUri()).build());
    links.add(Link.fromResource(CsarController.class).rel("csars").baseUri(this.uriInfo.getBaseUri()).build());
    links.add(
        Link.fromResource(SituationsController.class).rel("situationsapi").baseUri(this.uriInfo.getBaseUri()).build());

    return Response.ok(links).build();
}
 
Example #17
Source File: JsonLinkTest.java    From rest-schemagen with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithoutSchemaValues() throws IOException {
	jsonLink = new JsonLink(Link.fromUri(uriString).build());

	assertThat(jsonLink.getSchema()).isNull();
	assertThat(jsonLink.getTargetSchema()).isNull();
}
 
Example #18
Source File: LinkBuilderImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidString() throws Exception {
    try {
        Link.Builder linkBuilder = Link.fromMethod(TestResource.class, "consumesAppJson");
        linkBuilder.link("</cxf>>");
        fail("IllegalArgumentException is expected");
    } catch (java.lang.IllegalArgumentException e) {
        // expected
    }
}
 
Example #19
Source File: ResourceSupport.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(final List<Link> links, final JsonGenerator json,
                      final SerializerProvider provider) throws IOException, JsonProcessingException {
    if (links.isEmpty()) {
        return;
    }
    final LinkSerializer delegate = new LinkSerializer();
    json.writeStartObject();
    for (final Link link : links) {
        delegate.serialize(link, json, provider);
    }
    json.writeEndObject();
}
 
Example #20
Source File: LinkFactoryTest.java    From rest-schemagen with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleListOfQueryParameter() {
    linkMetaFactory = LinkMetaFactory.create(new RestJsonSchemaGenerator(), linkFactoryContext);

    final LinkFactory<ResourceClass> linkFactory = linkMetaFactory.createFactoryFor(ResourceClass.class);
    final Optional<Link> linkOption = linkFactory.forCall(Relation.of("multi-param"), r -> r
            .multipleQueryParameters(Arrays.asList("foo", "bar", "baz")));

    assertThat(linkOption).isPresent();

    final Link link = linkOption.get();

    assertThat(link.getUri().getPath()).isEqualTo("basePath/resource");
    assertThat(link.getUri().getQuery()).isEqualTo("test=foo&test=bar&test=baz");
}
 
Example #21
Source File: AbstractWebDAVTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testPutPreviouslyDeleted() {
    when(mockResourceService.get(eq(childIdentifier))).thenAnswer(inv -> completedFuture(DELETED_RESOURCE));
    when(mockResource.getInteractionModel()).thenReturn(LDP.BasicContainer);
    final Response res = target(CHILD_PATH).request().put(entity("another text document.", TEXT_PLAIN_TYPE));

    assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
    assertTrue(getLinks(res).stream().map(l ->
                l.getUri().toString()).anyMatch(isEqual(LDP.NonRDFSource.getIRIString())));
    assertTrue(getLinks(res).stream().map(Link::getRel).anyMatch(isEqual("describedby")),
            "Unexpected describedby link!");
}
 
Example #22
Source File: BoundaryDefinitionController.java    From container with Apache License 2.0 5 votes vote down vote up
@GET
@Produces( {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@ApiOperation(hidden = true, value = "")
public Response getBoundaryDefinitions(@PathParam("csar") final String csarId,
                                       @PathParam("servicetemplate") final String servicetemplate) {
    logger.debug("Invoking getBoundaryDefinitions");

    final Csar csar = this.storage.findById(new CsarId(csarId));
    final TServiceTemplate serviceTemplate;
    try {
        serviceTemplate = ToscaEngine.resolveServiceTemplate(csar, servicetemplate);
    } catch (org.opentosca.container.core.common.NotFoundException e) {
        throw new NotFoundException(e);
    }

    final ResourceSupport links = new ResourceSupport();
    links.add(UriUtil.generateSubResourceLink(this.uriInfo, "properties", false, "properties"));
    links.add(UriUtil.generateSubResourceLink(this.uriInfo, "interfaces", false, "interfaces"));

    // TODO This resource seems to be unused and not implemented
    // links.add(Link.fromUri(UriUtils.encode(this.uriInfo.getAbsolutePathBuilder().path("propertyconstraints").build())).rel("propertyconstraints").build());
    // TODO This resource seems to be unused and not implemented
    // links.add(Link.fromUri(UriUtils.encode(this.uriInfo.getAbsolutePathBuilder().path("requirements").build())).rel("requirements").build());
    // TODO This resource seems to be unused and not implemented
    // links.add(Link.fromUri(UriUtils.encode(this.uriInfo.getAbsolutePathBuilder().path("capabilities").build())).rel("capabilities").build());
    // TODO: This resource seems to be unused and not implemented
    // links.add(Link.fromUri(UriUtils.encode(this.uriInfo.getAbsolutePathBuilder().path("policies").build())).rel("policies").build());
    links.add(Link.fromUri(UriUtil.encode(this.uriInfo.getAbsolutePath())).rel("self").build());

    return Response.ok(links).build();
}
 
Example #23
Source File: TestClass24.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #24
Source File: LinkCreatorTest.java    From rest-schemagen with Apache License 2.0 5 votes vote down vote up
@Test
public void testPOST() throws NoSuchMethodException, SecurityException {
    Link link = createFor(ResourceClass.class, ResourceClass.class.getMethod("postSomething",
            Something.class), Relation.of(Rel.SELF));

    assertEquals("http://host/base/resource/method", link.getUri().toString());
    assertEquals("POST", link.getParams().get("method"));
    assertEquals(testSchema, link.getParams().get("schema"));
    assertThat(link.getParams().get("testKey")).isEqualTo("testValue");
}
 
Example #25
Source File: Customers.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@XmlTransient
public URI getNext()
{
   if (links == null) return null;
   for (Link link : links)
   {
      if ("next".equals(link.getRel())) return link.getUri();
   }
   return null;
}
 
Example #26
Source File: ResponseImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getsLinks() throws Exception {
    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    Link link = new LinkBuilderImpl().uri("http://localhost:8080/x/y/z").rel("xxx").build();
    headers.put(LINK, newArrayList(link));
    ResponseImpl response = new ResponseImpl(200, "foo", null, headers);

    assertEquals(newHashSet(link), response.getLinks());
}
 
Example #27
Source File: RibbonJerseyClient.java    From dropwizard-consul with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws IllegalStateException if there are no available servers
 */
@Override
public WebTarget target(Link link) {
  final Server server = fetchServerOrThrow();
  final UriBuilder builder = UriBuilder.fromLink(link);
  builder.scheme(server.getScheme());
  builder.host(server.getHost());
  builder.port(server.getPort());
  return delegate.target(builder);
}
 
Example #28
Source File: LinkBuilderImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void buildsLinkFromStringWithEmptyUri() {
    String uri = "<>";
    Link link = linkBuilder.link(uri).build();

    assertEquals(URI.create(""), link.getUri());
    assertNull(link.getRel());
    assertNull(link.getTitle());
    assertNull(link.getType());
    assertTrue(link.getRels().isEmpty());
    assertTrue(link.getParams().isEmpty());
}
 
Example #29
Source File: LinkBuilderImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void buildsLinkBuilderFromExistedLink() {
    Link link = mock(Link.class);
    URI uri = URI.create("http://localhost:8080/x/y/z");
    when(link.getUri()).thenReturn(uri);
    Map<String, String> params = ImmutableMap.of("rel", "xxx", "title", "yyy");
    when(link.getParams()).thenReturn(params);

    Link newLink = linkBuilder.link(link).build();

    assertEquals(uri, newLink.getUri());
    assertEquals(params, newLink.getParams());
}
 
Example #30
Source File: MementoResource.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Create a response builder for a TimeGate response.
 *
 * @param mementos the list of memento ranges
 * @param req the LDP request
 * @param baseUrl the base URL
 * @return a response builder object
 */
public ResponseBuilder getTimeGateBuilder(final SortedSet<Instant> mementos, final TrellisRequest req,
        final String baseUrl) {
    final String identifier = HttpUtils.buildResourceUrl(req, baseUrl);
    return status(FOUND)
        .location(fromUri(identifier + VERSION_PARAM + req.getDatetime().getInstant().getEpochSecond()).build())
        .link(identifier, ORIGINAL + " " + TIMEGATE)
        .links(getMementoHeaders(identifier, mementos).map(this::filterLinkParams).toArray(Link[]::new));
}