use of de.catma.backgroundservice.BackgroundServiceProvider 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.backgroundservice.BackgroundServiceProvider in project catma by forTEXT.
the class ImportIntrinsicMarkupStep method enter.
@Override
public void enter(boolean back) {
if (back) {
return;
}
contentPanel.setEnabled(false);
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
@SuppressWarnings("unchecked") final ArrayList<UploadFile> files = new ArrayList<UploadFile>(((Collection<UploadFile>) wizardContext.get(DocumentWizard.WizardContextKey.UPLOAD_FILE_LIST)).stream().filter(uploadFile -> uploadFile.getMimetype().equals(FileType.XML2.getMimeType())).collect(Collectors.toList()));
final TagManager tagmanager = new TagManager(new TagLibrary());
BackgroundServiceProvider backgroundServiceProvider = (BackgroundServiceProvider) UI.getCurrent();
backgroundServiceProvider.submit("inspecting-intrinsic-markup", new DefaultProgressCallable<List<UploadFile>>() {
@Override
public List<UploadFile> call() throws Exception {
IDGenerator idGenerator = new IDGenerator();
for (UploadFile uploadFile : files) {
XML2ContentHandler contentHandler = new XML2ContentHandler();
SourceDocument doc = new SourceDocument(uploadFile.getUuid(), contentHandler);
SourceDocumentInfo documentInfo = new SourceDocumentInfo();
TechInfoSet techInfoSet = new TechInfoSet();
techInfoSet.setURI(uploadFile.getTempFilename());
documentInfo.setTechInfoSet(techInfoSet);
contentHandler.setSourceDocumentInfo(documentInfo);
XmlMarkupCollectionSerializationHandler handler = new XmlMarkupCollectionSerializationHandler(tagmanager, contentHandler, project.getUser().getIdentifier());
try (FileInputStream fis = new FileInputStream(new File(uploadFile.getTempFilename()))) {
AnnotationCollection collection = handler.deserialize(doc, idGenerator.generateCollectionId(), fis);
uploadFile.setIntrinsicMarkupCollection(collection);
}
}
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();
tagsetImportList.clear();
String defaultIntrinsicXMLElmentsName = "Default Intrinsic XML Elements";
for (TagsetDefinition tagset : tagmanager.getTagLibrary()) {
if (!tagset.isEmpty()) {
TagsetDefinition targetTagset = project.getTagManager().getTagLibrary().getTagsetDefinition(tagset.getUuid());
boolean inProject = false;
if (targetTagset == null) {
targetTagset = tagset;
} else {
inProject = true;
}
String namespace = tagset.getName() == null ? "none" : tagset.getName();
if (tagset.getName() == null) {
tagset.setName(defaultIntrinsicXMLElmentsName);
}
TagsetImport tagsetImport = new TagsetImport(namespace, tagset, targetTagset, inProject ? TagsetImportState.WILL_BE_MERGED : TagsetImportState.WILL_BE_CREATED);
tagsetImportList.add(tagsetImport);
}
}
tagsetDataProvider.refreshAll();
wizardContext.put(DocumentWizard.WizardContextKey.TAGSET_IMPORT_LIST, tagsetImportList);
if (stepChangeListener != null) {
stepChangeListener.stepChanged(ImportIntrinsicMarkupStep.this);
}
}
@Override
public void error(Throwable t) {
Logger.getLogger(ImportIntrinsicMarkupStep.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);
}
});
}
use of de.catma.backgroundservice.BackgroundServiceProvider in project catma by forTEXT.
the class TaggerView method loadReplies.
@Override
public void loadReplies(Optional<Comment> optionalComment) {
if (optionalComment.isPresent()) {
final Comment comment = optionalComment.get();
final UI ui = UI.getCurrent();
((BackgroundServiceProvider) ui).submit("load-comment-replies", new DefaultProgressCallable<Void>() {
@Override
public Void call() throws Exception {
ui.accessSynchronously(() -> {
try {
List<Reply> replies = project.getCommentReplies(comment);
tagger.setReplies(replies, comment);
ui.push();
} catch (IOException e) {
logger.log(Level.WARNING, "error loading replies", e);
}
});
return null;
}
}, new ExecutionListener<Void>() {
@Override
public void done(Void result) {
ui.push();
}
@Override
public void error(Throwable t) {
errorHandler.showAndLogError("Error loading Replies!", t);
}
});
}
}
use of de.catma.backgroundservice.BackgroundServiceProvider in project catma by forTEXT.
the class KwicPanel method initActions.
private void initActions(EventBus eventBus) {
ContextMenu moreOptionsMenu = kwicGridComponent.getActionGridBar().getBtnMoreOptionsContextMenu();
moreOptionsMenu.addItem("Annotate selected rows", mi -> handleAnnotateSelectedRequest(eventBus));
ActionGridBar actionBar = kwicGridComponent.getActionGridBar();
actionBar.addButtonAfterSearchField(btnClearSelectedRows);
btnClearSelectedRows.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
handleRemoveRowRequest();
}
});
miRemoveAnnotations = moreOptionsMenu.addItem("Remove selected Annotations", mi -> handleRemoveAnnotationsRequest(eventBus));
miRemoveAnnotations.setEnabled(false);
MenuItem miExport = moreOptionsMenu.addItem("Export");
MenuItem miCSVFlatExport = miExport.addItem("Export as CSV");
StreamResource csvFlatExportResource = new StreamResource(new CSVExportFlatStreamSource(() -> getFilteredQueryResult(), project, kwicItemHandler.getKwicProviderCache(), ((BackgroundServiceProvider) UI.getCurrent())), "CATMA-KWIC_Export-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) + ".csv");
csvFlatExportResource.setCacheTime(0);
csvFlatExportResource.setMIMEType("text/comma-separated-values");
FileDownloader csvFlatExportFileDownloader = new FileDownloader(csvFlatExportResource);
csvFlatExportFileDownloader.extend(miCSVFlatExport);
kwicGridComponent.setSearchFilterProvider(new SearchFilterProvider<QueryResultRow>() {
@Override
public SerializablePredicate<QueryResultRow> createSearchFilter(String searchInput) {
return (row) -> kwicItemHandler.containsSearchInput(row, searchInput);
}
});
btExpandCompress.addClickListener(clickEvent -> handleMaxMinRequest());
defaultDoubleClickRegistration = kwicGrid.addItemClickListener(clickEvent -> handleKwicItemClick(clickEvent, eventBus));
}
use of de.catma.backgroundservice.BackgroundServiceProvider in project catma by forTEXT.
the class QueryResultPanel method initActions.
private void initActions(CloseListener resultPanelCloseListener) {
if (cardStyle) {
caretRightBt.addClickListener(new ClickListener() {
public void buttonClick(ClickEvent event) {
addComponent(treeGridPanel);
((HorizontalLayout) caretRightBt.getParent()).replaceComponent(caretRightBt, caretDownBt);
searchField.setEnabled(true);
}
});
caretDownBt.addClickListener(new ClickListener() {
public void buttonClick(ClickEvent event) {
removeComponent(treeGridPanel);
((HorizontalLayout) caretDownBt.getParent()).replaceComponent(caretDownBt, caretRightBt);
searchField.setEnabled(false);
}
});
}
optionsBt.addClickListener((evt) -> optionsMenu.open(evt.getClientX(), evt.getClientY()));
miGroupByPhrase = optionsMenu.addItem("Group by Phrase", mi -> initPhraseBasedData());
miGroupByPhrase.setEnabled(false);
miGroupByTagPath = optionsMenu.addItem("Group by Tag Path", mi -> initTagBasedData());
miFlatTable = optionsMenu.addItem("Display Annotations as flat table", mi -> initFlatTagBasedData());
miPropertiesAsColumns = optionsMenu.addItem("Display Properties as columns", mi -> initPropertiesAsColumnsTagBasedData());
MenuItem miExport = optionsMenu.addItem("Export");
MenuItem miCSVFlatExport = miExport.addItem("Export flat as CSV");
StreamResource csvFlatExportResource = new StreamResource(new CSVExportFlatStreamSource(() -> getFilteredQueryResult(), project, kwicProviderCache, ((BackgroundServiceProvider) UI.getCurrent())), "CATMA-Query-Result_Export-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) + ".csv");
csvFlatExportResource.setCacheTime(0);
csvFlatExportResource.setMIMEType("text/comma-separated-values");
FileDownloader csvFlatExportFileDownloader = new FileDownloader(csvFlatExportResource);
csvFlatExportFileDownloader.extend(miCSVFlatExport);
MenuItem miCSVGroupedByPhraseExport = miExport.addItem("Export grouped as CSV");
StreamResource csvGroupedByPhraseExportResource = new StreamResource(new CSVExportGroupedStreamSource(() -> getFilteredQueryResult(), project, () -> getDisplaySetting().equals(DisplaySetting.GROUPED_BY_TAG), kwicProviderCache, ((BackgroundServiceProvider) UI.getCurrent())), "CATMA-Query-Result_Export-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) + ".csv");
csvGroupedByPhraseExportResource.setCacheTime(0);
csvGroupedByPhraseExportResource.setMIMEType("text/comma-separated-values");
FileDownloader csvGroupedByPhraseExportFileDownloader = new FileDownloader(csvGroupedByPhraseExportResource);
csvGroupedByPhraseExportFileDownloader.extend(miCSVGroupedByPhraseExport);
MenuItem miFilterPunctuation = optionsMenu.addItem("Filter punctuation", mi -> queryResultGrid.getDataProvider().refreshAll());
miFilterPunctuation.setCheckable(true);
miFilterPunctuation.setChecked(true);
punctuationFilter = new PunctuationFilter(() -> miFilterPunctuation.isChecked());
if (resultPanelCloseListener != null) {
removeBt.addClickListener(clickEvent -> resultPanelCloseListener.closeRequest(QueryResultPanel.this));
} else {
removeBt.setVisible(false);
}
searchField.addValueChangeListener(event -> handleSearchValueInput(event.getValue()));
}
Aggregations