Example usage for com.vaadin.ui TextField getValue

List of usage examples for com.vaadin.ui TextField getValue

Introduction

In this page you can find the example usage for com.vaadin.ui TextField getValue.

Prototype

@Override
    public String getValue() 

Source Link

Usage

From source file:com.trivago.mail.pigeon.web.components.templates.ModalAddTemplate.java

License:Apache License

public ModalAddTemplate(final TemplateList tl, final Long templateId) {
    setResizable(true);//from ww  w . ja v  a  2 s  .c  o m
    setWidth("972px");
    setHeight("700px");
    Panel rootPanel = new Panel("Add new Template");
    TabSheet tSheet = new TabSheet();
    HorizontalLayout hLayout = new HorizontalLayout();

    final TextField title = new TextField("Template description");
    final TextField subject = new TextField("Newsletter Subject");

    final TextArea textContent = new TextArea("Text Version");
    textContent.setRows(40);
    textContent.setColumns(100);

    final CKEditorTextField htmlContent = new CKEditorTextField();
    htmlContent.setWidth("100%");
    htmlContent.setHeight("650px");

    // Load the content, if we receive a template id
    if (templateId != null) {
        MailTemplate mt = new MailTemplate(templateId);
        title.setValue(mt.getTitle());
        subject.setValue(mt.getSubject());
        textContent.setValue(mt.getText());
        htmlContent.setValue(mt.getHtml());
    }

    Button saveButton = new Button("Save");
    Button cancel = new Button("Cancel");

    saveButton.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            boolean hasError = false;
            if (title.getValue().equals("")) {
                title.setComponentError(new UserError("Name must not be empty"));
                hasError = true;
            } else {
                title.setComponentError(null);
            }

            if (subject.getValue().equals("")) {
                subject.setComponentError(new UserError("Subject must not be empty"));
                hasError = true;
            } else {
                subject.setComponentError(null);
            }

            if (htmlContent.getValue().equals("")) {
                htmlContent.setComponentError(new UserError("Please provide some HTML content"));
                hasError = true;
            } else {
                htmlContent.setComponentError(null);
            }

            if (textContent.getValue().equals("")) {
                textContent.setComponentError(new UserError("Please provide some text content"));
                hasError = true;
            } else {
                textContent.setComponentError(null);
            }

            if (!hasError) {
                if (templateId == null) {
                    long templateId = Util.generateId();
                    try {
                        MailTemplate mt = new MailTemplate(templateId, title.getValue().toString(),
                                textContent.getValue().toString(), htmlContent.getValue().toString(),
                                subject.getValue().toString());
                        event.getButton().getWindow().setVisible(false);
                        event.getButton().getWindow().getParent()
                                .removeComponent(event.getButton().getWindow());
                        event.getButton().getWindow().getParent().showNotification("Saved successfully",
                                Notification.TYPE_HUMANIZED_MESSAGE);
                        tl.getBeanContainer().addItem(mt.getId(), mt);
                    } catch (RuntimeException e) {
                        // Should never happen ... hopefully :D
                    }
                } else {
                    MailTemplate mt = new MailTemplate(templateId);

                    mt.setHtml(htmlContent.getValue().toString());
                    mt.setSubject(subject.getValue().toString());
                    mt.setText(textContent.getValue().toString());
                    mt.setTitle(title.getValue().toString());

                    event.getButton().getWindow().setVisible(false);
                    event.getButton().getWindow().getParent().removeComponent(event.getButton().getWindow());
                    event.getButton().getWindow().getParent().showNotification("Saved successfully",
                            Notification.TYPE_HUMANIZED_MESSAGE);

                    final int beanIndex = tl.getBeanContainer().indexOfId(mt.getId());
                    tl.getBeanContainer().removeItem(mt.getId());
                    tl.getBeanContainer().addItemAt(beanIndex, mt.getId(), mt);
                }
                TemplateSelectBox.reloadSelect();
            }
        }
    });

    hLayout.addComponent(saveButton);
    hLayout.addComponent(cancel);
    hLayout.setSpacing(true);

    VerticalLayout metaDataLayout = new VerticalLayout();

    Panel textFieldPanel = new Panel("Meta Data");
    VerticalLayout metaLayout = new VerticalLayout();
    metaLayout.addComponent(title);
    metaLayout.addComponent(subject);
    textFieldPanel.addComponent(metaLayout);

    Panel helpPanel = new Panel("Template Documentation");
    assembleHelpComponents(helpPanel);

    metaDataLayout.addComponent(textFieldPanel);
    metaDataLayout.addComponent(helpPanel);

    tSheet.addTab(metaDataLayout).setCaption("Meta Data");

    VerticalLayout textLayout = new VerticalLayout();
    textLayout.addComponent(textContent);
    tSheet.addTab(textLayout).setCaption("Text Content");

    VerticalLayout htmlLayout = new VerticalLayout();
    htmlLayout.addComponent(htmlContent);
    tSheet.addTab(htmlLayout).setCaption("HTML Content");

    rootPanel.addComponent(tSheet);
    rootPanel.addComponent(hLayout);
    addComponent(rootPanel);
}

From source file:com.wintindustries.pfserver.interfaces.view.dashboard.LoginView.java

private Component buildFields() {
    HorizontalLayout fields = new HorizontalLayout();
    fields.setSpacing(true);// w ww. j a v  a2  s  . c  o  m
    fields.addStyleName("fields");

    final TextField username = new TextField("Username");
    username.setIcon(FontAwesome.USER);
    username.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);

    final PasswordField password = new PasswordField("Password");
    password.setIcon(FontAwesome.LOCK);
    password.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);

    final Button signin = new Button("Sign In");
    signin.addStyleName(ValoTheme.BUTTON_PRIMARY);
    signin.setClickShortcut(KeyCode.ENTER);
    signin.focus();

    fields.addComponents(username, password, signin);
    fields.setComponentAlignment(signin, Alignment.BOTTOM_LEFT);

    signin.addClickListener(new ClickListener() {
        @Override
        public void buttonClick(final ClickEvent event) {

            System.out.println("TRIGGER LOGIN");
            DashboardEventBus.post(new UserLoginRequestedEvent(username.getValue(), password.getValue()));
        }
    });
    return fields;
}

From source file:de.escidoc.admintool.view.EscidocPagedTable.java

License:Open Source License

public HorizontalLayout createControls() {
    // final Label itemsPerPageLabel = new Label("Items per page:");
    final Label pageLabel = new Label("Page: ", Label.CONTENT_XHTML);
    final TextField currentPageTextField = new TextField();
    currentPageTextField.setValue(String.valueOf(getCurrentPage()));
    currentPageTextField.addValidator(new IntegerValidator(null));
    final Label separatorLabel = new Label(" / ", Label.CONTENT_XHTML);
    final Label totalPagesLabel = new Label(String.valueOf(getTotalAmountOfPages()), Label.CONTENT_XHTML);
    currentPageTextField.setStyleName(Reindeer.TEXTFIELD_SMALL);
    currentPageTextField.setImmediate(true);
    currentPageTextField.addListener(new ValueChangeListener() {
        private static final long serialVersionUID = -2255853716069800092L;

        public void valueChange(final com.vaadin.data.Property.ValueChangeEvent event) {
            if (currentPageTextField.isValid() && currentPageTextField.getValue() != null) {
                @SuppressWarnings("boxing")
                final int page = Integer.valueOf(String.valueOf(currentPageTextField.getValue()));
                setCurrentPage(page);/*from   w  ww. j  av  a2s  .  c  o m*/
            }
        }
    });
    pageLabel.setWidth(null);
    currentPageTextField.setWidth("20px");
    separatorLabel.setWidth(null);
    totalPagesLabel.setWidth(null);

    final HorizontalLayout controlBar = new HorizontalLayout();
    final HorizontalLayout pageSize = new HorizontalLayout();
    final HorizontalLayout pageManagement = new HorizontalLayout();
    final Button first = new Button("<<", new ClickListener() {
        private static final long serialVersionUID = -355520120491283992L;

        public void buttonClick(final ClickEvent event) {
            setCurrentPage(0);
        }
    });
    final Button previous = new Button("<", new ClickListener() {
        private static final long serialVersionUID = -355520120491283992L;

        public void buttonClick(final ClickEvent event) {
            previousPage();
        }
    });
    final Button next = new Button(">", new ClickListener() {
        private static final long serialVersionUID = -1927138212640638452L;

        public void buttonClick(final ClickEvent event) {
            nextPage();
        }
    });
    final Button last = new Button(">>", new ClickListener() {
        private static final long serialVersionUID = -355520120491283992L;

        public void buttonClick(final ClickEvent event) {
            setCurrentPage(getTotalAmountOfPages());
        }
    });
    first.setStyleName(BaseTheme.BUTTON_LINK);
    previous.setStyleName(BaseTheme.BUTTON_LINK);
    next.setStyleName(BaseTheme.BUTTON_LINK);
    last.setStyleName(BaseTheme.BUTTON_LINK);

    pageLabel.addStyleName("pagedtable-pagecaption");
    currentPageTextField.addStyleName("pagedtable-pagefield");
    separatorLabel.addStyleName("pagedtable-separator");
    totalPagesLabel.addStyleName("pagedtable-total");
    first.addStyleName("pagedtable-first");
    previous.addStyleName("pagedtable-previous");
    next.addStyleName("pagedtable-next");
    last.addStyleName("pagedtable-last");

    pageLabel.addStyleName("pagedtable-label");
    currentPageTextField.addStyleName("pagedtable-label");
    separatorLabel.addStyleName("pagedtable-label");
    totalPagesLabel.addStyleName("pagedtable-label");
    first.addStyleName("pagedtable-button");
    previous.addStyleName("pagedtable-button");
    next.addStyleName("pagedtable-button");
    last.addStyleName("pagedtable-button");

    pageSize.setSpacing(true);
    pageManagement.addComponent(first);
    pageManagement.addComponent(previous);
    pageManagement.addComponent(pageLabel);
    pageManagement.addComponent(currentPageTextField);
    pageManagement.addComponent(separatorLabel);
    pageManagement.addComponent(totalPagesLabel);
    pageManagement.addComponent(next);
    pageManagement.addComponent(last);
    pageManagement.setComponentAlignment(first, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(previous, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(pageLabel, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(currentPageTextField, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(separatorLabel, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(totalPagesLabel, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(next, Alignment.MIDDLE_LEFT);
    pageManagement.setComponentAlignment(last, Alignment.MIDDLE_LEFT);
    pageManagement.setWidth(null);
    pageManagement.setSpacing(true);
    controlBar.addComponent(pageSize);
    controlBar.addComponent(pageManagement);
    controlBar.setComponentAlignment(pageManagement, Alignment.MIDDLE_CENTER);
    controlBar.setWidth("100%");
    controlBar.setExpandRatio(pageSize, 1);
    addListener(new PageChangeListener() {
        @SuppressWarnings("boxing")
        public void pageChanged(final PagedTableChangeEvent event) {
            previous.setEnabled(true);
            next.setEnabled(true);
            currentPageTextField.setValue(String.valueOf(getCurrentPage()));
            totalPagesLabel.setValue(getTotalAmountOfPages());
        }
    });
    return controlBar;
}

From source file:de.fatalix.bookery.view.admin.AdminView.java

License:Open Source License

public VerticalLayout createServerSettings() {
    VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);//from   www . j a  v  a 2s .  c  om
    Label titleLabel = new Label("General Settings");
    titleLabel.addStyleName(ValoTheme.LABEL_H2);

    //layout.addComponent(titleLabel);
    layout.addComponent(serverSettingsLayout);
    Button resetIndex = new Button("reset Index", new Button.ClickListener() {

        @Override
        public void buttonClick(Button.ClickEvent event) {

            try {
                presenter.resetIndex();
                Notification.show("Succesfully reset Index", Notification.Type.HUMANIZED_MESSAGE);
            } catch (IOException | SolrServerException ex) {
                Notification.show(ex.getMessage(), Notification.Type.ERROR_MESSAGE);
            }
        }
    });
    resetIndex.addStyleName(ValoTheme.BUTTON_DANGER);

    final TextField eMailAdress = new TextField(null, "felix.husse@medavis.de");
    eMailAdress.setColumns(35);
    Button testMail = new Button("Test Mail", new Button.ClickListener() {

        @Override
        public void buttonClick(Button.ClickEvent event) {
            try {
                presenter.sendEmail(eMailAdress.getValue());
                Notification.show("Mail succesfully sent!", Notification.Type.HUMANIZED_MESSAGE);
            } catch (MessagingException ex) {
                Notification.show("Mail failed!" + ex.getMessage(), Notification.Type.ERROR_MESSAGE);
            }
        }
    });
    testMail.setEnabled(true);

    Button resetBatchJobs = new Button("reset BatchJobs", new Button.ClickListener() {

        @Override
        public void buttonClick(Button.ClickEvent event) {
            presenter.resetBatchJobs();
            Notification.show("Succesfully reset Batchjobs", Notification.Type.HUMANIZED_MESSAGE);

        }
    });
    resetBatchJobs.addStyleName(ValoTheme.BUTTON_DANGER);

    HorizontalLayout mailLayout = new HorizontalLayout(eMailAdress, testMail, resetBatchJobs);
    layout.addComponents(resetIndex, mailLayout);

    return layout;
}

From source file:de.fzi.fhemapi.view.vaadin.ui.ServerDetailsForm.java

License:Apache License

public ServerDetailsForm() {
    FormLayout layout = new FormLayout();
    setCompositionRoot(layout);/*from   w  ww  .  j ava  2 s.c o  m*/

    Label title = new Label("<h1> Server Details</h1>");
    title.setContentMode(Label.CONTENT_XHTML);
    layout.addComponent(title);

    final TextField serverIP = new TextField("Server IP");

    serverIP.setWidth(COMMON_FIELD_WIDTH);
    layout.addComponent(serverIP);

    final TextField port = new TextField("Port");
    port.setWidth(COMMON_FIELD_WIDTH);
    layout.addComponent(port);

    Button applyButton = new Button("Apply");
    layout.addComponent(applyButton);

    applyButton.addListener(new Button.ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                //               Window mainWindow = new Window();
                FHEMServer server = new FHEMServer((String) serverIP.getValue(),
                        Integer.parseInt((String) port.getValue()));
                getWindow().setContent(new HWindow(server));
                //               VaadinServletResponse response = 
                //                        (VaadinServletResponse) VaadinService.getCurrentResponse();
                //                     Cookie ipCookie = new Cookie("ip", (String)serverIP.getValue());
                //                     Cookie portCookie = new Cookie("port", (String) port.getValue());
                //                     ipCookie.setMaxAge(30 * 24 * 60 * 60);
                //                     ipCookie.setPath("/HWC");
                //                     portCookie.setMaxAge(30 * 24 * 60 * 60);
                //                     portCookie.setPath("/HWC");
                //                     response.addCookie(ipCookie);
                //                     response.addCookie(portCookie);
            } catch (ConnectException e) {
                getWindow().setContent(new Window("Could not connect to FHEM!\n Cause: " + e.getMessage()));
                getWindow().showNotification("Error!", e.getMessage(), Window.Notification.TYPE_ERROR_MESSAGE);
            }
        }
    });
    //
    //       VaadinServletRequest request = 
    //                (VaadinServletRequest) VaadinService.getCurrentRequest();
    //       if(request != null){
    //             Cookie[] cookies = request.getCookies();
    //             for (Cookie cookie : cookies) {
    //                if (cookie.getName().equals("ip")) {
    //                   serverIP.setValue(cookie.getValue());
    //                }else if(cookie.getName().equals("port")){
    //                   port.setValue(cookie.getValue());
    //                }
    //             }
    //       }

}

From source file:de.gedoplan.webclients.vaadin.LoginUi.java

@Override
protected void init(VaadinRequest request) {
    TextField name = new TextField(Messages.login_name.value());
    name.focus();/*ww  w  .ja  va 2 s  .  c  o  m*/
    PasswordField password = new PasswordField(Messages.login_password.value());
    Button login = new Button(Messages.login_submit.value(), e -> {
        try {
            JaasAccessControl.login(name.getValue(), password.getValue());
            Page.getCurrent().setLocation(Konstanten.VAADIN_UI_PATH);
        } catch (ServletException ex) {
            Notification.show(Messages.login_invalid.value(), Notification.Type.ERROR_MESSAGE);
        }
    });
    login.setClickShortcut(ShortcutAction.KeyCode.ENTER);
    FormLayout fieldLayout = new FormLayout(name, password, login);
    fieldLayout.setMargin(true);
    fieldLayout.setSpacing(true);
    Panel loginPanel = new Panel(Messages.login_title.value(), fieldLayout);
    loginPanel.setSizeUndefined();
    VerticalLayout page = new VerticalLayout();
    page.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER);
    page.addComponent(loginPanel);
    page.setSizeFull();
    setContent(page);
}

From source file:de.unioninvestment.portal.explorer.view.vfs.ConfigView.java

License:Apache License

public ConfigView(ConfigBean cb, VFSFileExplorerPortlet instance) {

    final OptionGroup group = new OptionGroup("Type");
    group.addItem("FILE");
    group.addItem("FTP");
    group.addItem("SFTP");
    group.setValue(cb.getVfsType());/*from   w w  w. j  a  v  a 2  s  .  c  o  m*/
    group.setImmediate(true);

    final TextField tfDirectory = new TextField("Directory");
    tfDirectory.setValue(cb.getVfsUrl());

    final TextField tfKeyFile = new TextField("Keyfile");
    tfKeyFile.setValue(cb.getKeyfile());

    final TextField tfProxyHost = new TextField("Proxy Host (sftp)");
    tfProxyHost.setValue(cb.getProxyHost());

    final TextField tfProxyPort = new TextField("Proxy Port (sftp)");
    tfProxyPort.setValue(cb.getProxyPort());

    final TextField tfUser = new TextField("User");
    tfUser.setValue(cb.getUsername());

    final PasswordField tfPw = new PasswordField("Password");
    tfPw.setValue(cb.getPassword());

    final CheckBox cbUploadEnabled = new CheckBox("Upload Enabled");
    if (cb.isUploadEnabled()) {
        cbUploadEnabled.setValue(true);
    } else
        cbUploadEnabled.setValue(false);

    final TextField tfRolesUpload = new TextField("Upload Rollen");
    tfRolesUpload.setValue(cb.getUploadRoles());

    final CheckBox cbDeleteEnabled = new CheckBox("Delete Enabled");
    if (cb.isDeleteEnabled()) {
        cbDeleteEnabled.setValue(true);
    } else
        cbDeleteEnabled.setValue(false);

    final TextField tfRolesDelete = new TextField("Delete Rollen");
    tfRolesDelete.setValue(cb.getDeleteRoles());

    group.addListener(new Property.ValueChangeListener() {

        private static final long serialVersionUID = 1L;

        public void valueChange(ValueChangeEvent event) {

            setVisibleFields(group, tfKeyFile, tfProxyHost, tfProxyPort, tfUser, tfPw);

        }

    });

    setVisibleFields(group, tfKeyFile, tfProxyHost, tfProxyPort, tfUser, tfPw);

    Button saveProps = new Button("Save");
    final VFSFileExplorerPortlet app = instance;
    saveProps.addListener(new Button.ClickListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                PortletPreferences prefs = app.getPortletPreferences();

                String type = group.getValue().toString();
                prefs.setValue("type", type);

                String con = tfDirectory.getValue().toString();
                prefs.setValue("directory", con);

                String key = tfKeyFile.getValue().toString();
                prefs.setValue("keyfile", key);

                String proxyHost = tfProxyHost.getValue().toString();
                prefs.setValue("proxyHost", proxyHost);

                String proxyPort = tfProxyPort.getValue().toString();
                prefs.setValue("proxyPort", proxyPort);

                String uploadRoles = tfRolesUpload.getValue().toString();
                prefs.setValue("uploadRoles", uploadRoles);

                String deleteRoles = tfRolesDelete.getValue().toString();
                prefs.setValue("deleteRoles", deleteRoles);

                String username = tfUser.getValue().toString();
                prefs.setValue("username", username);

                String password = tfPw.getValue().toString();
                prefs.setValue("password", password);

                Boolean bDel = (Boolean) cbDeleteEnabled.getValue();
                Boolean bUpl = (Boolean) cbUploadEnabled.getValue();
                if (bDel)
                    prefs.setValue("deleteEnabled", "true");
                else
                    prefs.setValue("deleteEnabled", "false");

                if (bUpl)
                    prefs.setValue("uploadEnabled", "true");
                else
                    prefs.setValue("uploadEnabled", "false");

                prefs.store();

                logger.log(Level.INFO, "Roles Upload " + prefs.getValue("uploadEnabled", "-"));
                logger.log(Level.INFO, "Roles Delete " + prefs.getValue("deleteEnabled", "-"));

                ConfigBean cb = new ConfigBean(type, bDel, false, bUpl, con, username, password, key, proxyHost,
                        proxyPort, uploadRoles, deleteRoles);

                app.getEventBus().fireEvent(new ConfigChangedEvent(cb));

            } catch (Exception e) {
                logger.log(Level.INFO, "Exception " + e.toString());
                e.printStackTrace();
            }
        }
    });
    addComponent(group);
    addComponent(tfDirectory);
    addComponent(tfKeyFile);
    addComponent(tfProxyHost);
    addComponent(tfProxyPort);
    addComponent(tfUser);
    addComponent(tfPw);

    HorizontalLayout ul = new HorizontalLayout();
    ul.setSpacing(true);
    ul.addComponent(cbUploadEnabled);
    ul.addComponent(tfRolesUpload);
    ul.setComponentAlignment(cbUploadEnabled, Alignment.MIDDLE_CENTER);
    ul.setComponentAlignment(tfRolesUpload, Alignment.MIDDLE_CENTER);
    addComponent(ul);

    HorizontalLayout dl = new HorizontalLayout();
    dl.setSpacing(true);
    dl.addComponent(cbDeleteEnabled);
    dl.addComponent(tfRolesDelete);
    dl.setComponentAlignment(cbDeleteEnabled, Alignment.MIDDLE_CENTER);
    dl.setComponentAlignment(tfRolesDelete, Alignment.MIDDLE_CENTER);
    addComponent(dl);
    addComponent(saveProps);
}

From source file:de.unioninvestment.portal.explorer.view.vfs.TableView.java

License:Apache License

public void attach() {

    selectedDir = cb.getVfsUrl();/* w  w w. ja  v a 2  s . c  om*/
    try {

        final VFSFileExplorerPortlet app = instance;
        final User user = (User) app.getUser();
        final FileSystemManager fFileSystemManager = fileSystemManager;
        final FileSystemOptions fOpts = opts;

        final Table table = new Table() {

            private static final long serialVersionUID = 1L;

            protected String formatPropertyValue(Object rowId, Object colId, Property property) {

                if (TABLE_PROP_FILE_NAME.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        return getDisplayPath(property.getValue().toString());
                    }
                }
                if (TABLE_PROP_FILE_DATE.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("dd.MMM yyyy HH:mm:ss");
                        return sdf.format((Date) property.getValue());
                    }
                }
                return super.formatPropertyValue(rowId, colId, property);
            }

        };
        table.setSizeFull();
        table.setMultiSelect(true);
        table.setSelectable(true);
        table.setImmediate(true);
        table.addContainerProperty(TABLE_PROP_FILE_NAME, String.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_SIZE, Long.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_DATE, Date.class, null);
        if (app != null) {
            app.getEventBus().addHandler(TableChangedEvent.class, new TableChangedEventHandler() {
                private static final long serialVersionUID = 1L;

                @Override
                public void onValueChanged(TableChangedEvent event) {
                    try {
                        selectedDir = event.getNewDirectory();
                        fillTableData(event.getNewDirectory(), table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        table.addListener(new Table.ValueChangeListener() {
            private static final long serialVersionUID = 1L;

            public void valueChange(ValueChangeEvent event) {

                Set<?> value = (Set<?>) event.getProperty().getValue();
                if (null == value || value.size() == 0) {
                    markedRows = null;
                } else {
                    markedRows = value;
                }
            }
        });

        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);

        Button btDownload = new Button("Download File(s)");
        btDownload.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    String[] files = new String[markedRows.size()];
                    int fileCount = 0;

                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        files[fileCount] = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        fileCount++;
                    }

                    File dlFile = null;
                    if (fileCount == 1) {
                        try {
                            String fileName = files[0];
                            dlFile = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                            logger.log(Level.INFO,
                                    "vfs2portlet: download file " + fileName + " by " + user.getScreenName());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        byte[] buf = new byte[1024];

                        try {
                            dlFile = File.createTempFile("Files", ".zip");
                            ZipOutputStream out = new ZipOutputStream(
                                    new FileOutputStream(dlFile.getAbsolutePath()));
                            for (int i = 0; i < files.length; i++) {
                                String fileName = files[i];
                                logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by "
                                        + user.getScreenName());
                                File f = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                                FileInputStream in = new FileInputStream(f);
                                out.putNextEntry(new ZipEntry(f.getName()));
                                int len;
                                while ((len = in.read(buf)) > 0) {
                                    out.write(buf, 0, len);
                                }
                                out.closeEntry();
                                in.close();
                            }
                            out.close();
                        } catch (IOException e) {
                        }

                    }

                    if (dlFile != null) {
                        try {
                            DownloadResource downloadResource = new DownloadResource(dlFile, getApplication());
                            getApplication().getMainWindow().open(downloadResource, "_new");
                        } catch (FileNotFoundException e) {
                            getWindow().showNotification("File not found !",
                                    Window.Notification.TYPE_ERROR_MESSAGE);
                            e.printStackTrace();
                        }

                    }

                    if (dlFile != null) {
                        dlFile.delete();
                    }
                }

            }
        });

        Button btDelete = new Button("Delete File(s)");
        btDelete.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {

                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        String fileToDelete = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        logger.log(Level.INFO, "Delete File " + fileToDelete);
                        try {
                            FileObject delFile = fFileSystemManager.resolveFile(fileToDelete, fOpts);
                            logger.log(Level.INFO, "vfs2portlet: delete file " + delFile.getName() + " by "
                                    + user.getScreenName());
                            boolean b = delFile.delete();
                            if (b)
                                logger.log(Level.INFO, "delete ok");
                            else
                                logger.log(Level.INFO, "delete failed");
                        } catch (FileSystemException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        Button selAll = new Button("Select All", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(table.getItemIds());
            }
        });

        Button selNone = new Button("Select None", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(null);
            }
        });

        final UploadReceiver receiver = new UploadReceiver();
        upload = new Upload(null, receiver);
        upload.setImmediate(true);
        upload.setButtonCaption("File Upload");

        upload.addListener((new Upload.SucceededListener() {

            private static final long serialVersionUID = 1L;

            public void uploadSucceeded(SucceededEvent event) {

                try {
                    String fileName = receiver.getFileName();
                    ByteArrayOutputStream bos = receiver.getUploadedFile();
                    byte[] buf = bos.toByteArray();
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    app.getMainWindow().showNotification("Upload " + fileName + " successful ! ",
                            Notification.TYPE_TRAY_NOTIFICATION);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }));

        upload.addListener(new Upload.FailedListener() {
            private static final long serialVersionUID = 1L;

            public void uploadFailed(FailedEvent event) {
                System.out.println("Upload failed ! ");
            }
        });

        multiFileUpload = new MultiFileUpload() {

            private static final long serialVersionUID = 1L;

            protected void handleFile(File file, String fileName, String mimeType, long length) {
                try {
                    byte[] buf = FileUtils.readFileToByteArray(file);
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (FileSystemException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            protected FileBuffer createReceiver() {
                FileBuffer receiver = super.createReceiver();
                /*
                 * Make receiver not to delete files after they have been
                 * handled by #handleFile().
                 */
                receiver.setDeleteFiles(false);
                return receiver;
            }
        };
        multiFileUpload.setUploadButtonCaption("Upload File(s)");

        HorizontalLayout filterGrp = new HorizontalLayout();
        filterGrp.setSpacing(true);
        final TextField tfFilter = new TextField();
        Button btFileFilter = new Button("Filter", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                String filterVal = (String) tfFilter.getValue();
                try {
                    if (filterVal == null || filterVal.length() == 0) {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } else {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, filterVal);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Button btResetFileFilter = new Button("Reset", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                try {
                    tfFilter.setValue("");
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (ReadOnlyException e) {
                    e.printStackTrace();
                } catch (ConversionException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        filterGrp.addComponent(tfFilter);
        filterGrp.addComponent(btFileFilter);
        filterGrp.addComponent(btResetFileFilter);

        addComponent(filterGrp);

        addComponent(table);

        HorizontalLayout btGrp = new HorizontalLayout();

        btGrp.setSpacing(true);
        btGrp.addComponent(selAll);
        btGrp.setComponentAlignment(selAll, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(selNone);
        btGrp.setComponentAlignment(selNone, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(btDownload);
        btGrp.setComponentAlignment(btDownload, Alignment.MIDDLE_CENTER);

        List<Role> roles = null;
        boolean matchUserRole = false;
        try {

            if (user != null) {
                roles = user.getRoles();

            }
        } catch (SystemException e) {
            e.printStackTrace();
        }

        if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() == 0) {
            btGrp.addComponent(btDelete);
            btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
        } else if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() > 0) {
            matchUserRole = isUserInRole(roles, cb.getDeleteRoles());
            if (matchUserRole) {
                btGrp.addComponent(btDelete);
                btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
            }

        }
        if (cb.isUploadEnabled() && cb.getUploadRoles().length() == 0) {
            btGrp.addComponent(upload);
            btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
            btGrp.addComponent(multiFileUpload);
            btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
        } else if (cb.isUploadEnabled() && cb.getUploadRoles().length() > 0) {

            matchUserRole = isUserInRole(roles, cb.getUploadRoles());
            if (matchUserRole) {
                btGrp.addComponent(upload);
                btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
                btGrp.addComponent(multiFileUpload);
                btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
            }
        }
        addComponent(btGrp);

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

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

License:Open Source License

public void updateUI(final String id, String type) {
    propLayout.removeAllComponents();/*www  .j  a  va  2s  .  c om*/
    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.ChangeSampleMetadataComponent.java

License:Open Source License

public void updateUI(final String id, String type) {
    propLayout.removeAllComponents();//from  w ww.  j a va2 s . c  om
    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);
}