List of usage examples for com.vaadin.ui Notification Notification
public Notification(String caption, String description, Type type, boolean htmlContentAllowed)
From source file:de.symeda.sormas.ui.utils.DownloadUtil.java
License:Open Source License
@SuppressWarnings("serial") public static StreamResource createFileStreamResource(String filePath, String fileName, String mimeType, String errorTitle, String errorText) { StreamResource streamResource = new StreamResource(new StreamSource() { @Override// ww w . j a va2s . co m public InputStream getStream() { try { return new BufferedInputStream(Files.newInputStream(new File(filePath).toPath())); } catch (IOException e) { // TODO This currently requires the user to click the "Export" button again or reload the page as the UI // is not automatically updated; this should be changed once Vaadin push is enabled (see #516) new Notification(errorTitle, errorText, Type.ERROR_MESSAGE, false).show(Page.getCurrent()); return null; } } }, fileName); streamResource.setMIMEType(mimeType); streamResource.setCacheTime(0); return streamResource; }
From source file:de.symeda.sormas.ui.utils.DownloadUtil.java
License:Open Source License
@SuppressWarnings("serial") public static <T> StreamResource createCsvExportStreamResource(Class<T> exportRowClass, BiFunction<Integer, Integer, List<T>> exportRowsSupplier, BiFunction<String, Class<?>, String> propertyIdCaptionFunction, String exportFileName) { StreamResource extendedStreamResource = new StreamResource(new StreamSource() { @Override//from ww w.j av a 2s. c o m public InputStream getStream() { try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) { try (CSVWriter writer = CSVUtils.createCSVWriter( new OutputStreamWriter(byteStream, StandardCharsets.UTF_8.name()), FacadeProvider.getConfigFacade().getCsvSeparator())) { // 1. fields in order of declaration - not using Introspector here, because it gives properties in alphabetical order List<Method> readMethods = new ArrayList<Method>(); readMethods.addAll(Arrays.stream(exportRowClass.getDeclaredMethods()) .filter(m -> (m.getName().startsWith("get") || m.getName().startsWith("is")) && m.isAnnotationPresent(Order.class)) .sorted((a, b) -> Integer.compare(a.getAnnotationsByType(Order.class)[0].value(), b.getAnnotationsByType(Order.class)[0].value())) .collect(Collectors.toList())); // 2. replace entity fields with all the columns of the entity Map<Method, Function<T, ?>> subEntityProviders = new HashMap<Method, Function<T, ?>>(); for (int i = 0; i < readMethods.size(); i++) { Method method = readMethods.get(i); if (EntityDto.class.isAssignableFrom(method.getReturnType())) { // allows us to access the sub entity Function<T, ?> subEntityProvider = (o) -> { try { return method.invoke(o); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } }; // remove entity field readMethods.remove(i); // add columns of the entity List<Method> subReadMethods = Arrays .stream(method.getReturnType().getDeclaredMethods()) .filter(m -> (m.getName().startsWith("get") || m.getName().startsWith("is")) && m.isAnnotationPresent(Order.class)) .sorted((a, b) -> Integer.compare( a.getAnnotationsByType(Order.class)[0].value(), b.getAnnotationsByType(Order.class)[0].value())) .collect(Collectors.toList()); readMethods.addAll(i, subReadMethods); i--; for (Method subReadMethod : subReadMethods) { subEntityProviders.put(subReadMethod, subEntityProvider); } } } String[] fieldValues = new String[readMethods.size()]; for (int i = 0; i < readMethods.size(); i++) { Method method = readMethods.get(i); // field caption String propertyId = method.getName().startsWith("get") ? method.getName().substring(3) : method.getName().substring(2); propertyId = Character.toLowerCase(propertyId.charAt(0)) + propertyId.substring(1); fieldValues[i] = propertyIdCaptionFunction.apply(propertyId, method.getReturnType()); } writer.writeNext(fieldValues); int startIndex = 0; List<T> exportRows = exportRowsSupplier.apply(startIndex, DETAILED_EXPORT_STEP_SIZE); while (!exportRows.isEmpty()) { try { for (T exportRow : exportRows) { for (int i = 0; i < readMethods.size(); i++) { Method method = readMethods.get(i); Function<T, ?> subEntityProvider = subEntityProviders.getOrDefault(method, null); Object entity = subEntityProvider != null ? subEntityProvider.apply(exportRow) : exportRow; // Sub entity might be null Object value = entity != null ? method.invoke(entity) : null; if (value == null) { fieldValues[i] = ""; } else if (value instanceof Date) { fieldValues[i] = DateHelper.formatLocalShortDate((Date) value); } else if (value.getClass().equals(boolean.class) || value.getClass().equals(Boolean.class)) { fieldValues[i] = DataHelper.parseBoolean((Boolean) value); } else if (value instanceof Set) { StringBuilder sb = new StringBuilder(); for (Object o : (Set<?>) value) { if (sb.length() != 0) { sb.append(", "); } sb.append(o); } fieldValues[i] = sb.toString(); } else { fieldValues[i] = value.toString(); } } writer.writeNext(fieldValues); } ; } catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException e) { throw new RuntimeException(e); } writer.flush(); startIndex += DETAILED_EXPORT_STEP_SIZE; exportRows = exportRowsSupplier.apply(startIndex, DETAILED_EXPORT_STEP_SIZE); } } return new BufferedInputStream(new ByteArrayInputStream(byteStream.toByteArray())); } catch (IOException e) { // TODO This currently requires the user to click the "Export" button again or reload the page as the UI // is not automatically updated; this should be changed once Vaadin push is enabled (see #516) new Notification(I18nProperties.getString(Strings.headingExportFailed), I18nProperties.getString(Strings.messageExportFailed), Type.ERROR_MESSAGE, false) .show(Page.getCurrent()); return null; } } }, exportFileName); extendedStreamResource.setMIMEType("text/csv"); extendedStreamResource.setCacheTime(0); return extendedStreamResource; }
From source file:de.symeda.sormas.ui.utils.GridExportStreamResource.java
License:Open Source License
public GridExportStreamResource(Grid<?> grid, String tempFilePrefix, String filename, String... ignoredPropertyIds) { super(new StreamSource() { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override/* w w w .ja v a 2 s.c o m*/ public InputStream getStream() { List<String> ignoredPropertyIdsList = Arrays.asList(ignoredPropertyIds); List<Column> columns = new ArrayList<>(grid.getColumns()); columns.removeIf(c -> c.isHidden()); columns.removeIf(c -> ignoredPropertyIdsList.contains(c.getId())); try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) { try (CSVWriter writer = CSVUtils.createCSVWriter( new OutputStreamWriter(byteStream, StandardCharsets.UTF_8.name()), FacadeProvider.getConfigFacade().getCsvSeparator())) { List<String> headerRow = new ArrayList<>(); columns.forEach(c -> { headerRow.add(c.getCaption()); }); writer.writeNext(headerRow.toArray(new String[headerRow.size()])); String[] rowValues = new String[columns.size()]; int totalRowCount = grid.getDataProvider().size(new Query()); for (int i = 0; i < totalRowCount; i += 100) { grid.getDataProvider().fetch(new Query(i, 100, grid.getSortOrder(), null, null)) .forEach(row -> { for (int c = 0; c < columns.size(); c++) { Column column = columns.get(c); Object value = column.getValueProvider().apply(row); String valueString; if (value != null) { if (value instanceof Date) { valueString = DateHelper.formatLocalDateTime((Date) value); } else if (value instanceof Boolean) { if ((Boolean) value == true) { valueString = I18nProperties .getEnumCaption(YesNoUnknown.YES); } else valueString = I18nProperties .getEnumCaption(YesNoUnknown.NO); } else { valueString = value.toString(); } } else { valueString = ""; } rowValues[c] = valueString; } writer.writeNext(rowValues); }); writer.flush(); } } return new BufferedInputStream(new ByteArrayInputStream(byteStream.toByteArray())); } catch (IOException e) { // TODO This currently requires the user to click the "Export" button again or reload the page as the UI // is not automatically updated; this should be changed once Vaadin push is enabled (see #516) new Notification(I18nProperties.getString(Strings.headingExportFailed), I18nProperties.getString(Strings.messageExportFailed), Type.ERROR_MESSAGE, false) .show(Page.getCurrent()); return null; } } }, filename); setMIMEType("text/csv"); setCacheTime(0); }
From source file:de.symeda.sormas.ui.utils.V7GridExportStreamResource.java
License:Open Source License
public V7GridExportStreamResource(Indexed container, List<Column> gridColumns, String tempFilePrefix, String filename, String... ignoredPropertyIds) { super(new StreamSource() { @Override//w w w . j av a2 s . c o m public InputStream getStream() { List<String> ignoredPropertyIdsList = Arrays.asList(ignoredPropertyIds); List<Column> columns = new ArrayList<>(gridColumns); columns.removeIf(c -> c.isHidden()); columns.removeIf(c -> ignoredPropertyIdsList.contains(c.getPropertyId())); Collection<?> itemIds = container.getItemIds(); try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) { try (CSVWriter writer = CSVUtils.createCSVWriter( new OutputStreamWriter(byteStream, StandardCharsets.UTF_8.name()), FacadeProvider.getConfigFacade().getCsvSeparator())) { List<String> headerRow = new ArrayList<>(); columns.forEach(c -> { headerRow.add(c.getHeaderCaption()); }); writer.writeNext(headerRow.toArray(new String[headerRow.size()])); itemIds.forEach(i -> { List<String> row = new ArrayList<>(); columns.forEach(c -> { Property<?> property = container.getItem(i).getItemProperty(c.getPropertyId()); if (property.getValue() != null) { if (property.getType() == Date.class) { row.add(DateHelper.formatLocalDateTime((Date) property.getValue())); } else if (property.getType() == Boolean.class) { if ((Boolean) property.getValue() == true) { row.add(I18nProperties.getEnumCaption(YesNoUnknown.YES)); } else row.add(I18nProperties.getEnumCaption(YesNoUnknown.NO)); } else { row.add(property.getValue().toString()); } } else { row.add(""); } }); writer.writeNext(row.toArray(new String[row.size()])); }); writer.flush(); } return new BufferedInputStream(new ByteArrayInputStream(byteStream.toByteArray())); } catch (IOException e) { // TODO This currently requires the user to click the "Export" button again or reload the page as the UI // is not automatically updated; this should be changed once Vaadin push is enabled (see #516) new Notification(I18nProperties.getString(Strings.headingExportFailed), I18nProperties.getString(Strings.messageExportFailed), Type.ERROR_MESSAGE, false) .show(Page.getCurrent()); return null; } } }, filename); setMIMEType("text/csv"); setCacheTime(0); }
From source file:de.symeda.sormas.ui.visit.VisitController.java
License:Open Source License
public void deleteAllSelectedItems(Collection<VisitIndexDto> selectedRows, Runnable callback) { if (selectedRows.size() == 0) { new Notification(I18nProperties.getString(Strings.headingNoVisitsSelected), I18nProperties.getString(Strings.messageNoVisitsSelected), Type.WARNING_MESSAGE, false) .show(Page.getCurrent()); } else {// w ww .j a va 2 s. co m VaadinUiUtil.showDeleteConfirmationWindow( String.format(I18nProperties.getString(Strings.confirmationDeleteVisits), selectedRows.size()), new Runnable() { public void run() { for (Object selectedRow : selectedRows) { FacadeProvider.getVisitFacade().deleteVisit( new VisitReferenceDto(((VisitDto) selectedRow).getUuid()), UserProvider.getCurrent().getUuid()); } callback.run(); new Notification(I18nProperties.getString(Strings.headingVisitsDeleted), I18nProperties.getString(Strings.messageVisitsDeleted), Type.HUMANIZED_MESSAGE, false).show(Page.getCurrent()); } }); } }
From source file:de.uni_tuebingen.qbic.qbicmainportlet.DatasetView.java
License:Open Source License
@Override public void enter(ViewChangeEvent event) { Map<String, String> map = getMap(event.getParameters()); if (map == null) return;/*from w w w.ja v a2s. co m*/ try { HierarchicalContainer datasetContainer = new HierarchicalContainer(); datasetContainer.addContainerProperty("Select", CheckBox.class, null); datasetContainer.addContainerProperty("Project", String.class, null); datasetContainer.addContainerProperty("Sample", String.class, null); // datasetContainer.addContainerProperty("Sample Type", String.class, null); datasetContainer.addContainerProperty("File Name", String.class, null); datasetContainer.addContainerProperty("File Type", String.class, null); datasetContainer.addContainerProperty("Dataset Type", String.class, null); datasetContainer.addContainerProperty("Registration Date", Timestamp.class, null); datasetContainer.addContainerProperty("Validated", Boolean.class, null); datasetContainer.addContainerProperty("File Size", String.class, null); datasetContainer.addContainerProperty("file_size_bytes", Long.class, null); datasetContainer.addContainerProperty("dl_link", String.class, null); datasetContainer.addContainerProperty("CODE", String.class, null); List<ch.systemsx.cisd.openbis.generic.shared.api.v1.dto.DataSet> retrievedDatasets = null; switch (map.get("type")) { case "project": String projectIdentifier = map.get("id"); retrievedDatasets = datahandler.getOpenBisClient() .getDataSetsOfProjectByIdentifierWithSearchCriteria(projectIdentifier); break; case "experiment": String experimentIdentifier = map.get("id"); retrievedDatasets = datahandler.getOpenBisClient() .getDataSetsOfExperimentByCodeWithSearchCriteria(experimentIdentifier); break; case "sample": String sampleIdentifier = map.get("id"); String sampleCode = sampleIdentifier.split("/")[2]; retrievedDatasets = datahandler.getOpenBisClient().getDataSetsOfSample(sampleCode); break; default: retrievedDatasets = new ArrayList<ch.systemsx.cisd.openbis.generic.shared.api.v1.dto.DataSet>(); break; } numberOfDatasets = retrievedDatasets.size(); if (numberOfDatasets == 0) { new Notification("No datasets available.", "<br/>Please contact the project manager.", Type.WARNING_MESSAGE, true).show(Page.getCurrent()); } else { Map<String, String> samples = new HashMap<String, String>(); // project same for all datasets String projectCode = retrievedDatasets.get(0).getExperimentIdentifier().split("/")[2]; for (ch.systemsx.cisd.openbis.generic.shared.api.v1.dto.DataSet dataset : retrievedDatasets) { samples.put(dataset.getCode(), dataset.getSampleIdentifierOrNull().split("/")[2]); } List<DatasetBean> dsBeans = datahandler.queryDatasetsForFolderStructure(retrievedDatasets); for (DatasetBean d : dsBeans) { Date date = d.getRegistrationDate(); SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String dateString = sd.format(date); Timestamp ts = Timestamp.valueOf(dateString); String sampleID = samples.get(d.getCode()); registerDatasetInTable(d, datasetContainer, projectCode, sampleID, ts, null); } } this.setContainerDataSource(datasetContainer); } catch (Exception e) { e.printStackTrace(); LOGGER.error(String.format("getting dataset failed for dataset %s", map.toString()), e.getStackTrace()); } }
From source file:de.uni_tuebingen.qbic.qbicmainportlet.MSHBiologicalSampleStateMachine.java
License:Open Source License
public boolean traverseToNextState(String sampleID) { // first, check if all conditions are met before traversing into next state String fromState = new String(currentState.name()); String toState = new String(currentState.nextState().name()); if (fromState.equals(toState)) { // nothing to do... however, we should notify the user Notification errorEndStateReached = new Notification( "The current process seems to have reached it's end state.", "<i>Skipping this transition with no changes performed...</i>", Type.WARNING_MESSAGE, true); errorEndStateReached.setHtmlContentAllowed(true); errorEndStateReached.show(Page.getCurrent()); return false; }/* ww w . j a va2 s .c o m*/ if (currentState.checkConditions()) { stateMachineLogging.debug("traversing from " + fromState + " to " + toState); // first check if OpenBIS is still in the currentState String mostRecentStateName = retrieveCurrentStateFromOpenBIS(); if (mostRecentStateName != null && !fromState.equals(mostRecentStateName)) { sampleViewRef.updateContent(); Notification errorStateMoved = new Notification("The sample's status has changed in the meantime!", "<i>Most likely, someone else in your group is working on the same data.</i>", Type.ERROR_MESSAGE, true); errorStateMoved.setHtmlContentAllowed(true); errorStateMoved.show(Page.getCurrent()); // this should redraw the current state //this.setState(mostRecentStateName); //this.buildCurrentInterface(); return false; } updateOpenBISCurrentProcessState(sampleID, toState); sampleViewRef.updateContent(); notifyUsersOfTransition(fromState, toState); return true; } return false; }
From source file:de.uni_tuebingen.qbic.qbicmainportlet.PatientView.java
License:Open Source License
void updateProjectStatus() { BeanItemContainer<ExperimentStatusBean> experimentstatusBeans = datahandler .computeIvacPatientStatus(currentBean); int finishedExperiments = 0; status.removeAllComponents();/*w ww .j a v a 2 s. co m*/ status.setWidth(100.0f, Unit.PERCENTAGE); // Generate button caption column final GeneratedPropertyContainer gpc = new GeneratedPropertyContainer(experimentstatusBeans); gpc.addGeneratedProperty("started", new PropertyValueGenerator<String>() { @Override public Class<String> getType() { return String.class; } @Override public String getValue(Item item, Object itemId, Object propertyId) { String status = null; if ((double) item.getItemProperty("status").getValue() > 0.0) { status = "<span class=\"v-icon\" style=\"font-family: " + FontAwesome.CHECK.getFontFamily() + ";color:" + "#2dd085" + "\">&#x" + Integer.toHexString(FontAwesome.CHECK.getCodepoint()) + ";</span>"; } else { status = "<span class=\"v-icon\" style=\"font-family: " + FontAwesome.TIMES.getFontFamily() + ";color:" + "#f54993" + "\">&#x" + Integer.toHexString(FontAwesome.TIMES.getCodepoint()) + ";</span>"; } return status.toString(); } }); gpc.removeContainerProperty("identifier"); experiments.setContainerDataSource(gpc); // experiments.setHeaderVisible(false); experiments.setHeightMode(HeightMode.ROW); experiments.setHeightByRows(gpc.size()); experiments.setWidth(Page.getCurrent().getBrowserWindowWidth() * 0.6f, Unit.PIXELS); experiments.getColumn("status").setRenderer(new ProgressBarRenderer()); experiments.setColumnOrder("started", "code", "description", "status", "download", "runWorkflow"); ButtonRenderer downloadRenderer = new ButtonRenderer(new RendererClickListener() { @Override public void click(RendererClickEvent event) { ExperimentStatusBean esb = (ExperimentStatusBean) event.getItemId(); if (esb.getDescription().equals("Barcode Generation")) { new Notification("Download of Barcodes not available.", "<br/>Please create barcodes by clicking 'Run'.", Type.WARNING_MESSAGE, true) .show(Page.getCurrent()); } else if (esb.getIdentifier() == null || esb.getIdentifier().isEmpty()) { new Notification("No data available for download.", "<br/>Please do the analysis by clicking 'Run' first.", Type.WARNING_MESSAGE, true) .show(Page.getCurrent()); } else { ArrayList<String> message = new ArrayList<String>(); message.add("clicked"); StringBuilder sb = new StringBuilder("type="); sb.append("experiment"); sb.append("&"); sb.append("id="); // sb.append(currentBean.getId()); sb.append(esb.getIdentifier()); message.add(sb.toString()); message.add(DatasetView.navigateToLabel); state.notifyObservers(message); } } }); experiments.getColumn("download").setRenderer(downloadRenderer); experiments.getColumn("runWorkflow").setRenderer(new ButtonRenderer(new RendererClickListener() { @Override public void click(RendererClickEvent event) { ExperimentStatusBean esb = (ExperimentStatusBean) event.getItemId(); // TODO idea get description of item to navigate to the correct workflow ?! if (esb.getDescription().equals("Barcode Generation")) { ArrayList<String> message = new ArrayList<String>(); message.add("clicked"); message.add(currentBean.getId()); // TODO link to barcode dragon // message.add(BarcodeView.navigateToLabel); // state.notifyObservers(message); } else { ArrayList<String> message = new ArrayList<String>(); message.add("clicked"); StringBuilder sb = new StringBuilder("type="); sb.append("workflowExperimentType"); sb.append("&"); sb.append("id="); sb.append("Q_WF_MS_PEPTIDEID"); sb.append("&"); sb.append("project="); sb.append(currentBean.getId()); message.add(sb.toString()); message.add(WorkflowView.navigateToLabel); state.notifyObservers(message); } } })); experiments.getColumn("started").setRenderer(new HtmlRenderer()); ProgressBar progressBar = new ProgressBar(); progressBar.setCaption("Overall Progress"); progressBar.setWidth(Page.getCurrent().getBrowserWindowWidth() * 0.6f, Unit.PIXELS); progressBar.setStyleName("patientprogress"); status.addComponent(progressBar); status.addComponent(experiments); status.setComponentAlignment(progressBar, Alignment.MIDDLE_CENTER); status.setComponentAlignment(experiments, Alignment.MIDDLE_CENTER); /** * Defined Experiments for iVac - Barcodes available -> done with project creation (done) - * Sequencing done (Status Q_NGS_MEASUREMENT) - Variants annotated (Status * Q_NGS_VARIANT_CALLING) - HLA Typing done (STATUS Q_NGS_WF_HLA_TYPING) - Epitope Prediction * done (STATUS Q_WF_NGS_EPITOPE_PREDICTION) */ for (Iterator i = experimentstatusBeans.getItemIds().iterator(); i.hasNext();) { ExperimentStatusBean statusBean = (ExperimentStatusBean) i.next(); // HorizontalLayout experimentStatusRow = new HorizontalLayout(); // experimentStatusRow.setSpacing(true); finishedExperiments += statusBean.getStatus(); // statusBean.setDownload("Download"); statusBean.setWorkflow("Run"); /* * if ((Integer) pairs.getValue() == 0) { Label statusLabel = new Label(pairs.getKey() + ": " * + FontAwesome.TIMES.getHtml(), ContentMode.HTML); statusLabel.addStyleName("redicon"); * experimentStatusRow.addComponent(statusLabel); * statusContent.addComponent(experimentStatusRow); } * * else { * * Label statusLabel = new Label(pairs.getKey() + ": " + FontAwesome.CHECK.getHtml(), * ContentMode.HTML); statusLabel.addStyleName("greenicon"); * experimentStatusRow.addComponent(statusLabel); * statusContent.addComponent(experimentStatusRow); * * finishedExperiments += (Integer) pairs.getValue(); } * experimentStatusRow.addComponent(runWorkflow); * * } */ } progressBar.setValue((float) finishedExperiments / experimentstatusBeans.size()); }
From source file:dhbw.clippinggorilla.utilities.ui.VaadinUtils.java
public static void errorNotification(String caption, String description) { Notification not = new Notification(caption, null, Notification.Type.TRAY_NOTIFICATION, true); not.setDelayMsec(1000);//w w w . j ava 2s . c o m not.setPosition(Position.TOP_CENTER); not.setStyleName(ValoTheme.NOTIFICATION_FAILURE + " " + ValoTheme.NOTIFICATION_SMALL); not.show(Page.getCurrent()); }
From source file:dhbw.clippinggorilla.utilities.ui.VaadinUtils.java
public static void infoNotification(String caption, String description) { Notification not = new Notification(caption, null, Notification.Type.TRAY_NOTIFICATION, true); not.setDelayMsec(1000);/*from w w w . j a v a2s. co m*/ not.setPosition(Position.BOTTOM_CENTER); not.show(Page.getCurrent()); }