Example usage for com.vaadin.server Page getCurrent

List of usage examples for com.vaadin.server Page getCurrent

Introduction

In this page you can find the example usage for com.vaadin.server Page getCurrent.

Prototype

public static Page getCurrent() 

Source Link

Document

Gets the Page to which the current uI belongs.

Usage

From source file:de.symeda.sormas.ui.utils.CommitDiscardWrapperComponent.java

License:Open Source License

public void commitAndHandle() {
    try {//  ww w . j  a v a2s . c o m
        commit();
    } catch (InvalidValueException ex) {
        StringBuilder htmlMsg = new StringBuilder();
        String message = ex.getMessage();
        if (message != null && !message.isEmpty()) {
            htmlMsg.append(ex.getHtmlMessage());
        } else {

            InvalidValueException[] causes = ex.getCauses();
            if (causes != null) {

                InvalidValueException firstCause = null;
                boolean multipleCausesFound = false;
                for (int i = 0; i < causes.length; i++) {
                    if (!causes[i].isInvisible()) {
                        if (firstCause == null) {
                            firstCause = causes[i];
                        } else {
                            multipleCausesFound = true;
                            break;
                        }
                    }
                }
                if (multipleCausesFound) {
                    htmlMsg.append("<ul>");
                    // Alle nochmal
                    for (int i = 0; i < causes.length; i++) {
                        if (!causes[i].isInvisible()) {
                            htmlMsg.append("<li style=\"color: #FFF;\">").append(findHtmlMessage(causes[i]))
                                    .append("</li>");
                        }
                    }
                    htmlMsg.append("</ul>");
                } else if (firstCause != null) {
                    htmlMsg.append(findHtmlMessage(firstCause));
                }

            }
        }

        new Notification(I18nProperties.getString(Strings.messageCheckInputData), htmlMsg.toString(),
                Type.ERROR_MESSAGE, true).show(Page.getCurrent());
    }
}

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/*from www.  jav  a 2 s .  c  o 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 a  va  2  s.  c  om
        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/*from ww  w .  ja va 2s.  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/*from   ww  w  .j  a  v a2s  .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  w  w. j  a  v a 2  s .c o  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.unioninvestment.eai.portal.portlet.crud.CrudErrorHandler.java

License:Apache License

@Override
public void error(ErrorEvent event) {
    Throwable throwable = event.getThrowable();
    LOGGER.error("Internal error", StackTraceUtils.deepSanitize(throwable));
    if (Page.getCurrent() != null) {
        displayRootCauseAsErrorNotification(throwable);
    }/*from ww  w .j  a  v a 2s.  c  o m*/
}

From source file:de.unioninvestment.eai.portal.portlet.crud.CrudUI.java

License:Apache License

private void applyBrowserLocale() {
    setLocale(Page.getCurrent().getWebBrowser().getLocale());
}

From source file:de.unioninvestment.eai.portal.portlet.crud.mvp.views.DefaultTableView.java

License:Apache License

/**
 * {@inheritDoc}//from  ww w .ja  va2s.c  o m
 * 
 * @see de.unioninvestment.eai.portal.portlet.crud.mvp.views.TableView#initialize(de.unioninvestment.eai.portal.portlet.crud.mvp.views.TableView.Presenter,
 *      de.unioninvestment.eai.portal.portlet.crud.domain.model.DataContainer,
 *      de.unioninvestment.eai.portal.portlet.crud.domain.model.Table, int,
 *      double)
 */
@Override
public void initialize(TableView.Presenter presenter, DataContainer databaseContainer, Table tableModel,
        int pageLength, double cacheRate) {

    this.presenter = presenter;
    this.container = databaseContainer;
    this.tableModel = tableModel;

    // @since 1.45
    if (tableModel.getWidth() != null) {
        setWidth(tableModel.getWidth());
    }
    // @since 1.45
    if (tableModel.getHeight() != null) {
        setHeight(tableModel.getHeight());
    }

    table = new CrudTable(container, tableModel.getColumns(), tableModel.isSortingEnabled());
    table.disableContentRefreshing();
    table.setColumnCollapsingAllowed(true);
    table.setColumnReorderingAllowed(true);
    table.setSizeFull();
    table.setImmediate(true);
    table.setEditable(false);

    if (tableModel.getSelectionMode() == SelectionMode.MULTIPLE) {
        table.setSelectable(true);
        table.setNullSelectionAllowed(false);
        table.setMultiSelect(true);
        table.setMultiSelectMode(MultiSelectMode.DEFAULT);
    } else if (tableModel.getSelectionMode() == SelectionMode.SINGLE) {
        table.setSelectable(true);
        table.setNullSelectionAllowed(false);
    }

    if (!tableModel.isSortingEnabled()) {
        table.setSortEnabled(false);
    }

    table.addStyleName("crudViewMode");
    table.addStyleName("crudTable");

    Integer rowHeight = tableModel.getRowHeight();
    if (rowHeight != null) {
        table.addStyleName("rowheight" + rowHeight);
        String css = ".v-table-rowheight" + rowHeight + " .v-table-cell-content { height: " + rowHeight
                + "px; }";
        css += "div.crudTable td div.v-table-cell-wrapper { max-height: " + rowHeight + "px; }";
        Page.getCurrent().getStyles().add(css);
    }

    table.setPageLength(pageLength);
    table.setCacheRate(cacheRate);

    initializeTableFieldFactory();

    // since 1.45
    table.setHeight("100%");
    addComponent(table);
    setExpandRatio(table, 1);

    Layout buttonBar = initButtonBar();
    if (buttonBar.iterator().hasNext()) {
        addComponent(buttonBar);
    }

    renderTableHeader();

    updateColumnWidths();

    setColumnGenerator(table, rowHeight);

    updateVisibleColumns(false);

    initializeListener();

    setupErrorHandling();

    setTableStyleRenderer();

    presenter.doInitialize();

    if (tableModel.getMode() == Mode.EDIT) {
        switchToEditMode();
    }

    table.enableContentRefreshing(false);
}

From source file:de.unioninvestment.eai.portal.portlet.crud.mvp.views.DefaultTableView.java

License:Apache License

private boolean automaticDownloadIsPossible() {
    WebBrowser browser = Page.getCurrent().getWebBrowser();
    return browser != null && !browser.isIE();
}