Search in sources :

Example 11 with Entity

use of nl.knaw.huygens.timbuctoo.v5.serializable.dto.Entity in project timbuctoo by HuygensING.

the class DataSetMetadataMutation method get.

@Override
public Object get(DataFetchingEnvironment env) {
    DataSet dataSet = MutationHelpers.getDataSet(env, dataSetRepository::getDataSet);
    MutationHelpers.checkAdminPermissions(env, dataSet.getMetadata());
    try {
        Map md = env.getArgument("metadata");
        final String baseUri = dataSet.getMetadata().getBaseUri().endsWith("/") ? dataSet.getMetadata().getBaseUri() : dataSet.getMetadata().getBaseUri() + "/";
        addMutation(dataSet, new PredicateMutation().entity(baseUri, this.<String>parseProp(md, "title", v -> replace("http://purl.org/dc/terms/title", value(v))), this.<String>parseProp(md, "description", v -> replace("http://purl.org/dc/terms/description", value(v, MARKDOWN))), this.<String>parseProp(md, "imageUrl", v -> replace("http://xmlns.com/foaf/0.1/depiction", value(v))), this.<String>parseProp(md, "license", v -> replace("http://purl.org/dc/terms/license", subject(v))), this.<Map>parseProp(md, "owner", owner -> getOrCreate("http://purl.org/dc/terms/rightsHolder", baseUri + "rightsHolder", this.<String>parseProp(owner, "name", v -> replace("http://schema.org/name", value(v))), this.<String>parseProp(owner, "email", v -> replace("http://schema.org/email", value(v))))), this.<Map>parseProp(md, "contact", owner -> getOrCreate("http://schema.org/ContactPoint", baseUri + "ContactPoint", this.<String>parseProp(owner, "name", v -> replace("http://schema.org/name", value(v))), this.<String>parseProp(owner, "email", v -> replace("http://schema.org/email", value(v))))), this.<Map>parseProp(md, "provenanceInfo", owner -> getOrCreate("http://purl.org/dc/terms/provenance", baseUri + "Provenance", this.<String>parseProp(owner, "title", v -> replace("http://purl.org/dc/terms/title", value(v))), this.<String>parseProp(owner, "body", v -> replace("http://purl.org/dc/terms/description", value(v, MARKDOWN)))))));
        return new DataSetWithDatabase(dataSet);
    } catch (LogStorageFailedException | InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
}
Also used : PredicateMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.dto.PredicateMutation) DataSetWithDatabase(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.DataSetWithDatabase) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) LogStorageFailedException(nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.LogStorageFailedException) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map)

Example 12 with Entity

use of nl.knaw.huygens.timbuctoo.v5.serializable.dto.Entity in project timbuctoo by HuygensING.

the class IndexConfigMutation method get.

@Override
public Object get(DataFetchingEnvironment env) {
    String collectionUri = env.getArgument("collectionUri");
    Object indexConfig = env.getArgument("indexConfig");
    DataSet dataSet = MutationHelpers.getDataSet(env, dataSetRepository::getDataSet);
    MutationHelpers.checkAdminPermissions(env, dataSet.getMetadata());
    try {
        MutationHelpers.addMutation(dataSet, new PredicateMutation().entity(collectionUri, replace(TIM_HASINDEXERCONFIG, value(OBJECT_MAPPER.writeValueAsString(indexConfig)))));
        return indexConfig;
    } catch (LogStorageFailedException | InterruptedException | ExecutionException | JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
Also used : PredicateMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.dto.PredicateMutation) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) LogStorageFailedException(nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.LogStorageFailedException) ExecutionException(java.util.concurrent.ExecutionException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 13 with Entity

use of nl.knaw.huygens.timbuctoo.v5.serializable.dto.Entity in project timbuctoo by HuygensING.

the class JsonLdEditEndpoint method submitChanges.

@PUT
public Response submitChanges(String jsonLdImport, @PathParam("user") String ownerId, @PathParam("dataset") String dataSetId, @HeaderParam("authorization") String authHeader) throws LogStorageFailedException {
    Optional<User> user;
    try {
        user = userValidator.getUserFromAccessToken(authHeader);
    } catch (UserValidationException e) {
        user = Optional.empty();
    }
    Optional<DataSet> dataSetOpt = dataSetRepository.getDataSet(user.get(), ownerId, dataSetId);
    if (!dataSetOpt.isPresent()) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    final DataSet dataSet = dataSetOpt.get();
    final QuadStore quadStore = dataSet.getQuadStore();
    final ImportManager importManager = dataSet.getImportManager();
    final Response response = checkWriteAccess(dataSet, user, permissionFetcher);
    if (response != null) {
        return response;
    }
    try {
        final Future<ImportStatus> promise = importManager.generateLog(dataSet.getMetadata().getBaseUri(), dataSet.getMetadata().getBaseUri(), fromCurrentState(documentLoader, jsonLdImport, quadStore, TIM_USERS + user.get().getPersistentId(), UUID.randomUUID().toString(), Clock.systemUTC()));
        return handleImportManagerResult(promise);
    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
    } catch (ConcurrentUpdateException e) {
        return Response.status(Response.Status.CONFLICT).entity(e.getMessage()).build();
    }
}
Also used : Response(javax.ws.rs.core.Response) UserValidationException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException) ImportManager(nl.knaw.huygens.timbuctoo.v5.dataset.ImportManager) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) QuadStore(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) ImportStatus(nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus) IOException(java.io.IOException) ConcurrentUpdateException(nl.knaw.huygens.timbuctoo.v5.jsonldimport.ConcurrentUpdateException) PUT(javax.ws.rs.PUT)

Example 14 with Entity

use of nl.knaw.huygens.timbuctoo.v5.serializable.dto.Entity in project timbuctoo by HuygensING.

the class RdfUpload method upload.

@Consumes(MediaType.MULTIPART_FORM_DATA)
@POST
public Response upload(@FormDataParam("file") final InputStream rdfInputStream, @FormDataParam("file") final FormDataBodyPart body, @FormDataParam("fileMimeTypeOverride") final MediaType mimeTypeOverride, @FormDataParam("encoding") final String encoding, @FormDataParam("baseUri") final URI baseUri, @FormDataParam("defaultGraph") final URI defaultGraph, @HeaderParam("authorization") final String authHeader, @PathParam("userId") final String userId, @PathParam("dataSet") final String dataSetId, @QueryParam("forceCreation") boolean forceCreation, @QueryParam("async") final boolean async) throws ExecutionException, InterruptedException, LogStorageFailedException, DataStoreCreationException {
    final Either<Response, Response> result = authCheck.getOrCreate(authHeader, userId, dataSetId, forceCreation).flatMap(userAndDs -> authCheck.hasAdminAccess(userAndDs.getLeft(), userAndDs.getRight())).map((Tuple<User, DataSet> userDataSetTuple) -> {
        final MediaType mediaType = mimeTypeOverride == null ? body.getMediaType() : mimeTypeOverride;
        final DataSet dataSet = userDataSetTuple.getRight();
        ImportManager importManager = dataSet.getImportManager();
        if (mediaType == null || !importManager.isRdfTypeSupported(mediaType)) {
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity("{\"error\": \"We do not support the mediatype '" + mediaType + "'. Make sure to add the correct " + "mediatype to the file parameter. In curl you'd use `-F \"file=@<filename>;type=<mediatype>\"`. In a " + "webbrowser you probably have no way of setting the correct mimetype. So you can use a special " + "parameter " + "to override it: `formData.append(\"fileMimeTypeOverride\", \"<mimetype>\");`\"}").build();
        }
        if (StringUtils.isBlank(encoding)) {
            return Response.status(Response.Status.BAD_REQUEST).entity("Please provide an 'encoding' parameter").build();
        }
        if (StringUtils.isBlank(body.getContentDisposition().getFileName())) {
            return Response.status(400).entity("filename cannot be empty.").build();
        }
        Future<ImportStatus> promise = null;
        try {
            promise = importManager.addLog(baseUri == null ? dataSet.getMetadata().getBaseUri() : baseUri.toString(), defaultGraph == null ? dataSet.getMetadata().getBaseUri() : defaultGraph.toString(), body.getContentDisposition().getFileName(), rdfInputStream, Optional.of(Charset.forName(encoding)), mediaType);
        } catch (LogStorageFailedException e) {
            return Response.serverError().build();
        }
        if (!async) {
            return handleImportManagerResult(promise);
        }
        return Response.accepted().build();
    });
    if (result.isLeft()) {
        return result.getLeft();
    } else {
        return result.get();
    }
}
Also used : Response(javax.ws.rs.core.Response) PathParam(javax.ws.rs.PathParam) ImportStatus(nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus) Path(javax.ws.rs.Path) Tuple(nl.knaw.huygens.timbuctoo.util.Tuple) StringUtils(org.apache.commons.lang3.StringUtils) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) MediaType(javax.ws.rs.core.MediaType) Future(java.util.concurrent.Future) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Charset(java.nio.charset.Charset) FormDataBodyPart(org.glassfish.jersey.media.multipart.FormDataBodyPart) HeaderParam(javax.ws.rs.HeaderParam) URI(java.net.URI) LogStorageFailedException(nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.LogStorageFailedException) AuthCheck(nl.knaw.huygens.timbuctoo.v5.dropwizard.endpoints.auth.AuthCheck) Either(javaslang.control.Either) POST(javax.ws.rs.POST) ImportManager(nl.knaw.huygens.timbuctoo.v5.dataset.ImportManager) DataStoreCreationException(nl.knaw.huygens.timbuctoo.v5.dataset.exceptions.DataStoreCreationException) ErrorResponseHelper.handleImportManagerResult(nl.knaw.huygens.timbuctoo.v5.dropwizard.endpoints.ErrorResponseHelper.handleImportManagerResult) ExecutionException(java.util.concurrent.ExecutionException) FormDataParam(org.glassfish.jersey.media.multipart.FormDataParam) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) InputStream(java.io.InputStream) ImportManager(nl.knaw.huygens.timbuctoo.v5.dataset.ImportManager) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) LogStorageFailedException(nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.LogStorageFailedException) ImportStatus(nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus) MediaType(javax.ws.rs.core.MediaType) Tuple(nl.knaw.huygens.timbuctoo.util.Tuple) Consumes(javax.ws.rs.Consumes) POST(javax.ws.rs.POST)

Example 15 with Entity

use of nl.knaw.huygens.timbuctoo.v5.serializable.dto.Entity in project timbuctoo by HuygensING.

the class SingleEntity method delete.

@DELETE
public Response delete(@PathParam("collection") String collectionName, @HeaderParam("Authorization") String authHeader, @PathParam("id") UUIDParam id) {
    Optional<User> user;
    try {
        user = userValidator.getUserFromAccessToken(authHeader);
    } catch (UserValidationException e) {
        user = Optional.empty();
    }
    Optional<User> newUser = user;
    if (!newUser.isPresent()) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    } else {
        return transactionEnforcer.executeAndReturn(timbuctooActions -> {
            JsonCrudService jsonCrudService = crudServiceFactory.newJsonCrudService(timbuctooActions);
            try {
                jsonCrudService.delete(collectionName, id.get(), newUser.get());
                return commitAndReturn(Response.noContent().build());
            } catch (InvalidCollectionException e) {
                return rollbackAndReturn(Response.status(Response.Status.NOT_FOUND).entity(jsnO("message", jsn(e.getMessage()))).build());
            } catch (NotFoundException e) {
                return rollbackAndReturn(Response.status(Response.Status.NOT_FOUND).entity(jsnO("message", jsn("not found"))).build());
            } catch (PermissionFetchingException e) {
                return rollbackAndReturn(Response.status(Response.Status.FORBIDDEN).entity(jsnO("message", jsn(e.getMessage()))).build());
            } catch (IOException e) {
                return rollbackAndReturn(Response.status(Response.Status.BAD_REQUEST).entity(jsnO("message", jsn(e.getMessage()))).build());
            }
        });
    }
}
Also used : UserValidationException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) PermissionFetchingException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.PermissionFetchingException) JsonCrudService(nl.knaw.huygens.timbuctoo.crud.JsonCrudService) InvalidCollectionException(nl.knaw.huygens.timbuctoo.crud.InvalidCollectionException) NotFoundException(nl.knaw.huygens.timbuctoo.core.NotFoundException) IOException(java.io.IOException) DELETE(javax.ws.rs.DELETE)

Aggregations

User (nl.knaw.huygens.timbuctoo.v5.security.dto.User)7 IOException (java.io.IOException)6 DataSet (nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet)6 UserValidationException (nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException)6 ExecutionException (java.util.concurrent.ExecutionException)5 LogStorageFailedException (nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.LogStorageFailedException)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 List (java.util.List)3 Map (java.util.Map)3 Optional (java.util.Optional)3 UUID (java.util.UUID)3 POST (javax.ws.rs.POST)3 NotFoundException (nl.knaw.huygens.timbuctoo.core.NotFoundException)3 PermissionFetchingException (nl.knaw.huygens.timbuctoo.v5.security.exceptions.PermissionFetchingException)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 Future (java.util.concurrent.Future)2 Either (javaslang.control.Either)2