Search in sources :

Example 26 with Type

use of nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Type in project timbuctoo by HuygensING.

the class SerializerExecutionStrategy method execute.

@Override
public CompletableFuture<ExecutionResult> execute(ExecutionContext executionContext, ExecutionStrategyParameters parameters) throws NonNullableFieldWasNullException {
    Map<String, java.util.List<Field>> fields = parameters.fields();
    GraphQLObjectType parentType = parameters.typeInfo().castType(GraphQLObjectType.class);
    return super.execute(executionContext, parameters).thenApply(sourceResult -> {
        Map<String, Object> data = sourceResult.getData();
        if (parameters.source() instanceof TypedValue) {
            String value = ((TypedValue) parameters.source()).getValue();
            String typename = ((TypedValue) parameters.source()).getType();
            Value result;
            if (value == null) {
                result = null;
            } else if (data.containsKey("__typename")) {
                result = Value.create(value, typename, (String) data.get("__typename"));
            } else {
                result = Value.create(value, typename);
            }
            return new ExecutionResultImpl(result, sourceResult.getErrors(), sourceResult.getExtensions());
        } else if (parameters.source() instanceof SubjectReference) {
            final String uri = ((SubjectReference) parameters.source()).getSubjectUri();
            final Set<String> types = ((SubjectReference) parameters.source()).getTypes();
            final String graphqlType = getDirectiveArgument(parentType, "rdfType", "uri").orElse(null);
            String type;
            if (graphqlType != null && types.contains(graphqlType)) {
                type = graphqlType;
            } else {
                Optional<String> firstType = types.stream().sorted().findFirst();
                if (firstType.isPresent()) {
                    type = firstType.get();
                } else {
                    LOG.error("No type present on " + uri + ". Expected at least TIM_UNKNOWN");
                    type = RdfConstants.UNKNOWN;
                }
            }
            LinkedHashMap<PredicateInfo, Serializable> copy = new LinkedHashMap<>();
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                final String graphqlFieldName = entry.getKey();
                final GraphQLFieldDefinition fieldDesc = parentType.getFieldDefinition(entry.getKey());
                Optional<String> predicateUri = getDirectiveArgument(fieldDesc, "rdf", "predicate");
                Optional<Direction> direction = getDirectiveArgument(fieldDesc, "rdf", "direction").map(Direction::valueOf);
                final PredicateInfo predicateInfo;
                predicateInfo = predicateUri.map(predUri -> PredicateInfo.predicateInfo(graphqlFieldName, predUri, direction.orElse(Direction.OUT))).orElseGet(() -> PredicateInfo.predicateInfo(graphqlFieldName, null, Direction.OUT));
                if (entry.getValue() == null || entry.getValue() instanceof Serializable) {
                    copy.put(predicateInfo, (Serializable) entry.getValue());
                } else {
                    copy.put(predicateInfo, Value.fromRawJavaType(entry.getValue()));
                }
            }
            return new ExecutionResultImpl(Entity.entity(uri, type, copy), sourceResult.getErrors(), sourceResult.getExtensions());
        } else if (parameters.source() instanceof PaginatedList) {
            PaginatedList<? extends DatabaseResult> source = (PaginatedList) parameters.source();
            return new ExecutionResultImpl(serializableList(source.getPrevCursor().orElse(null), source.getNextCursor().orElse(null), ((GraphqlIntrospectionList) data.get("items")).getItems()), sourceResult.getErrors(), sourceResult.getExtensions());
        } else if (executionContext.getGraphQLSchema().getQueryType() == parentType) {
            return new ExecutionResultImpl(QueryContainer.queryContainer(sourceResult.getData()), sourceResult.getErrors(), sourceResult.getExtensions());
        } else {
            LinkedHashMap<String, Serializable> copy = new LinkedHashMap<>();
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                if (entry.getValue() == null || entry.getValue() instanceof Serializable) {
                    copy.put(entry.getKey(), (Serializable) entry.getValue());
                } else {
                    copy.put(entry.getKey(), GraphqlIntrospectionValue.fromRawJavaType(entry.getValue()));
                }
            }
            return new ExecutionResultImpl(graphqlIntrospectionObject(copy), sourceResult.getErrors(), sourceResult.getExtensions());
        }
    });
}
Also used : TypedValue(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.TypedValue) SerializableList.serializableList(nl.knaw.huygens.timbuctoo.v5.serializable.dto.SerializableList.serializableList) GraphqlIntrospectionValue(nl.knaw.huygens.timbuctoo.v5.serializable.dto.GraphqlIntrospectionValue) GraphQLFieldDefinition(graphql.schema.GraphQLFieldDefinition) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutionContext(graphql.execution.ExecutionContext) GraphqlIntrospectionObject.graphqlIntrospectionObject(nl.knaw.huygens.timbuctoo.v5.serializable.dto.GraphqlIntrospectionObject.graphqlIntrospectionObject) SubjectReference(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.SubjectReference) ExecutionStrategyParameters(graphql.execution.ExecutionStrategyParameters) Value(nl.knaw.huygens.timbuctoo.v5.serializable.dto.Value) ExecutionResult(graphql.ExecutionResult) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) AsyncExecutionStrategy(graphql.execution.AsyncExecutionStrategy) ExecutionResultImpl(graphql.ExecutionResultImpl) QueryContainer(nl.knaw.huygens.timbuctoo.v5.serializable.dto.QueryContainer) GraphQLObjectType(graphql.schema.GraphQLObjectType) GraphqlIntrospectionList(nl.knaw.huygens.timbuctoo.v5.serializable.dto.GraphqlIntrospectionList) Logger(org.slf4j.Logger) NonNullableFieldWasNullException(graphql.execution.NonNullableFieldWasNullException) RdfConstants(nl.knaw.huygens.timbuctoo.v5.util.RdfConstants) Set(java.util.Set) Serializable(nl.knaw.huygens.timbuctoo.v5.serializable.dto.Serializable) Field(graphql.language.Field) DatabaseResult(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.DatabaseResult) Collectors(java.util.stream.Collectors) List(java.util.List) PaginatedList(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.PaginatedList) StringValue(graphql.language.StringValue) PredicateInfo(nl.knaw.huygens.timbuctoo.v5.serializable.dto.PredicateInfo) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) Optional(java.util.Optional) Direction(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.Direction) GraphqlIntrospectionList.graphqlIntrospectionList(nl.knaw.huygens.timbuctoo.v5.serializable.dto.GraphqlIntrospectionList.graphqlIntrospectionList) Entity(nl.knaw.huygens.timbuctoo.v5.serializable.dto.Entity) Serializable(nl.knaw.huygens.timbuctoo.v5.serializable.dto.Serializable) Set(java.util.Set) Optional(java.util.Optional) GraphqlIntrospectionList(nl.knaw.huygens.timbuctoo.v5.serializable.dto.GraphqlIntrospectionList) SubjectReference(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.SubjectReference) GraphQLFieldDefinition(graphql.schema.GraphQLFieldDefinition) LinkedHashMap(java.util.LinkedHashMap) ExecutionResultImpl(graphql.ExecutionResultImpl) GraphQLObjectType(graphql.schema.GraphQLObjectType) TypedValue(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.TypedValue) GraphqlIntrospectionValue(nl.knaw.huygens.timbuctoo.v5.serializable.dto.GraphqlIntrospectionValue) Value(nl.knaw.huygens.timbuctoo.v5.serializable.dto.Value) StringValue(graphql.language.StringValue) SerializableList.serializableList(nl.knaw.huygens.timbuctoo.v5.serializable.dto.SerializableList.serializableList) GraphqlIntrospectionList(nl.knaw.huygens.timbuctoo.v5.serializable.dto.GraphqlIntrospectionList) List(java.util.List) PaginatedList(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.PaginatedList) GraphqlIntrospectionList.graphqlIntrospectionList(nl.knaw.huygens.timbuctoo.v5.serializable.dto.GraphqlIntrospectionList.graphqlIntrospectionList) GraphqlIntrospectionObject.graphqlIntrospectionObject(nl.knaw.huygens.timbuctoo.v5.serializable.dto.GraphqlIntrospectionObject.graphqlIntrospectionObject) PredicateInfo(nl.knaw.huygens.timbuctoo.v5.serializable.dto.PredicateInfo) PaginatedList(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.PaginatedList) TypedValue(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.TypedValue)

Example 27 with Type

use of nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Type in project timbuctoo by HuygensING.

the class Rdf4jRdfParser method importRdf.

@Override
public void importRdf(CachedLog input, String baseUri, String defaultGraph, RdfProcessor rdfProcessor) throws RdfProcessingFailedException {
    try {
        RDFFormat format = Rio.getParserFormatForMIMEType(input.getMimeType().toString()).orElseThrow(() -> new UnsupportedRDFormatException(input.getMimeType() + " is not a supported rdf type."));
        RDFParser rdfParser = Rio.createParser(format);
        rdfParser.setPreserveBNodeIDs(true);
        rdfParser.setRDFHandler(new TimRdfHandler(rdfProcessor, defaultGraph, input.getFile().getName()));
        rdfParser.parse(input.getReader(), baseUri);
    } catch (IOException | RDFParseException | UnsupportedRDFormatException e) {
        throw new RdfProcessingFailedException(e);
    } catch (RDFHandlerException e) {
        if (e.getCause() instanceof RdfProcessingFailedException) {
            throw (RdfProcessingFailedException) e.getCause();
        } else {
            throw new RdfProcessingFailedException(e);
        }
    }
}
Also used : UnsupportedRDFormatException(org.eclipse.rdf4j.rio.UnsupportedRDFormatException) RDFHandlerException(org.eclipse.rdf4j.rio.RDFHandlerException) TimRdfHandler(nl.knaw.huygens.timbuctoo.v5.rdfio.implementations.rdf4j.parsers.TimRdfHandler) IOException(java.io.IOException) RDFParser(org.eclipse.rdf4j.rio.RDFParser) RdfProcessingFailedException(nl.knaw.huygens.timbuctoo.v5.dataset.exceptions.RdfProcessingFailedException) RDFFormat(org.eclipse.rdf4j.rio.RDFFormat) RDFParseException(org.eclipse.rdf4j.rio.RDFParseException)

Example 28 with Type

use of nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Type in project timbuctoo by HuygensING.

the class JsonLdSerialization method writeContext.

private void writeContext(Set<PredicateInfo> context) throws IOException {
    generator.writeFieldName("@context");
    generator.writeStartObject();
    // ignore the data wrapper by marking it as an index map and as the @graph container
    generator.writeFieldName("data");
    generator.writeStartObject();
    generator.writeStringField("@id", "@graph");
    generator.writeStringField("@container", "@index");
    generator.writeEndObject();
    generator.writeStringField("value", "@value");
    generator.writeStringField("type", "@type");
    for (PredicateInfo entry : context) {
        if (entry.getUri().isPresent()) {
            if (entry.getDirection() == Direction.IN) {
                generator.writeFieldName(entry.getSafeName());
                generator.writeStartObject();
                if (entry.getDirection() == Direction.IN) {
                    generator.writeStringField("@reverse", entry.getUri().get());
                } else {
                    generator.writeStringField("@id", entry.getUri().get());
                }
                generator.writeEndObject();
            } else {
                generator.writeStringField(entry.getSafeName(), entry.getUri().get());
            }
        } else {
            generator.writeNullField(entry.getSafeName());
        }
    }
    generator.writeEndObject();
}
Also used : PredicateInfo(nl.knaw.huygens.timbuctoo.v5.serializable.dto.PredicateInfo)

Example 29 with Type

use of nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Type in project timbuctoo by HuygensING.

the class MergeSchemasTest method mergeSchemaMergesMatchingPredicates.

@Test
public void mergeSchemaMergesMatchingPredicates() throws Exception {
    final MergeSchemas mergeSchemas = new MergeSchemas();
    Map<String, Type> generatedSchema = new HashMap<>();
    Type predType1 = createTypeWithPredicate("generated", Direction.IN);
    predType1.getPredicate("generated", Direction.IN).setHasBeenList(true);
    predType1.getPredicate("generated", Direction.IN).setOwner(new Type("testOwner"));
    generatedSchema.put("Type", predType1);
    Map<String, Type> customSchema = new HashMap<>();
    Type predType2 = createTypeWithPredicate("generated", Direction.IN);
    predType2.getPredicate("generated", Direction.IN).setHasBeenList(false);
    predType2.getPredicate("generated", Direction.IN).setOwner(new Type("testOwner"));
    customSchema.put("Type", predType2);
    Map<String, Type> mergedSchema = mergeSchemas.mergeSchema(generatedSchema, customSchema);
    assertThat(mergedSchema, hasEntry(is("Type"), hasProperty("predicates", contains(predicateMatcher().withName("generated").withDirection(Direction.IN).withWasList(true)))));
    assertThat(mergedSchema, hasEntry(is("Type"), hasProperty("predicates", not(hasItem(predicateMatcher().withName("generated").withDirection(Direction.IN).withWasList(false))))));
}
Also used : MergeSchemas(nl.knaw.huygens.timbuctoo.v5.graphql.customschema.MergeSchemas) Type(nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Type) HashMap(java.util.HashMap) Test(org.junit.Test)

Example 30 with Type

use of nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Type in project timbuctoo by HuygensING.

the class JsonProvenanceToRdfPatchTest method doesOptimisticLocking.

@Test
public void doesOptimisticLocking() throws Exception {
    String examplePatch = "{\n" + "   \"@type\":\"prov:Activity\",\n" + "   \"http://www.w3.org/ns/prov#generates\":[\n" + "      {\n" + "         \"@type\":\"prov:Entity\",\n" + "         \"specializationOf\":{\n" + "            \"@id\":\"http://example.com/the/actual/entity1\"\n" + "         },\n" + "        \"wasRevisionOf\":{\n" + "            \"@id\":\"http://example.org/revision1\"\n" + "         },\n" + "         \"additions\":[\n" + "            {\n" + "               \"@type\":\"http://timbuctoo.huygens.knaw.nl/v5/vocabulary#mutation\",\n" + "               \"predicate\":\"http://example.org/pred1\",\n" + "               \"value\":\"value1\"\n" + "            }\n" + "         ]\n" + "      }\n" + "   ],\n" + context + "}";
    QuadStore testQuadStore = new DummyQuadStore().with("http://example.org/entity1", RdfConstants.TIM_LATEST_REVISION, "http://example.org/revision2", null);
    boolean exceptionWasThrown = false;
    try {
        fromCurrentState(new DocumentLoader(), examplePatch, testQuadStore, "http://example.org/users/myUser", UUID.randomUUID().toString(), CLOCK);
    } catch (ConcurrentUpdateException e) {
        exceptionWasThrown = true;
    }
    assertThat(exceptionWasThrown, is(true));
}
Also used : QuadStore(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore) DocumentLoader(com.github.jsonldjava.core.DocumentLoader) Test(org.junit.Test)

Aggregations

Type (nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Type)17 Test (org.junit.Test)13 HashMap (java.util.HashMap)9 Map (java.util.Map)8 Predicate (nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Predicate)8 MergeSchemas (nl.knaw.huygens.timbuctoo.v5.graphql.customschema.MergeSchemas)8 IOException (java.io.IOException)6 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)5 List (java.util.List)5 Optional (java.util.Optional)5 DataSet (nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet)5 QuadStore (nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore)5 Logger (org.slf4j.Logger)5 ArrayList (java.util.ArrayList)4 ImportStatus (nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus)4 CursorQuad (nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.CursorQuad)4 Direction (nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.Direction)4 DocumentLoader (com.github.jsonldjava.core.DocumentLoader)3 Collectors (java.util.stream.Collectors)3 LoggerFactory (org.slf4j.LoggerFactory)3