Example usage for org.apache.commons.rdf.api IRI getIRIString

List of usage examples for org.apache.commons.rdf.api IRI getIRIString

Introduction

In this page you can find the example usage for org.apache.commons.rdf.api IRI getIRIString.

Prototype

String getIRIString();

Source Link

Document

Return the IRI encoded as a native Unicode String.
The returned string must not include URL-encoding to escape non-ASCII characters.

Usage

From source file:org.trellisldp.http.HttpResolver.java

@Override
public Optional<InputStream> getContent(final String partition, final IRI identifier) {
    requireNonNull(identifier, NON_NULL_IDENTIFIER);
    final Response res = httpClient.target(identifier.getIRIString()).request().get();
    LOGGER.info("HTTP GET request to {} returned status {}", identifier, res.getStatus());
    if (res.hasEntity()) {
        return of(res.getEntity()).map(x -> (InputStream) x);
    }/*w  w w.  j  a v  a 2  s .  c  om*/
    return empty();
}

From source file:org.trellisldp.http.HttpResolver.java

@Override
public void setContent(final String partition, final IRI identifier, final InputStream stream,
        final Map<String, String> metadata) {
    requireNonNull(identifier, NON_NULL_IDENTIFIER);
    final Response res = httpClient.target(identifier.getIRIString()).request()
            .put(entity(stream, ofNullable(metadata.get(CONTENT_TYPE)).map(MediaType::valueOf)
                    .orElse(APPLICATION_OCTET_STREAM_TYPE)));
    LOGGER.info("HTTP PUT request to {} returned {}", identifier, res.getStatusInfo());
    final Boolean ok = res.getStatusInfo().getFamily().equals(SUCCESSFUL);
    res.close();//from w  w w . ja v  a2s  .  c  o  m
    if (!ok) {
        throw new RuntimeRepositoryException(
                "HTTP PUT request to " + identifier + " failed with a " + res.getStatusInfo());
    }
}

From source file:org.trellisldp.http.HttpResolver.java

@Override
public void purgeContent(final String partition, final IRI identifier) {
    requireNonNull(identifier, NON_NULL_IDENTIFIER);
    final Response res = httpClient.target(identifier.getIRIString()).request().delete();
    LOGGER.info("HTTP DELETE request to {} returned {}", identifier, res.getStatusInfo());
    final Boolean ok = res.getStatusInfo().getFamily().equals(SUCCESSFUL);
    res.close();/*from   w  w  w.  j  av a  2 s .  c  o m*/
    if (!ok) {
        throw new RuntimeRepositoryException(
                "HTTP DELETE request to " + identifier + " failed with a " + res.getStatusInfo());

    }
}

From source file:org.trellisldp.http.impl.GetHandlerTest.java

private static Predicate<Link> hasLink(final IRI iri, final String rel) {
    return link -> rel.equals(link.getRel()) && iri.getIRIString().equals(link.getUri().toString());
}

From source file:org.trellisldp.http.impl.HttpUtils.java

/**
 * Get all of the LDP resource (super) types for the given LDP interaction model.
 *
 * @param ixnModel the interaction model
 * @return a stream of types/*from www .  jav  a  2 s  . c o m*/
 */
public static Stream<IRI> ldpResourceTypes(final IRI ixnModel) {
    final Stream.Builder<IRI> supertypes = Stream.builder();
    if (nonNull(ixnModel)) {
        LOGGER.debug("Finding types that subsume {}", ixnModel.getIRIString());
        supertypes.accept(ixnModel);
        final IRI superClass = LDP.getSuperclassOf(ixnModel);
        LOGGER.debug("... including {}", superClass);
        ldpResourceTypes(superClass).forEach(supertypes::accept);
    }
    return supertypes.build();
}

From source file:org.trellisldp.http.impl.PostHandler.java

/**
 * Create a new resource/*from   w ww.  j av  a  2 s . co  m*/
 * @return the response builder
 */
public ResponseBuilder createResource() {
    final String baseUrl = getBaseUrl();
    final String identifier = baseUrl + req.getPartition() + req.getPath() + id;
    final String contentType = req.getContentType();
    final Session session = ofNullable(req.getSession()).orElseGet(HttpSession::new);

    LOGGER.info("Creating resource as {}", identifier);

    final Optional<RDFSyntax> rdfSyntax = ofNullable(contentType).flatMap(RDFSyntax::byMediaType)
            .filter(SUPPORTED_RDF_TYPES::contains);

    final IRI defaultType = nonNull(contentType) && !rdfSyntax.isPresent() ? LDP.NonRDFSource : LDP.RDFSource;
    final IRI internalId = rdf.createIRI(TRELLIS_PREFIX + req.getPartition() + req.getPath() + id);

    // Add LDP type (ldp:Resource results in the defaultType)
    final IRI ldpType = ofNullable(req.getLink()).filter(l -> "type".equals(l.getRel())).map(Link::getUri)
            .map(URI::toString).filter(l -> l.startsWith(LDP.URI)).map(rdf::createIRI)
            .filter(l -> !LDP.Resource.equals(l)).orElse(defaultType);

    if (ldpType.equals(LDP.NonRDFSource) && rdfSyntax.isPresent()) {
        return status(BAD_REQUEST).type(TEXT_PLAIN).entity("Cannot save a NonRDFSource with RDF syntax");
    }

    try (final TrellisDataset dataset = TrellisDataset.createDataset()) {

        // Add Audit quads
        audit.ifPresent(svc -> svc.creation(internalId, session).stream()
                .map(skolemizeQuads(resourceService, baseUrl)).forEachOrdered(dataset::add));

        dataset.add(rdf.createQuad(PreferServerManaged, internalId, RDF.type, ldpType));

        // Add user-supplied data
        if (ldpType.equals(LDP.NonRDFSource)) {
            // Check the expected digest value
            final Digest digest = req.getDigest();
            if (nonNull(digest) && !getDigestForEntity(digest).equals(digest.getDigest())) {
                return status(BAD_REQUEST);
            }

            final Map<String, String> metadata = singletonMap(CONTENT_TYPE,
                    ofNullable(contentType).orElse(APPLICATION_OCTET_STREAM));
            final IRI binaryLocation = rdf
                    .createIRI(binaryService.getIdentifierSupplier(req.getPartition()).get());
            dataset.add(rdf.createQuad(PreferServerManaged, internalId, DC.hasPart, binaryLocation));
            dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.modified,
                    rdf.createLiteral(now().toString(), XSD.dateTime)));
            dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.format,
                    rdf.createLiteral(ofNullable(contentType).orElse(APPLICATION_OCTET_STREAM))));
            dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.extent,
                    rdf.createLiteral(Long.toString(entity.length()), XSD.long_)));

            // Persist the content
            persistContent(binaryLocation, metadata);
        } else {
            readEntityIntoDataset(identifier, baseUrl, PreferUserManaged, rdfSyntax.orElse(TURTLE), dataset);

            // Check for any constraints
            checkConstraint(dataset, PreferUserManaged, ldpType, TRELLIS_PREFIX + req.getPartition(),
                    rdfSyntax.orElse(TURTLE));
        }

        if (resourceService.put(internalId, dataset.asDataset())) {
            final ResponseBuilder builder = status(CREATED).location(create(identifier));

            // Add LDP types
            ldpResourceTypes(ldpType).map(IRI::getIRIString).forEach(type -> builder.link(type, "type"));

            return builder;
        }
    }

    LOGGER.error("Unable to persist data to location at {}", internalId.getIRIString());
    return serverError().type(TEXT_PLAIN)
            .entity("Unable to persist data. Please consult the logs for more information");
}

From source file:org.trellisldp.http.impl.PutHandler.java

/**
 * Set the data for a resource//w  w w. jav  a2s  . c  o  m
 * @param res the resource
 * @return the response builder
 */
public ResponseBuilder setResource(final Resource res) {
    final String baseUrl = getBaseUrl();
    final String identifier = baseUrl + req.getPartition() + req.getPath()
            + (ACL.equals(req.getExt()) ? "?ext=acl" : "");

    // Check the cache
    ofNullable(res).ifPresent(r -> checkResourceCache(identifier, r));

    final Session session = ofNullable(req.getSession()).orElseGet(HttpSession::new);
    final Optional<RDFSyntax> rdfSyntax = ofNullable(req.getContentType()).flatMap(RDFSyntax::byMediaType)
            .filter(SUPPORTED_RDF_TYPES::contains);

    // One cannot put binaries into the ACL graph
    if (isAclAndNonRdfContent(rdfSyntax)) {
        return status(NOT_ACCEPTABLE);
    }

    LOGGER.info("Setting resource as {}", identifier);

    final IRI heuristicType = nonNull(req.getContentType()) && !rdfSyntax.isPresent() ? LDP.NonRDFSource
            : LDP.RDFSource;

    final IRI defaultType = ofNullable(res).map(Resource::getInteractionModel).orElse(heuristicType);

    final IRI ldpType = ofNullable(req.getLink()).filter(l -> "type".equals(l.getRel())).map(Link::getUri)
            .map(URI::toString).filter(l -> l.startsWith(LDP.URI)).map(rdf::createIRI)
            .filter(l -> !LDP.Resource.equals(l)).orElse(defaultType);

    // It is not possible to change the LDP type to a type that is not a subclass
    if (nonNull(res) && !ldpResourceTypes(ldpType).anyMatch(res.getInteractionModel()::equals)) {
        return status(CONFLICT).entity("Cannot change the LDP type to " + ldpType).type(TEXT_PLAIN);
    }

    final IRI internalId = rdf.createIRI(TRELLIS_PREFIX + req.getPartition() + req.getPath());

    try (final TrellisDataset dataset = TrellisDataset.createDataset()) {
        final IRI graphName = getActiveGraphName();
        final IRI otherGraph = getInactiveGraphName();

        // Add audit quads
        audit.map(addAuditQuads(res, internalId, session)).ifPresent(
                q -> q.stream().map(skolemizeQuads(resourceService, baseUrl)).forEachOrdered(dataset::add));

        // Add LDP type
        dataset.add(rdf.createQuad(PreferServerManaged, internalId, RDF.type, ldpType));

        // Add user-supplied data
        if (rdfSyntax.isPresent()) {
            readEntityIntoDataset(identifier, baseUrl, graphName, rdfSyntax.get(), dataset);

            // Check for any constraints
            checkConstraint(dataset, PreferUserManaged, ldpType, baseUrl, rdfSyntax.get());

        } else {
            // Check the expected digest value
            final Digest digest = req.getDigest();
            if (nonNull(digest) && !getDigestForEntity(digest).equals(digest.getDigest())) {
                return status(BAD_REQUEST);
            }

            final Map<String, String> metadata = singletonMap(CONTENT_TYPE,
                    ofNullable(req.getContentType()).orElse(APPLICATION_OCTET_STREAM));
            final IRI binaryLocation = rdf
                    .createIRI(binaryService.getIdentifierSupplier(req.getPartition()).get());

            // Persist the content
            persistContent(binaryLocation, metadata);

            dataset.add(rdf.createQuad(PreferServerManaged, internalId, DC.hasPart, binaryLocation));
            dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.modified,
                    rdf.createLiteral(now().toString(), XSD.dateTime)));
            dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.format,
                    rdf.createLiteral(ofNullable(req.getContentType()).orElse(APPLICATION_OCTET_STREAM))));
            dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.extent,
                    rdf.createLiteral(Long.toString(entity.length()), XSD.long_)));
        }

        if (nonNull(res)) {
            try (final Stream<? extends Triple> remaining = res.stream(otherGraph)) {
                remaining.map(t -> rdf.createQuad(otherGraph, t.getSubject(), t.getPredicate(), t.getObject()))
                        .forEachOrdered(dataset::add);
            }
        }

        if (resourceService.put(internalId, dataset.asDataset())) {
            final ResponseBuilder builder = status(NO_CONTENT);

            ldpResourceTypes(ldpType).map(IRI::getIRIString).forEach(type -> builder.link(type, "type"));
            return builder;
        }
    }

    LOGGER.error("Unable to persist data to location at {}", internalId.getIRIString());
    return serverError().type(TEXT_PLAIN)
            .entity("Unable to persist data. Please consult the logs for more information");
}

From source file:org.trellisldp.http.PartitionedRootResource.java

/**
 * Get a representation of the root resource
 * @param uriInfo information about the URI
 * @param headers the request headers/* w  ww.  j a v a 2s .c o  m*/
 * @return the root resource
 */
@GET
@Timed
public Response getPartitions(@Context final UriInfo uriInfo, @Context final HttpHeaders headers) {

    final IRI identifier = rdf.createIRI(properties.getProperty("baseUrl", uriInfo.getBaseUri().toString()));

    LOGGER.debug("Request for root resource at: {}", identifier.getIRIString());

    final List<Triple> graph = new ArrayList<>();
    partitions.entrySet().stream().map(e -> rdf.createIRI(e.getValue() + e.getKey()))
            .map(obj -> rdf.createTriple(identifier, LDP.contains, obj)).forEach(graph::add);

    properties.stringPropertyNames().stream().filter(propMapping::containsKey)
            .map(name -> rdf.createTriple(identifier, propMapping.get(name),
                    isUrl(properties.getProperty(name)) ? rdf.createIRI(properties.getProperty(name))
                            : rdf.createLiteral(properties.getProperty(name))))
            .forEach(graph::add);

    final RDFSyntax syntax = getSyntax(headers.getAcceptableMediaTypes(), empty())
            .orElseThrow(NotAcceptableException::new);

    final IRI profile = ofNullable(getProfile(headers.getAcceptableMediaTypes(), syntax))
            .orElseGet(() -> getDefaultProfile(syntax, identifier));

    final StreamingOutput stream = new StreamingOutput() {
        @Override
        public void write(final OutputStream out) throws IOException {
            ioService.write(graph.stream(), out, syntax, profile);
        }
    };

    return ok().header(ALLOW, join(",", HttpMethod.GET, HEAD, OPTIONS))
            .link(LDP.Resource.getIRIString(), "type").link(LDP.RDFSource.getIRIString(), "type")
            .type(syntax.mediaType).entity(stream).build();
}

From source file:org.trellisldp.io.JenaIOService.java

private String getCustomJsonLdProfile(final IRI... profiles) {
    for (final IRI p : profiles) {
        final String profile = p.getIRIString();
        if (!profile.startsWith(getNamespace())) {
            if (whitelist.contains(profile)) {
                return profile;
            }/*from   w  w w  .  j  ava 2s.  co m*/
            for (final String domain : whitelistDomains) {
                if (profile.startsWith(domain)) {
                    return profile;
                }
            }
        }
    }
    return null;
}

From source file:org.trellisldp.rosid.file.CachedResource.java

/**
 * Create a File-based resource reader//  w  ww  .j  a v a2 s .com
 * @param directory the data storage directory
 * @param identifier the resource to retrieve
 * @param data the resource data
 */
protected CachedResource(final File directory, final IRI identifier, final ResourceData data) {
    super(directory, identifier, data);
    LOGGER.debug("Fetching a Cached Resource for {}", identifier.getIRIString());
}