Search in sources :

Example 21 with RDFFormat

use of org.eclipse.rdf4j.rio.RDFFormat in project inception by inception-project.

the class TestFixtures method importData.

@SuppressWarnings("resource")
private static void importData(Repository aRepo, String aBasePrefix, String aUrl) throws IOException {
    try (InputStream aIS = openAsStream(aUrl)) {
        InputStream is = new BufferedInputStream(aIS);
        try {
            // Stream is expected to be closed by caller of importData
            is = new CompressorStreamFactory().createCompressorInputStream(is);
        } catch (CompressorException e) {
        // Probably not compressed then or unknown format - just try as is.
        }
        // Detect the file format
        RDFFormat format = Rio.getParserFormatForFileName(aUrl).orElse(RDFFormat.RDFXML);
        try (RepositoryConnection conn = aRepo.getConnection()) {
            // If the RDF file contains relative URLs, then they probably start with a hash.
            // To avoid having two hashes here, we drop the hash from the base prefix configured
            // by the user.
            String prefix = StringUtils.removeEnd(aBasePrefix, "#");
            conn.add(is, prefix, format);
        }
    }
}
Also used : RepositoryConnection(org.eclipse.rdf4j.repository.RepositoryConnection) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) CompressorException(org.apache.commons.compress.compressors.CompressorException) CompressorStreamFactory(org.apache.commons.compress.compressors.CompressorStreamFactory) RDFFormat(org.eclipse.rdf4j.rio.RDFFormat)

Example 22 with RDFFormat

use of org.eclipse.rdf4j.rio.RDFFormat in project ldp-coap-framework by sisinflab-swot.

the class CoAPLDPDirectContainer method postResource.

private void postResource(CoapExchange exchange, boolean putToCreate) {
    Request req = exchange.advanced().getCurrentRequest();
    HashMap<String, String> atts = serializeAttributes(req.getOptions().getUriQuery());
    String title = atts.get(LinkFormat.TITLE);
    if (title == null) {
        title = getAnonymousResource();
    }
    int ct = exchange.getRequestOptions().getContentFormat();
    if ((ct != -1) && (title != null)) {
        String body = exchange.getRequestText();
        try {
            String childName = resource.getURI() + "/" + title;
            if (mng.isDeleted(childName)) {
                if (!putToCreate) {
                    title = getAnonymousResource();
                    childName = resource.getURI() + "/" + title;
                } else {
                    throw new CoAPLDPException("LDP Resource previously deleted!");
                }
            }
            if (!existChild(childName)) {
                if (ct == MediaTypeRegistry.TEXT_TURTLE || ct == MediaTypeRegistry.APPLICATION_LD_JSON) {
                    RDFFormat f;
                    if (ct == MediaTypeRegistry.TEXT_TURTLE)
                        f = RDFFormat.TURTLE;
                    else
                        f = RDFFormat.JSONLD;
                    mng.postRDFSource(mng.getBaseURI() + childName, body, f);
                    String rt = atts.get(LinkFormat.RESOURCE_TYPE);
                    if ((rt == null) || (rt.equals(LDP.LINK_LDP + ":" + LDP.CLASS_LNAME_RESOURCE))) {
                        /**
                         * Add LDP-RDFSource **
                         */
                        CoAPLDPRDFSource s = new CoAPLDPRDFSource(title, resource.getURI(), mng);
                        this.addRDFResource(s);
                    } else if (rt.equals(LDP.LINK_LDP + ":" + LDP.CLASS_LNAME_BASIC_CONTAINER)) {
                        /**
                         * Add LDP-BasicContainer **
                         */
                        CoAPLDPBasicContainer bc = new CoAPLDPBasicContainer(title, mng);
                        bc.setRDFCreated();
                        this.addRDFResource(bc);
                    } else if (rt.equals(LDP.LINK_LDP + ":" + LDP.CLASS_LNAME_DIRECT_CONTAINER)) {
                        String memberRel = mng.getMemberRelation(body, f);
                        String isMemberOfRel = mng.getIsMemberOfRelation(body, f);
                        String resName = mng.getMemberResource(body, f);
                        if (resName.equals(mng.getBaseURI())) {
                            mng.deleteMemberResourceStatement(childName);
                            resName = "resource";
                        }
                        /**
                         * Add LDP-DirectContainer **
                         */
                        CoAPLDPRDFSource memberRes = new CoAPLDPRDFSource(resName, childName, mng);
                        CoAPLDPDirectContainer dc = new CoAPLDPDirectContainer(title, resource.getFullName(), mng, memberRes, memberRel, isMemberOfRel);
                        dc.setRDFCreated();
                        this.addRDFResource(dc);
                    } else
                        throw new CoAPLDPException("Invalid RT query parameter.");
                } else if (options.getAcceptedPostTypes().contains(ct)) {
                    /**
                     * Add LDP-NonRDFSource **
                     */
                    CoAPLDPNonRDFSource nRDF = new CoAPLDPNonRDFSource(title, mng, ct);
                    nRDF.setData(exchange.getRequestPayload());
                    this.addRDFResource(nRDF);
                } else
                    throw new CoAPLDPContentFormatException("Content-Format (CT) Not Accepted.");
                exchange.setLocationPath(mng.getBaseURI() + childName);
                exchange.setLocationQuery(LinkFormat.RESOURCE_TYPE + "=" + LDP.LINK_LDP + ":" + LDP.CLASS_LNAME_RESOURCE);
                exchange.respond(ResponseCode.CREATED);
            } else
                exchange.respond(ResponseCode.FORBIDDEN);
        } catch (CoAPLDPContentFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            exchange.respond(ResponseCode.UNSUPPORTED_CONTENT_FORMAT);
        } catch (RDFParseException | CoAPLDPException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            exchange.respond(ResponseCode.BAD_REQUEST);
        } catch (RepositoryException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            exchange.respond(ResponseCode.INTERNAL_SERVER_ERROR);
        }
    } else {
        exchange.respond(ResponseCode.BAD_REQUEST);
    }
}
Also used : Request(org.eclipse.californium.core.coap.Request) CoAPLDPContentFormatException(it.poliba.sisinflab.coap.ldp.exception.CoAPLDPContentFormatException) RepositoryException(org.eclipse.rdf4j.repository.RepositoryException) IOException(java.io.IOException) CoAPLDPException(it.poliba.sisinflab.coap.ldp.exception.CoAPLDPException) RDFFormat(org.eclipse.rdf4j.rio.RDFFormat) RDFParseException(org.eclipse.rdf4j.rio.RDFParseException)

Example 23 with RDFFormat

use of org.eclipse.rdf4j.rio.RDFFormat in project FAIRDataPoint by FAIRDataTeam.

the class GenericController method storeMetaData.

@Operation(hidden = true)
@PostMapping(path = "{urlPrefix:[^.]+}", produces = { "!application/json" })
public ResponseEntity<Model> storeMetaData(@PathVariable final String urlPrefix, @RequestBody String reqBody, @RequestHeader(value = "Content-Type", required = false) String contentType) throws MetadataServiceException {
    // 1. Check if user is authenticated
    // - it can't be in SecurityConfig because the authentication is done based on content-type
    Optional<User> oUser = currentUserService.getCurrentUser();
    if (oUser.isEmpty()) {
        throw new ForbiddenException("You have to be login at first");
    }
    // 2. Init
    // String urlPrefix = getResourceNameForList(getRequestURL(request, persistentUrl));
    MetadataService metadataService = metadataServiceFactory.getMetadataServiceByUrlPrefix(urlPrefix);
    ResourceDefinition rd = resourceDefinitionService.getByUrlPrefix(urlPrefix);
    // 3. Generate URI
    IRI uri = generateNewMetadataIRI(persistentUrl, urlPrefix);
    // 4. Parse reqDto
    RDFFormat rdfContentType = getRdfContentType(contentType);
    Model oldDto = read(reqBody, uri.stringValue(), rdfContentType);
    Model reqDto = changeBaseUri(oldDto, uri.stringValue(), resourceDefinitionService.getTargetClassUris(rd));
    for (ResourceDefinitionChild rdChild : rd.getChildren()) {
        reqDto.remove(null, i(rdChild.getRelationUri()), null);
    }
    // 5. Store metadata
    Model metadata = metadataService.store(reqDto, uri, rd);
    // 6. Create response
    return ResponseEntity.created(URI.create(uri.stringValue())).body(metadata);
}
Also used : IRI(org.eclipse.rdf4j.model.IRI) ForbiddenException(nl.dtls.fairdatapoint.entity.exception.ForbiddenException) User(nl.dtls.fairdatapoint.entity.user.User) ResourceDefinition(nl.dtls.fairdatapoint.entity.resource.ResourceDefinition) Model(org.eclipse.rdf4j.model.Model) LinkedHashModel(org.eclipse.rdf4j.model.impl.LinkedHashModel) ResourceDefinitionChild(nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionChild) MetadataService(nl.dtls.fairdatapoint.service.metadata.common.MetadataService) RDFFormat(org.eclipse.rdf4j.rio.RDFFormat) Operation(io.swagger.v3.oas.annotations.Operation)

Example 24 with RDFFormat

use of org.eclipse.rdf4j.rio.RDFFormat in project d3web-KnowWE by denkbares.

the class OntologyDownloadAction method execute.

@Override
public void execute(UserActionContext context) throws IOException {
    OntologyCompiler compiler = getCompiler(context);
    if (compiler == null) {
        context.sendError(HttpServletResponse.SC_NOT_FOUND, "No compiler found");
        return;
    }
    if (!KnowWEUtils.canView(compiler.getCompileSection().getArticle(), context)) {
        context.sendError(HttpServletResponse.SC_FORBIDDEN, "You are not allowed to download this knowledge base");
        return;
    }
    Compilers.awaitTermination(context.getArticleManager().getCompilerManager());
    if (Boolean.parseBoolean(context.getParameter(PARAM_FULL_COMPILE, "false"))) {
        if (compiler.isIncrementalBuild()) {
            RecompileAction.recompile(compiler.getCompileSection().getArticle(), true);
            Compilers.awaitTermination(context.getArticleManager().getCompilerManager());
            compiler = getCompiler(context);
            if (compiler == null)
                failUnexpected(context, "Compile no longer available after recompile");
        }
    }
    Rdf2GoCore rdf2GoCore = compiler.getRdf2GoCore();
    RDFFormat syntax = Rio.getParserFormatForMIMEType(context.getParameter(PARAM_SYNTAX)).orElse(RDFFormat.RDFXML);
    String mimeType = syntax.getDefaultMIMEType() + "; charset=UTF-8";
    String filename = context.getParameter(PARAM_FILENAME);
    if (filename == null) {
        filename = Compilers.getCompilerName(compiler) + "." + syntax.getFileExtensions().stream().findFirst().orElse("ontology");
    }
    context.setContentType(mimeType);
    context.getResponse().addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    context.getResponse().addHeader("Last-Modified", org.apache.http.client.utils.DateUtils.formatDate(compiler.getLastModified()));
    Stopwatch stopwatch = new Stopwatch();
    try (OutputStream outputStream = context.getOutputStream()) {
        if (syntax == RDFFormat.TURTLE) {
            // pretty formatted turtle doesn't always work, we try first and do fallback in case it does not work
            // since we can't fallback if we write to the response directly, we have to write to a temp file first
            final File tempFile = Files.createTempFile(rdf2GoCore.getName(), filename).toFile();
            tempFile.deleteOnExit();
            try {
                try (FileOutputStream out = new FileOutputStream(tempFile)) {
                    rdf2GoCore.writeModel(out, syntax);
                }
                try (FileInputStream inputStream = new FileInputStream(tempFile)) {
                    Streams.stream(inputStream, outputStream);
                }
            } catch (Exception e) {
                LOGGER.warn("Formatted turtle export failed, very likely due to setting inline_blank_nodes, trying again without...");
                // formatted writing didn't work, just write to response directly, we don't expect failure
                rdf2GoCore.writeModel(Rio.createWriter(syntax, outputStream));
            } finally {
                tempFile.delete();
            }
        } else {
            rdf2GoCore.writeModel(outputStream, syntax);
        }
    }
    stopwatch.log("Exported " + filename);
}
Also used : Rdf2GoCore(de.knowwe.rdf2go.Rdf2GoCore) OntologyCompiler(de.knowwe.ontology.compile.OntologyCompiler) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) Stopwatch(com.denkbares.utils.Stopwatch) File(java.io.File) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) RDFFormat(org.eclipse.rdf4j.rio.RDFFormat)

Example 25 with RDFFormat

use of org.eclipse.rdf4j.rio.RDFFormat in project AJAN-service by aantakli.

the class RDFConsumer method readFrom.

@Override
public Model readFrom(final Class<Model> t, final Type type, final Annotation[] annts, final MediaType mt, final MultivaluedMap<String, String> mm, final InputStream in) throws IOException, WebApplicationException {
    RDFParserRegistry registry = RDFParserRegistry.getInstance();
    Optional<RDFFormat> format = registry.getFileFormatForMIMEType(mt.toString());
    if (!format.isPresent()) {
        String msg = "Can not consume RDF of mimetype + " + mt.toString();
        Response response = Response.status(Response.Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(msg).build();
        throw new WebApplicationException(response);
    }
    Model input = Rio.parse(in, TURTLE_BASE_URI, format.get());
    return AgentUtil.setMessageInformation(input, mm);
}
Also used : Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException) Model(org.eclipse.rdf4j.model.Model) RDFParserRegistry(org.eclipse.rdf4j.rio.RDFParserRegistry) RDFFormat(org.eclipse.rdf4j.rio.RDFFormat)

Aggregations

RDFFormat (org.eclipse.rdf4j.rio.RDFFormat)62 ByteArrayOutputStream (java.io.ByteArrayOutputStream)17 IOException (java.io.IOException)17 WriteRdf4j (mom.trd.opentheso.core.exports.rdf4j.WriteRdf4j)14 InputStream (java.io.InputStream)12 RDFParseException (org.eclipse.rdf4j.rio.RDFParseException)11 RepositoryException (org.eclipse.rdf4j.repository.RepositoryException)8 FileInputStream (java.io.FileInputStream)7 Model (org.eclipse.rdf4j.model.Model)6 RDFHandlerException (org.eclipse.rdf4j.rio.RDFHandlerException)6 RDFParser (org.eclipse.rdf4j.rio.RDFParser)5 UnsupportedRDFormatException (org.eclipse.rdf4j.rio.UnsupportedRDFormatException)5 Rdf2GoCore (de.knowwe.rdf2go.Rdf2GoCore)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 File (java.io.File)4 NodePreference (mom.trd.opentheso.bdd.helper.nodes.NodePreference)4 ExportRdf4jHelper (mom.trd.opentheso.core.exports.rdf4j.ExportRdf4jHelper)4 IRI (org.eclipse.rdf4j.model.IRI)4 Statement (org.eclipse.rdf4j.model.Statement)4 Test (org.junit.Test)4