Search in sources :

Example 1 with Entity

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

the class GraphQl method executeGraphql.

public Response executeGraphql(String query, String acceptHeader, String acceptParam, String queryFromBody, Map variables, String operationName, String authHeader) {
    final SerializerWriter serializerWriter;
    if (acceptParam != null && !acceptParam.isEmpty()) {
        // Accept param overrules header because it's more under the user's control
        acceptHeader = acceptParam;
    }
    if (unSpecifiedAcceptHeader(acceptHeader)) {
        acceptHeader = MediaType.APPLICATION_JSON;
    }
    if (MediaType.APPLICATION_JSON.equals(acceptHeader)) {
        serializerWriter = null;
    } else {
        Optional<SerializerWriter> bestMatch = serializerWriterRegistry.getBestMatch(acceptHeader);
        if (bestMatch.isPresent()) {
            serializerWriter = bestMatch.get();
        } else {
            return Response.status(415).type(MediaType.APPLICATION_JSON_TYPE).entity("{\"errors\": [\"The available mediatypes are: " + String.join(", ", serializerWriterRegistry.getSupportedMimeTypes()) + "\"]}").build();
        }
    }
    if (query != null && queryFromBody != null) {
        return Response.status(400).type(MediaType.APPLICATION_JSON_TYPE).entity("{\"errors\": [\"There's both a query as url paramatere and a query in the body. Please pick one.\"]}").build();
    }
    if (query == null && queryFromBody == null) {
        return Response.status(400).type(MediaType.APPLICATION_JSON_TYPE).entity("{\"errors\": [\"Please provide the graphql query as the query property of a JSON encoded object. " + "E.g. {query: \\\"{\\n  persons {\\n ... \\\"}\"]}").build();
    }
    Optional<User> user;
    try {
        user = userValidator.getUserFromAccessToken(authHeader);
    } catch (UserValidationException e) {
        user = Optional.empty();
    }
    UserPermissionCheck userPermissionCheck = new UserPermissionCheck(user, permissionFetcher, newHashSet(Permission.READ));
    final GraphQLSchema transform = graphqlGetter.get().transform(b -> b.fieldVisibility(new PermissionBasedFieldVisibility(userPermissionCheck, dataSetRepository)));
    final GraphQL.Builder builder = GraphQL.newGraphQL(transform);
    if (serializerWriter != null) {
        builder.queryExecutionStrategy(new SerializerExecutionStrategy());
    }
    GraphQL graphQl = builder.build();
    final ExecutionResult result = graphQl.execute(newExecutionInput().root(new RootData(user)).context(contextData(userPermissionCheck, user)).query(queryFromBody).operationName(operationName).variables(variables == null ? Collections.emptyMap() : variables).build());
    if (serializerWriter == null) {
        return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(result.toSpecification()).build();
    } else {
        if (result.getErrors() != null && !result.getErrors().isEmpty()) {
            return Response.status(415).type(MediaType.APPLICATION_JSON_TYPE).entity(result.toSpecification()).build();
        }
        return Response.ok().type(serializerWriter.getMimeType()).entity((StreamingOutput) os -> {
            serializerWriter.getSerializationFactory().create(os).serialize(new SerializableResult(result.getData()));
        }).build();
    }
}
Also used : UserValidationException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) GraphQL(graphql.GraphQL) SerializableResult(nl.knaw.huygens.timbuctoo.v5.serializable.SerializableResult) SerializerWriter(nl.knaw.huygens.timbuctoo.v5.dropwizard.contenttypes.SerializerWriter) ExecutionResult(graphql.ExecutionResult) StreamingOutput(javax.ws.rs.core.StreamingOutput) GraphQLSchema(graphql.schema.GraphQLSchema) RootData(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.RootData) PermissionBasedFieldVisibility(nl.knaw.huygens.timbuctoo.v5.graphql.security.PermissionBasedFieldVisibility) SerializerExecutionStrategy(nl.knaw.huygens.timbuctoo.v5.graphql.serializable.SerializerExecutionStrategy) UserPermissionCheck(nl.knaw.huygens.timbuctoo.v5.graphql.security.UserPermissionCheck)

Example 2 with Entity

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

the class TabularUpload method upload.

@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@POST
public Response upload(@FormDataParam("file") final InputStream rdfInputStream, @FormDataParam("file") final FormDataBodyPart body, @FormDataParam("file") final FormDataContentDisposition fileInfo, @FormDataParam("fileMimeTypeOverride") final MediaType mimeTypeOverride, FormDataMultiPart formData, @HeaderParam("authorization") final String authHeader, @PathParam("userId") final String ownerId, @PathParam("dataSetId") final String dataSetId, @QueryParam("forceCreation") boolean forceCreation) throws DataStoreCreationException, FileStorageFailedException, ExecutionException, InterruptedException, LogStorageFailedException {
    final Either<Response, Response> result = authCheck.getOrCreate(authHeader, ownerId, dataSetId, forceCreation).flatMap(userAndDs -> authCheck.hasAdminAccess(userAndDs.getLeft(), userAndDs.getRight())).map(userAndDs -> {
        final MediaType mediaType = mimeTypeOverride == null ? body.getMediaType() : mimeTypeOverride;
        Optional<Loader> loader = LoaderFactory.createFor(mediaType.toString(), formData.getFields().entrySet().stream().filter(entry -> entry.getValue().size() > 0).filter(entry -> entry.getValue().get(0) != null).filter(entry -> MediaTypes.typeEqual(MediaType.TEXT_PLAIN_TYPE, entry.getValue().get(0).getMediaType())).collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().get(0).getValue())));
        if (!loader.isPresent()) {
            return errorResponseHelper.error(400, "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>\");`");
        }
        final DataSet dataSet = userAndDs.getRight();
        ImportManager importManager = dataSet.getImportManager();
        if (StringUtils.isBlank(fileInfo.getName())) {
            return Response.status(400).entity("filename cannot be empty.").build();
        }
        try {
            String fileToken = importManager.addFile(rdfInputStream, fileInfo.getFileName(), mediaType);
            Future<ImportStatus> promise = importManager.generateLog(dataSet.getMetadata().getBaseUri(), dataSet.getMetadata().getBaseUri(), new TabularRdfCreator(loader.get(), fileToken, fileInfo.getFileName()));
            return handleImportManagerResult(promise);
        } catch (FileStorageFailedException | LogStorageFailedException e) {
            LOG.error("Tabular upload failed", e);
            return Response.serverError().build();
        }
    });
    if (result.isLeft()) {
        return result.getLeft();
    } else {
        return result.get();
    }
}
Also used : PathParam(javax.ws.rs.PathParam) ImportStatus(nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus) FormDataContentDisposition(org.glassfish.jersey.media.multipart.FormDataContentDisposition) Produces(javax.ws.rs.Produces) DataSetRepository(nl.knaw.huygens.timbuctoo.v5.dataset.DataSetRepository) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) FormDataMultiPart(org.glassfish.jersey.media.multipart.FormDataMultiPart) StringUtils(org.apache.commons.lang3.StringUtils) MediaType(javax.ws.rs.core.MediaType) Future(java.util.concurrent.Future) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) FormDataBodyPart(org.glassfish.jersey.media.multipart.FormDataBodyPart) HeaderParam(javax.ws.rs.HeaderParam) Loader(nl.knaw.huygens.timbuctoo.bulkupload.loaders.Loader) LogStorageFailedException(nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.LogStorageFailedException) AuthCheck(nl.knaw.huygens.timbuctoo.v5.dropwizard.endpoints.auth.AuthCheck) Either(javaslang.control.Either) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) ImportManager(nl.knaw.huygens.timbuctoo.v5.dataset.ImportManager) DataStoreCreationException(nl.knaw.huygens.timbuctoo.v5.dataset.exceptions.DataStoreCreationException) LoaderFactory(nl.knaw.huygens.timbuctoo.bulkupload.loaders.LoaderFactory) Collectors(java.util.stream.Collectors) ErrorResponseHelper.handleImportManagerResult(nl.knaw.huygens.timbuctoo.v5.dropwizard.endpoints.ErrorResponseHelper.handleImportManagerResult) ExecutionException(java.util.concurrent.ExecutionException) MediaTypes(org.glassfish.jersey.message.internal.MediaTypes) FormDataParam(org.glassfish.jersey.media.multipart.FormDataParam) Response(javax.ws.rs.core.Response) FileStorageFailedException(nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.FileStorageFailedException) TabularRdfCreator(nl.knaw.huygens.timbuctoo.v5.bulkupload.TabularRdfCreator) 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) Loader(nl.knaw.huygens.timbuctoo.bulkupload.loaders.Loader) FileStorageFailedException(nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.FileStorageFailedException) Response(javax.ws.rs.core.Response) ImportStatus(nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus) MediaType(javax.ws.rs.core.MediaType) TabularRdfCreator(nl.knaw.huygens.timbuctoo.v5.bulkupload.TabularRdfCreator) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) POST(javax.ws.rs.POST)

Example 3 with Entity

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

the class JsonCrudService method getCollection.

public List<ObjectNode> getCollection(String collectionName, int rows, int start, boolean withRelations) throws InvalidCollectionException {
    final Collection collection = mappings.getCollection(collectionName).orElseThrow(() -> new InvalidCollectionException(collectionName));
    DataStream<ReadEntity> entities = timDbAccess.getCollection(collection, start, rows, withRelations, (traversalSource, vre) -> {
    }, (entity1, entityVertex, target, relationRef) -> {
    });
    List<ObjectNode> result = entities.map(entity -> entityToJsonMapper.mapEntity(collection, entity, withRelations, (readEntity, resultJson) -> {
    }, (relationRef, resultJson) -> {
    }));
    return result;
}
Also used : ReadEntity(nl.knaw.huygens.timbuctoo.core.dto.ReadEntity) UserValidator(nl.knaw.huygens.timbuctoo.v5.security.UserValidator) JsonBuilder.jsnO(nl.knaw.huygens.timbuctoo.util.JsonBuilder.jsnO) AlreadyUpdatedException(nl.knaw.huygens.timbuctoo.core.AlreadyUpdatedException) PermissionFetchingException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.PermissionFetchingException) Collection(nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) CreateRelation(nl.knaw.huygens.timbuctoo.core.dto.CreateRelation) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) EntityToJsonMapper(nl.knaw.huygens.timbuctoo.crud.conversion.EntityToJsonMapper) TimbuctooActions(nl.knaw.huygens.timbuctoo.core.TimbuctooActions) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonBuilder.jsn(nl.knaw.huygens.timbuctoo.util.JsonBuilder.jsn) TimProperty(nl.knaw.huygens.timbuctoo.core.dto.property.TimProperty) Iterator(java.util.Iterator) DataStream(nl.knaw.huygens.timbuctoo.core.dto.DataStream) IOException(java.io.IOException) NotFoundException(nl.knaw.huygens.timbuctoo.core.NotFoundException) UUID(java.util.UUID) Vres(nl.knaw.huygens.timbuctoo.model.vre.Vres) ReadEntity(nl.knaw.huygens.timbuctoo.core.dto.ReadEntity) UpdateEntity(nl.knaw.huygens.timbuctoo.core.dto.UpdateEntity) List(java.util.List) JsonToEntityMapper(nl.knaw.huygens.timbuctoo.crud.conversion.JsonToEntityMapper) Optional(java.util.Optional) UpdateRelation(nl.knaw.huygens.timbuctoo.core.dto.UpdateRelation) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Collection(nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection)

Example 4 with Entity

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

the class Index method createNew.

@POST
public Response createNew(@PathParam("collection") String collectionName, @HeaderParam("Authorization") String authHeader, ObjectNode body) throws URISyntaxException {
    Optional<User> user;
    try {
        user = userValidator.getUserFromAccessToken(authHeader);
    } catch (UserValidationException e) {
        user = Optional.empty();
    }
    Optional<User> newUser = user;
    if (!user.isPresent()) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    } else {
        return transactionEnforcer.executeAndReturn(timbuctooActions -> {
            JsonCrudService crudService = crudServiceFactory.newJsonCrudService(timbuctooActions);
            try {
                UUID id = crudService.create(collectionName, body, newUser.get());
                return commitAndReturn(Response.created(SingleEntity.makeUrl(collectionName, id)).build());
            } catch (InvalidCollectionException e) {
                return rollbackAndReturn(Response.status(Response.Status.NOT_FOUND).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());
            } catch (PermissionFetchingException e) {
                return rollbackAndReturn(Response.status(Response.Status.FORBIDDEN).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) IOException(java.io.IOException) UUID(java.util.UUID) POST(javax.ws.rs.POST)

Example 5 with Entity

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

the class SingleEntity method put.

@PUT
public Response put(@PathParam("collection") String collectionName, @HeaderParam("Authorization") String authHeader, @PathParam("id") UUIDParam id, ObjectNode body) {
    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 {
        UpdateMessage updateMessage = transactionEnforcer.executeAndReturn(timbuctooActions -> {
            JsonCrudService crudService = crudServiceFactory.newJsonCrudService(timbuctooActions);
            try {
                crudService.replace(collectionName, id.get(), body, newUser.get());
                return commitAndReturn(UpdateMessage.success());
            } catch (InvalidCollectionException e) {
                return rollbackAndReturn(UpdateMessage.failure(e.getMessage(), Response.Status.NOT_FOUND));
            } catch (NotFoundException e) {
                return rollbackAndReturn(UpdateMessage.failure("not found", Response.Status.NOT_FOUND));
            } catch (IOException e) {
                return rollbackAndReturn(UpdateMessage.failure(e.getMessage(), Response.Status.BAD_REQUEST));
            } catch (AlreadyUpdatedException e) {
                return rollbackAndReturn(UpdateMessage.failure("Entry was already updated", Response.Status.EXPECTATION_FAILED));
            } catch (PermissionFetchingException e) {
                return rollbackAndReturn(UpdateMessage.failure(e.getMessage(), Response.Status.FORBIDDEN));
            }
        });
        // committed in the database
        if (updateMessage.isSuccess()) {
            return transactionEnforcer.executeAndReturn(timbuctooActions -> {
                JsonCrudService crudService = crudServiceFactory.newJsonCrudService(timbuctooActions);
                try {
                    JsonNode jsonNode = crudService.get(collectionName, id.get());
                    return commitAndReturn(Response.ok(jsonNode).build());
                } catch (InvalidCollectionException e) {
                    return rollbackAndReturn(Response.status(Response.Status.NOT_FOUND).entity(jsnO("message", jsn("Collection '" + collectionName + "' was available a moment ago, but not anymore: " + e.getMessage()))).build());
                } catch (NotFoundException e) {
                    return rollbackAndReturn(Response.status(Response.Status.NOT_FOUND).entity(jsnO("message", jsn("not found"))).build());
                }
            });
        } else {
            return Response.status(updateMessage.getResponseStatus()).entity(jsnO("message", jsn(updateMessage.getException().get()))).build();
        }
    }
}
Also used : UserValidationException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) AlreadyUpdatedException(nl.knaw.huygens.timbuctoo.core.AlreadyUpdatedException) 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) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) PUT(javax.ws.rs.PUT)

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