Search in sources :

Example 6 with DataSet

use of nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet in project timbuctoo by HuygensING.

the class ImportManager method processLogsUntil.

private synchronized ImportStatus processLogsUntil(int maxIndex) {
    importStatus.start(this.getClass().getSimpleName() + ".processLogs", null);
    ListIterator<LogEntry> unprocessed = logListStore.getData().getUnprocessed();
    boolean dataWasAdded = false;
    while (unprocessed.hasNext() && unprocessed.nextIndex() <= maxIndex) {
        int index = unprocessed.nextIndex();
        LogEntry entry = unprocessed.next();
        importStatus.startEntry(entry);
        if (entry.getLogToken().isPresent()) {
            // logToken
            String logToken = entry.getLogToken().get();
            try (CachedLog log = logStorage.getLog(logToken)) {
                final Stopwatch stopwatch = Stopwatch.createStarted();
                for (RdfProcessor processor : subscribedProcessors) {
                    if (processor.getCurrentVersion() <= index) {
                        String msg = "******* " + processor.getClass().getSimpleName() + " Started importing full log...";
                        LOG.info(msg);
                        importStatus.setStatus(msg);
                        RdfParser rdfParser = serializerFactory.makeRdfParser(log);
                        processor.start(index);
                        rdfParser.importRdf(log, entry.getBaseUri(), entry.getDefaultGraph(), processor);
                        processor.commit();
                    }
                }
                long elapsedTime = stopwatch.elapsed(TimeUnit.SECONDS);
                String msg = "Finished importing. Total import took " + elapsedTime + " seconds.";
                LOG.info(msg);
                importStatus.setStatus(msg);
                dataWasAdded = true;
            } catch (Exception e) {
                LOG.error("Processing log failed", e);
                importStatus.addError("Processing log failed", e);
            }
            // Update the log, even after RdfProcessingFailedException | IOException
            try {
                logListStore.updateData(logList -> {
                    logList.markAsProcessed(index);
                    return logList;
                });
            } catch (IOException e) {
                LOG.error("Updating the log failed", e);
                importStatus.addError("Updating log failed", e);
            }
        } else {
            // no logToken
            RdfCreator creator = entry.getRdfCreator().get();
            String token = "";
            MediaType mediaType;
            Optional<Charset> charset;
            File tempFile = null;
            try {
                tempFile = File.createTempFile("log_to_generate", "nq");
                try (OutputStream stream = new GZIPOutputStream(new FileOutputStream(tempFile))) {
                    if (creator instanceof PlainRdfCreator) {
                        try (RdfSerializer serializer = serializerFactory.makeRdfSerializer(stream)) {
                            mediaType = serializer.getMediaType();
                            charset = Optional.of(serializer.getCharset());
                            ((PlainRdfCreator) creator).sendQuads(serializer, dataSet, importStatus::setStatus);
                        } catch (Exception e) {
                            LOG.error("Log generation failed", e);
                            importStatus.addError("Log generation failed", e);
                            break;
                        }
                    } else {
                        try (RdfPatchSerializer srlzr = serializerFactory.makeRdfPatchSerializer(stream, entry.getBaseUri())) {
                            mediaType = srlzr.getMediaType();
                            charset = Optional.of(srlzr.getCharset());
                            ((PatchRdfCreator) creator).sendQuads(srlzr, importStatus::setStatus, dataSet);
                        } catch (Exception e) {
                            LOG.error("Log generation failed", e);
                            importStatus.addError("Log generation failed", e);
                            break;
                        }
                    }
                }
                try (InputStream inputStream = new GZIPInputStream(new FileInputStream(tempFile))) {
                    token = logStorage.saveLog(inputStream, "log_generated_by_" + creator.getClass().getSimpleName(), mediaType, charset);
                }
                LogEntry entryWithLog;
                entryWithLog = LogEntry.addLogToEntry(entry, token);
                unprocessed.set(entryWithLog);
                token = "";
                // move back to process this item again
                unprocessed.previous();
            } catch (Exception e) {
                if (token.isEmpty()) {
                    LOG.error("Log processing failed", e);
                } else {
                    LOG.error("Log processing failed. Log created but not added to the list!", e);
                }
                importStatus.addError("Log processing failed", e);
                break;
            } finally {
                if (tempFile != null) {
                    tempFile.delete();
                }
            }
        }
        // end else with no condition
        importStatus.finishEntry();
    }
    // end main while loop
    if (dataWasAdded) {
        webhooks.run();
    }
    importStatus.finishList();
    // update log.json
    try {
        logListStore.updateData(Function.identity());
    } catch (IOException e) {
        LOG.error("Updating the log failed", e);
        importStatus.addError("Updating log failed", e);
    }
    return importStatus;
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) Stopwatch(com.google.common.base.Stopwatch) GZIPInputStream(java.util.zip.GZIPInputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) MediaType(javax.ws.rs.core.MediaType) CachedLog(nl.knaw.huygens.timbuctoo.v5.filestorage.dto.CachedLog) LogEntry(nl.knaw.huygens.timbuctoo.v5.dataset.dto.LogEntry) GZIPInputStream(java.util.zip.GZIPInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) IOException(java.io.IOException) LogStorageFailedException(nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.LogStorageFailedException) IOException(java.io.IOException) FileStorageFailedException(nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.FileStorageFailedException) FileInputStream(java.io.FileInputStream) RdfSerializer(nl.knaw.huygens.timbuctoo.v5.rdfio.RdfSerializer) RdfPatchSerializer(nl.knaw.huygens.timbuctoo.v5.rdfio.RdfPatchSerializer) FileOutputStream(java.io.FileOutputStream) RdfCreator(nl.knaw.huygens.timbuctoo.v5.dataset.dto.RdfCreator) CachedFile(nl.knaw.huygens.timbuctoo.v5.filestorage.dto.CachedFile) File(java.io.File) RdfParser(nl.knaw.huygens.timbuctoo.v5.rdfio.RdfParser)

Example 7 with DataSet

use of nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet in project timbuctoo by HuygensING.

the class RsDocumentBuilder method getCapabilityList.

/**
 * Get the capability list for the dataSet denoted by <code>ownerId</code> and <code>dataSetId</code>.
 * The {@link Optional} is empty if the dataSet is not published and the given <code>user</code> == <code>null</code>
 * or has no read access for the dataSet or the dataSet does not exist.
 *
 * @param user User that requests the list, may be <code>null</code>
 * @param ownerId ownerId
 * @param dataSetId dataSetId
 * @return the capability list for the dataSet denoted by <code>ownerId</code> and <code>dataSetId</code>
 */
public Optional<Urlset> getCapabilityList(@Nullable User user, String ownerId, String dataSetId) {
    Urlset capabilityList = null;
    Optional<DataSet> maybeDataSet = dataSetRepository.getDataSet(user, ownerId, dataSetId);
    if (maybeDataSet.isPresent()) {
        RsMd rsMd = new RsMd(Capability.CAPABILITYLIST.xmlValue);
        capabilityList = new Urlset(rsMd).addLink(new RsLn(REL_UP, rsUriHelper.uriForWellKnownResourceSync()));
        DataSetMetaData dataSetMetaData = maybeDataSet.get().getMetadata();
        String descriptionUrl = rsUriHelper.uriForRsDocument(dataSetMetaData, DESCRIPTION_FILENAME);
        capabilityList.addLink(new RsLn(REL_DESCRIBED_BY, descriptionUrl).withType(DESCRIPTION_TYPE));
        String loc = rsUriHelper.uriForRsDocument(dataSetMetaData, Capability.RESOURCELIST);
        UrlItem item = new UrlItem(loc).withMetadata(new RsMd(Capability.RESOURCELIST.xmlValue));
        capabilityList.addItem(item);
    }
    return Optional.ofNullable(capabilityList);
}
Also used : DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) RsLn(nl.knaw.huygens.timbuctoo.remote.rs.xml.RsLn) Urlset(nl.knaw.huygens.timbuctoo.remote.rs.xml.Urlset) DataSetMetaData(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSetMetaData) UrlItem(nl.knaw.huygens.timbuctoo.remote.rs.xml.UrlItem) RsMd(nl.knaw.huygens.timbuctoo.remote.rs.xml.RsMd)

Example 8 with DataSet

use of nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet 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());
}
Also used : CursorQuad(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.CursorQuad) DataSetRepository(nl.knaw.huygens.timbuctoo.v5.dataset.DataSetRepository) ImmutableProperty(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.ImmutableProperty) ExplicitType(nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.ExplicitType) Type(nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Type) MakePublicMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.MakePublicMutation) LoggerFactory(org.slf4j.LoggerFactory) ExtendSchemaMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.ExtendSchemaMutation) DerivedSchemaTypeGenerator(nl.knaw.huygens.timbuctoo.v5.graphql.derivedschema.DerivedSchemaTypeGenerator) DeleteDataSetMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.DeleteDataSetMutation) SubjectReference(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.SubjectReference) Map(java.util.Map) SummaryPropsMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.SummaryPropsMutation) ImmutableCollectionMetadataList(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.ImmutableCollectionMetadataList) TypeNameStore(nl.knaw.huygens.timbuctoo.v5.datastores.prefixstore.TypeNameStore) ImmutablePropertyList(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.ImmutablePropertyList) ViewConfigFetcher(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.ViewConfigFetcher) CreateDataSetMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.CreateDataSetMutation) RootData(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.RootData) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) Collectors(java.util.stream.Collectors) Resources.getResource(com.google.common.io.Resources.getResource) List(java.util.List) Stream(java.util.stream.Stream) DataSetMetaData(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSetMetaData) ExplicitField(nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.ExplicitField) Optional(java.util.Optional) Direction(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.Direction) RdfWiringFactory(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.RdfWiringFactory) ImportStatus(nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus) CollectionMetadata(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.CollectionMetadata) SupportedExportFormats(nl.knaw.huygens.timbuctoo.v5.dropwizard.SupportedExportFormats) CollectionMetadataList(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.CollectionMetadataList) DataSetImportStatus(nl.knaw.huygens.timbuctoo.v5.dataset.DataSetImportStatus) Tuple(nl.knaw.huygens.timbuctoo.util.Tuple) HashMap(java.util.HashMap) QuadStore(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore) Supplier(java.util.function.Supplier) ContextData(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.ContextData) ArrayList(java.util.ArrayList) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) SchemaParser(graphql.schema.idl.SchemaParser) ImmutableStringList(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.ImmutableStringList) GraphQLSchema(graphql.schema.GraphQLSchema) ImmutableCollectionMetadata(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.ImmutableCollectionMetadata) Charsets(com.google.common.base.Charsets) ViewConfigMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.ViewConfigMutation) Logger(org.slf4j.Logger) UserPermissionCheck(nl.knaw.huygens.timbuctoo.v5.graphql.security.UserPermissionCheck) Resources(com.google.common.io.Resources) MimeTypeDescription(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.MimeTypeDescription) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) MergeSchemas(nl.knaw.huygens.timbuctoo.v5.graphql.customschema.MergeSchemas) Property(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.Property) IOException(java.io.IOException) DataSetWithDatabase(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.DataSetWithDatabase) EntryImportStatus(nl.knaw.huygens.timbuctoo.v5.dataset.dto.EntryImportStatus) TIM_HASINDEXERCONFIG(nl.knaw.huygens.timbuctoo.v5.util.RdfConstants.TIM_HASINDEXERCONFIG) Permission(nl.knaw.huygens.timbuctoo.v5.security.dto.Permission) IndexConfigMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.IndexConfigMutation) RuntimeWiring(graphql.schema.idl.RuntimeWiring) DataSetMetadataMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.DataSetMetadataMutation) CollectionMetadataMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.CollectionMetadataMutation) SchemaGenerator(graphql.schema.idl.SchemaGenerator) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) Collections(java.util.Collections) MergeSchemas(nl.knaw.huygens.timbuctoo.v5.graphql.customschema.MergeSchemas) QuadStore(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) HashMap(java.util.HashMap) TypeNameStore(nl.knaw.huygens.timbuctoo.v5.datastores.prefixstore.TypeNameStore) ViewConfigMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.ViewConfigMutation) Permission(nl.knaw.huygens.timbuctoo.v5.security.dto.Permission) ContextData(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.ContextData) Stream(java.util.stream.Stream) ImmutableCollectionMetadataList(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.ImmutableCollectionMetadataList) ImmutablePropertyList(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.ImmutablePropertyList) List(java.util.List) CollectionMetadataList(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.CollectionMetadataList) ArrayList(java.util.ArrayList) ImmutableStringList(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.ImmutableStringList) MakePublicMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.MakePublicMutation) ExplicitType(nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.ExplicitType) Optional(java.util.Optional) RootData(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.RootData) IndexConfigMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.IndexConfigMutation) RuntimeWiring(graphql.schema.idl.RuntimeWiring) DataSetWithDatabase(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.DataSetWithDatabase) DataSetMetaData(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSetMetaData) Map(java.util.Map) HashMap(java.util.HashMap) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) CollectionMetadataMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.CollectionMetadataMutation) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) SubjectReference(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.SubjectReference) DeleteDataSetMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.DeleteDataSetMutation) CursorQuad(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.CursorQuad) CreateDataSetMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.CreateDataSetMutation) DataSetMetadataMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.DataSetMetadataMutation) ExtendSchemaMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.ExtendSchemaMutation) SchemaGenerator(graphql.schema.idl.SchemaGenerator) IOException(java.io.IOException) ViewConfigFetcher(nl.knaw.huygens.timbuctoo.v5.graphql.rootquery.dataproviders.ViewConfigFetcher) ExplicitType(nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.ExplicitType) Type(nl.knaw.huygens.timbuctoo.v5.datastores.schemastore.dto.Type) SummaryPropsMutation(nl.knaw.huygens.timbuctoo.v5.graphql.mutations.SummaryPropsMutation) UserPermissionCheck(nl.knaw.huygens.timbuctoo.v5.graphql.security.UserPermissionCheck)

Example 9 with DataSet

use of nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet in project timbuctoo by HuygensING.

the class RdfWiringFactory method getDataFetcher.

@Override
public DataFetcher getDataFetcher(FieldWiringEnvironment environment) {
    if (environment.getFieldDefinition().getDirective("passThrough") != null) {
        return DataFetchingEnvironment::getSource;
    } else if (environment.getFieldDefinition().getDirective("related") != null) {
        final Directive directive = environment.getFieldDefinition().getDirective("related");
        String source = ((StringValue) directive.getArgument("source").getValue()).getValue();
        String predicate = ((StringValue) directive.getArgument("predicate").getValue()).getValue();
        String direction = ((StringValue) directive.getArgument("direction").getValue()).getValue();
        return new CollectionFetcherWrapper(argumentsHelper, new RelationsOfSubjectDataFetcher(source, predicate, Direction.valueOf(direction)));
    } else if (environment.getFieldDefinition().getDirective("fromCollection") != null) {
        final Directive directive = environment.getFieldDefinition().getDirective("fromCollection");
        String uri = ((StringValue) directive.getArgument("uri").getValue()).getValue();
        boolean listAll = ((BooleanValue) directive.getArgument("listAll").getValue()).isValue();
        if (listAll) {
            return new CollectionFetcherWrapper(argumentsHelper, new CollectionDataFetcher(uri));
        } else {
            return lookupFetcher;
        }
    } else if (environment.getFieldDefinition().getDirective("rdf") != null) {
        final Directive directive = environment.getFieldDefinition().getDirective("rdf");
        String uri = ((StringValue) directive.getArgument("predicate").getValue()).getValue();
        Direction direction = valueOf(((StringValue) directive.getArgument("direction").getValue()).getValue());
        boolean isList = ((BooleanValue) directive.getArgument("isList").getValue()).isValue();
        boolean isObject = ((BooleanValue) directive.getArgument("isObject").getValue()).isValue();
        boolean isValue = ((BooleanValue) directive.getArgument("isValue").getValue()).isValue();
        if (isObject && isValue) {
            return new DataFetcherWrapper(argumentsHelper, isList, new UnionDataFetcher(uri, direction));
        } else {
            if (isObject) {
                return new DataFetcherWrapper(argumentsHelper, isList, new RelationDataFetcher(uri, direction));
            } else {
                return new DataFetcherWrapper(argumentsHelper, isList, new TypedLiteralDataFetcher(uri));
            }
        }
    } else if (environment.getFieldDefinition().getDirective("uri") != null) {
        return uriFetcher;
    } else if (environment.getFieldDefinition().getDirective("dataSet") != null) {
        final Directive directive = environment.getFieldDefinition().getDirective("dataSet");
        String userId = ((StringValue) directive.getArgument("userId").getValue()).getValue();
        String dataSetId = ((StringValue) directive.getArgument("dataSetId").getValue()).getValue();
        final DataSet dataSet = dataSetRepository.unsafeGetDataSetWithoutCheckingPermissions(userId, dataSetId).orElse(null);
        return dataFetchingEnvironment -> new DatabaseResult() {

            @Override
            public DataSet getDataSet() {
                return dataSet;
            }
        };
    } else if (environment.getFieldDefinition().getDirective("entityTitle") != null) {
        return entityTitleFetcher;
    } else if (environment.getFieldDefinition().getDirective("entityDescription") != null) {
        return entityDescriptionFetcher;
    } else if (environment.getFieldDefinition().getDirective("entityImage") != null) {
        return entityImageFetcher;
    }
    return null;
}
Also used : CollectionDataFetcher(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.berkeleydb.datafetchers.CollectionDataFetcher) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) DatabaseResult(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.DatabaseResult) RelationsOfSubjectDataFetcher(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.berkeleydb.datafetchers.RelationsOfSubjectDataFetcher) TypedLiteralDataFetcher(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.berkeleydb.datafetchers.TypedLiteralDataFetcher) Direction(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.Direction) BooleanValue(graphql.language.BooleanValue) UnionDataFetcher(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.berkeleydb.datafetchers.UnionDataFetcher) StringValue(graphql.language.StringValue) Directive(graphql.language.Directive) RelationDataFetcher(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.berkeleydb.datafetchers.RelationDataFetcher)

Example 10 with DataSet

use of nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet in project timbuctoo by HuygensING.

the class SummaryPropDataRetriever method createSummaryProperty.

public Optional<TypedValue> createSummaryProperty(SubjectReference source, DataSet dataSet) {
    QuadStore quadStore = dataSet.getQuadStore();
    final Optional<TypedValue> localConfiguredSummaryProp = getQuad(quadStore, source.getSubjectUri(), RdfConstants.RDF_TYPE).flatMap(collection -> getQuad(quadStore, collection.getObject(), summaryPropConfigPredicate)).flatMap(userConfigured -> {
        try {
            SummaryProp summaryProp = OBJECT_MAPPER.readValue(userConfigured.getObject(), SummaryProp.class);
            return getQuad(summaryProp.getPath(), source.getSubjectUri(), quadStore).map(quad -> createTypedValue(quad, dataSet));
        } catch (IOException e) {
            LOG.error("Cannot parse SummaryProp: '{}'", userConfigured.getObject());
        }
        return Optional.empty();
    });
    if (localConfiguredSummaryProp.isPresent()) {
        return localConfiguredSummaryProp;
    } else {
        // fallback to default summary props
        for (SummaryProp prop : defaultProperties) {
            Optional<CursorQuad> quad = getQuad(prop.getPath(), source.getSubjectUri(), quadStore);
            if (quad.isPresent()) {
                return Optional.of(createTypedValue(quad.get(), dataSet));
            }
        }
        return Optional.empty();
    }
}
Also used : CursorQuad(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.CursorQuad) TypedValue(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.TypedValue) SummaryProp(nl.knaw.huygens.timbuctoo.v5.graphql.defaultconfiguration.SummaryProp) Logger(org.slf4j.Logger) RdfConstants(nl.knaw.huygens.timbuctoo.v5.util.RdfConstants) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) QuadStore(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore) SubjectReference(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.SubjectReference) GuavaModule(com.fasterxml.jackson.datatype.guava.GuavaModule) List(java.util.List) Stream(java.util.stream.Stream) Optional(java.util.Optional) Direction(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.Direction) DataSet(nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet) QuadStore(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.QuadStore) CursorQuad(nl.knaw.huygens.timbuctoo.v5.datastores.quadstore.dto.CursorQuad) SummaryProp(nl.knaw.huygens.timbuctoo.v5.graphql.defaultconfiguration.SummaryProp) IOException(java.io.IOException) TypedValue(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.TypedValue)

Aggregations

DataSet (nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSet)44 DataSetRepository (nl.knaw.huygens.timbuctoo.v5.dataset.DataSetRepository)12 DataSetMetaData (nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSetMetaData)12 User (nl.knaw.huygens.timbuctoo.v5.security.dto.User)12 Test (org.junit.Test)12 IOException (java.io.IOException)11 LogStorageFailedException (nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.LogStorageFailedException)11 Map (java.util.Map)10 GraphQLFieldDefinition (graphql.schema.GraphQLFieldDefinition)7 GraphQLFieldsContainer (graphql.schema.GraphQLFieldsContainer)7 List (java.util.List)7 Optional (java.util.Optional)7 ExecutionException (java.util.concurrent.ExecutionException)7 Logger (org.slf4j.Logger)7 LoggerFactory (org.slf4j.LoggerFactory)7 HashMap (java.util.HashMap)6 Collectors (java.util.stream.Collectors)6 ImportManager (nl.knaw.huygens.timbuctoo.v5.dataset.ImportManager)6 ImportStatus (nl.knaw.huygens.timbuctoo.v5.dataset.ImportStatus)6 DataStoreCreationException (nl.knaw.huygens.timbuctoo.v5.dataset.exceptions.DataStoreCreationException)6