Example usage for com.vaadin.ui TextField setValue

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

Introduction

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

Prototype

@Override
public void setValue(String value) 

Source Link

Document

Sets the value of this text field.

Usage

From source file:de.decidr.ui.view.windows.FieldBuilder.java

License:Apache License

@Override
public Field createControl(TTaskItem taskItem, String value) {
    TextField field = new TextField(taskItem.getLabel());
    field.setImmediate(true);/* www.  j  a  va2s  .  c  o  m*/
    field.setValue(value);
    return field;
}

From source file:de.decidr.ui.view.windows.FieldBuilder.java

License:Apache License

@Override
public Field createControl(TTaskItem taskItem, String value) {
    TextField field = new TextField(taskItem.getLabel());
    field.addValidator(new FloatValidator("Please enter a valid float"));
    field.setImmediate(true);//from ww w .  ja v  a  2s.  c  o  m
    field.setValue(value);
    return field;
}

From source file:de.decidr.ui.view.windows.FieldBuilder.java

License:Apache License

@Override
public Field createControl(TTaskItem taskItem, String value) {
    TextField field = new TextField(taskItem.getLabel());
    field.addValidator(new IntegerValidator("Please enter an Integer!"));
    field.setImmediate(true);//  w ww . java 2  s . c o  m

    field.setValue(value);
    return field;
}

From source file:de.escidoc.admintool.view.admintask.repositoryinfo.ShowRepoInfoCommandImpl.java

License:Open Source License

private TextField createReadOnlyField(final Entry<String, String> entry) {
    final TextField textField = new TextField();
    textField.setCaption(entry.getKey());
    textField.setValue(entry.getValue());
    textField.setWidth(400, RepositoryInfoView.UNITS_PIXELS);
    textField.setReadOnly(true);//from ww w .j  av  a  2 s.  com
    return textField;
}

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:&nbsp;", Label.CONTENT_XHTML);
    final TextField currentPageTextField = new TextField();
    currentPageTextField.setValue(String.valueOf(getCurrentPage()));
    currentPageTextField.addValidator(new IntegerValidator(null));
    final Label separatorLabel = new Label("&nbsp;/&nbsp;", 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);/*w  w w.  j  a v a 2s . 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.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 ww  .  j a  v a2  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();/*www  . j  a  va  2s.  co  m*/
    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.BiologicalSamplesComponent.java

License:Open Source License

/**
 * /* ww w  . ja  va 2  s  .com*/
 */
private void initUI() {
    vert = new VerticalLayout();
    sampleBioGrid = new Grid();
    sampleEntityGrid = new Grid();

    vert.setMargin(new MarginInfo(false, true, false, false));

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

    });

    mainLayout = new VerticalLayout(vert);
    mainLayout.setResponsive(true);
    setResponsive(true);

    exportSources.setIcon(FontAwesome.DOWNLOAD);
    exportSamples.setIcon(FontAwesome.DOWNLOAD);

    // this.setWidth(Page.getCurrent().getBrowserWindowWidth() * 0.8f, Unit.PIXELS);
    this.setCompositionRoot(mainLayout);
}

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

License:Open Source License

/**
 * //  w ww .jav  a2 s  . co m
 * @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.ChangeExperimentMetadataComponent.java

License:Open Source License

private void buildFormLayout() {
    final FieldGroup fieldGroup = new FieldGroup();
    final FormLayout form2 = new FormLayout();

    Map<String, PropertyBean> controlledVocabularies = getControlledVocabularies();
    Map<String, PropertyBean> properties = getProperties();
    List<Property> xmlProps = getXMLProperties();

    for (Property f : xmlProps) {
        PropertyType type = f.getType();

        String label = f.getLabel();
        if (f.hasUnit())
            label += " in " + f.getUnit();
        TextField tf = new TextField(label);
        tf.setData(type);// save property type for later, when it is written back
        fieldGroup.bind(tf, label);//from  ww  w. j  a va  2 s. c om
        tf.setCaption(label);
        tf.setDescription("Q_PROPERTIES");
        tf.setValue((String) f.getValue());
        form2.addComponent(tf);
    }

    for (String key : properties.keySet()) {
        if (controlledVocabularies.keySet().contains(key)) {
            ComboBox select = new ComboBox(controlledVocabularies.get(key).getLabel());
            fieldGroup.bind(select, key);

            // Add items with given item IDs
            select.addItems(controlledVocabularies.get(key).getVocabularyValues());

            select.setDescription(controlledVocabularies.get(key).getCode());
            select.setValue(properties.get(key).getValue());

            form2.addComponent(select);

        } else {
            TextField tf = new TextField(key);
            fieldGroup.bind(tf, key);
            tf.setCaption(properties.get(key).getLabel());
            tf.setDescription(properties.get(key).getCode());
            tf.setValue((String) properties.get(key).getValue());
            form2.addComponent(tf);
        }
    }
    this.fieldGroup = fieldGroup;
    this.form = form2;
}