use of de.catma.ui.CatmaApplication in project catma by forTEXT.
the class ProjectView method initActions.
private void initActions() {
documentGridComponent.setSearchFilterProvider(searchInput -> createSearchFilter(searchInput));
documentGrid.addItemClickListener(itemClickEvent -> handleResourceItemClick(itemClickEvent));
ContextMenu addContextMenu = documentGridComponent.getActionGridBar().getBtnAddContextMenu();
MenuItem addDocumentBtn = addContextMenu.addItem("Add Document", clickEvent -> handleAddDocumentRequest());
addDocumentBtn.setEnabled(false);
rbacEnforcer.register(RBACConstraint.ifAuthorized(role -> (project.hasPermission(role, RBACPermission.DOCUMENT_CREATE_OR_UPLOAD)), () -> addDocumentBtn.setEnabled(true)));
MenuItem addCollectionBtn = addContextMenu.addItem("Add Annotation Collection", e -> handleAddCollectionRequest());
addCollectionBtn.setEnabled(false);
rbacEnforcer.register(RBACConstraint.ifAuthorized(role -> (project.hasPermission(role, RBACPermission.COLLECTION_CREATE)), () -> addCollectionBtn.setEnabled(true)));
ContextMenu documentsGridMoreOptionsContextMenu = documentGridComponent.getActionGridBar().getBtnMoreOptionsContextMenu();
MenuItem editDocBtn = documentsGridMoreOptionsContextMenu.addItem("Edit Documents / Collections", (menuItem) -> handleEditResources());
editDocBtn.setEnabled(false);
rbacEnforcer.register(RBACConstraint.ifAuthorized(role -> (project.hasPermission(role, RBACPermission.COLLECTION_DELETE_OR_EDIT) || project.hasPermission(role, RBACPermission.DOCUMENT_DELETE_OR_EDIT)), () -> editDocBtn.setEnabled(true)));
MenuItem deleteDocsBtn = documentsGridMoreOptionsContextMenu.addItem("Delete Documents / Collections", (menuItem) -> handleDeleteResources(menuItem, documentGrid));
deleteDocsBtn.setEnabled(false);
rbacEnforcer.register(RBACConstraint.ifAuthorized(role -> (project.hasPermission(role, RBACPermission.COLLECTION_DELETE_OR_EDIT) || project.hasPermission(role, RBACPermission.DOCUMENT_DELETE_OR_EDIT)), () -> deleteDocsBtn.setEnabled(true)));
documentsGridMoreOptionsContextMenu.addItem("Analyze Documents / Collections", (menuItem) -> handleAnalyzeResources(menuItem, documentGrid));
documentsGridMoreOptionsContextMenu.addItem("Import a Collection", mi -> handleImportCollectionRequest());
MenuItem miExportCollections = documentsGridMoreOptionsContextMenu.addItem("Export Documents & Collections");
StreamResource collectionXmlExportResource = new StreamResource(new CollectionXMLExportStreamSource(() -> getSelectedDocuments(), () -> documentGrid.getSelectedItems().stream().filter(resource -> resource.isCollection()).map(resource -> ((CollectionResource) resource).getCollectionReference()).collect(Collectors.toList()), () -> project), "CATMA-Corpus_Export-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) + ".tar.gz");
collectionXmlExportResource.setCacheTime(0);
collectionXmlExportResource.setMIMEType("application/gzip");
FileDownloader collectionXmlExportFileDownloader = new FileDownloader(collectionXmlExportResource);
collectionXmlExportFileDownloader.extend(miExportCollections);
documentsGridMoreOptionsContextMenu.addItem("Select filtered entries", mi -> handleSelectFilteredDocuments());
tagsetGridComponent.getActionGridBar().addBtnAddClickListener(click -> handleAddTagsetRequest());
tagsetGridComponent.getActionGridBar().setAddBtnEnabled(false);
rbacEnforcer.register(RBACConstraint.ifAuthorized(role -> project.hasPermission(role, RBACPermission.TAGSET_CREATE_OR_UPLOAD), () -> tagsetGridComponent.getActionGridBar().setAddBtnEnabled(true)));
ContextMenu moreOptionsMenu = tagsetGridComponent.getActionGridBar().getBtnMoreOptionsContextMenu();
MenuItem editTagset = moreOptionsMenu.addItem("Edit Tagset", mi -> handleEditTagsetRequest());
editTagset.setEnabled(false);
rbacEnforcer.register(RBACConstraint.ifAuthorized(role -> (project.hasPermission(role, RBACPermission.TAGSET_DELETE_OR_EDIT)), () -> editTagset.setEnabled(true)));
MenuItem deleteTagSetBtn = moreOptionsMenu.addItem("Delete Tagset", mi -> handleDeleteTagsetRequest());
deleteTagSetBtn.setEnabled(false);
rbacEnforcer.register(RBACConstraint.ifAuthorized(role -> (project.hasPermission(role, RBACPermission.TAGSET_DELETE_OR_EDIT)), () -> deleteTagSetBtn.setEnabled(true)));
MenuItem importTagSetBtn = moreOptionsMenu.addItem("Import Tagsets", mi -> handleImportTagsetsRequest());
importTagSetBtn.setEnabled(false);
rbacEnforcer.register(RBACConstraint.ifAuthorized(role -> (project.hasPermission(role, RBACPermission.TAGSET_CREATE_OR_UPLOAD)), () -> importTagSetBtn.setEnabled(true)));
MenuItem miExportTagsets = moreOptionsMenu.addItem("Export Tagsets");
MenuItem miExportTagsetsAsXML = miExportTagsets.addItem("as XML");
StreamResource tagsetXmlExportResource = new StreamResource(new TagsetXMLExportStreamSource(() -> tagsetGrid.getSelectedItems(), () -> project), "CATMA-Tag-Library_Export-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) + ".xml");
tagsetXmlExportResource.setCacheTime(0);
tagsetXmlExportResource.setMIMEType("text/xml");
FileDownloader tagsetXmlExportFileDownloader = new FileDownloader(tagsetXmlExportResource);
tagsetXmlExportFileDownloader.extend(miExportTagsetsAsXML);
MenuItem miExportTagsetsAsCSV = miExportTagsets.addItem("as CSV");
StreamResource tagsetCsvExportResource = new StreamResource(new TagsetCSVExportStreamSource(() -> tagsetGrid.getSelectedItems(), () -> project), "CATMA-Tag-Library_Export-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) + ".csv");
tagsetCsvExportResource.setCacheTime(0);
tagsetCsvExportResource.setMIMEType("text/comma-separated-values");
FileDownloader tagsetCsvExportFileDownloader = new FileDownloader(tagsetCsvExportResource);
tagsetCsvExportFileDownloader.extend(miExportTagsetsAsCSV);
moreOptionsMenu.addItem("Fork Tagsets into another Project", miForkTagset -> handleForkTagsetRequest());
ContextMenu hugeCardMoreOptions = getMoreOptionsContextMenu();
hugeCardMoreOptions.addItem("Commit all changes", mi -> handleCommitRequest());
hugeCardMoreOptions.addItem("Synchronize with the team", mi -> handleSynchronizeRequest());
hugeCardMoreOptions.addSeparator();
hugeCardMoreOptions.addItem("Share project resources (experimental API)", mi -> handleShareProjectResources());
MenuItem miImportCorpus = hugeCardMoreOptions.addItem("Import CATMA 5 Corpus", mi -> handleCorpusImport());
miImportCorpus.setVisible(CATMAPropertyKey.EXPERT.getValue(false) || Boolean.valueOf(((CatmaApplication) UI.getCurrent()).getParameter(Parameter.EXPERT, Boolean.FALSE.toString())));
btSynchBell.addClickListener(event -> handleBtSynchBellClick(event));
// TODO:
// hugeCardMoreOptions.addItem("Print status", e -> project.printStatus());
tagsetGridComponent.setSearchFilterProvider(new SearchFilterProvider<TagsetDefinition>() {
@Override
public SerializablePredicate<TagsetDefinition> createSearchFilter(final String searchInput) {
return new SerializablePredicate<TagsetDefinition>() {
@Override
public boolean test(TagsetDefinition t) {
if (t != null) {
String name = t.getName();
if (name != null) {
return name.toLowerCase().contains(searchInput.toLowerCase());
}
}
return false;
}
};
}
});
tagsetGrid.addItemClickListener(clickEvent -> handleTagsetClick(clickEvent));
}
use of de.catma.ui.CatmaApplication in project catma by forTEXT.
the class ProjectView method handleImportTagsetsRequest.
private void handleImportTagsetsRequest() {
GenericUploadDialog uploadDialog = new GenericUploadDialog("Upload a Tag Library with one or more Tagsets:", new SaveCancelListener<byte[]>() {
public void savePressed(byte[] result) {
InputStream is = new ByteArrayInputStream(result);
try {
if (BOMFilterInputStream.hasBOM(result)) {
is = new BOMFilterInputStream(is, // $NON-NLS-1$
Charset.forName("UTF-8"));
}
List<TagsetDefinitionImportStatus> tagsetDefinitionImportStatusList = project.loadTagLibrary(is);
TagsetImportDialog tagsetImportDialog = new TagsetImportDialog(tagsetDefinitionImportStatusList, new SaveCancelListener<List<TagsetDefinitionImportStatus>>() {
@Override
public void savePressed(List<TagsetDefinitionImportStatus> result) {
try {
project.importTagsets(result);
} catch (IOException e) {
((CatmaApplication) UI.getCurrent()).showAndLogError("Error importing Tagsets", e);
}
}
});
tagsetImportDialog.show();
} catch (IOException e) {
((CatmaApplication) UI.getCurrent()).showAndLogError("Error loading external Tagsets", e);
} finally {
CloseSafe.close(is);
}
}
});
uploadDialog.show();
}
use of de.catma.ui.CatmaApplication in project catma by forTEXT.
the class UploadStep method handleZipFile.
private void handleZipFile(UploadFile uploadFile) throws IOException {
URI uri = uploadFile.getTempFilename();
ZipFile zipFile = new ZipFile(uri.getPath());
Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
String tempDir = ((CatmaApplication) UI.getCurrent()).accquirePersonalTempFolder();
IDGenerator idGenerator = new IDGenerator();
while (entries.hasMoreElements()) {
ZipArchiveEntry entry = entries.nextElement();
String fileName = FilenameUtils.getName(entry.getName());
if (fileName.startsWith(".")) {
// we treat them as hidden files, that's probably what most users would expect
continue;
}
final String fileId = idGenerator.generateDocumentId();
File entryDestination = new File(tempDir, fileId);
if (entryDestination.exists()) {
entryDestination.delete();
}
entryDestination.getParentFile().mkdirs();
if (entry.isDirectory()) {
entryDestination.mkdirs();
} else {
try (BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(entryDestination))) {
IOUtils.copy(bis, bos);
}
try (FileInputStream fis = new FileInputStream(entryDestination)) {
String type = tika.detect(fis, fileName);
UploadFile extractedUploadFile = new UploadFile(fileId, entryDestination.toURI(), fileName, type, entry.getSize());
fileList.add(extractedUploadFile);
fileDataProvider.refreshAll();
stepChangeListener.stepChanged(this);
}
}
}
ZipFile.closeQuietly(zipFile);
}
use of de.catma.ui.CatmaApplication in project catma by forTEXT.
the class UploadStep method fetchFileURL.
private void fetchFileURL() {
if (urlInputField.getValue() != null && !urlInputField.getValue().trim().isEmpty()) {
String urlValue = urlInputField.getValue();
try {
if (urlValue.toLowerCase().startsWith("www")) {
// $NON-NLS-1$
// $NON-NLS-1$
urlValue = "http://" + urlValue;
}
URL url = new URL(urlValue);
urlInputField.setValue("");
URLConnection conn = url.openConnection();
String urlConnContentEncoding = conn.getContentEncoding();
final String fileId = idGenerator.generateDocumentId();
String tempDir = ((CatmaApplication) UI.getCurrent()).accquirePersonalTempFolder();
final File tempFile = new File(new File(tempDir), fileId);
if (tempFile.exists()) {
tempFile.delete();
}
final String originalFilename = urlValue;
progressBar.setIndeterminate(true);
progressBar.setVisible(true);
BackgroundServiceProvider backgroundServiceProvider = (BackgroundServiceProvider) UI.getCurrent();
backgroundServiceProvider.submit("fetch URL", new DefaultProgressCallable<Long>() {
@Override
public Long call() throws Exception {
ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
FileChannel outChannel = fos.getChannel();
outChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
return outChannel.size();
}
}
}, new ExecutionListener<Long>() {
@Override
public void done(Long result) {
try {
progressBar.setVisible(false);
progressBar.setIndeterminate(false);
UploadFile uploadFile = new UploadFile(fileId, tempFile.toURI(), originalFilename, urlConnContentEncoding, result);
String type = urlConnContentEncoding;
Metadata metadata = new Metadata();
if (url.getFile() != null && !url.getFile().isEmpty()) {
metadata.set(Metadata.RESOURCE_NAME_KEY, url.getFile());
}
MediaType mediaType = MediaType.parse(uploadFile.getMimetype());
if (mediaType != null) {
metadata.set(Metadata.CONTENT_TYPE, mediaType.toString());
}
try (FileInputStream fis = new FileInputStream(tempFile)) {
tika.parseToString(fis, metadata);
}
mediaType = MediaType.parse(metadata.get("Content-Type"));
uploadFile.setEncoding(mediaType.getParameters().get("charset"));
uploadFile.setMimetype(metadata.get("Content-Type"));
if (type != null && type.toLowerCase().trim().equals(FileType.ZIP.getMimeType())) {
handleZipFile(uploadFile);
} else {
fileList.add(uploadFile);
fileDataProvider.refreshAll();
stepChangeListener.stepChanged(UploadStep.this);
}
} catch (Exception e) {
e.printStackTrace();
String errorMsg = e.getMessage();
if ((errorMsg == null) || (errorMsg.trim().isEmpty())) {
errorMsg = "";
}
Notification.show("Error", String.format("Error loading %1$s, file will be skipped!\n%2$s", originalFilename, errorMsg), Type.WARNING_MESSAGE);
}
}
@Override
public void error(Throwable t) {
t.printStackTrace();
progressBar.setVisible(false);
progressBar.setIndeterminate(false);
String errorMsg = t.getMessage();
if ((errorMsg == null) || (errorMsg.trim().isEmpty())) {
errorMsg = "";
}
Notification.show("Error", String.format("Error loading %1$s, file will be skipped!\n" + "This can happen for a lot of reasons, e. g. archive providers block third party access to their archives " + " or problems with a SSL connection. Try to download the file with your browser and then use the upload mechanism\n\n" + "The underlying error was:" + "\n%2$s", originalFilename, errorMsg), Type.WARNING_MESSAGE);
}
});
} catch (Exception e) {
e.printStackTrace();
String errorMsg = e.getMessage();
if ((errorMsg == null) || (errorMsg.trim().isEmpty())) {
errorMsg = "";
}
Notification.show("Error", String.format("Error loading %1$s, file will be skipped!\n" + "This can happen for a lot of reasons, e. g. archive providers block third party access to ther archives " + " or problems with SSL. Try to download the file with your browser and then use the upload mechanism\n" + "The underlying error was:" + "\n%2$s", urlValue, errorMsg), Type.WARNING_MESSAGE);
}
}
}
use of de.catma.ui.CatmaApplication in project catma by forTEXT.
the class TaggerView method initData.
private void initData(final AfterDocumentLoadedOperation afterDocumentLoadedOperation) {
if (sourceDocument != null) {
// loading of the Document is done in an extra step,
// because of a client side rendering racing condition which prevents the first page to be displayed
final UI ui = UI.getCurrent();
((CatmaApplication) ui).submit("Load Document", new DefaultProgressCallable<Void>() {
@Override
public Void call() throws Exception {
ui.accessSynchronously(() -> {
try {
linesPerPageSlider.setEnabled(true);
btAnalyze.setEnabled(project instanceof IndexedProject);
pagerComponent.setEnabled(true);
TaggerView.this.comments.clear();
TaggerView.this.comments.addAll(TaggerView.this.project.getComments(sourceDocument.getUuid()));
tagger.setText(sourceDocument.getContent(), TaggerView.this.comments);
totalLineCount = pager.getTotalLineCount();
try {
linesPerPageSlider.setValue((100.0 / totalLineCount) * maxPageLengthInLines);
} catch (ValueOutOfBoundsException toBeIgnored) {
}
List<AnnotationCollectionReference> collectionReferences = resourcePanel.getSelectedAnnotationCollectionReferences();
userMarkupCollectionManager.clear();
for (AnnotationCollectionReference collectionRef : collectionReferences) {
AnnotationCollection collection = project.getUserMarkupCollection(collectionRef);
userMarkupCollectionManager.add(collection);
}
Collection<TagsetDefinition> tagsets = new HashSet<>(resourcePanel.getSelectedTagsets());
annotationPanel.setData(sourceDocument, tagsets, new ArrayList<>(userMarkupCollectionManager.getUserMarkupCollections()));
if (taggerContextMenu != null) {
taggerContextMenu.setTagsets(tagsets);
}
if (afterDocumentLoadedOperation != null) {
afterDocumentLoadedOperation.afterDocumentLoaded(TaggerView.this);
}
ui.push();
} catch (IOException e) {
errorHandler.showAndLogError("Error showing the Document!", e);
}
});
return null;
}
}, new ExecutionListener<Void>() {
@Override
public void done(Void result) {
/*noop*/
}
@Override
public void error(Throwable t) {
errorHandler.showAndLogError("Error showing the Document!", t);
}
});
} else {
linesPerPageSlider.setEnabled(false);
btAnalyze.setEnabled(false);
pagerComponent.setEnabled(false);
}
}
Aggregations