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);
}
}
}
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);
}
}
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);
}
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);
}
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);
}
Aggregations