Example usage for com.vaadin.ui Button addClickListener

List of usage examples for com.vaadin.ui Button addClickListener

Introduction

In this page you can find the example usage for com.vaadin.ui Button addClickListener.

Prototype

public Registration addClickListener(ClickListener listener) 

Source Link

Document

Adds the button click listener.

Usage

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

License:Apache License

@Override
public Button addBackButton(String caption, ClickListener clickListener) {
    AbstractOrderedLayout layout = getLayoutInternal();

    Button backButton = new Button(caption);
    backButton.addClickListener(clickListener);
    layout.addComponent(backButton, 0);//ww w  . j  av a  2 s. c o  m
    layout.setComponentAlignment(backButton, Alignment.MIDDLE_RIGHT);
    return backButton;
}

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

License:Apache License

private void buildViewComponents(boolean addSwitchModeButton) {
    fieldLayout = new FormLayout();
    addComponent(fieldLayout);// www  .j  av  a 2s . c om

    errorLabel = new Label();
    errorLabel.setStyleName("error");
    errorLabel.setVisible(false);
    addComponent(errorLabel);

    footerLayout = new CssLayout();
    footerLayout.setStyleName("actions");
    addComponent(footerLayout);

    if (addSwitchModeButton) {
        switchModeButton = new Button(getMessage("portlet.crud.button.editMode"));
        switchModeButton.addClickListener(new ClickListener() {
            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                presenter.changeMode();
            }
        });
        footerLayout.addComponent(switchModeButton);
    }

    saveButton = new Button(getMessage("portlet.crud.button.save"));
    saveButton.addClickListener(new ClickListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            presenter.save();
        }
    });

    resetButton = new Button(getMessage("portlet.crud.button.reset"));
    resetButton.addClickListener(new ClickListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            presenter.resetFields();
        }
    });

    deleteButton = new Button(getMessage("portlet.crud.button.remove"));
    deleteButton.addClickListener(new ClickListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            presenter.delete();
        }
    });

    previousRowButton = new Button(getMessage("portlet.crud.button.previousRow"));
    previousRowButton.addClickListener(new ClickListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            presenter.previousRow();
        }
    });

    nextRowButton = new Button(getMessage("portlet.crud.button.nextRow"));
    nextRowButton.addClickListener(new ClickListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            presenter.nextRow();
        }
    });

    Button cancelButton = new Button(getMessage("portlet.crud.button.cancel"));
    cancelButton.addClickListener(new ClickListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            presenter.cancel();
        }
    });
    footerLayout.addComponents(saveButton, saveButton, deleteButton, previousRowButton, nextRowButton,
            cancelButton);
}

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

License:Apache License

private void addCustomButtonsListeners() {
    if (!actionButtons.isEmpty()) {
        for (final Button button : actionButtons.values()) {
            button.setDisableOnClick(true);
            final TableAction action = buttonToTableActionMap.get(button);
            button.addClickListener(new Button.ClickListener() {

                private static final long serialVersionUID = 42L;

                @Override/*from  w  ww.  ja v a 2s . c om*/
                public void buttonClick(ClickEvent event) {
                    try {
                        presenter.callClosure(action);

                        if (action.isExportAction()) {
                            switch (action.getExportType()) {
                            case XLS:
                                exportExcelSheet(action.generateExportFilename());
                                break;
                            case CSV:
                                exportCSVSheet(action.generateExportFilename());
                                break;
                            default:
                                throw new IllegalArgumentException("Unknown export type '"
                                        + action.getExportType() + "' set on action with title '"
                                        + action.getTitle() + "' and id '" + action.getId() + "'");
                            }
                        }
                    } finally {
                        button.setEnabled(true);
                    }
                }
            });
        }
    }
}

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

License:Open Source License

/**
 * /*  www  .  j a va2s  .co m*/
 * @return
 */
void initOptionLayout() {
    optionLayout.removeAllComponents();
    optionLayout.setWidth("100%");
    optionLayout.setVisible(false);

    VerticalLayout optionLayoutContent = new VerticalLayout();

    Button addSample = new Button("Add Sample");
    addSample.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            sampleOptions.addBean(new NewIvacSampleBean("", 0, "", false, false, false, "", ""));
        }
    });

    optionLayoutContent.setMargin(new MarginInfo(true, false, false, false));
    optionLayoutContent.setHeight(null);
    optionLayoutContent.setWidth("100%");
    optionLayoutContent.setSpacing(true);

    final Grid optionGrid = new Grid();
    optionGrid.setWidth("80%");
    // optionGrid.setCaption("Which biological samples are available for the patient(s) and which
    // experiments will be performed?");

    gridInfo = new CustomVisibilityComponent(new Label(""));
    ((Label) gridInfo.getInnerComponent()).addStyleName(ValoTheme.LABEL_LARGE);

    Component gridInfoContent = Utils.questionize(gridInfo,
            "Which biological samples are available for the patient(s) and which experiments will be performed?",
            "Extracted Samples");

    // optionGrid.setSelectionMode(SelectionMode.MULTI);
    optionGrid.setEditorEnabled(true);

    optionGrid.setContainerDataSource(sampleOptions);
    optionGrid.setColumnOrder("type", "secondaryName", "tissue", "amount", "dnaSeq", "rnaSeq", "deepSeq");

    optionLayoutContent.addComponent(gridInfoContent);
    optionLayoutContent.addComponent(optionGrid);
    optionLayoutContent.addComponent(addSample);

    final GridEditForm form = new GridEditForm(
            datahandler.getOpenBisClient().getVocabCodesForVocab("Q_PRIMARY_TISSUES"),
            datahandler.getOpenBisClient().getVocabCodesForVocab("Q_SEQUENCER_DEVICES"));

    optionLayoutContent.addComponent(form);
    form.setVisible(false);

    optionGrid.addSelectionListener(new SelectionListener() {

        @Override
        public void select(SelectionEvent event) {
            BeanItem<NewIvacSampleBean> item = sampleOptions.getItem(optionGrid.getSelectedRow());
            form.fieldGroup.setItemDataSource(item);
            form.setVisible(true);
        }
    });

    optionLayout.addComponent(optionLayoutContent);
}

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

License:Open Source License

public void updateUI(final String id, String type) {
    propLayout.removeAllComponents();/*from w w  w. j  a  va2 s. co  m*/
    Button saveButton = new Button("Submit Changes");
    saveButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);

    completeProperties = datahandler.getOpenBisClient()
            .listPropertiesForType(datahandler.getOpenBisClient().getExperimentTypeByString(type));

    assignedProperties = datahandler.getOpenBisClient().getExperimentById2(id).get(0).getProperties();

    saveButton.addClickListener(new ClickListener() {
        @Override
        public void buttonClick(final ClickEvent event) {
            HashMap<String, Object> props = new HashMap<String, Object>();
            Collection<Field<?>> registeredFields = fieldGroup.getFields();
            XMLParser xmlParser = new XMLParser();

            List<Property> factors = new ArrayList<Property>();

            boolean qpropertiesDefined = false;

            for (Field<?> field : registeredFields) {
                if (field.getDescription().equals("Q_PROPERTIES")) {
                    TextField tf = (TextField) field;
                    qpropertiesDefined = true;
                    String label = tf.getCaption();
                    String val = (String) tf.getValue();
                    String[] splt = label.split(" in ");
                    Property f = null;
                    PropertyType type = (PropertyType) tf.getData();
                    if (splt.length > 1) {
                        label = splt[0];
                        properties.Unit unit = properties.Unit.valueOf(splt[1]);
                        f = new Property(label, val, unit, type);
                    } else {
                        f = new Property(label, val, type);
                    }
                    factors.add(f);
                }

                else {
                    props.put(field.getDescription(), field.getValue());
                }
            }

            if (qpropertiesDefined) {
                String qProperties = "";

                try {
                    qProperties = xmlParser.toString(xmlParser.createXMLFromProperties(factors));
                    props.put("Q_PROPERTIES", qProperties);
                } catch (JAXBException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            HashMap<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("user", LiferayAndVaadinUtils.getUser().getScreenName());
            parameters.put("identifier", id);
            parameters.put("properties", props);

            datahandler.getOpenBisClient().triggerIngestionService("update-experiment-metadata", parameters);
            Utils.Notification("Metadata changed succesfully",
                    String.format("Metadata values of experiment %s have been commited successfully.", id),
                    "success");
        }
    });
    buildFormLayout();
    propLayout.addComponent(new Label(String.format(
            "This view shows metadata connected to this experiment and can be used to change the corresponding values. \nIdentifier: %s",
            id), Label.CONTENT_PREFORMATTED));

    propLayout.addComponent(this.form);
    propLayout.addComponent(saveButton);
}

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

License:Open Source License

public void updateUI(final ProjectBean projectBean) {
    properties.removeAllComponents();/*from  w  ww  . ja v a 2 s.  c o  m*/
    Button saveButton = new Button("Submit Changes");
    saveButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);

    currentDescription = projectBean.getDescription();

    saveButton.addClickListener(new ClickListener() {
        @Override
        public void buttonClick(final ClickEvent event) {
            HashMap<String, Object> parameters = new HashMap<String, Object>();
            Collection<Field<?>> registeredFields = fieldGroup.getFields();

            // List<Property> factors = new ArrayList<Property>();

            for (Field<?> field : registeredFields) {
                parameters.put("description", field.getValue());
            }

            parameters.put("identifier", projectBean.getId());
            parameters.put("user", LiferayAndVaadinUtils.getUser().getScreenName());
            datahandler.getOpenBisClient().triggerIngestionService("update-project-metadata", parameters);
            Utils.Notification("Project details changed succesfully", String.format(
                    "Details of project %s have been commited successfully.", projectBean.getId()), "success");
        }
    });

    buildFormLayout();
    Label desc = new Label(String.format(
            "This view shows project details and can be used to change the corresponding values. \nIdentifier: %s",
            projectBean.getId()), Label.CONTENT_PREFORMATTED);
    desc.setWidth("50%");
    properties.addComponent(desc);

    properties.addComponent(this.form);
    properties.addComponent(saveButton);
}

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

License:Open Source License

public void updateUI(final String id, String type) {
    propLayout.removeAllComponents();//  w w  w . j  a v  a  2  s  .co m
    Button saveButton = new Button("Submit Changes");
    saveButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);

    completeProperties = datahandler.getOpenBisClient()
            .listPropertiesForType(datahandler.getOpenBisClient().getSampleTypeByString(type));

    assignedProperties = datahandler.getOpenBisClient().getSampleByIdentifier(id).getProperties();

    saveButton.addClickListener(new ClickListener() {
        @Override
        public void buttonClick(final ClickEvent event) {
            HashMap<String, Object> props = new HashMap<String, Object>();
            Collection<Field<?>> registeredFields = fieldGroup.getFields();
            XMLParser xmlParser = new XMLParser();

            List<Property> factors = new ArrayList<Property>();

            boolean qpropertiesDefined = false;

            for (Field<?> field : registeredFields) {
                if (field.getDescription().equals("Q_PROPERTIES")) {
                    TextField tf = (TextField) field;
                    qpropertiesDefined = true;
                    String label = tf.getCaption();
                    String val = (String) tf.getValue();
                    String[] splt = label.split(" in ");
                    Property f = null;
                    properties.PropertyType type = (properties.PropertyType) tf.getData();
                    if (splt.length > 1) {
                        label = splt[0];
                        properties.Unit unit = properties.Unit.valueOf(splt[1]);
                        f = new Property(label, val, unit, type);
                    } else {
                        f = new Property(label, val, type);
                    }
                    factors.add(f);
                }

                else {
                    props.put(field.getDescription(), field.getValue());
                }
            }

            if (qpropertiesDefined) {
                String qProperties = "";

                try {
                    qProperties = xmlParser.toString(xmlParser.createXMLFromProperties(factors));
                    props.put("Q_PROPERTIES", qProperties);
                } catch (JAXBException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            HashMap<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("user", LiferayAndVaadinUtils.getUser().getScreenName());
            parameters.put("identifier", id);
            parameters.put("properties", props);

            datahandler.getOpenBisClient().triggerIngestionService("update-single-sample-metadata", parameters);
            Utils.Notification("Metadata changed succesfully",
                    String.format("Metadata values of sample %s have been commited successfully.", id),
                    "success");
        }
    });
    buildFormLayout();
    propLayout.addComponent(new Label(String.format(
            "This view shows metadata connected to this sample and can be used to change the corresponding values. \nIdentifier: %s",
            id), Label.CONTENT_PREFORMATTED));

    propLayout.addComponent(this.form);
    propLayout.addComponent(saveButton);
}

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

License:Open Source License

/**
 * Precondition: {DatasetView#table} has to be initialized. e.g. with
 * {DatasetView#buildFilterTable} If it is not, strange behaviour has to be expected. builds the
 * Layout of this view.//from   www. j a v a  2s . c  o m
 */
private void buildLayout() {
    this.vert.removeAllComponents();
    this.vert.setSizeFull();

    vert.setResponsive(true);

    // Table (containing datasets) section
    VerticalLayout tableSection = new VerticalLayout();
    HorizontalLayout tableSectionContent = new HorizontalLayout();
    tableSection.setResponsive(true);
    tableSectionContent.setResponsive(true);

    // tableSectionContent.setCaption("Datasets");
    // tableSectionContent.setIcon(FontAwesome.FLASK);
    // tableSection.addComponent(new Label(String.format("This project contains %s dataset(s).",
    // numberOfDatasets)));
    tableSectionContent.setMargin(new MarginInfo(true, false, true, false));

    tableSection.addComponent(headerLabel);
    tableSectionContent.addComponent(this.table);
    vert.setMargin(new MarginInfo(false, true, false, false));

    tableSection.setMargin(new MarginInfo(true, false, false, true));
    // tableSectionContent.setMargin(true);
    // tableSection.setMargin(true);

    tableSection.addComponent(tableSectionContent);
    this.vert.addComponent(tableSection);

    table.setSizeFull();
    tableSection.setSizeFull();
    tableSectionContent.setSizeFull();

    // this.table.setSizeFull();

    HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setMargin(new MarginInfo(false, false, true, true));
    buttonLayout.setHeight(null);
    // buttonLayout.setWidth("100%");
    buttonLayout.setSpacing(true);
    buttonLayout.setResponsive(true);

    // final Button visualize = new Button(VISUALIZE_BUTTON_CAPTION);

    Button checkAll = new Button("Select all datasets");
    checkAll.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            for (Object itemId : table.getItemIds()) {
                ((CheckBox) table.getItem(itemId).getItemProperty("Select").getValue()).setValue(true);
            }
        }
    });

    Button uncheckAll = new Button("Unselect all datasets");
    uncheckAll.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            for (Object itemId : table.getItemIds()) {
                ((CheckBox) table.getItem(itemId).getItemProperty("Select").getValue()).setValue(false);
            }
        }
    });

    String content = "<p> In case of multiple file selections, Project Browser will create a tar archive.</p>"
            + "<hr>" + "<p> If you need help on extracting a tar archive file, follow the tips below: </p>"
            + "<p>" + FontAwesome.WINDOWS.getHtml() + " Windows </p>"
            + "<p> To open/extract TAR file on Windows, you can use 7-Zip, Easy 7-Zip, PeaZip.</p>" + "<hr>"
            + "<p>" + FontAwesome.APPLE.getHtml() + " MacOS </p>"
            + "<p> To open/extract TAR file on Mac, you can use Mac OS built-in utility Archive Utility,<br> or third-party freeware. </p>"
            + "<hr>" + "<p>" + FontAwesome.LINUX.getHtml() + " Linux </p>"
            + "<p> You need to use command tar. The tar is the GNU version of tar archiving utility. <br> "
            + "To extract/unpack a tar file, type: $ tar -xvf file.tar</p>";

    export.setIcon(FontAwesome.DOWNLOAD);

    PopupView tooltip = new PopupView(new helpers.ToolTip(content));
    tooltip.setHeight("44px");

    HorizontalLayout help = new HorizontalLayout();
    help.setSizeFull();
    HorizontalLayout helpContent = new HorizontalLayout();
    // helpContent.setSizeFull();

    help.setMargin(new MarginInfo(false, false, false, true));
    Label helpText = new Label("Attention: Click here before Download!");
    helpContent.addComponent(new Label(FontAwesome.QUESTION_CIRCLE.getHtml(), ContentMode.HTML));
    helpContent.addComponent(helpText);
    helpContent.addComponent(tooltip);
    helpContent.setSpacing(true);

    help.addComponent(helpContent);
    help.setComponentAlignment(helpContent, Alignment.TOP_CENTER);

    buttonLayout.addComponent(export);
    buttonLayout.addComponent(checkAll);
    buttonLayout.addComponent(uncheckAll);
    // buttonLayout.addComponent(visualize);
    buttonLayout.addComponent(this.download);

    /**
     * prepare download.
     */
    download.setEnabled(false);
    download.setResource(new ExternalResource("javascript:"));
    // visualize.setEnabled(false);

    for (final Object itemId : this.table.getItemIds()) {
        setCheckedBox(itemId, (String) this.table.getItem(itemId).getItemProperty("CODE").getValue());
    }

    this.table.addItemClickListener(new ItemClickListener() {
        @Override
        public void itemClick(ItemClickEvent event) {
            if (!event.isDoubleClick()
                    & !((boolean) table.getItem(event.getItemId()).getItemProperty("isDirectory").getValue())) {
                String datasetCode = (String) table.getItem(event.getItemId()).getItemProperty("CODE")
                        .getValue();
                String datasetFileName = (String) table.getItem(event.getItemId()).getItemProperty("File Name")
                        .getValue();
                URL url;
                try {
                    Resource res = null;
                    Object parent = table.getParent(event.getItemId());
                    if (parent != null) {
                        String parentDatasetFileName = (String) table.getItem(parent)
                                .getItemProperty("File Name").getValue();
                        url = datahandler.getOpenBisClient().getUrlForDataset(datasetCode,
                                parentDatasetFileName + "/" + datasetFileName);
                    } else {
                        url = datahandler.getOpenBisClient().getUrlForDataset(datasetCode, datasetFileName);
                    }

                    Window subWindow = new Window();
                    VerticalLayout subContent = new VerticalLayout();
                    subContent.setMargin(true);
                    subContent.setSizeFull();
                    subWindow.setContent(subContent);
                    QbicmainportletUI ui = (QbicmainportletUI) UI.getCurrent();
                    Boolean visualize = false;

                    if (datasetFileName.endsWith(".pdf")) {
                        QcMlOpenbisSource re = new QcMlOpenbisSource(url);
                        StreamResource streamres = new StreamResource(re, datasetFileName);
                        streamres.setMIMEType("application/pdf");
                        res = streamres;
                        visualize = true;
                    }

                    if (datasetFileName.endsWith(".png")) {
                        QcMlOpenbisSource re = new QcMlOpenbisSource(url);
                        StreamResource streamres = new StreamResource(re, datasetFileName);
                        // streamres.setMIMEType("application/png");
                        res = streamres;
                        visualize = true;
                    }

                    if (datasetFileName.endsWith(".qcML")) {
                        QcMlOpenbisSource re = new QcMlOpenbisSource(url);
                        StreamResource streamres = new StreamResource(re, datasetFileName);
                        streamres.setMIMEType("text/xml");
                        res = streamres;
                        visualize = true;
                    }

                    if (datasetFileName.endsWith(".alleles")) {
                        QcMlOpenbisSource re = new QcMlOpenbisSource(url);
                        StreamResource streamres = new StreamResource(re, datasetFileName);
                        streamres.setMIMEType("text/plain");
                        res = streamres;
                        visualize = true;
                    }

                    if (datasetFileName.endsWith(".tsv")) {
                        QcMlOpenbisSource re = new QcMlOpenbisSource(url);
                        StreamResource streamres = new StreamResource(re, datasetFileName);
                        streamres.setMIMEType("text/plain");
                        res = streamres;
                        visualize = true;
                    }

                    if (datasetFileName.endsWith(".GSvar")) {
                        QcMlOpenbisSource re = new QcMlOpenbisSource(url);
                        StreamResource streamres = new StreamResource(re, datasetFileName);
                        streamres.setMIMEType("text/plain");
                        res = streamres;
                        visualize = true;
                    }

                    if (datasetFileName.endsWith(".log")) {
                        QcMlOpenbisSource re = new QcMlOpenbisSource(url);
                        StreamResource streamres = new StreamResource(re, datasetFileName);
                        streamres.setMIMEType("text/plain");
                        res = streamres;
                        visualize = true;
                    }

                    if (datasetFileName.endsWith(".html")) {
                        QcMlOpenbisSource re = new QcMlOpenbisSource(url);
                        StreamResource streamres = new StreamResource(re, datasetFileName);
                        streamres.setMIMEType("text/html");
                        res = streamres;
                        visualize = true;
                    }

                    if (visualize) {
                        // LOGGER.debug("Is resource null?: " + String.valueOf(res == null));
                        BrowserFrame frame = new BrowserFrame("", res);

                        subContent.addComponent(frame);

                        // Center it in the browser window
                        subWindow.center();
                        subWindow.setModal(true);
                        subWindow.setSizeUndefined();
                        subWindow.setHeight("75%");
                        subWindow.setWidth("75%");
                        subWindow.setResizable(false);

                        frame.setSizeFull();
                        frame.setHeight("100%");
                        // frame.setHeight((int) (ui.getPage().getBrowserWindowHeight() * 0.9), Unit.PIXELS);

                        // Open it in the UI
                        ui.addWindow(subWindow);
                    }

                } catch (MalformedURLException e) {
                    LOGGER.error(String.format("Visualization failed because of malformedURL for dataset: %s",
                            datasetCode));
                    Notification.show(
                            "Given dataset has no file attached to it!! Please Contact your project manager. Or check whether it already has some data",
                            Notification.Type.ERROR_MESSAGE);
                }
            }
        }
    });

    this.vert.addComponent(buttonLayout);
    this.vert.addComponent(help);

}

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

License:Open Source License

/**
 * Precondition: {DatasetView#table} has to be initialized. e.g. with
 * {DatasetView#buildFilterTable} If it is not, strange behaviour has to be expected. builds the
 * Layout of this view./* w  ww .j  a  v a2 s  .  c om*/
 */
private void buildLayout() {
    this.vert.removeAllComponents();

    int browserWidth = UI.getCurrent().getPage().getBrowserWindowWidth();
    int browserHeight = UI.getCurrent().getPage().getBrowserWindowHeight();

    this.vert.setWidth("100%");
    this.setWidth(String.format("%spx", (browserWidth * 0.6)));
    // this.setHeight(String.format("%spx", (browserHeight * 0.8)));

    VerticalLayout statistics = new VerticalLayout();
    HorizontalLayout statContent = new HorizontalLayout();
    statContent.setCaption("Statistics");
    statContent.setIcon(FontAwesome.BAR_CHART_O);
    statContent.addComponent(new Label(String.format("%s registered dataset(s).", numberOfDatasets)));
    statContent.setMargin(true);
    statContent.setSpacing(true);
    statistics.addComponent(statContent);
    statistics.setMargin(true);
    this.vert.addComponent(statistics);

    // Table (containing datasets) section
    VerticalLayout tableSection = new VerticalLayout();
    HorizontalLayout tableSectionContent = new HorizontalLayout();

    tableSectionContent.setCaption("Registered Datasets");
    tableSectionContent.setIcon(FontAwesome.FLASK);
    tableSectionContent.addComponent(this.table);

    tableSectionContent.setMargin(true);
    tableSection.setMargin(true);

    tableSection.addComponent(tableSectionContent);
    this.vert.addComponent(tableSection);

    table.setWidth("100%");
    tableSection.setWidth("100%");
    tableSectionContent.setWidth("100%");

    // this.table.setSizeFull();

    HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setHeight(null);
    buttonLayout.setWidth("100%");
    buttonLayout.setSpacing(false);

    final Button visualize = new Button(VISUALIZE_BUTTON_CAPTION);
    buttonLayout.addComponent(this.download);
    buttonLayout.addComponent(visualize);

    Button checkAll = new Button("Select all datasets");
    checkAll.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            for (Object itemId : table.getItemIds()) {
                ((CheckBox) table.getItem(itemId).getItemProperty("Select").getValue()).setValue(true);
            }
        }
    });

    Button uncheckAll = new Button("Unselect all datasets");
    uncheckAll.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            for (Object itemId : table.getItemIds()) {
                ((CheckBox) table.getItem(itemId).getItemProperty("Select").getValue()).setValue(false);
            }
        }
    });

    buttonLayout.addComponent(checkAll);
    buttonLayout.addComponent(uncheckAll);
    /**
     * prepare download.
     */
    download.setResource(new ExternalResource("javascript:"));
    download.setEnabled(false);
    visualize.setEnabled(false);

    for (final Object itemId : this.table.getItemIds()) {
        setCheckedBox(itemId, (String) this.table.getItem(itemId).getItemProperty("CODE").getValue());
    }

    /*
     * Update the visualize button. It is only enabled, if the files can be visualized.
     */
    this.table.addValueChangeListener(new ValueChangeListener() {
        /**
         * 
         */
        private static final long serialVersionUID = -4875903343717437913L;

        /**
         * check for what selection can be visualized. If so, enable the button. TODO change to
         * checked.
         */
        @Override
        public void valueChange(ValueChangeEvent event) {
            // Nothing selected or more than one selected.
            Set<Object> selectedValues = (Set<Object>) event.getProperty().getValue();
            if (selectedValues == null || selectedValues.size() == 0 || selectedValues.size() > 1) {
                visualize.setEnabled(false);
                return;
            }
            // if one selected check whether its dataset type is either fastqc or qcml.
            // For now we only visulize these two file types.
            Iterator<Object> iterator = selectedValues.iterator();
            Object next = iterator.next();
            String datasetType = (String) table.getItem(next).getItemProperty("Dataset Type").getValue();
            String fileName = (String) table.getItem(next).getItemProperty("File Name").getValue();
            // TODO: No hardcoding!!
            // if (datasetType.equals("FASTQC") || datasetType.equals("QCML") ||
            // datasetType.equals("BAM")
            // || datasetType.equals("VCF")) {
            if (datasetType.equals("Q_WF_MS_QUALITYCONTROL_RESULTS")
                    && (fileName.endsWith(".html") || fileName.endsWith(".qcML"))) {
                visualize.setEnabled(true);
            } else if (datasetType.equals("Q_WF_MS_QUALITYCONTROL_LOGS")
                    && (fileName.endsWith(".err") || fileName.endsWith(".out"))) {
                visualize.setEnabled(true);
            } else {
                visualize.setEnabled(false);
            }
        }
    });

    // TODO Workflow Views should get those data and be happy
    /*
     * Send message that in datasetview the following was selected. WorkflowViews get those messages
     * and save them, if it is valid information for them.
     */
    this.table.addValueChangeListener(new ValueChangeListener() {
        /**
         * 
         */
        private static final long serialVersionUID = -3554627008191389648L;

        @Override
        public void valueChange(ValueChangeEvent event) {
            // Nothing selected or more than one selected.
            Set<Object> selectedValues = (Set<Object>) event.getProperty().getValue();
            State state = (State) UI.getCurrent().getSession().getAttribute("state");
            ArrayList<String> message = new ArrayList<String>();
            message.add("DataSetView");
            if (selectedValues != null && selectedValues.size() == 1) {
                Iterator<Object> iterator = selectedValues.iterator();
                Object next = iterator.next();
                String datasetType = (String) table.getItem(next).getItemProperty("Dataset Type").getValue();
                message.add(datasetType);
                String project = (String) table.getItem(next).getItemProperty("Project").getValue();

                String space = datahandler.getOpenBisClient().getProjectByCode(project).getSpaceCode();// .getIdentifier().split("/")[1];
                message.add(project);
                message.add((String) table.getItem(next).getItemProperty("Sample").getValue());
                // message.add((String) table.getItem(next).getItemProperty("Sample Type").getValue());
                message.add((String) table.getItem(next).getItemProperty("dl_link").getValue());
                message.add((String) table.getItem(next).getItemProperty("File Name").getValue());
                message.add(space);
                // state.notifyObservers(message);
            } else {
                message.add("null");
            } // TODO
              // state.notifyObservers(message);

        }
    });

    // TODO get the GV to work here. Together with reverse proxy
    // Assumes that table Value Change listner is enabling or disabling the button if preconditions
    // are not fullfilled
    visualize.addClickListener(new ClickListener() {
        /**
         * 
         */
        private static final long serialVersionUID = 9015273307461506369L;

        @Override
        public void buttonClick(ClickEvent event) {
            Set<Object> selectedValues = (Set<Object>) table.getValue();
            Iterator<Object> iterator = selectedValues.iterator();
            Object next = iterator.next();
            String datasetCode = (String) table.getItem(next).getItemProperty("CODE").getValue();
            String datasetFileName = (String) table.getItem(next).getItemProperty("File Name").getValue();
            URL url;
            try {
                Object parent = table.getParent(next);
                if (parent != null) {
                    String parentDatasetFileName = (String) table.getItem(parent).getItemProperty("File Name")
                            .getValue();
                    url = datahandler.getOpenBisClient().getUrlForDataset(datasetCode,
                            parentDatasetFileName + "/" + datasetFileName);
                } else {
                    url = datahandler.getOpenBisClient().getUrlForDataset(datasetCode, datasetFileName);
                }

                Window subWindow = new Window(
                        "QC of Sample: " + (String) table.getItem(next).getItemProperty("Sample").getValue());
                VerticalLayout subContent = new VerticalLayout();
                subContent.setMargin(true);
                subWindow.setContent(subContent);
                QbicmainportletUI ui = (QbicmainportletUI) UI.getCurrent();
                // Put some components in it
                Resource res = null;
                String datasetType = (String) table.getItem(next).getItemProperty("Dataset Type").getValue();
                final RequestHandler rh = new ProxyForGenomeViewerRestApi();
                boolean rhAttached = false;
                if (datasetType.equals("Q_WF_MS_QUALITYCONTROL_RESULTS") && datasetFileName.endsWith(".qcML")) {
                    QcMlOpenbisSource re = new QcMlOpenbisSource(url);
                    StreamResource streamres = new StreamResource(re, datasetFileName);
                    streamres.setMIMEType("application/xml");
                    res = streamres;
                } else if (datasetType.equals("Q_WF_MS_QUALITYCONTROL_RESULTS")
                        && datasetFileName.endsWith(".html")) {
                    QcMlOpenbisSource re = new QcMlOpenbisSource(url);
                    StreamResource streamres = new StreamResource(re, datasetFileName);
                    streamres.setMIMEType("text/html");
                    res = streamres;
                } else if (datasetType.equals("Q_WF_MS_QUALITYCONTROL_LOGS")
                        && (datasetFileName.endsWith(".err") || datasetFileName.endsWith(".out"))) {
                    QcMlOpenbisSource re = new QcMlOpenbisSource(url);
                    StreamResource streamres = new StreamResource(re, datasetFileName);
                    streamres.setMIMEType("text/plain");
                    res = streamres;
                } else if (datasetType.equals("FASTQC")) {
                    res = new ExternalResource(url);
                } else if (datasetType.equals("BAM") || datasetType.equals("VCF")) {
                    String filePath = (String) table.getItem(next).getItemProperty("dl_link").getValue();
                    filePath = String.format("/store%s", filePath.split("store")[1]);
                    String fileId = (String) table.getItem(next).getItemProperty("File Name").getValue();
                    // fileId = "control.1kg.panel.samples.vcf.gz";
                    // UI.getCurrent().getSession().addRequestHandler(rh);
                    rhAttached = true;
                    ThemeDisplay themedisplay = (ThemeDisplay) VaadinService.getCurrentRequest()
                            .getAttribute(WebKeys.THEME_DISPLAY);
                    String hostTmp = "http://localhost:7778/vizrest/rest";// "http://localhost:8080/web/guest/mainportlet?p_p_id=QbicmainportletApplicationPortlet_WAR_QBiCMainPortlet_INSTANCE_5pPd5JQ8uGOt&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_cacheability=cacheLevelPage&p_p_col_id=column-1&p_p_col_count=1";
                    // hostTmp +=
                    // "&qbicsession=" + UI.getCurrent().getSession().getAttribute("gv-restapi-session")
                    // + "&someblabla=";
                    // String hostTmp = themedisplay.getURLPortal() +
                    // UI.getCurrent().getPage().getLocation().getPath() + "?qbicsession=" +
                    // UI.getCurrent().getSession().getAttribute("gv-restapi-session") + "&someblabla=" ;
                    // String host = Base64.encode(hostTmp.getBytes());
                    String title = (String) table.getItem(next).getItemProperty("Sample").getValue();
                    // res =
                    // new ExternalResource(
                    // String
                    // .format(
                    // "http://localhost:7778/genomeviewer/?host=%s&title=%s&fileid=%s&featuretype=alignments&filepath=%s&removeZeroGenotypes=false",
                    // host, title, fileId, filePath));
                }
                BrowserFrame frame = new BrowserFrame("", res);
                if (rhAttached) {
                    frame.addDetachListener(new DetachListener() {

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

                        @Override
                        public void detach(DetachEvent event) {
                            UI.getCurrent().getSession().removeRequestHandler(rh);
                        }

                    });
                }

                frame.setSizeFull();
                subContent.addComponent(frame);

                // Center it in the browser window
                subWindow.center();
                subWindow.setModal(true);
                subWindow.setSizeFull();

                frame.setHeight((int) (ui.getPage().getBrowserWindowHeight() * 0.8), Unit.PIXELS);
                // Open it in the UI
                ui.addWindow(subWindow);
            } catch (MalformedURLException e) {
                LOGGER.error(String.format("Visualization failed because of malformedURL for dataset: %s",
                        datasetCode));
                Notification.show(
                        "Given dataset has no file attached to it!! Please Contact your project manager. Or check whether it already has some data",
                        Notification.Type.ERROR_MESSAGE);
            }
        }
    });

    this.vert.addComponent(buttonLayout);

}