Example usage for com.vaadin.server FileDownloader FileDownloader

List of usage examples for com.vaadin.server FileDownloader FileDownloader

Introduction

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

Prototype

public FileDownloader(Resource resource) 

Source Link

Document

Creates a new file downloader for the given resource.

Usage

From source file:de.symeda.sormas.ui.configuration.infrastructure.RegionsView.java

License:Open Source License

public RegionsView() {
    super(VIEW_NAME);

    criteria = ViewModelProviders.of(RegionsView.class).get(RegionCriteria.class);

    grid = new RegionsGrid();
    grid.setCriteria(criteria);/*from w  w  w. j  av  a 2s.  c o  m*/
    gridLayout = new VerticalLayout();
    gridLayout.addComponent(createFilterBar());
    gridLayout.addComponent(grid);
    gridLayout.setMargin(true);
    gridLayout.setSpacing(false);
    gridLayout.setExpandRatio(grid, 1);
    gridLayout.setSizeFull();
    gridLayout.setStyleName("crud-main-layout");

    if (UserProvider.getCurrent().hasUserRight(UserRight.INFRASTRUCTURE_EXPORT)) {
        Button exportButton = new Button(I18nProperties.getCaption(Captions.export));
        exportButton.setDescription(I18nProperties.getDescription(Descriptions.descExportButton));
        exportButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
        exportButton.setIcon(VaadinIcons.TABLE);
        addHeaderComponent(exportButton);

        StreamResource streamResource = new GridExportStreamResource(grid, "sormas_regions",
                "sormas_regions_" + DateHelper.formatDateForExport(new Date()) + ".csv",
                RegionsGrid.EDIT_BTN_ID);
        FileDownloader fileDownloader = new FileDownloader(streamResource);
        fileDownloader.extend(exportButton);
    }

    if (UserProvider.getCurrent().hasUserRight(UserRight.INFRASTRUCTURE_CREATE)) {
        createButton = new Button(I18nProperties.getCaption(Captions.actionNewEntry));
        createButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
        createButton.setIcon(VaadinIcons.PLUS_CIRCLE);
        createButton.addClickListener(e -> ControllerProvider.getInfrastructureController().createRegion());
        addHeaderComponent(createButton);
    }

    addComponent(gridLayout);
}

From source file:de.symeda.sormas.ui.contact.ContactsView.java

License:Open Source License

public ContactsView() {
    super(VIEW_NAME);

    originalViewTitle = getViewTitleLabel().getValue();

    criteria = ViewModelProviders.of(ContactsView.class).get(ContactCriteria.class);
    if (criteria.getArchived() == null) {
        criteria.archived(false);//  w  w w  .  ja v  a  2 s. c  o  m
    }

    grid = new ContactGrid();
    grid.setCriteria(criteria);
    gridLayout = new VerticalLayout();
    gridLayout.addComponent(createFilterBar());
    gridLayout.addComponent(createStatusFilterBar());
    gridLayout.addComponent(grid);
    gridLayout.setMargin(true);
    gridLayout.setSpacing(false);
    gridLayout.setSizeFull();
    gridLayout.setExpandRatio(grid, 1);
    gridLayout.setStyleName("crud-main-layout");
    grid.getDataProvider().addDataProviderListener(e -> updateStatusButtons());

    if (UserProvider.getCurrent().hasUserRight(UserRight.CONTACT_EXPORT)) {

        PopupButton exportButton = new PopupButton(I18nProperties.getCaption(Captions.export));
        exportButton.setIcon(VaadinIcons.DOWNLOAD);
        VerticalLayout exportLayout = new VerticalLayout();
        exportLayout.setSpacing(true);
        exportLayout.setMargin(true);
        exportLayout.addStyleName(CssStyles.LAYOUT_MINIMAL);
        exportLayout.setWidth(200, Unit.PIXELS);
        exportButton.setContent(exportLayout);
        addHeaderComponent(exportButton);

        Button basicExportButton = new Button(I18nProperties.getCaption(Captions.exportBasic));
        basicExportButton.setDescription(I18nProperties.getDescription(Descriptions.descExportButton));
        basicExportButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
        basicExportButton.setIcon(VaadinIcons.TABLE);
        basicExportButton.setWidth(100, Unit.PERCENTAGE);
        exportLayout.addComponent(basicExportButton);

        StreamResource streamResource = new GridExportStreamResource(grid, "sormas_contacts",
                "sormas_contacts_" + DateHelper.formatDateForExport(new Date()) + ".csv");
        FileDownloader fileDownloader = new FileDownloader(streamResource);
        fileDownloader.extend(basicExportButton);

        Button extendedExportButton = new Button(I18nProperties.getCaption(Captions.exportDetailed));
        extendedExportButton
                .setDescription(I18nProperties.getDescription(Descriptions.descDetailedExportButton));
        extendedExportButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
        extendedExportButton.setIcon(VaadinIcons.FILE_TEXT);
        extendedExportButton.setWidth(100, Unit.PERCENTAGE);
        exportLayout.addComponent(extendedExportButton);

        StreamResource extendedExportStreamResource = DownloadUtil.createCsvExportStreamResource(
                ContactExportDto.class,
                (Integer start, Integer max) -> FacadeProvider.getContactFacade()
                        .getExportList(UserProvider.getCurrent().getUuid(), grid.getCriteria(), start, max),
                (propertyId, type) -> {
                    String caption = I18nProperties.getPrefixCaption(ContactExportDto.I18N_PREFIX, propertyId,
                            I18nProperties.getPrefixCaption(ContactDto.I18N_PREFIX, propertyId,
                                    I18nProperties.getPrefixCaption(CaseDataDto.I18N_PREFIX, propertyId,
                                            I18nProperties.getPrefixCaption(PersonDto.I18N_PREFIX, propertyId,
                                                    I18nProperties.getPrefixCaption(SymptomsDto.I18N_PREFIX,
                                                            propertyId,
                                                            I18nProperties.getPrefixCaption(
                                                                    HospitalizationDto.I18N_PREFIX,
                                                                    propertyId))))));
                    if (Date.class.isAssignableFrom(type)) {
                        caption += " (" + DateHelper.getLocalShortDatePattern() + ")";
                    }
                    return caption;
                }, "sormas_contacts_" + DateHelper.formatDateForExport(new Date()) + ".csv");
        new FileDownloader(extendedExportStreamResource).extend(extendedExportButton);

        // Warning if no filters have been selected
        Label warningLabel = new Label(I18nProperties.getString(Strings.infoExportNoFilters));
        warningLabel.setWidth(100, Unit.PERCENTAGE);
        exportLayout.addComponent(warningLabel);
        warningLabel.setVisible(false);

        exportButton.addClickListener(e -> {
            warningLabel.setVisible(!criteria.hasAnyFilterActive());
        });
    }

    addComponent(gridLayout);
}

From source file:de.symeda.sormas.ui.events.EventsView.java

License:Open Source License

public EventsView() {
    super(VIEW_NAME);

    originalViewTitle = getViewTitleLabel().getValue();

    criteria = ViewModelProviders.of(EventsView.class).get(EventCriteria.class);
    if (criteria.getArchived() == null) {
        criteria.archived(false);// w  w  w . j  a v  a2 s  .  c  om
    }

    grid = new EventGrid();
    grid.setCriteria(criteria);
    gridLayout = new VerticalLayout();
    gridLayout.addComponent(createFilterBar());
    gridLayout.addComponent(createStatusFilterBar());
    gridLayout.addComponent(grid);
    gridLayout.setMargin(true);
    gridLayout.setSpacing(false);
    gridLayout.setSizeFull();
    gridLayout.setExpandRatio(grid, 1);
    gridLayout.setStyleName("crud-main-layout");
    grid.getDataProvider().addDataProviderListener(e -> updateStatusButtons());

    addComponent(gridLayout);

    if (UserProvider.getCurrent().hasUserRight(UserRight.EVENT_EXPORT)) {
        Button exportButton = new Button(I18nProperties.getCaption(Captions.export));
        exportButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
        exportButton.setIcon(VaadinIcons.DOWNLOAD);

        StreamResource streamResource = new GridExportStreamResource(grid, "sormas_events",
                "sormas_events_" + DateHelper.formatDateForExport(new Date()) + ".csv");
        FileDownloader fileDownloader = new FileDownloader(streamResource);
        fileDownloader.extend(exportButton);

        addHeaderComponent(exportButton);
    }

    if (UserProvider.getCurrent().hasUserRight(UserRight.EVENT_CREATE)) {
        createButton = new Button(I18nProperties.getCaption(Captions.eventNewEvent));
        createButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
        createButton.setIcon(VaadinIcons.PLUS_CIRCLE);
        createButton.addClickListener(e -> ControllerProvider.getEventController().create());
        addHeaderComponent(createButton);
    }
}

From source file:de.symeda.sormas.ui.samples.SamplesView.java

License:Open Source License

public SamplesView() {
    super(VIEW_NAME);

    sampleListComponent = new SampleGridComponent(getViewTitleLabel(), this);
    setSizeFull();/*  w  w  w.jav a2s . c o  m*/
    addComponent(sampleListComponent);

    if (UserProvider.getCurrent().hasUserRight(UserRight.SAMPLE_EXPORT)) {
        PopupButton exportButton = new PopupButton(I18nProperties.getCaption(Captions.export));
        exportButton.setIcon(VaadinIcons.DOWNLOAD);
        VerticalLayout exportLayout = new VerticalLayout();
        exportLayout.setSpacing(true);
        exportLayout.setMargin(true);
        exportLayout.addStyleName(CssStyles.LAYOUT_MINIMAL);
        exportLayout.setWidth(200, Unit.PIXELS);
        exportButton.setContent(exportLayout);
        addHeaderComponent(exportButton);

        Button basicExportButton = new Button(I18nProperties.getCaption(Captions.exportBasic));
        basicExportButton.setDescription(I18nProperties.getString(Strings.infoBasicExport));
        basicExportButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
        basicExportButton.setIcon(VaadinIcons.TABLE);
        basicExportButton.setWidth(100, Unit.PERCENTAGE);
        exportLayout.addComponent(basicExportButton);

        StreamResource streamResource = new GridExportStreamResource(sampleListComponent.getGrid(),
                "sormas_samples", "sormas_samples_" + DateHelper.formatDateForExport(new Date()) + ".csv",
                SampleGrid.EDIT_BTN_ID);
        FileDownloader fileDownloader = new FileDownloader(streamResource);
        fileDownloader.extend(basicExportButton);

        Button extendedExportButton = new Button(I18nProperties.getCaption(Captions.exportDetailed));
        extendedExportButton.setDescription(I18nProperties.getString(Strings.infoDetailedExport));
        extendedExportButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
        extendedExportButton.setIcon(VaadinIcons.FILE_TEXT);
        extendedExportButton.setWidth(100, Unit.PERCENTAGE);
        exportLayout.addComponent(extendedExportButton);

        StreamResource extendedExportStreamResource = DownloadUtil.createCsvExportStreamResource(
                SampleExportDto.class,
                (Integer start, Integer max) -> FacadeProvider.getSampleFacade().getExportList(
                        UserProvider.getCurrent().getUuid(), sampleListComponent.getGrid().getCriteria(), start,
                        max),
                (propertyId, type) -> {
                    String caption = I18nProperties.getPrefixCaption(SampleExportDto.I18N_PREFIX, propertyId,
                            I18nProperties.getPrefixCaption(SampleDto.I18N_PREFIX, propertyId,
                                    I18nProperties.getPrefixCaption(CaseDataDto.I18N_PREFIX, propertyId,
                                            I18nProperties.getPrefixCaption(PersonDto.I18N_PREFIX, propertyId,
                                                    I18nProperties.getPrefixCaption(
                                                            AdditionalTestDto.I18N_PREFIX, propertyId)))));
                    if (Date.class.isAssignableFrom(type)) {
                        caption += " (" + DateHelper.getLocalShortDatePattern() + ")";
                    }
                    return caption;
                }, "sormas_samples_" + DateHelper.formatDateForExport(new Date()) + ".csv");
        new FileDownloader(extendedExportStreamResource).extend(extendedExportButton);
    }
}

From source file:de.symeda.sormas.ui.statistics.DatabaseExportView.java

License:Open Source License

public DatabaseExportView() {
    super(VIEW_NAME);

    databaseTableToggles = new HashMap<>();
    databaseExportLayout = new VerticalLayout();
    databaseExportLayout.setSpacing(false);
    databaseExportLayout.setMargin(false);
    HorizontalLayout headerLayout = new HorizontalLayout();
    headerLayout.setSpacing(true);/*from w  ww . j  a  va 2  s.c  o m*/
    headerLayout.setMargin(false);
    Label infoLabel = new Label(I18nProperties.getString(Strings.infoDatabaseExportTables));
    headerLayout.addComponent(infoLabel);
    headerLayout.setComponentAlignment(infoLabel, Alignment.MIDDLE_LEFT);
    headerLayout.addComponent(createSelectionButtonsLayout());
    databaseExportLayout.addComponent(headerLayout);
    databaseExportLayout.addComponent(createDatabaseTablesLayout());
    Button exportButton = new Button(I18nProperties.getCaption(Captions.export), VaadinIcons.DOWNLOAD);
    CssStyles.style(exportButton, ValoTheme.BUTTON_PRIMARY);
    StreamResource streamResource = DownloadUtil.createDatabaseExportStreamResource(this,
            "sormas_export_" + DateHelper.formatDateForExport(new Date()) + ".zip", "application/zip");
    FileDownloader fileDownloader = new FileDownloader(streamResource);
    fileDownloader.extend(exportButton);
    databaseExportLayout.addComponent(exportButton);
    databaseExportLayout.setMargin(true);
    databaseExportLayout.setSpacing(true);

    addComponent(databaseExportLayout);
}

From source file:de.symeda.sormas.ui.statistics.StatisticsView.java

License:Open Source License

public void generateTable() {
    List<Object[]> resultData = generateStatistics();

    if (resultData.isEmpty()) {
        resultsLayout.addComponent(emptyResultLabel);
        return;/*from   w w  w. j ava2 s  .  com*/
    }

    exportButton = new Button(I18nProperties.getCaption(Captions.export));
    exportButton.setDescription(I18nProperties.getDescription(Descriptions.descExportButton));
    exportButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
    exportButton.setIcon(VaadinIcons.TABLE);
    resultsLayout.addComponent(exportButton);
    resultsLayout.setComponentAlignment(exportButton, Alignment.TOP_RIGHT);

    statisticsCaseGrid = new StatisticsCaseGrid(visualizationComponent.getRowsAttribute(),
            visualizationComponent.getRowsSubAttribute(), visualizationComponent.getColumnsAttribute(),
            visualizationComponent.getColumnsSubAttribute(), zeroValues.getValue(), resultData, caseCriteria);
    resultsLayout.addComponent(statisticsCaseGrid);
    resultsLayout.setExpandRatio(statisticsCaseGrid, 1);

    StreamResource streamResource = DownloadUtil.createGridExportStreamResource(
            statisticsCaseGrid.getContainerDataSource(), statisticsCaseGrid.getColumns(), "sormas_statistics",
            "sormas_statistics_" + DateHelper.formatDateForExport(new Date()) + ".csv");
    FileDownloader fileDownloader = new FileDownloader(streamResource);
    fileDownloader.extend(exportButton);
}

From source file:de.uni_tuebingen.qbic.qbicmainportlet.BiologicalSamplesComponent.java

License:Open Source License

/**
 * //w  w w . j a  v  a 2 s.c om
 * @param id
 */
public void updateUI(String id) {

    currentID = id;
    sampleBioGrid = new Grid();
    sampleEntityGrid = new Grid();

    sampleEntityGrid.addSelectionListener(new SelectionListener() {

        @Override
        public void select(SelectionEvent event) {
            BeanItem<BiologicalEntitySampleBean> selectedBean = samplesEntity
                    .getItem(sampleEntityGrid.getSelectedRow());

            if (selectedBean == null) {
                TextField filterField = (TextField) sampleBioGrid.getHeaderRow(1).getCell("biologicalEntity")
                        .getComponent();
                filterField.setValue("");
            } else {
                TextField filterField = (TextField) sampleBioGrid.getHeaderRow(1).getCell("biologicalEntity")
                        .getComponent();
                filterField.setValue(selectedBean.getBean().getCode());
                // samplesBio.addContainerFilter("biologicalEntity",
                // selectedBean.getBean().getSecondaryName(), false, false);
            }
        }

    });

    if (id == null)
        return;

    BeanItemContainer<BiologicalSampleBean> samplesBioContainer = new BeanItemContainer<BiologicalSampleBean>(
            BiologicalSampleBean.class);
    BeanItemContainer<BiologicalEntitySampleBean> samplesEntityContainer = new BeanItemContainer<BiologicalEntitySampleBean>(
            BiologicalEntitySampleBean.class);

    List<Sample> allSamples = datahandler.getOpenBisClient()
            .getSamplesWithParentsAndChildrenOfProjectBySearchService(id);

    List<VocabularyTerm> terms = null;
    Map<String, String> termsMap = new HashMap<String, String>();

    for (Sample sample : allSamples) {

        if (sample.getSampleTypeCode().equals(sampleTypes.Q_BIOLOGICAL_ENTITY.toString())) {

            Map<String, String> sampleProperties = sample.getProperties();

            BiologicalEntitySampleBean newEntityBean = new BiologicalEntitySampleBean();
            newEntityBean.setCode(sample.getCode());
            newEntityBean.setId(sample.getIdentifier());
            newEntityBean.setType(sample.getSampleTypeCode());
            newEntityBean.setAdditionalInfo(sampleProperties.get("Q_ADDITIONAL_INFO"));
            newEntityBean.setExternalDB(sampleProperties.get("Q_EXTERNALDB_ID"));
            newEntityBean.setSecondaryName(sampleProperties.get("Q_SECONDARY_NAME"));

            String organismID = sampleProperties.get("Q_NCBI_ORGANISM");
            newEntityBean.setOrganism(organismID);

            if (terms != null) {
                if (termsMap.containsKey(organismID)) {
                    newEntityBean.setOrganismName(termsMap.get(organismID));
                } else {
                    for (VocabularyTerm term : terms) {
                        if (term.getCode().equals(organismID)) {
                            newEntityBean.setOrganismName(term.getLabel());
                            break;
                        }
                    }
                }
            } else {
                for (Vocabulary vocab : datahandler.getOpenBisClient().getFacade().listVocabularies()) {
                    if (vocab.getCode().equals("Q_NCBI_TAXONOMY")) {
                        terms = vocab.getTerms();
                        for (VocabularyTerm term : vocab.getTerms()) {
                            if (term.getCode().equals(organismID)) {
                                newEntityBean.setOrganismName(term.getLabel());
                                termsMap.put(organismID, term.getLabel());
                                break;
                            }
                        }
                        break;
                    }
                }
            }

            newEntityBean.setProperties(sampleProperties);
            newEntityBean.setGender(sampleProperties.get("Q_GENDER"));
            samplesEntityContainer.addBean(newEntityBean);

            // for (Sample child : datahandler.getOpenBisClient().getChildrenSamples(sample)) {
            for (Sample realChild : sample.getChildren()) {
                if (realChild.getSampleTypeCode().equals(sampleTypes.Q_BIOLOGICAL_SAMPLE.toString())) {
                    // Sample realChild =
                    // datahandler.getOpenBisClient().getSampleByIdentifier(child.getIdentifier());

                    Map<String, String> sampleBioProperties = realChild.getProperties();

                    BiologicalSampleBean newBean = new BiologicalSampleBean();
                    newBean.setCode(realChild.getCode());
                    newBean.setId(realChild.getIdentifier());
                    newBean.setType(realChild.getSampleTypeCode());
                    newBean.setPrimaryTissue(sampleBioProperties.get("Q_PRIMARY_TISSUE"));
                    newBean.setTissueDetailed(sampleBioProperties.get("Q_TISSUE_DETAILED"));
                    newBean.setBiologicalEntity(sample.getCode());

                    newBean.setAdditionalInfo(sampleBioProperties.get("Q_ADDITIONAL_INFO"));
                    newBean.setExternalDB(sampleBioProperties.get("Q_EXTERNALDB_ID"));
                    newBean.setSecondaryName(sampleBioProperties.get("Q_SECONDARY_NAME"));
                    newBean.setProperties(sampleBioProperties);

                    samplesBioContainer.addBean(newBean);
                }
            }
        }
    }

    numberOfBioSamples = samplesBioContainer.size();
    numberOfEntitySamples = samplesEntityContainer.size();

    samplesBio = samplesBioContainer;
    samplesEntity = samplesEntityContainer;

    sampleEntityGrid.removeAllColumns();

    final GeneratedPropertyContainer gpcEntity = new GeneratedPropertyContainer(samplesEntity);
    gpcEntity.removeContainerProperty("id");
    gpcEntity.removeContainerProperty("type");
    gpcEntity.removeContainerProperty("organismName");
    gpcEntity.removeContainerProperty("organism");

    sampleEntityGrid.setContainerDataSource(gpcEntity);
    sampleEntityGrid.setColumnReorderingAllowed(true);

    gpcEntity.addGeneratedProperty("Organism", new PropertyValueGenerator<String>() {

        @Override
        public Class<String> getType() {
            return String.class;
        }

        @Override
        public String getValue(Item item, Object itemId, Object propertyId) {
            String ncbi = String.format(
                    "http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Undef&name=%s&lvl=0&srchmode=1&keep=1&unlock' target='_blank'>%s</a>",
                    item.getItemProperty("organism").getValue(),
                    item.getItemProperty("organismName").getValue());
            String link = String.format("<a href='%s", ncbi);

            return link;
        }
    });

    sampleEntityGrid.getColumn("Organism").setRenderer(new HtmlRenderer());

    final GeneratedPropertyContainer gpcBio = new GeneratedPropertyContainer(samplesBio);
    gpcBio.removeContainerProperty("id");
    gpcBio.removeContainerProperty("type");

    sampleBioGrid.setContainerDataSource(gpcBio);
    sampleBioGrid.setColumnReorderingAllowed(true);
    sampleBioGrid.setColumnOrder("secondaryName", "code");

    gpcEntity.addGeneratedProperty("edit", new PropertyValueGenerator<String>() {
        @Override
        public String getValue(Item item, Object itemId, Object propertyId) {
            return "Edit";
        }

        @Override
        public Class<String> getType() {
            return String.class;
        }
    });

    gpcBio.addGeneratedProperty("edit", new PropertyValueGenerator<String>() {
        @Override
        public String getValue(Item item, Object itemId, Object propertyId) {
            return "Edit";
        }

        @Override
        public Class<String> getType() {
            return String.class;
        }
    });

    sampleEntityGrid.addItemClickListener(new ItemClickListener() {

        @Override
        public void itemClick(ItemClickEvent event) {

            BeanItem selected = (BeanItem) samplesEntity.getItem(event.getItemId());
            BiologicalEntitySampleBean selectedExp = (BiologicalEntitySampleBean) selected.getBean();

            State state = (State) UI.getCurrent().getSession().getAttribute("state");
            ArrayList<String> message = new ArrayList<String>();
            message.add("clicked");
            message.add(selectedExp.getId());
            message.add("sample");
            state.notifyObservers(message);
        }
    });

    sampleEntityGrid.getColumn("edit").setRenderer(new ButtonRenderer(new RendererClickListener() {

        @Override
        public void click(RendererClickEvent event) {
            BeanItem selected = (BeanItem) samplesEntity.getItem(event.getItemId());
            BiologicalEntitySampleBean selectedSample = (BiologicalEntitySampleBean) selected.getBean();

            Window subWindow = new Window("Edit Metadata");

            changeMetadata.updateUI(selectedSample.getId(), selectedSample.getType());
            VerticalLayout subContent = new VerticalLayout();
            subContent.setMargin(true);
            subContent.addComponent(changeMetadata);
            subWindow.setContent(subContent);
            // Center it in the browser window
            subWindow.center();
            subWindow.setModal(true);
            subWindow.setIcon(FontAwesome.PENCIL);
            subWindow.setHeight("75%");

            subWindow.addCloseListener(new CloseListener() {
                /**
                 * 
                 */
                private static final long serialVersionUID = -1329152609834711109L;

                @Override
                public void windowClose(CloseEvent e) {
                    updateUI(currentID);
                }
            });

            QbicmainportletUI ui = (QbicmainportletUI) UI.getCurrent();
            ui.addWindow(subWindow);
        }
    }));
    sampleEntityGrid.getColumn("edit").setWidth(70);
    sampleEntityGrid.getColumn("edit").setHeaderCaption("");
    sampleEntityGrid.setColumnOrder("edit", "secondaryName", "Organism", "properties", "code", "additionalInfo",
            "gender", "externalDB");

    sampleBioGrid.addItemClickListener(new ItemClickListener() {

        @Override
        public void itemClick(ItemClickEvent event) {

            BeanItem selected = (BeanItem) samplesBio.getItem(event.getItemId());
            BiologicalSampleBean selectedExp = (BiologicalSampleBean) selected.getBean();

            State state = (State) UI.getCurrent().getSession().getAttribute("state");
            ArrayList<String> message = new ArrayList<String>();
            message.add("clicked");
            message.add(selectedExp.getId());
            message.add("sample");
            state.notifyObservers(message);
        }
    });

    sampleBioGrid.getColumn("edit").setRenderer(new ButtonRenderer(new RendererClickListener() {

        @Override
        public void click(RendererClickEvent event) {
            BeanItem selected = (BeanItem) samplesBio.getItem(event.getItemId());

            try {
                BiologicalSampleBean selectedSample = (BiologicalSampleBean) selected.getBean();

                Window subWindow = new Window();

                changeMetadata.updateUI(selectedSample.getId(), selectedSample.getType());
                VerticalLayout subContent = new VerticalLayout();
                subContent.setMargin(true);
                subContent.addComponent(changeMetadata);
                subWindow.setContent(subContent);
                // Center it in the browser window
                subWindow.center();
                subWindow.setModal(true);
                subWindow.setResizable(false);

                subWindow.addCloseListener(new CloseListener() {
                    /**
                    * 
                    */
                    private static final long serialVersionUID = -1329152609834711109L;

                    @Override
                    public void windowClose(CloseEvent e) {
                        updateUI(currentID);
                    }
                });

                QbicmainportletUI ui = (QbicmainportletUI) UI.getCurrent();
                ui.addWindow(subWindow);
            } catch (NullPointerException e) {
                System.err.println("NullPointerException while trying to set metadata: " + e.getMessage());

            }
        }
    }));

    sampleBioGrid.getColumn("edit").setWidth(70);
    sampleBioGrid.getColumn("edit").setHeaderCaption("");
    sampleBioGrid.setColumnOrder("edit", "secondaryName", "primaryTissue", "properties", "tissueDetailed",
            "code", "additionalInfo", "biologicalEntity", "externalDB");

    sampleBioGrid.getColumn("biologicalEntity").setHeaderCaption("Source");

    helpers.GridFunctions.addColumnFilters(sampleBioGrid, gpcBio);
    helpers.GridFunctions.addColumnFilters(sampleEntityGrid, gpcEntity);

    if (fileDownloaderSources != null)
        exportSources.removeExtension(fileDownloaderSources);
    StreamResource srSource = Utils.getTSVStream(Utils.containerToString(samplesEntityContainer),
            String.format("%s_%s_", id.substring(1).replace("/", "_"), "sample_sources"));
    fileDownloaderSources = new FileDownloader(srSource);
    fileDownloaderSources.extend(exportSources);

    if (fileDownloaderSamples != null)
        exportSamples.removeExtension(fileDownloaderSamples);
    StreamResource srSamples = Utils.getTSVStream(Utils.containerToString(samplesBioContainer),
            String.format("%s_%s_", id.substring(1).replace("/", "_"), "extracted_samples"));
    fileDownloaderSamples = new FileDownloader(srSamples);
    fileDownloaderSamples.extend(exportSamples);

    this.buildLayout();
}

From source file:de.uni_tuebingen.qbic.qbicmainportlet.DatasetComponent.java

License:Open Source License

public void updateUI(String type, String id) {

    if (id == null)
        return;//from  ww w.j  a  va 2  s. com
    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("Description", 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", String.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("isDirectory", Boolean.class, null);
        datasetContainer.addContainerProperty("CODE", String.class, null);

        List<ch.systemsx.cisd.openbis.generic.shared.api.v1.dto.DataSet> retrievedDatasets = null;

        // clear download queue for new view
        PortletSession portletSession = ((QbicmainportletUI) UI.getCurrent()).getPortletSession();
        portletSession.setAttribute("qbic_download",
                new HashMap<String, AbstractMap.SimpleEntry<String, Long>>(), PortletSession.APPLICATION_SCOPE);

        Map<String, Sample> checkedTestSamples = new HashMap<String, Sample>();

        switch (type) {
        case "project":
            String projectIdentifier = id;
            retrievedDatasets = datahandler.getOpenBisClient()
                    .getDataSetsOfProjectByIdentifierWithSearchCriteria(projectIdentifier);

            List<Sample> allSamples = datahandler.getOpenBisClient()
                    .getSamplesWithParentsAndChildrenOfProjectBySearchService(projectIdentifier);

            for (Sample sample : allSamples) {
                checkedTestSamples.put(sample.getCode(), sample);
            }
            break;

        case "experiment":
            String experimentIdentifier = id;
            retrievedDatasets = datahandler.getOpenBisClient()
                    .getDataSetsOfExperimentByCodeWithSearchCriteria(experimentIdentifier);

            Project proj = datahandler.getOpenBisClient()
                    .getProjectOfExperimentByIdentifier(experimentIdentifier);

            List<Sample> extSamples = datahandler.getOpenBisClient()
                    .getSamplesWithParentsAndChildrenOfProjectBySearchService(proj.getIdentifier());

            for (Sample sample : extSamples) {
                checkedTestSamples.put(sample.getCode(), sample);
            }
            break;

        case "sample":
            String sampleIdentifier = id;
            retrievedDatasets = new ArrayList<ch.systemsx.cisd.openbis.generic.shared.api.v1.dto.DataSet>();

            String code = sampleIdentifier.split("/")[2];
            Sample start = datahandler.getOpenBisClient().getSamplesWithParentsAndChildren(code).get(0);

            Project sampProject = datahandler.getOpenBisClient()
                    .getProjectOfExperimentByIdentifier(start.getExperimentIdentifierOrNull());

            retrievedDatasets.addAll(datahandler.getOpenBisClient().getDataSetsOfSample(start.getCode()));

            List<Sample> allProjSamples = datahandler.getOpenBisClient()
                    .getSamplesWithParentsAndChildrenOfProjectBySearchService(sampProject.getIdentifier());

            for (Sample sample : allProjSamples) {
                checkedTestSamples.put(sample.getCode(), sample);
            }

            Set<Sample> startList = new HashSet<Sample>();
            Set<Sample> allChildren = getAllChildren(startList, start);

            for (Sample samp : allChildren) {
                retrievedDatasets.addAll(datahandler.getOpenBisClient().getDataSetsOfSample(samp.getCode()));
            }
            break;

        default:
            retrievedDatasets = new ArrayList<ch.systemsx.cisd.openbis.generic.shared.api.v1.dto.DataSet>();
            break;
        }

        numberOfDatasets = retrievedDatasets.size();

        BeanItemContainer<DatasetBean> forExport = new BeanItemContainer(DatasetBean.class);
        if (numberOfDatasets == 0) {

            if (type.equals("project")) {
                headerLabel.setValue(String.format(
                        "This view shows all datasets associated with this project. There are %s registered datasets.",
                        numberOfDatasets));

                helpers.Utils.Notification("No datasets available.",
                        "No data is available for this project. Please contact the project manager if this is not expected.",
                        "warning");
            } else {
                headerLabel.setValue(String.format(
                        "This view shows all datasets associated with this sample (including samples which have been derived from this sample). There are %s registered datasets.",
                        numberOfDatasets));

                helpers.Utils.Notification("No datasets available.",
                        "No data is connected to this sample. Please contact the project manager if this is not expected.",
                        "warning");
            }
        }

        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);

            numberOfDatasets = dsBeans.size();

            if (type.equals("project")) {
                headerLabel.setValue(String.format(
                        "This view shows all datasets associated with this project. There are %s registered datasets.",
                        numberOfDatasets));
            } else if (type.equals("sample")) {
                headerLabel.setValue(String.format(
                        "This view shows all datasets associated with this sample (including samples which have been derived from this sample). There are %s registered datasets.",
                        numberOfDatasets));
            }

            for (DatasetBean d : dsBeans) {
                Date date = d.getRegistrationDate();
                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
                String dateString = sd.format(date);
                // Timestamp ts = Timestamp.valueOf(dateString);
                String sampleID = samples.get(d.getCode());

                Sample dsSample = checkedTestSamples.get(sampleID);

                String secNameDS = d.getProperties().get("Q_SECONDARY_NAME");

                String secName = datahandler.getSecondaryName(dsSample, secNameDS);

                forExport.addBean(d);

                registerDatasetInTable(d, datasetContainer, projectCode, sampleID, dateString, null, secName);
            }
        }

        this.setContainerDataSource(datasetContainer);

        if (fileDownloader != null)
            this.export.removeExtension(fileDownloader);
        StreamResource sr = Utils.getTSVStream(Utils.containerToString(forExport),
                String.format("%s_%s_", id.substring(1).replace("/", "_"), "registered_datasets"));
        fileDownloader = new FileDownloader(sr);
        fileDownloader.extend(export);

    } catch (

    Exception e) {
        e.printStackTrace();
        LOGGER.error(String.format("getting dataset failed for dataset %s %s", type, id), e.getStackTrace());
    }
}

From source file:de.uni_tuebingen.qbic.qbicmainportlet.ExperimentComponent.java

License:Open Source License

public void updateUI(ProjectBean currentBean) {
    projectBean = currentBean;/*from  ww  w .  j a va2 s  .  c o  m*/
    experiments.removeAllColumns();
    // experiments.setContainerDataSource(projectBean.getExperiments());

    // BeanItemContainer<ExperimentBean> experimentBeans =
    // loadMoreExperimentInformation(projectBean.getExperiments());
    // GeneratedPropertyContainer gpc = new GeneratedPropertyContainer(experimentBeans);
    GeneratedPropertyContainer gpc = new GeneratedPropertyContainer(projectBean.getExperiments());

    gpc.removeContainerProperty("containsData");
    gpc.removeContainerProperty("controlledVocabularies");
    gpc.removeContainerProperty("id");
    gpc.removeContainerProperty("lastChangedDataset");
    gpc.removeContainerProperty("lastChangedSample");
    gpc.removeContainerProperty("properties");
    gpc.removeContainerProperty("type");
    gpc.removeContainerProperty("samples");
    gpc.removeContainerProperty("status");
    gpc.removeContainerProperty("typeLabels");
    gpc.removeContainerProperty("registrationDate");

    experiments.addItemClickListener(new ItemClickListener() {

        /**
         * 
         */
        private static final long serialVersionUID = -43367719647620455L;

        @Override
        public void itemClick(ItemClickEvent event) {

            BeanItem selected = (BeanItem) projectBean.getExperiments().getItem(event.getItemId());
            ExperimentBean selectedExp = (ExperimentBean) selected.getBean();

            State state = (State) UI.getCurrent().getSession().getAttribute("state");
            ArrayList<String> message = new ArrayList<String>();
            message.add("clicked");
            message.add(selectedExp.getId());
            message.add("experiment");
            state.notifyObservers(message);
        }
    });

    gpc.addGeneratedProperty("edit", new PropertyValueGenerator<String>() {

        /**
         * 
         */
        private static final long serialVersionUID = 7558511163500976236L;

        @Override
        public String getValue(Item item, Object itemId, Object propertyId) {
            return "Edit";
        }

        @Override
        public Class<String> getType() {
            return String.class;
        }
    });

    gpc.addGeneratedProperty("registrationDate", new PropertyValueGenerator<String>() {

        @Override
        public Class<String> getType() {
            return String.class;
        }

        @Override
        public String getValue(Item item, Object itemId, Object propertyId) {
            BeanItem selected = (BeanItem) projectBean.getExperiments().getItem(itemId);
            ExperimentBean expBean = (ExperimentBean) selected.getBean();
            Date date = expBean.getRegistrationDate();
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
            String dateString = sd.format(date);

            return dateString;
        }
    });

    experiments.setContainerDataSource(gpc);
    experiments.getColumn("prettyType").setHeaderCaption("Type");
    experiments.getColumn("edit").setRenderer(new ButtonRenderer(new RendererClickListener() {

        @Override
        public void click(RendererClickEvent event) {
            BeanItem selected = (BeanItem) projectBean.getExperiments().getItem(event.getItemId());
            ExperimentBean selectedSample = (ExperimentBean) selected.getBean();

            Window subWindow = new Window("Edit Metadata");

            changeMetadata.updateUI(selectedSample.getId(), selectedSample.getType());
            VerticalLayout subContent = new VerticalLayout();
            subContent.setMargin(true);
            subContent.addComponent(changeMetadata);
            subWindow.setContent(subContent);
            // Center it in the browser window
            subWindow.center();
            subWindow.setModal(true);
            subWindow.setSizeUndefined();
            subWindow.setIcon(FontAwesome.PENCIL);
            subWindow.setHeight("75%");
            subWindow.setResizable(false);

            QbicmainportletUI ui = (QbicmainportletUI) UI.getCurrent();
            ui.addWindow(subWindow);
        }

    }));

    experiments.getColumn("edit").setWidth(70);
    experiments.setColumnOrder("edit", "prettyType");
    experiments.getColumn("edit").setHeaderCaption("");

    // experiments.setHeightMode(HeightMode.ROW);
    // experiments.setHeightByRows(gpc.size());

    if (fileDownloader != null)
        this.export.removeExtension(fileDownloader);
    StreamResource sr = Utils.getTSVStream(Utils.containerToString(projectBean.getExperiments()),
            String.format("%s_%s_", projectBean.getId().substring(1).replace("/", "_"), "experimental_steps"));
    fileDownloader = new FileDownloader(sr);
    fileDownloader.extend(export);
}

From source file:de.uni_tuebingen.qbic.qbicmainportlet.ExperimentView.java

License:Open Source License

void updateContentButtonLayout() {
    if (fileDownloader != null)
        this.export.removeExtension(fileDownloader);
    StreamResource sr = Utils.getTSVStream(Utils.containerToString(currentBean.getSamples()),
            currentBean.getId());/*from   w ww. j  a va2  s.co  m*/
    fileDownloader = new FileDownloader(sr);
    fileDownloader.extend(this.export);
}