use of nl.knaw.huygens.timbuctoo.v5.graphql.mutations.Change.Value in project timbuctoo by HuygensING.
the class RootQuery method rebuildSchema.
public synchronized GraphQLSchema rebuildSchema() {
final TypeDefinitionRegistry staticQuery = schemaParser.parse(this.staticQuery);
if (archetypes != null && !archetypes.isEmpty()) {
staticQuery.merge(schemaParser.parse(archetypes + "extend type DataSetMetadata {\n" + " archetypes: Archetypes! @passThrough\n" + "}\n" + "\n"));
}
TypeDefinitionRegistry registry = new TypeDefinitionRegistry();
registry.merge(staticQuery);
final RuntimeWiring.Builder wiring = RuntimeWiring.newRuntimeWiring();
wiring.type("Query", builder -> builder.dataFetcher("promotedDataSets", env -> dataSetRepository.getPromotedDataSets().stream().map(DataSetWithDatabase::new).collect(Collectors.toList())).dataFetcher("allDataSets", env -> dataSetRepository.getDataSets().stream().map(DataSetWithDatabase::new).filter(x -> {
if (x.isPublished()) {
return true;
} else {
ContextData contextData = env.getContext();
UserPermissionCheck userPermissionCheck = contextData.getUserPermissionCheck();
return userPermissionCheck.getPermissions(x.getDataSet().getMetadata()).contains(Permission.READ);
}
}).collect(Collectors.toList())).dataFetcher("dataSetMetadata", env -> {
final String dataSetId = env.getArgument("dataSetId");
ContextData context = env.getContext();
final User user = context.getUser().orElse(null);
Tuple<String, String> splitCombinedId = DataSetMetaData.splitCombinedId(dataSetId);
return dataSetRepository.getDataSet(user, splitCombinedId.getLeft(), splitCombinedId.getRight()).map(DataSetWithDatabase::new);
}).dataFetcher("dataSetMetadataList", env -> {
Stream<DataSetWithDatabase> dataSets = dataSetRepository.getDataSets().stream().map(DataSetWithDatabase::new);
if (env.getArgument("promotedOnly")) {
dataSets = dataSets.filter(DataSetWithDatabase::isPromoted);
}
if (env.getArgument("publishedOnly")) {
dataSets = dataSets.filter(DataSetWithDatabase::isPublished);
}
return dataSets.filter(x -> {
ContextData contextData = env.getContext();
UserPermissionCheck userPermissionCheck = contextData.getUserPermissionCheck();
return userPermissionCheck.getPermissions(x.getDataSet().getMetadata()).contains(Permission.READ);
}).collect(Collectors.toList());
}).dataFetcher("aboutMe", env -> ((RootData) env.getRoot()).getCurrentUser().orElse(null)).dataFetcher("availableExportMimetypes", env -> supportedFormats.getSupportedMimeTypes().stream().map(MimeTypeDescription::create).collect(Collectors.toList())));
wiring.type("DataSetMetadata", builder -> builder.dataFetcher("currentImportStatus", env -> {
DataSetMetaData input = env.getSource();
Optional<User> currentUser = ((RootData) env.getRoot()).getCurrentUser();
if (!currentUser.isPresent()) {
throw new RuntimeException("User is not provided");
}
return dataSetRepository.getDataSet(currentUser.get(), input.getOwnerId(), input.getDataSetId()).map(dataSet -> dataSet.getImportManager().getImportStatus());
}).dataFetcher("dataSetImportStatus", env -> {
Optional<User> currentUser = ((RootData) env.getRoot()).getCurrentUser();
if (!currentUser.isPresent()) {
throw new RuntimeException("User is not provided");
}
DataSetMetaData input = env.getSource();
return dataSetRepository.getDataSet(currentUser.get(), input.getOwnerId(), input.getDataSetId()).map(dataSet -> dataSet.getImportManager().getDataSetImportStatus());
}).dataFetcher("collectionList", env -> getCollections(env.getSource(), ((ContextData) env.getContext()).getUser())).dataFetcher("collection", env -> {
String collectionId = (String) env.getArguments().get("collectionId");
if (collectionId != null && collectionId.endsWith("List")) {
collectionId = collectionId.substring(0, collectionId.length() - "List".length());
}
DataSetMetaData input = env.getSource();
ContextData context = env.getContext();
final User user = context.getUser().orElse(null);
final DataSet dataSet = dataSetRepository.getDataSet(user, input.getOwnerId(), input.getDataSetId()).get();
final TypeNameStore typeNameStore = dataSet.getTypeNameStore();
String collectionUri = typeNameStore.makeUri(collectionId);
if (dataSet.getSchemaStore().getStableTypes() == null || dataSet.getSchemaStore().getStableTypes().get(collectionUri) == null) {
return null;
} else {
return getCollection(dataSet, typeNameStore, dataSet.getSchemaStore().getStableTypes().get(collectionUri));
}
}).dataFetcher("dataSetId", env -> ((DataSetMetaData) env.getSource()).getCombinedId()).dataFetcher("dataSetName", env -> ((DataSetMetaData) env.getSource()).getDataSetId()).dataFetcher("ownerId", env -> ((DataSetMetaData) env.getSource()).getOwnerId()));
wiring.type("CurrentImportStatus", builder -> builder.dataFetcher("elapsedTime", env -> {
final String timeUnit = env.getArgument("unit");
return ((ImportStatus) env.getSource()).getElapsedTime(timeUnit);
}));
wiring.type("DataSetImportStatus", builder -> builder.dataFetcher("lastImportDuration", env -> {
final String timeUnit = env.getArgument("unit");
return ((DataSetImportStatus) env.getSource()).getLastImportDuration(timeUnit);
}));
wiring.type("EntryImportStatus", builder -> builder.dataFetcher("elapsedTime", env -> {
final String timeUnit = env.getArgument("unit");
return ((EntryImportStatus) env.getSource()).getElapsedTime(timeUnit);
}));
wiring.type("CollectionMetadata", builder -> builder.dataFetcher("indexConfig", env -> {
SubjectReference source = env.getSource();
final QuadStore qs = source.getDataSet().getQuadStore();
try (Stream<CursorQuad> quads = qs.getQuads(source.getSubjectUri(), TIM_HASINDEXERCONFIG, Direction.OUT, "")) {
final Map result = quads.findFirst().map(q -> {
try {
return objectMapper.readValue(q.getObject(), Map.class);
} catch (IOException e) {
LOG.error("Value not a Map", e);
return new HashMap<>();
}
}).orElse(new HashMap());
if (!result.containsKey("facet") || !(result.get("facet") instanceof List)) {
result.put("facet", new ArrayList<>());
}
if (!result.containsKey("fullText") || !(result.get("fullText") instanceof List)) {
result.put("fullText", new ArrayList<>());
}
return result;
}
}).dataFetcher("viewConfig", new ViewConfigFetcher(objectMapper)));
wiring.type("AboutMe", builder -> builder.dataFetcher("dataSets", env -> (Iterable) () -> dataSetRepository.getDataSetsWithWriteAccess(env.getSource()).stream().map(DataSetWithDatabase::new).iterator()).dataFetcher("dataSetMetadataList", env -> (Iterable) () -> {
Stream<DataSetWithDatabase> dataSets = dataSetRepository.getDataSets().stream().map(DataSetWithDatabase::new);
if (env.getArgument("ownOnly")) {
String userId = ((ContextData) env.getContext()).getUser().map(u -> "u" + u.getPersistentId()).orElse(null);
dataSets = dataSets.filter(d -> d.getOwnerId().equals(userId));
}
Permission permission = Permission.valueOf(env.getArgument("permission"));
if (permission != Permission.READ) {
// Read is implied
UserPermissionCheck check = ((ContextData) env.getContext()).getUserPermissionCheck();
dataSets = dataSets.filter(d -> check.getPermissions(d).contains(permission));
}
return dataSets.iterator();
}).dataFetcher("id", env -> ((User) env.getSource()).getPersistentId()).dataFetcher("name", env -> ((User) env.getSource()).getDisplayName()).dataFetcher("personalInfo", env -> "http://example.com").dataFetcher("canCreateDataSet", env -> true));
wiring.type("Mutation", builder -> builder.dataFetcher("setViewConfig", new ViewConfigMutation(dataSetRepository)).dataFetcher("setSummaryProperties", new SummaryPropsMutation(dataSetRepository)).dataFetcher("setIndexConfig", new IndexConfigMutation(dataSetRepository)).dataFetcher("createDataSet", new CreateDataSetMutation(dataSetRepository)).dataFetcher("deleteDataSet", new DeleteDataSetMutation(dataSetRepository)).dataFetcher("publish", new MakePublicMutation(dataSetRepository)).dataFetcher("extendSchema", new ExtendSchemaMutation(dataSetRepository)).dataFetcher("setDataSetMetadata", new DataSetMetadataMutation(dataSetRepository)).dataFetcher("setCollectionMetadata", new CollectionMetadataMutation(dataSetRepository)));
wiring.wiringFactory(wiringFactory);
StringBuilder root = new StringBuilder("type DataSets {\n sillyWorkaroundWhenNoDataSetsAreVisible: Boolean\n");
boolean[] dataSetAvailable = new boolean[] { false };
dataSetRepository.getDataSets().forEach(dataSet -> {
final DataSetMetaData dataSetMetaData = dataSet.getMetadata();
final String name = dataSetMetaData.getCombinedId();
Map<String, Type> types = dataSet.getSchemaStore().getStableTypes();
Map<String, List<ExplicitField>> customSchema = dataSet.getCustomSchema();
final Map<String, Type> customTypes = new HashMap<>();
for (Map.Entry<String, List<ExplicitField>> entry : customSchema.entrySet()) {
ExplicitType explicitType = new ExplicitType(entry.getKey(), entry.getValue());
customTypes.put(entry.getKey(), explicitType.convertToType());
}
Map<String, Type> mergedTypes;
MergeSchemas mergeSchemas = new MergeSchemas();
mergedTypes = mergeSchemas.mergeSchema(types, customTypes);
types = mergedTypes;
if (types != null) {
dataSetAvailable[0] = true;
root.append(" ").append(name).append(":").append(name).append(" @dataSet(userId:\"").append(dataSetMetaData.getOwnerId()).append("\", dataSetId:\"").append(dataSetMetaData.getDataSetId()).append("\")\n");
wiring.type(name, c -> c.dataFetcher("metadata", env -> new DataSetWithDatabase(dataSet)));
final String schema = typeGenerator.makeGraphQlTypes(name, types, dataSet.getTypeNameStore());
staticQuery.merge(schemaParser.parse(schema));
}
});
root.append("}\n\nextend type Query {\n #The actual dataSets\n dataSets: DataSets @passThrough\n}\n\n");
if (dataSetAvailable[0]) {
staticQuery.merge(schemaParser.parse(root.toString()));
}
SchemaGenerator schemaGenerator = new SchemaGenerator();
return schemaGenerator.makeExecutableSchema(staticQuery, wiring.build());
}
use of nl.knaw.huygens.timbuctoo.v5.graphql.mutations.Change.Value in project timbuctoo by HuygensING.
the class JsonProvenanceToRdfPatch method collectReplacements.
public static Map<String, List<CursorQuad>> collectReplacements(JsonNode activity, QuadStore quadStore) {
Map<String, List<CursorQuad>> toReplace = new HashMap<>();
for (JsonNode revision : activity.get(PROV_GENERATES)) {
final JsonNode replacements = revision.get(TIM_REPLACEMENTS);
if (replacements != null) {
String entity = revision.get(PROV_SPECIALIZATION_OF).get(0).get("@id").asText();
List<CursorQuad> quads = new ArrayList<>();
toReplace.put(revision.get("@id").asText(), quads);
for (JsonNode replacement : replacements) {
if (replacement.has(TIM_PREDICATE)) {
final String predicate = replacement.get(TIM_PREDICATE).get(0).get("@value").asText();
try (Stream<CursorQuad> source = quadStore.getQuads(entity, predicate, Direction.OUT, "")) {
source.forEach(quads::add);
}
}
}
}
}
return toReplace;
}
use of nl.knaw.huygens.timbuctoo.v5.graphql.mutations.Change.Value in project timbuctoo by HuygensING.
the class ViewConfigMutation method get.
@Override
public Object get(DataFetchingEnvironment env) {
String collectionUri = env.getArgument("collectionUri");
Object viewConfig = env.getArgument("viewConfig");
DataSet dataSet = MutationHelpers.getDataSet(env, dataSetRepository::getDataSet);
MutationHelpers.checkAdminPermissions(env, dataSet.getMetadata());
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);
}
}
use of nl.knaw.huygens.timbuctoo.v5.graphql.mutations.Change.Value in project timbuctoo by HuygensING.
the class JsonProvenanceToRdfPatchTest method retractsPreviousRevision.
@Test
public void retractsPreviousRevision() throws Exception {
String testRetractsRevision = "{\n" + " \"@type\":\"prov:Activity\",\n" + " \"http://www.w3.org/ns/prov#generates\":[\n" + " {\n" + " \"@type\":\"prov:Entity\",\n" + " \"@id\":\"_:b2\",\n" + " \"specializationOf\":{\n" + " \"@id\":\"http://example.com/the/actual/entitys\"\n" + " },\n" + " \"wasRevisionOf\":{\n" + " \"@id\":\"http://example.org/revision1\"\n" + " },\n" + " \"replacements\":[\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/revision1", PROV_SPECIALIZATION_OF, "http://example.com/the/actual/entitys", null).with("http://example.com/the/actual/entitys", TIM_LATEST_REVISION, "http://example.org/revision1");
JsonProvenanceToRdfPatch creator = fromCurrentState(new DocumentLoader(), testRetractsRevision, testQuadStore, EDITOR_URI, "test", CLOCK);
creator.sendQuads(basicRdfPatchSerializer, s -> {
}, null);
List<String> filteredResult = Lists.newArrayList(Collections2.filter(result, Predicates.containsPattern("latestRevision")));
assertThat(filteredResult, containsInAnyOrder("-<http://example.com/the/actual/entitys> <" + TIM_LATEST_REVISION + "> <http://example.org/revision1" + "> <" + defaultGraph + "> .\n", "+<http://example.com/the/actual/entitys> <" + TIM_LATEST_REVISION + "> <http://timbuctoo.huygens.knaw.nl/static/v5/skolemized/test/b1> <" + defaultGraph + "> .\n"));
}
use of nl.knaw.huygens.timbuctoo.v5.graphql.mutations.Change.Value in project timbuctoo by HuygensING.
the class SummaryPropDataRetrieverTest method createSummaryPropertyIgnoresValueTypesIfThePathIsLongerThanOne.
@Test
public void createSummaryPropertyIgnoresValueTypesIfThePathIsLongerThanOne() {
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.of(RdfConstants.STRING));
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 notBeRetrieved = quadWithObject(NOT_TO_BE_RETRIEVED, Optional.empty());
given(quadStore.getQuadsInGraph(OBJECT_1, DEFAULT_PATH_2, Direction.OUT, "", Optional.of(new Graph(GRAPH)))).willReturn(Stream.of(notBeRetrieved));
CursorQuad quadWithObjectUriOfPath2 = quadWithObject(OBJECT_OF_PATH2, Optional.empty());
given(quadStore.getQuadsInGraph(OBJECT_2, DEFAULT_PATH_2, Direction.OUT, "", Optional.of(new Graph(GRAPH)))).willReturn(Stream.of(quadWithObjectUriOfPath2));
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_2, DEFAULT_PATH_2, Direction.OUT, "", Optional.of(new Graph(GRAPH)));
verify(quadStore, never()).getQuadsInGraph(eq(NOT_TO_BE_RETRIEVED), anyString(), any(Direction.class), anyString(), eq(Optional.of(new Graph(GRAPH))));
}
Aggregations