Search in sources :

Example 51 with Value

use of nl.knaw.huygens.timbuctoo.v5.graphql.mutations.Change.Value in project timbuctoo by HuygensING.

the class SerializerExecutionStrategy method execute.

@Override
public CompletableFuture<ExecutionResult> execute(ExecutionContext executionContext, ExecutionStrategyParameters parameters) throws NonNullableFieldWasNullException {
    GraphQLObjectType parentType = (GraphQLObjectType) parameters.getExecutionStepInfo().getUnwrappedNonNullType();
    return super.execute(executionContext, parameters).thenApply(sourceResult -> {
        Map<String, Object> data = sourceResult.getData();
        if (parameters.getSource() instanceof TypedValue) {
            String value = ((TypedValue) parameters.getSource()).getValue();
            String typename = ((TypedValue) parameters.getSource()).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.getSource() instanceof SubjectReference) {
            final String uri = ((SubjectReference) parameters.getSource()).getSubjectUri();
            final Set<String> types = ((SubjectReference) parameters.getSource()).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 RDFS_RESOURCE");
                    type = RdfConstants.RDFS_RESOURCE;
                }
            }
            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.getSource() instanceof PaginatedList) {
            PaginatedList<? extends DatabaseResult> source = (PaginatedList) parameters.getSource();
            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) DirectiveRetriever.getDirectiveArgument(nl.knaw.huygens.timbuctoo.v5.graphql.DirectiveRetriever.getDirectiveArgument) 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) 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) PredicateInfo(nl.knaw.huygens.timbuctoo.v5.serializable.dto.PredicateInfo) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) Optional(java.util.Optional) FieldValueInfo(graphql.execution.FieldValueInfo) 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) 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 52 with Value

use of nl.knaw.huygens.timbuctoo.v5.graphql.mutations.Change.Value in project timbuctoo by HuygensING.

the class OpenIdConnectUserValidator method getUserFromAccessToken.

@Override
public Optional<User> getUserFromAccessToken(String accessToken) throws UserValidationException {
    if (StringUtils.isBlank(accessToken)) {
        return Optional.empty();
    }
    final User local = users.getIfPresent(accessToken);
    if (local != null) {
        return Optional.of(local);
    }
    try {
        final Optional<UserInfo> userInfoOpt = openIdClient.getUserInfo(accessToken);
        if (userInfoOpt.isEmpty()) {
            return Optional.empty();
        }
        final UserInfo userInfo = userInfoOpt.get();
        final String subject = userInfo.getSubject().getValue();
        final Optional<User> user = userStore.userFor(subject);
        if (user.isPresent()) {
            user.ifPresent(value -> users.put(accessToken, value));
            return user;
        } else {
            final User newUser = userStore.saveNew(userInfo.getNickname(), subject);
            users.put(subject, newUser);
            return Optional.of(newUser);
        }
    } catch (AuthenticationUnavailableException | IOException | ParseException e) {
        throw new UserValidationException(e);
    }
}
Also used : UserValidationException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException) AuthenticationUnavailableException(nl.knaw.huygens.timbuctoo.security.exceptions.AuthenticationUnavailableException) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) IOException(java.io.IOException) ParseException(com.nimbusds.oauth2.sdk.ParseException)

Example 53 with Value

use of nl.knaw.huygens.timbuctoo.v5.graphql.mutations.Change.Value in project timbuctoo by HuygensING.

the class ViewConfigMutation method executeAction.

@Override
public Object executeAction(DataFetchingEnvironment env) {
    String collectionUri = env.getArgument("collectionUri");
    Object viewConfig = env.getArgument("viewConfig");
    DataSet dataSet = MutationHelpers.getDataSet(env, dataSetRepository::getDataSet);
    MutationHelpers.checkPermission(env, dataSet.getMetadata(), Permission.CONFIG_VIEW);
    try {
        MutationHelpers.addMutation(dataSet, new PredicateMutation().entity(collectionUri, replace(HAS_VIEW_CONFIG, value(OBJECT_MAPPER.writeValueAsString(viewConfig)))));
        return viewConfig;
    } 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 54 with Value

use of nl.knaw.huygens.timbuctoo.v5.graphql.mutations.Change.Value 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 55 with Value

use of nl.knaw.huygens.timbuctoo.v5.graphql.mutations.Change.Value in project timbuctoo by HuygensING.

the class SummaryPropDataRetrieverTest method createSummaryPropertyWalksTheSecondPathIfTheFirstGivesNoValue.

@Test
public void createSummaryPropertyWalksTheSecondPathIfTheFirstGivesNoValue() {
    List<SummaryProp> defaultProperties = Lists.newArrayList(summaryPropertyWithPath(DEFAULT_PATH, DEFAULT_PATH_2));
    SummaryPropDataRetriever instance = new SummaryPropDataRetriever(USER_CONFIGURED_PATH, defaultProperties);
    QuadStore quadStore = mock(QuadStore.class);
    CursorQuad foundQuad1 = quadWithObject(OBJECT_1, Optional.empty());
    CursorQuad foundQuad2 = quadWithObject(OBJECT_2, Optional.empty());
    given(quadStore.getQuadsInGraph(SOURCE, DEFAULT_PATH, Direction.OUT, "", Optional.of(new Graph(GRAPH)))).willReturn(Stream.of(foundQuad1, foundQuad2));
    CursorQuad objectOfPath2 = quadWithObject(OBJECT_OF_PATH2, Optional.empty());
    given(quadStore.getQuadsInGraph(OBJECT_2, DEFAULT_PATH_2, Direction.OUT, "", Optional.of(new Graph(GRAPH)))).willReturn(Stream.of(objectOfPath2));
    Optional<TypedValue> summaryProperty = instance.createSummaryProperty(subjectWithUriAndGraph(SOURCE, Optional.of(new Graph(GRAPH))), dataSetWithQuadStore(quadStore), COLLECTION);
    assertThat(summaryProperty, is(present()));
    assertThat(summaryProperty.get(), hasProperty("value", is(OBJECT_OF_PATH2)));
    verify(quadStore).getQuadsInGraph(SOURCE, DEFAULT_PATH, Direction.OUT, "", Optional.of(new Graph(GRAPH)));
    verify(quadStore).getQuadsInGraph(OBJECT_1, DEFAULT_PATH_2, Direction.OUT, "", Optional.of(new Graph(GRAPH)));
    verify(quadStore).getQuadsInGraph(OBJECT_2, DEFAULT_PATH_2, Direction.OUT, "", Optional.of(new Graph(GRAPH)));
}
Also used : QuadStore(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore) Graph(nl.knaw.huygens.timbuctoo.v5.util.Graph) CursorQuad(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.CursorQuad) SummaryProp(nl.knaw.huygens.timbuctoo.v5.graphql.defaultconfiguration.SummaryProp) TypedValue(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.TypedValue) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)42 Value (nl.knaw.huygens.timbuctoo.v5.graphql.mutations.Change.Value)32 Graph (nl.knaw.huygens.timbuctoo.v5.util.Graph)22 ChangeMatcher.likeChange (nl.knaw.huygens.timbuctoo.v5.graphql.mutations.ChangeMatcher.likeChange)18 Map (java.util.Map)15 DataSet (nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet)15 ExecutionException (java.util.concurrent.ExecutionException)12 LogStorageFailedException (nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.LogStorageFailedException)11 PredicateMutation (nl.knaw.huygens.timbuctoo.v5.graphql.mutations.dto.PredicateMutation)11 EditMutationChangeLog (nl.knaw.huygens.timbuctoo.v5.graphql.mutations.dto.EditMutationChangeLog)10 QuadStore (nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore)9 CursorQuad (nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.CursorQuad)9 List (java.util.List)8 IOException (java.io.IOException)7 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 Direction (nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.Direction)6 CustomProvenance (nl.knaw.huygens.timbuctoo.v5.graphql.mutations.dto.CustomProvenance)6 Optional (java.util.Optional)5