Search in sources :

Example 1 with ExecutionListener

use of de.catma.backgroundservice.ExecutionListener in project catma by forTEXT.

the class GraphWorktreeProject method synchronizeWithRemote.

@Override
public void synchronizeWithRemote(OpenProjectListener openProjectListener) throws Exception {
    if (hasUncommittedChanges()) {
        throw new IllegalStateException("There are uncommitted changes that need to be committed first!");
    }
    for (TagsetDefinition tagset : getTagsets()) {
        gitProjectHandler.synchronizeTagsetWithRemote(tagset.getUuid());
    }
    for (SourceDocument document : getSourceDocuments()) {
        gitProjectHandler.synchronizeSourceDocumentWithRemote(document.getUuid());
        for (AnnotationCollectionReference collectionReference : document.getUserMarkupCollectionRefs()) {
            gitProjectHandler.synchronizeCollectionWithRemote(collectionReference.getId());
        }
    }
    gitProjectHandler.synchronizeWithRemote();
    if (gitProjectHandler.hasConflicts()) {
        gitProjectHandler.initAndUpdateSubmodules();
        openProjectListener.conflictResolutionNeeded(new GitConflictedProject(projectReference, gitProjectHandler, documentId -> getSourceDocumentURI(documentId)));
    } else {
        boolean forceGraphReload = gitProjectHandler.loadRolesPerResource();
        gitProjectHandler.initAndUpdateSubmodules();
        gitProjectHandler.removeStaleSubmoduleDirectories();
        gitProjectHandler.ensureDevBranches();
        rootRevisionHash = gitProjectHandler.getRootRevisionHash();
        ProgressListener progressListener = new ProgressListener() {

            @Override
            public void setProgress(String value, Object... args) {
                openProjectListener.progress(value, args);
            }
        };
        graphProjectHandler.ensureProjectRevisionIsLoaded(new ExecutionListener<TagManager>() {

            @Override
            public void error(Throwable t) {
                openProjectListener.failure(t);
            }

            @Override
            public void done(TagManager result) {
                tagManager.load(result.getTagLibrary());
                openProjectListener.ready(GraphWorktreeProject.this);
            }
        }, progressListener, rootRevisionHash, tagManager, () -> gitProjectHandler.getTagsets(), () -> gitProjectHandler.getDocuments(), (tagLibrary) -> gitProjectHandler.getCollections(tagLibrary, progressListener), forceGraphReload, backgroundService);
    }
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) Reply(de.catma.document.comment.Reply) LoadingCache(com.google.common.cache.LoadingCache) Status(org.eclipse.jgit.api.Status) UI(com.vaadin.ui.UI) IndexedProject(de.catma.indexer.IndexedProject) TermExtractor(de.catma.indexer.TermExtractor) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInfoProvider(de.catma.repository.git.graph.FileInfoProvider) ErrorHandler(de.catma.ui.module.main.ErrorHandler) Locale(java.util.Locale) Map(java.util.Map) DocumentChangeEvent(de.catma.project.event.DocumentChangeEvent) URI(java.net.URI) Path(java.nio.file.Path) CommitInfo(de.catma.project.CommitInfo) CATMAPropertyKey(de.catma.properties.CATMAPropertyKey) ExecutionListener(de.catma.backgroundservice.ExecutionListener) Collection(java.util.Collection) Set(java.util.Set) TagInstance(de.catma.tag.TagInstance) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) ProjectReference(de.catma.project.ProjectReference) TagReference(de.catma.document.annotation.TagReference) CacheLoader(com.google.common.cache.CacheLoader) List(java.util.List) PropertyChangeListener(java.beans.PropertyChangeListener) TPGraphProjectHandler(de.catma.repository.git.graph.tp.TPGraphProjectHandler) TagDefinition(de.catma.tag.TagDefinition) CacheBuilder(com.google.common.cache.CacheBuilder) ContentInfoSet(de.catma.document.source.ContentInfoSet) CollectionChangeEvent(de.catma.project.event.CollectionChangeEvent) RBACPermission(de.catma.rbac.RBACPermission) StatusPrinter(de.catma.repository.git.managers.StatusPrinter) PropertyDefinition(de.catma.tag.PropertyDefinition) TagManager(de.catma.tag.TagManager) CommentProvider(de.catma.repository.git.graph.CommentProvider) RBACRole(de.catma.rbac.RBACRole) MediaType(org.apache.tika.mime.MediaType) Multimap(com.google.common.collect.Multimap) Function(java.util.function.Function) User(de.catma.user.User) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) EventBus(com.google.common.eventbus.EventBus) CommentChangeEvent(de.catma.project.event.CommentChangeEvent) Comment(de.catma.document.comment.Comment) Charset(java.nio.charset.Charset) TeiTagLibrarySerializationHandler(de.catma.serialization.tei.TeiTagLibrarySerializationHandler) Member(de.catma.user.Member) StandardContentHandler(de.catma.document.source.contenthandler.StandardContentHandler) TagsetDefinition(de.catma.tag.TagsetDefinition) Pair(de.catma.util.Pair) IDGenerator(de.catma.util.IDGenerator) RBACSubject(de.catma.rbac.RBACSubject) TagLibrary(de.catma.tag.TagLibrary) PropertyChangeEvent(java.beans.PropertyChangeEvent) OpenProjectListener(de.catma.project.OpenProjectListener) TeiSerializationHandlerFactory(de.catma.serialization.tei.TeiSerializationHandlerFactory) RemovalNotification(com.google.common.cache.RemovalNotification) ProgressListener(de.catma.backgroundservice.ProgressListener) Property(de.catma.tag.Property) AnnotationCollectionReference(de.catma.document.annotation.AnnotationCollectionReference) TermInfo(de.catma.indexer.TermInfo) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) SourceDocument(de.catma.document.source.SourceDocument) AnnotationCollection(de.catma.document.annotation.AnnotationCollection) File(java.io.File) TagsetDefinitionImportStatus(de.catma.serialization.TagsetDefinitionImportStatus) TagManagerEvent(de.catma.tag.TagManager.TagManagerEvent) TagLibrarySerializationHandler(de.catma.serialization.TagLibrarySerializationHandler) Indexer(de.catma.indexer.Indexer) ChangeType(de.catma.project.event.ChangeType) GraphProjectHandler(de.catma.repository.git.graph.GraphProjectHandler) ReplyChangeEvent(de.catma.project.event.ReplyChangeEvent) Paths(java.nio.file.Paths) PropertyChangeSupport(java.beans.PropertyChangeSupport) RemovalListener(com.google.common.cache.RemovalListener) BackgroundService(de.catma.backgroundservice.BackgroundService) InputStream(java.io.InputStream) TeiUserMarkupCollectionDeserializer(de.catma.serialization.tei.TeiUserMarkupCollectionDeserializer) SourceDocument(de.catma.document.source.SourceDocument) AnnotationCollectionReference(de.catma.document.annotation.AnnotationCollectionReference) TagsetDefinition(de.catma.tag.TagsetDefinition) TagManager(de.catma.tag.TagManager) ProgressListener(de.catma.backgroundservice.ProgressListener)

Example 2 with ExecutionListener

use of de.catma.backgroundservice.ExecutionListener in project catma by forTEXT.

the class InspectContentStep method enter.

@Override
public void enter(boolean back) {
    if (back) {
        return;
    }
    @SuppressWarnings("unchecked") Collection<UploadFile> fileList = (Collection<UploadFile>) wizardContext.get(DocumentWizard.WizardContextKey.UPLOAD_FILE_LIST);
    contentPanel.setEnabled(false);
    progressBar.setVisible(true);
    progressBar.setIndeterminate(true);
    final ArrayList<UploadFile> files = new ArrayList<UploadFile>(fileList);
    BackgroundServiceProvider backgroundServiceProvider = (BackgroundServiceProvider) UI.getCurrent();
    backgroundServiceProvider.submit("inspecting-files", new DefaultProgressCallable<List<UploadFile>>() {

        @Override
        public List<UploadFile> call() throws Exception {
            Tika tika = new Tika();
            LanguageDetector languageDetector = LanguageDetector.getDefaultLanguageDetector();
            try {
                languageDetector.loadModels();
            } catch (IOException e) {
                ((ErrorHandler) UI.getCurrent()).showAndLogError("Error loading language detection models!", e);
            }
            for (UploadFile uploadFile : files) {
                if (uploadFile.getMimetype().equals(FileType.XML2.getMimeType())) {
                    XML2ContentHandler contentHandler = new XML2ContentHandler();
                    SourceDocumentInfo sourceDocumentInfo = new SourceDocumentInfo();
                    TechInfoSet techInfoSet = new TechInfoSet(uploadFile.getOriginalFilename(), uploadFile.getMimetype(), uploadFile.getTempFilename());
                    sourceDocumentInfo.setTechInfoSet(techInfoSet);
                    contentHandler.setSourceDocumentInfo(sourceDocumentInfo);
                    contentHandler.load();
                    String content = contentHandler.getContent();
                    LanguageResult languageResult = languageDetector.detect(content);
                    if (languageResult.isReasonablyCertain() && languageResult.getLanguage() != null) {
                        uploadFile.setLanguage(new LanguageItem(new Locale(languageResult.getLanguage())));
                    }
                } else {
                    Metadata metadata = new Metadata();
                    try {
                        try (FileInputStream fis = new FileInputStream(new File(uploadFile.getTempFilename()))) {
                            String content = tika.parseToString(fis, metadata);
                            String contentType = metadata.get(Metadata.CONTENT_TYPE);
                            MediaType mediaType = MediaType.parse(contentType);
                            String charset = mediaType.getParameters().get("charset");
                            if (charset != null) {
                                uploadFile.setCharset(Charset.forName(charset));
                            }
                            LanguageResult languageResult = languageDetector.detect(content);
                            if (languageResult.isReasonablyCertain() && languageResult.getLanguage() != null) {
                                uploadFile.setLanguage(new LanguageItem(new Locale(languageResult.getLanguage())));
                            }
                        }
                    } catch (Exception e) {
                        Logger.getLogger(InspectContentStep.class.getName()).log(Level.SEVERE, String.format("Error inspecting %1$s", uploadFile.getOriginalFilename()), e);
                        String errorMsg = e.getMessage();
                        if ((errorMsg == null) || (errorMsg.trim().isEmpty())) {
                            errorMsg = "";
                        }
                        Notification.show("Error", String.format("Error inspecting content of %1$s! " + "Adding this file to your Project might fail!\n The underlying error message was:\n%2$s", uploadFile.getOriginalFilename(), errorMsg), Type.ERROR_MESSAGE);
                    }
                }
            }
            return files;
        }
    }, new ExecutionListener<List<UploadFile>>() {

        @Override
        public void done(List<UploadFile> result) {
            contentPanel.setEnabled(true);
            progressBar.setVisible(false);
            progressBar.setIndeterminate(false);
            fileList.clear();
            fileList.addAll(result);
            fileDataProvider.refreshAll();
            if (!fileList.isEmpty()) {
                fileList.stream().findFirst().ifPresent(uploadFile -> {
                    fileGrid.select(uploadFile);
                    updatePreview(uploadFile);
                });
            }
            if (stepChangeListener != null) {
                stepChangeListener.stepChanged(InspectContentStep.this);
            }
        }

        @Override
        public void error(Throwable t) {
            Logger.getLogger(InspectContentStep.class.getName()).log(Level.SEVERE, "Error inspecting files", t);
            String errorMsg = t.getMessage();
            if ((errorMsg == null) || (errorMsg.trim().isEmpty())) {
                errorMsg = "";
            }
            Notification.show("Error", String.format("Error inspecting the contents! " + "\n The underlying error message was:\n%1$s", errorMsg), Type.ERROR_MESSAGE);
        }
    });
}
Also used : Locale(java.util.Locale) BackgroundServiceProvider(de.catma.backgroundservice.BackgroundServiceProvider) DefaultProgressCallable(de.catma.backgroundservice.DefaultProgressCallable) StepChangeListener(de.catma.ui.dialog.wizard.StepChangeListener) VerticalLayout(com.vaadin.ui.VerticalLayout) LanguageItem(de.catma.document.source.LanguageItem) ComboBox(com.vaadin.ui.ComboBox) UI(com.vaadin.ui.UI) LanguageDetector(org.apache.tika.language.detect.LanguageDetector) WizardContext(de.catma.ui.dialog.wizard.WizardContext) MediaType(org.apache.tika.mime.MediaType) ActionGridComponent(de.catma.ui.component.actiongrid.ActionGridComponent) ProgressStep(de.catma.ui.dialog.wizard.ProgressStep) TechInfoSet(de.catma.document.source.TechInfoSet) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) Binding(com.vaadin.data.Binder.Binding) Metadata(org.apache.tika.metadata.Metadata) Charset(java.nio.charset.Charset) CheckBox(com.vaadin.ui.CheckBox) Notification(com.vaadin.ui.Notification) ErrorHandler(de.catma.ui.module.main.ErrorHandler) Locale(java.util.Locale) Label(com.vaadin.ui.Label) ProgressBar(com.vaadin.ui.ProgressBar) TextArea(com.vaadin.ui.TextArea) ListDataProvider(com.vaadin.data.provider.ListDataProvider) ContentMode(com.vaadin.shared.ui.ContentMode) XML2ContentHandler(de.catma.document.source.contenthandler.XML2ContentHandler) ExecutionListener(de.catma.backgroundservice.ExecutionListener) Collection(java.util.Collection) IndexInfoSet(de.catma.document.source.IndexInfoSet) ProgressStepFactory(de.catma.ui.dialog.wizard.ProgressStepFactory) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Logger(java.util.logging.Logger) File(java.io.File) SourceDocumentInfo(de.catma.document.source.SourceDocumentInfo) List(java.util.List) Type(com.vaadin.ui.Notification.Type) HorizontalLayout(com.vaadin.ui.HorizontalLayout) FileType(de.catma.document.source.FileType) Tika(org.apache.tika.Tika) WizardStep(de.catma.ui.dialog.wizard.WizardStep) Collections(java.util.Collections) LanguageResult(org.apache.tika.language.detect.LanguageResult) Grid(com.vaadin.ui.Grid) SingleOptionInputDialog(de.catma.ui.dialog.SingleOptionInputDialog) LanguageResult(org.apache.tika.language.detect.LanguageResult) SourceDocumentInfo(de.catma.document.source.SourceDocumentInfo) ArrayList(java.util.ArrayList) BackgroundServiceProvider(de.catma.backgroundservice.BackgroundServiceProvider) Metadata(org.apache.tika.metadata.Metadata) Tika(org.apache.tika.Tika) MediaType(org.apache.tika.mime.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) TechInfoSet(de.catma.document.source.TechInfoSet) ErrorHandler(de.catma.ui.module.main.ErrorHandler) XML2ContentHandler(de.catma.document.source.contenthandler.XML2ContentHandler) IOException(java.io.IOException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) LanguageDetector(org.apache.tika.language.detect.LanguageDetector) Collection(java.util.Collection) LanguageItem(de.catma.document.source.LanguageItem) File(java.io.File)

Example 3 with ExecutionListener

use of de.catma.backgroundservice.ExecutionListener in project catma by forTEXT.

the class ProjectView method handleSaveDocumentWizardContext.

private void handleSaveDocumentWizardContext(final WizardContext result) {
    setEnabled(false);
    setProgressBarVisible(true);
    final UI ui = UI.getCurrent();
    BackgroundServiceProvider backgroundServiceProvider = (BackgroundServiceProvider) UI.getCurrent();
    BackgroundService backgroundService = backgroundServiceProvider.accuireBackgroundService();
    backgroundService.submit(new DefaultProgressCallable<Void>() {

        @SuppressWarnings("unchecked")
        @Override
        public Void call() throws Exception {
            IDGenerator idGenerator = new IDGenerator();
            boolean useApostropheAsSeparator = (Boolean) result.get(DocumentWizard.WizardContextKey.APOSTROPHE_AS_SEPARATOR);
            String collectionNamePattern = (String) result.get(DocumentWizard.WizardContextKey.COLLECTION_NAME_PATTERN);
            Collection<TagsetImport> tagsetImports = (Collection<TagsetImport>) result.get(DocumentWizard.WizardContextKey.TAGSET_IMPORT_LIST);
            Collection<UploadFile> uploadFiles = (Collection<UploadFile>) result.get(DocumentWizard.WizardContextKey.UPLOAD_FILE_LIST);
            if (tagsetImports == null) {
                tagsetImports = Collections.emptyList();
            }
            // Ignoring Tagsets
            tagsetImports.stream().filter(ti -> ti.getImportState().equals(TagsetImportState.WILL_BE_IGNORED)).forEach(tagsetImport -> {
                for (TagDefinition tag : tagsetImport.getExtractedTagset()) {
                    for (UploadFile uploadFile : uploadFiles) {
                        if (uploadFile.getIntrinsicMarkupCollection() != null) {
                            AnnotationCollection intrinsicMarkupCollection = uploadFile.getIntrinsicMarkupCollection();
                            intrinsicMarkupCollection.removeTagReferences(intrinsicMarkupCollection.getTagReferences(tag));
                        }
                    }
                }
            });
            getProgressListener().setProgress("Creating imported Tagsets");
            // Creating Tagsets
            tagsetImports.stream().filter(ti -> ti.getImportState().equals(TagsetImportState.WILL_BE_CREATED)).forEach(tagsetImport -> {
                getProgressListener().setProgress("Creating Tagset %1$s", tagsetImport.getTargetTagset().getName());
                ui.accessSynchronously(() -> {
                    if (project.getTagManager().getTagLibrary().getTagsetDefinition(tagsetImport.getTargetTagset().getUuid()) != null) {
                        // already imported, so it will be a merge
                        tagsetImport.setImportState(TagsetImportState.WILL_BE_MERGED);
                    } else {
                        TagsetDefinition extractedTagset = tagsetImport.getExtractedTagset();
                        try {
                            project.importTagsets(Collections.singletonList(new TagsetDefinitionImportStatus(extractedTagset, project.inProjectHistory(extractedTagset.getUuid()), project.getTagManager().getTagLibrary().getTagsetDefinition(extractedTagset.getUuid()) != null)));
                        } catch (Exception e) {
                            Logger.getLogger(ProjectView.class.getName()).log(Level.SEVERE, String.format("Error importing tagset %1$s with ID %2$s", extractedTagset.getName(), extractedTagset.getUuid()), e);
                            String errorMsg = e.getMessage();
                            if ((errorMsg == null) || (errorMsg.trim().isEmpty())) {
                                errorMsg = "";
                            }
                            Notification.show("Error", String.format("Error importing tagset %1$s! " + "This tagset will be skipped!\n The underlying error message was:\n%2$s", extractedTagset.getName(), errorMsg), Type.ERROR_MESSAGE);
                        }
                    }
                    ui.push();
                });
            });
            // Merging Tagsets
            tagsetImports.stream().filter(ti -> ti.getImportState().equals(TagsetImportState.WILL_BE_MERGED)).forEach(tagsetImport -> {
                getProgressListener().setProgress("Merging Tagset %1$s", tagsetImport.getTargetTagset().getName());
                ui.accessSynchronously(() -> {
                    TagsetDefinition targetTagset = project.getTagManager().getTagLibrary().getTagsetDefinition(tagsetImport.getTargetTagset().getUuid());
                    for (TagDefinition tag : tagsetImport.getExtractedTagset()) {
                        Optional<TagDefinition> optionalTag = targetTagset.getTagDefinitionsByName(tag.getName()).findFirst();
                        if (optionalTag.isPresent()) {
                            TagDefinition existingTag = optionalTag.get();
                            tag.getUserDefinedPropertyDefinitions().forEach(pd -> {
                                if (existingTag.getPropertyDefinition(pd.getName()) == null) {
                                    project.getTagManager().addUserDefinedPropertyDefinition(existingTag, new PropertyDefinition(pd));
                                }
                            });
                            for (UploadFile uploadFile : uploadFiles) {
                                if (uploadFile.getIntrinsicMarkupCollection() != null) {
                                    AnnotationCollection intrinsicMarkupCollection = uploadFile.getIntrinsicMarkupCollection();
                                    List<TagReference> tagReferences = intrinsicMarkupCollection.getTagReferences(tag);
                                    intrinsicMarkupCollection.removeTagReferences(tagReferences);
                                    Multimap<TagInstance, TagReference> referencesByInstance = ArrayListMultimap.create();
                                    tagReferences.forEach(tr -> referencesByInstance.put(tr.getTagInstance(), tr));
                                    for (TagInstance incomingTagInstance : referencesByInstance.keySet()) {
                                        TagInstance newTagInstance = new TagInstance(idGenerator.generate(), existingTag.getUuid(), incomingTagInstance.getAuthor(), incomingTagInstance.getTimestamp(), existingTag.getUserDefinedPropertyDefinitions(), targetTagset.getUuid());
                                        for (Property oldProp : incomingTagInstance.getUserDefinedProperties()) {
                                            String oldPropDefId = oldProp.getPropertyDefinitionId();
                                            PropertyDefinition oldPropDef = tag.getPropertyDefinitionByUuid(oldPropDefId);
                                            PropertyDefinition existingPropDef = existingTag.getPropertyDefinition(oldPropDef.getName());
                                            newTagInstance.addUserDefinedProperty(new Property(existingPropDef.getUuid(), oldProp.getPropertyValueList()));
                                        }
                                        ArrayList<TagReference> newReferences = new ArrayList<>();
                                        referencesByInstance.get(incomingTagInstance).forEach(tr -> {
                                            try {
                                                newReferences.add(new TagReference(newTagInstance, tr.getTarget().toString(), tr.getRange(), tr.getUserMarkupCollectionUuid()));
                                            } catch (URISyntaxException e) {
                                                e.printStackTrace();
                                            }
                                        });
                                        intrinsicMarkupCollection.addTagReferences(newReferences);
                                    }
                                }
                            }
                        } else {
                            tag.setTagsetDefinitionUuid(targetTagset.getUuid());
                            project.getTagManager().addTagDefinition(targetTagset, tag);
                        }
                    }
                    ui.push();
                });
            });
            // Importing docs and collections
            for (UploadFile uploadFile : uploadFiles) {
                getProgressListener().setProgress("Importing Document %1$s", uploadFile.getTitle());
                ui.accessSynchronously(() -> {
                    addUploadFile(uploadFile, useApostropheAsSeparator, collectionNamePattern);
                    ui.push();
                });
            }
            return null;
        }
    }, new ExecutionListener<Void>() {

        @Override
        public void done(Void result) {
            setProgressBarVisible(false);
            setEnabled(true);
        }

        @Override
        public void error(Throwable t) {
            setProgressBarVisible(false);
            setEnabled(true);
            errorHandler.showAndLogError("Error adding Documents", t);
        }
    }, progressListener);
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) BackgroundServiceProvider(de.catma.backgroundservice.BackgroundServiceProvider) HTMLNotification(de.catma.ui.component.HTMLNotification) Alignment(com.vaadin.ui.Alignment) IndexedProject(de.catma.indexer.IndexedProject) MembersChangedEvent(de.catma.ui.events.MembersChangedEvent) HeaderContextChangeEvent(de.catma.ui.events.HeaderContextChangeEvent) RouteToTagsEvent(de.catma.ui.events.routing.RouteToTagsEvent) TreeDataProvider(com.vaadin.data.provider.TreeDataProvider) TagsetImport(de.catma.ui.module.project.documentwizard.TagsetImport) DocumentChangeEvent(de.catma.project.event.DocumentChangeEvent) CorpusImporter(de.catma.ui.module.project.corpusimport.CorpusImporter) CommitInfo(de.catma.project.CommitInfo) ExecutionListener(de.catma.backgroundservice.ExecutionListener) MenuBar(com.vaadin.ui.MenuBar) VerticalFlexLayout(de.catma.ui.layout.VerticalFlexLayout) Set(java.util.Set) RBACConstraint(de.catma.rbac.RBACConstraint) TagInstance(de.catma.tag.TagInstance) CorpusImportDocumentMetadata(de.catma.ui.module.project.corpusimport.CorpusImportDocumentMetadata) ItemClick(com.vaadin.ui.Grid.ItemClick) Stream(java.util.stream.Stream) Type(com.vaadin.ui.Notification.Type) PropertyChangeListener(java.beans.PropertyChangeListener) SingleTextInputDialog(de.catma.ui.dialog.SingleTextInputDialog) CollectionChangeEvent(de.catma.project.event.CollectionChangeEvent) CanReloadAll(de.catma.ui.module.main.CanReloadAll) SelectionMode(com.vaadin.ui.Grid.SelectionMode) DocumentWizard(de.catma.ui.module.project.documentwizard.DocumentWizard) HugeCard(de.catma.ui.component.hugecard.HugeCard) ProjectChangedEvent(de.catma.ui.events.ProjectChangedEvent) DefaultProgressCallable(de.catma.backgroundservice.DefaultProgressCallable) TagManager(de.catma.tag.TagManager) com.vaadin.server(com.vaadin.server) LocalDateTime(java.time.LocalDateTime) WizardContext(de.catma.ui.dialog.wizard.WizardContext) ActionGridComponent(de.catma.ui.component.actiongrid.ActionGridComponent) ArrayList(java.util.ArrayList) Member(de.catma.user.Member) Pair(de.catma.util.Pair) TreeGridFactory(de.catma.ui.component.TreeGridFactory) SaveCancelListener(de.catma.ui.dialog.SaveCancelListener) Collator(java.text.Collator) ProgressListener(de.catma.backgroundservice.ProgressListener) XML2ContentHandler(de.catma.document.source.contenthandler.XML2ContentHandler) Property(de.catma.tag.Property) TreeData(com.vaadin.data.TreeData) IOException(java.io.IOException) SourceDocument(de.catma.document.source.SourceDocument) ProjectReadyEvent(de.catma.project.event.ProjectReadyEvent) AnnotationCollection(de.catma.document.annotation.AnnotationCollection) File(java.io.File) TagManagerEvent(de.catma.tag.TagManager.TagManagerEvent) Button(com.vaadin.ui.Button) ChangeType(de.catma.project.event.ChangeType) CRC32(java.util.zip.CRC32) HtmlRenderer(com.vaadin.ui.renderers.HtmlRenderer) Grid(com.vaadin.ui.Grid) MenuItem(com.vaadin.ui.MenuBar.MenuItem) GenericUploadDialog(de.catma.ui.dialog.GenericUploadDialog) URISyntaxException(java.net.URISyntaxException) UI(com.vaadin.ui.UI) FlexWrap(de.catma.ui.layout.FlexLayout.FlexWrap) ConfirmDialog(org.vaadin.dialogs.ConfirmDialog) SearchFilterProvider(de.catma.ui.component.actiongrid.SearchFilterProvider) RouteToAnalyzeEvent(de.catma.ui.events.routing.RouteToAnalyzeEvent) TikaContentHandler(de.catma.document.source.contenthandler.TikaContentHandler) ByteArrayInputStream(java.io.ByteArrayInputStream) HorizontalFlexLayout(de.catma.ui.layout.HorizontalFlexLayout) ErrorHandler(de.catma.ui.module.main.ErrorHandler) Locale(java.util.Locale) CatmaApplication(de.catma.ui.CatmaApplication) VaadinIcons(com.vaadin.icons.VaadinIcons) Version(de.catma.tag.Version) RouteToConflictedProjectEvent(de.catma.ui.events.routing.RouteToConflictedProjectEvent) ProgressBar(com.vaadin.ui.ProgressBar) IconButton(de.catma.ui.component.IconButton) CATMAPropertyKey(de.catma.properties.CATMAPropertyKey) Collection(java.util.Collection) TreeGrid(com.vaadin.ui.TreeGrid) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) SourceDocumentInfo(de.catma.document.source.SourceDocumentInfo) ProjectReference(de.catma.project.ProjectReference) TagReference(de.catma.document.annotation.TagReference) List(java.util.List) CloseSafe(de.catma.util.CloseSafe) Corpus(de.catma.document.corpus.Corpus) TagDefinition(de.catma.tag.TagDefinition) RBACConstraintEnforcer(de.catma.rbac.RBACConstraintEnforcer) RouteToAnnotateEvent(de.catma.ui.events.routing.RouteToAnnotateEvent) Optional(java.util.Optional) FileType(de.catma.document.source.FileType) RBACPermission(de.catma.rbac.RBACPermission) CorpusImportDialog(de.catma.ui.module.project.corpusimport.CorpusImportDialog) ProjectManager(de.catma.project.ProjectManager) PropertyDefinition(de.catma.tag.PropertyDefinition) UploadFile(de.catma.ui.module.project.documentwizard.UploadFile) RBACRole(de.catma.rbac.RBACRole) Multimap(com.google.common.collect.Multimap) Function(java.util.function.Function) User(de.catma.user.User) Level(java.util.logging.Level) HashSet(java.util.HashSet) EventBus(com.google.common.eventbus.EventBus) Charset(java.nio.charset.Charset) Notification(com.vaadin.ui.Notification) Label(com.vaadin.ui.Label) TagsetDefinition(de.catma.tag.TagsetDefinition) IDGenerator(de.catma.util.IDGenerator) Subscribe(com.google.common.eventbus.Subscribe) TagLibrary(de.catma.tag.TagLibrary) PropertyChangeEvent(java.beans.PropertyChangeEvent) OpenProjectListener(de.catma.project.OpenProjectListener) ListDataProvider(com.vaadin.data.provider.ListDataProvider) FileOSType(de.catma.document.source.FileOSType) ClickEvent(com.vaadin.ui.Button.ClickEvent) AnnotationCollectionReference(de.catma.document.annotation.AnnotationCollectionReference) Project(de.catma.project.Project) RepositoryChangeEvent(de.catma.project.Project.RepositoryChangeEvent) ConflictedProject(de.catma.project.conflict.ConflictedProject) TagsetDefinitionImportStatus(de.catma.serialization.TagsetDefinitionImportStatus) ContextMenu(com.vaadin.contextmenu.ContextMenu) SourceContentHandler(de.catma.document.source.contenthandler.SourceContentHandler) TagsetImportState(de.catma.ui.module.project.documentwizard.TagsetImportState) BOMFilterInputStream(de.catma.document.source.contenthandler.BOMFilterInputStream) DateTimeFormatter(java.time.format.DateTimeFormatter) HierarchicalQuery(com.vaadin.data.provider.HierarchicalQuery) Parameter(de.catma.ui.Parameter) Comparator(java.util.Comparator) Collections(java.util.Collections) BackgroundService(de.catma.backgroundservice.BackgroundService) InputStream(java.io.InputStream) Component(com.vaadin.ui.Component) TagsetImport(de.catma.ui.module.project.documentwizard.TagsetImport) TagDefinition(de.catma.tag.TagDefinition) BackgroundService(de.catma.backgroundservice.BackgroundService) BackgroundServiceProvider(de.catma.backgroundservice.BackgroundServiceProvider) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) UI(com.vaadin.ui.UI) ArrayList(java.util.ArrayList) List(java.util.List) Property(de.catma.tag.Property) AnnotationCollection(de.catma.document.annotation.AnnotationCollection) Optional(java.util.Optional) PropertyDefinition(de.catma.tag.PropertyDefinition) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) TagsetDefinition(de.catma.tag.TagsetDefinition) ArrayListMultimap(com.google.common.collect.ArrayListMultimap) Multimap(com.google.common.collect.Multimap) UploadFile(de.catma.ui.module.project.documentwizard.UploadFile) TagInstance(de.catma.tag.TagInstance) AnnotationCollection(de.catma.document.annotation.AnnotationCollection) Collection(java.util.Collection) TagReference(de.catma.document.annotation.TagReference) TagsetDefinitionImportStatus(de.catma.serialization.TagsetDefinitionImportStatus) IDGenerator(de.catma.util.IDGenerator)

Example 4 with ExecutionListener

use of de.catma.backgroundservice.ExecutionListener in project catma by forTEXT.

the class AnalyzeView method executeSearch.

private void executeSearch(String searchInput, Consumer<QueryResultPanel> addToLayoutFunction) {
    QueryOptions queryOptions = new QueryOptions(new QueryId(searchInput), currentCorpus.getDocumentIds(), currentCorpus.getCollectionIds(), indexInfoSet.getUnseparableCharacterSequences(), indexInfoSet.getUserDefinedSeparatingCharacters(), indexInfoSet.getLocale(), project);
    QueryJob job = new QueryJob(searchInput, queryOptions);
    showProgress(true);
    ((BackgroundServiceProvider) UI.getCurrent()).submit("Searching...", job, new ExecutionListener<QueryResult>() {

        public void done(QueryResult result) {
            try {
                QueryResultPanel queryResultPanel = new QueryResultPanel(project, result, new QueryId(searchInput.toString()), kwicProviderCache, closingPanel -> handleRemoveQueryResultPanel(closingPanel));
                addToLayoutFunction.accept(queryResultPanel);
                addQueryResultPanelSetting(queryResultPanel.getQueryResultPanelSetting());
            } finally {
                showProgress(false);
            }
        }

        public void error(Throwable t) {
            showProgress(false);
            if (t instanceof QueryException) {
                QueryJob.QueryException qe = (QueryJob.QueryException) t;
                String input = qe.getInput();
                int idx = ((RecognitionException) qe.getCause()).charPositionInLine;
                if ((idx >= 0) && (input.length() > idx)) {
                    char character = input.charAt(idx);
                    String message = MessageFormat.format("<html><p>There is something wrong with your query <b>{0}</b> approximately at positon {1} character <b>{2}</b>.</p> <p>If you are unsure about how to construct a query try the Query Builder!</p></html>", input, idx + 1, character);
                    HTMLNotification.show("Info", message, Type.TRAY_NOTIFICATION);
                } else {
                    String message = MessageFormat.format("<html><p>There is something wrong with your query <b>{0}</b>.</p> <p>If you are unsure about how to construct a query try the Query Builder!</p></html>", input);
                    HTMLNotification.show("Info", message, Type.TRAY_NOTIFICATION);
                }
            } else {
                ((ErrorHandler) UI.getCurrent()).showAndLogError("Error during search!", t);
            }
        }
    });
}
Also used : ThemeResource(com.vaadin.server.ThemeResource) Panel(com.vaadin.ui.Panel) BackgroundServiceProvider(de.catma.backgroundservice.BackgroundServiceProvider) HTMLNotification(de.catma.ui.component.HTMLNotification) LoadingCache(com.google.common.cache.LoadingCache) WordCloudDisplaySettingHandler(de.catma.ui.module.analyze.visualization.vega.WordCloudDisplaySettingHandler) Alignment(com.vaadin.ui.Alignment) UI(com.vaadin.ui.UI) IndexedProject(de.catma.indexer.IndexedProject) KwicProvider(de.catma.indexer.KwicProvider) RecognitionException(org.antlr.runtime.RecognitionException) ErrorHandler(de.catma.ui.module.main.ErrorHandler) Locale(java.util.Locale) SliderPanel(org.vaadin.sliderpanel.SliderPanel) VaadinIcons(com.vaadin.icons.VaadinIcons) QueryId(de.catma.queryengine.QueryId) ProgressBar(com.vaadin.ui.ProgressBar) IconButton(de.catma.ui.component.IconButton) ExecutionListener(de.catma.backgroundservice.ExecutionListener) QueryOptions(de.catma.queryengine.QueryOptions) IndexInfoSet(de.catma.document.source.IndexInfoSet) ClosableTab(de.catma.ui.component.tabbedview.ClosableTab) QueryBuilder(de.catma.ui.module.analyze.querybuilder.QueryBuilder) MarginInfo(com.vaadin.shared.ui.MarginInfo) List(java.util.List) Type(com.vaadin.ui.Notification.Type) Corpus(de.catma.document.corpus.Corpus) RefreshQueryResultPanel(de.catma.ui.module.analyze.queryresultpanel.RefreshQueryResultPanel) Optional(java.util.Optional) SliderPanelBuilder(org.vaadin.sliderpanel.SliderPanelBuilder) QueryJob(de.catma.queryengine.QueryJob) SliderMode(org.vaadin.sliderpanel.client.SliderMode) KwicPanel(de.catma.ui.module.analyze.visualization.kwic.KwicPanel) FormatStyle(java.time.format.FormatStyle) QueryResultPanelSetting(de.catma.ui.module.analyze.queryresultpanel.QueryResultPanelSetting) DoubleTreePanel(de.catma.ui.module.analyze.visualization.doubletree.DoubleTreePanel) QueryResultPanel(de.catma.ui.module.analyze.queryresultpanel.QueryResultPanel) VerticalLayout(com.vaadin.ui.VerticalLayout) LocalDateTime(java.time.LocalDateTime) ComboBox(com.vaadin.ui.ComboBox) WizardContext(de.catma.ui.dialog.wizard.WizardContext) DistributionDisplaySettingHandler(de.catma.ui.module.analyze.visualization.vega.DistributionDisplaySettingHandler) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) EventBus(com.google.common.eventbus.EventBus) MaterialTheme(com.github.appreciated.material.MaterialTheme) Notification(com.vaadin.ui.Notification) VegaPanel(de.catma.ui.module.analyze.visualization.vega.VegaPanel) Label(com.vaadin.ui.Label) ClassResource(com.vaadin.server.ClassResource) SaveCancelListener(de.catma.ui.dialog.SaveCancelListener) QueryException(de.catma.queryengine.QueryJob.QueryException) AnalyzeResourcePanel(de.catma.ui.module.analyze.resourcepanel.AnalyzeResourcePanel) ListDataProvider(com.vaadin.data.provider.ListDataProvider) QueryResult(de.catma.queryengine.result.QueryResult) Iterator(java.util.Iterator) Consumer(java.util.function.Consumer) Button(com.vaadin.ui.Button) HorizontalLayout(com.vaadin.ui.HorizontalLayout) TabCaptionChangeListener(de.catma.ui.component.tabbedview.TabCaptionChangeListener) DateTimeFormatter(java.time.format.DateTimeFormatter) QueryTree(de.catma.queryengine.querybuilder.QueryTree) Collections(java.util.Collections) Component(com.vaadin.ui.Component) QueryResult(de.catma.queryengine.result.QueryResult) QueryException(de.catma.queryengine.QueryJob.QueryException) QueryJob(de.catma.queryengine.QueryJob) RefreshQueryResultPanel(de.catma.ui.module.analyze.queryresultpanel.RefreshQueryResultPanel) QueryResultPanel(de.catma.ui.module.analyze.queryresultpanel.QueryResultPanel) QueryId(de.catma.queryengine.QueryId) BackgroundServiceProvider(de.catma.backgroundservice.BackgroundServiceProvider) QueryOptions(de.catma.queryengine.QueryOptions)

Example 5 with ExecutionListener

use of de.catma.backgroundservice.ExecutionListener in project catma by forTEXT.

the class GraphWorktreeProject method open.

@Override
public void open(OpenProjectListener openProjectListener) {
    try {
        logger.info(String.format("Opening Project %1$s with ID %2$s", projectReference.getName(), projectReference.getProjectId()));
        this.rootRevisionHash = gitProjectHandler.getRootRevisionHash();
        logger.info(String.format("Revision Hash for Project %1$s is %2$s", projectReference.getProjectId(), this.rootRevisionHash));
        this.gitProjectHandler.loadRolesPerResource();
        logger.info(String.format("Checking for conflicts in Project %1$s", projectReference.getProjectId()));
        if (gitProjectHandler.hasConflicts()) {
            gitProjectHandler.initAndUpdateSubmodules();
            openProjectListener.conflictResolutionNeeded(new GitConflictedProject(projectReference, gitProjectHandler, documentId -> getSourceDocumentURI(documentId)));
        } else {
            gitProjectHandler.initAndUpdateSubmodules();
            gitProjectHandler.removeStaleSubmoduleDirectories();
            gitProjectHandler.ensureDevBranches();
            gitProjectHandler.verifyCollections();
            ProgressListener progressListener = new ProgressListener() {

                @Override
                public void setProgress(String value, Object... args) {
                    logger.info(String.format(value, args));
                    openProjectListener.progress(value, args);
                }
            };
            graphProjectHandler.ensureProjectRevisionIsLoaded(new ExecutionListener<TagManager>() {

                @Override
                public void error(Throwable t) {
                    openProjectListener.failure(t);
                }

                @Override
                public void done(TagManager result) {
                    logger.info(String.format("Loading Tag library for Project %1$s", projectReference.getProjectId()));
                    tagManager.load(result.getTagLibrary());
                    initTagManagerListeners();
                    logger.info(String.format("Project %1$s is loaded.", projectReference.getProjectId()));
                    openProjectListener.ready(GraphWorktreeProject.this);
                }
            }, progressListener, rootRevisionHash, tagManager, () -> gitProjectHandler.getTagsets(), () -> gitProjectHandler.getDocuments(), (tagLibrary) -> gitProjectHandler.getCollections(tagLibrary, progressListener), // forceGraphReload
            false, backgroundService);
        }
    } catch (Exception e) {
        openProjectListener.failure(e);
    }
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) Reply(de.catma.document.comment.Reply) LoadingCache(com.google.common.cache.LoadingCache) Status(org.eclipse.jgit.api.Status) UI(com.vaadin.ui.UI) IndexedProject(de.catma.indexer.IndexedProject) TermExtractor(de.catma.indexer.TermExtractor) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInfoProvider(de.catma.repository.git.graph.FileInfoProvider) ErrorHandler(de.catma.ui.module.main.ErrorHandler) Locale(java.util.Locale) Map(java.util.Map) DocumentChangeEvent(de.catma.project.event.DocumentChangeEvent) URI(java.net.URI) Path(java.nio.file.Path) CommitInfo(de.catma.project.CommitInfo) CATMAPropertyKey(de.catma.properties.CATMAPropertyKey) ExecutionListener(de.catma.backgroundservice.ExecutionListener) Collection(java.util.Collection) Set(java.util.Set) TagInstance(de.catma.tag.TagInstance) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) ProjectReference(de.catma.project.ProjectReference) TagReference(de.catma.document.annotation.TagReference) CacheLoader(com.google.common.cache.CacheLoader) List(java.util.List) PropertyChangeListener(java.beans.PropertyChangeListener) TPGraphProjectHandler(de.catma.repository.git.graph.tp.TPGraphProjectHandler) TagDefinition(de.catma.tag.TagDefinition) CacheBuilder(com.google.common.cache.CacheBuilder) ContentInfoSet(de.catma.document.source.ContentInfoSet) CollectionChangeEvent(de.catma.project.event.CollectionChangeEvent) RBACPermission(de.catma.rbac.RBACPermission) StatusPrinter(de.catma.repository.git.managers.StatusPrinter) PropertyDefinition(de.catma.tag.PropertyDefinition) TagManager(de.catma.tag.TagManager) CommentProvider(de.catma.repository.git.graph.CommentProvider) RBACRole(de.catma.rbac.RBACRole) MediaType(org.apache.tika.mime.MediaType) Multimap(com.google.common.collect.Multimap) Function(java.util.function.Function) User(de.catma.user.User) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) EventBus(com.google.common.eventbus.EventBus) CommentChangeEvent(de.catma.project.event.CommentChangeEvent) Comment(de.catma.document.comment.Comment) Charset(java.nio.charset.Charset) TeiTagLibrarySerializationHandler(de.catma.serialization.tei.TeiTagLibrarySerializationHandler) Member(de.catma.user.Member) StandardContentHandler(de.catma.document.source.contenthandler.StandardContentHandler) TagsetDefinition(de.catma.tag.TagsetDefinition) Pair(de.catma.util.Pair) IDGenerator(de.catma.util.IDGenerator) RBACSubject(de.catma.rbac.RBACSubject) TagLibrary(de.catma.tag.TagLibrary) PropertyChangeEvent(java.beans.PropertyChangeEvent) OpenProjectListener(de.catma.project.OpenProjectListener) TeiSerializationHandlerFactory(de.catma.serialization.tei.TeiSerializationHandlerFactory) RemovalNotification(com.google.common.cache.RemovalNotification) ProgressListener(de.catma.backgroundservice.ProgressListener) Property(de.catma.tag.Property) AnnotationCollectionReference(de.catma.document.annotation.AnnotationCollectionReference) TermInfo(de.catma.indexer.TermInfo) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) SourceDocument(de.catma.document.source.SourceDocument) AnnotationCollection(de.catma.document.annotation.AnnotationCollection) File(java.io.File) TagsetDefinitionImportStatus(de.catma.serialization.TagsetDefinitionImportStatus) TagManagerEvent(de.catma.tag.TagManager.TagManagerEvent) TagLibrarySerializationHandler(de.catma.serialization.TagLibrarySerializationHandler) Indexer(de.catma.indexer.Indexer) ChangeType(de.catma.project.event.ChangeType) GraphProjectHandler(de.catma.repository.git.graph.GraphProjectHandler) ReplyChangeEvent(de.catma.project.event.ReplyChangeEvent) Paths(java.nio.file.Paths) PropertyChangeSupport(java.beans.PropertyChangeSupport) RemovalListener(com.google.common.cache.RemovalListener) BackgroundService(de.catma.backgroundservice.BackgroundService) InputStream(java.io.InputStream) TeiUserMarkupCollectionDeserializer(de.catma.serialization.tei.TeiUserMarkupCollectionDeserializer) TagManager(de.catma.tag.TagManager) ProgressListener(de.catma.backgroundservice.ProgressListener) IOException(java.io.IOException)

Aggregations

UI (com.vaadin.ui.UI)5 ExecutionListener (de.catma.backgroundservice.ExecutionListener)5 EventBus (com.google.common.eventbus.EventBus)4 IndexedProject (de.catma.indexer.IndexedProject)4 ErrorHandler (de.catma.ui.module.main.ErrorHandler)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Locale (java.util.Locale)4 LoadingCache (com.google.common.cache.LoadingCache)3 ArrayListMultimap (com.google.common.collect.ArrayListMultimap)3 Multimap (com.google.common.collect.Multimap)3 ListDataProvider (com.vaadin.data.provider.ListDataProvider)3 Label (com.vaadin.ui.Label)3 Notification (com.vaadin.ui.Notification)3 Type (com.vaadin.ui.Notification.Type)3 ProgressBar (com.vaadin.ui.ProgressBar)3 BackgroundService (de.catma.backgroundservice.BackgroundService)3 BackgroundServiceProvider (de.catma.backgroundservice.BackgroundServiceProvider)3 ProgressListener (de.catma.backgroundservice.ProgressListener)3 AnnotationCollection (de.catma.document.annotation.AnnotationCollection)3