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