Example usage for com.vaadin.ui Button setEnabled

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

Introduction

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

Prototype

@Override
    public void setEnabled(boolean enabled) 

Source Link

Usage

From source file:org.apache.ace.webui.vaadin.component.BaseObjectPanel.java

License:Apache License

/**
 * Creates a remove-link button for the given repository object.
 * //w  w w  . j ava  2  s .c o m
 * @param object
 *            the object to create a remove-link button, cannot be <code>null</code>;
 * @param displayName
 *            the display name for the description of the button, cannot be <code>null</code>.
 * @return a remove-link button, never <code>null</code>.
 */
protected final Button createRemoveLinkButton(RepositoryObject object, String displayName) {
    Button result = new Button();
    result.setIcon(createIconResource("unlink"));
    result.setStyleName("small tiny");
    result.setData(object.getDefinition());
    result.setDescription("Unlink " + displayName);
    // Only enable this button when actually selected...
    result.setEnabled(false);
    result.setDisableOnClick(true);

    result.addListener(new Button.ClickListener() {
        public void buttonClick(Button.ClickEvent event) {
            handleItemRemoveLink(event.getButton().getData());
        }

    });

    return result;
}

From source file:org.apache.ace.webui.vaadin.GenericAddWindow.java

License:Apache License

/**
 * Initializes this dialog by placing all components on it.
 *//*  w ww .  j a  v a2 s  . com*/
protected void initDialog() {
    VerticalLayout fields = new VerticalLayout();
    fields.setSpacing(true);
    fields.addComponent(m_name);
    fields.addComponent(m_description);

    final Button okButton = new Button("Ok", new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            try {
                onOk((String) m_name.getValue(), (String) m_description.getValue());
                close();
            } catch (Exception e) {
                handleError(e);
            }
        }
    });
    okButton.setEnabled(false);
    // Allow enter to be used to close this dialog with enter directly...
    okButton.setClickShortcut(KeyCode.ENTER);
    okButton.addStyleName(Reindeer.BUTTON_DEFAULT);

    Button cancelButton = new Button("Cancel", new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            close();
        }
    });
    cancelButton.setClickShortcut(KeyCode.ESCAPE);

    m_name.addListener(new TextChangeListener() {
        @Override
        public void textChange(TextChangeEvent event) {
            String text = event.getText();
            okButton.setEnabled((text != null) && !"".equals(text.trim()));
        }
    });
    m_name.setTextChangeTimeout(250);
    m_name.setTextChangeEventMode(TextChangeEventMode.TIMEOUT);

    HorizontalLayout buttonBar = new HorizontalLayout();
    buttonBar.setSpacing(true);
    buttonBar.addComponent(okButton);
    buttonBar.addComponent(cancelButton);

    VerticalLayout layout = (VerticalLayout) getContent();
    layout.setMargin(true);
    layout.setSpacing(true);
    layout.addComponent(fields);
    layout.addComponent(buttonBar);

    // The components added to the window are actually added to the window's
    // layout; you can use either. Alignments are set using the layout
    layout.setComponentAlignment(buttonBar, Alignment.BOTTOM_RIGHT);

    // Allow direct typing...
    m_name.focus();
}

From source file:org.apache.ace.webui.vaadin.LoginWindow.java

License:Apache License

/**
 * Creates a new {@link LoginWindow} instance.
 * /*from  ww w  . j a  v a  2 s . c  om*/
 * @param log
 *            the log service to use;
 * @param loginFunction
 *            the login callback to use.
 */
public LoginWindow(LogService log, LoginFunction loginFunction) {
    super("Apache ACE Login");

    m_log = log;
    m_loginFunction = loginFunction;

    setResizable(false);
    setClosable(false);
    setModal(true);
    setWidth("20em");

    m_additionalInfo = new Label("");
    m_additionalInfo.setImmediate(true);
    m_additionalInfo.setStyleName("alert");
    m_additionalInfo.setHeight("1.2em");
    // Ensures the information message disappears when starting typing...
    FieldEvents.TextChangeListener changeListener = new FieldEvents.TextChangeListener() {
        @Override
        public void textChange(TextChangeEvent event) {
            m_additionalInfo.setValue("");
        }
    };

    final TextField nameField = new TextField("Name", "");
    nameField.addListener(changeListener);
    nameField.setImmediate(true);
    nameField.setWidth("100%");

    final PasswordField passwordField = new PasswordField("Password", "");
    passwordField.addListener(changeListener);
    passwordField.setImmediate(true);
    passwordField.setWidth("100%");

    Button loginButton = new Button("Login");
    loginButton.setImmediate(true);
    // Allow enter to be used to login directly...
    loginButton.setClickShortcut(KeyCode.ENTER);
    // Highlight this button as the default one...
    loginButton.addStyleName(Reindeer.BUTTON_DEFAULT);

    loginButton.addListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            Button button = event.getButton();
            button.setEnabled(false);

            try {
                String username = (String) nameField.getValue();
                String password = (String) passwordField.getValue();

                if (m_loginFunction.login(username, password)) {
                    m_log.log(LogService.LOG_INFO, "Apache Ace WebUI succesfull login by user: " + username);

                    closeWindow();
                } else {
                    m_log.log(LogService.LOG_WARNING, "Apache Ace WebUI invalid username or password entered.");

                    m_additionalInfo.setValue("Invalid username or password!");

                    nameField.focus();
                    nameField.selectAll();
                }
            } finally {
                button.setEnabled(true);
            }
        }
    });

    final VerticalLayout content = (VerticalLayout) getContent();
    content.setSpacing(true);
    content.setMargin(true);
    content.setSizeFull();

    content.addComponent(nameField);
    content.addComponent(passwordField);
    content.addComponent(m_additionalInfo);
    content.addComponent(loginButton);

    content.setComponentAlignment(loginButton, Alignment.BOTTOM_CENTER);

    nameField.focus();
}

From source file:org.apache.ace.webui.vaadin.VaadinClient.java

License:Apache License

/**
 * @return a button to approve one or more targets.
 *///from  ww  w.  j  av  a2  s  .  com
private Button createApproveTargetsButton() {
    final Button button = new Button("A");
    button.setDisableOnClick(true);
    button.setImmediate(true);
    button.setEnabled(false);
    button.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            m_targetsPanel.approveSelectedTargets();
        }
    });
    m_targetsPanel.addListener(new ValueChangeListener() {
        @Override
        public void valueChange(ValueChangeEvent event) {
            TargetsPanel targetsPanel = (TargetsPanel) event.getProperty();

            Collection<?> itemIDs = (Collection<?>) targetsPanel.getValue();

            boolean enabled = false;
            for (Object itemID : itemIDs) {
                if (targetsPanel.isItemApproveNeeded(itemID)) {
                    enabled = true;
                    break;
                }
            }

            button.setEnabled(enabled);
        }
    });
    return button;
}

From source file:org.apache.ace.webui.vaadin.VaadinClient.java

License:Apache License

private Button createRegisterTargetsButton() {
    final Button button = new Button("R");
    button.setDisableOnClick(true);// ww w . ja v a 2  s .co m
    button.setImmediate(true);
    button.setEnabled(false);
    button.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            m_targetsPanel.registerSelectedTargets();
        }
    });
    m_targetsPanel.addListener(new ValueChangeListener() {
        @Override
        public void valueChange(ValueChangeEvent event) {
            TargetsPanel targetsPanel = (TargetsPanel) event.getProperty();

            Collection<?> itemIDs = (Collection<?>) targetsPanel.getValue();

            boolean enabled = false;
            for (Object itemID : itemIDs) {
                if (targetsPanel.isItemRegistrationNeeded(itemID)) {
                    enabled = true;
                    break;
                }
            }

            button.setEnabled(enabled);
        }
    });
    return button;
}

From source file:org.asi.ui.pagedtable.PagedTable.java

License:Apache License

public HorizontalLayout createControls(PagedControlConfig config) {
    Label itemsPerPageLabel = new Label(config.getItemsPerPage(), ContentMode.HTML);
    itemsPerPageLabel.setSizeUndefined();
    final ComboBox itemsPerPageSelect = new ComboBox();

    for (Integer i : config.getPageLengths()) {
        itemsPerPageSelect.addItem(i);/*www.  j a  v a  2 s  .c  o m*/
        itemsPerPageSelect.setItemCaption(i, String.valueOf(i));
    }
    itemsPerPageSelect.setImmediate(true);
    itemsPerPageSelect.setNullSelectionAllowed(false);
    itemsPerPageSelect.setWidth(null);
    itemsPerPageSelect.addValueChangeListener(new Property.ValueChangeListener() {
        private static final long serialVersionUID = -2255853716069800092L;

        @Override
        public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
            setPageLength((Integer) event.getProperty().getValue());
        }
    });
    if (itemsPerPageSelect.containsId(getPageLength())) {
        itemsPerPageSelect.select(getPageLength());
    } else {
        itemsPerPageSelect.select(itemsPerPageSelect.getItemIds().iterator().next());
    }
    Label pageLabel = new Label(config.getPage(), ContentMode.HTML);
    final TextField currentPageTextField = new TextField();
    currentPageTextField.setValue(String.valueOf(getCurrentPage()));
    currentPageTextField.setConverter(new StringToIntegerConverter() {
        @Override
        protected NumberFormat getFormat(Locale locale) {
            NumberFormat result = super.getFormat(UI.getCurrent().getLocale());
            result.setGroupingUsed(false);
            return result;
        }
    });
    Label separatorLabel = new Label("&nbsp;/&nbsp;", ContentMode.HTML);
    final Label totalPagesLabel = new Label(String.valueOf(getTotalAmountOfPages()), ContentMode.HTML);
    currentPageTextField.setStyleName(Reindeer.TEXTFIELD_SMALL);
    currentPageTextField.setImmediate(true);
    currentPageTextField.addValueChangeListener(new Property.ValueChangeListener() {
        private static final long serialVersionUID = -2255853716069800092L;

        @Override
        public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
            if (currentPageTextField.isValid() && currentPageTextField.getValue() != null) {
                int page = Integer.valueOf(String.valueOf(currentPageTextField.getValue()));
                setCurrentPage(page);
            }
        }
    });
    pageLabel.setWidth(null);
    currentPageTextField.setColumns(3);
    separatorLabel.setWidth(null);
    totalPagesLabel.setWidth(null);

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

        @Override
        public void buttonClick(Button.ClickEvent event) {
            setCurrentPage(0);
        }
    });
    final Button previous = new Button(config.getPrevious(), new Button.ClickListener() {
        private static final long serialVersionUID = -355520120491283992L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            previousPage();
        }
    });
    final Button next = new Button(config.getNext(), new Button.ClickListener() {
        private static final long serialVersionUID = -1927138212640638452L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            nextPage();
        }
    });
    final Button last = new Button(config.getLast(), new Button.ClickListener() {
        private static final long serialVersionUID = -355520120491283992L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            setCurrentPage(getTotalAmountOfPages());
        }
    });
    first.setStyleName(Reindeer.BUTTON_LINK);
    previous.setStyleName(Reindeer.BUTTON_LINK);
    next.setStyleName(Reindeer.BUTTON_LINK);
    last.setStyleName(Reindeer.BUTTON_LINK);

    itemsPerPageLabel.addStyleName("pagedtable-itemsperpagecaption");
    itemsPerPageSelect.addStyleName("pagedtable-itemsperpagecombobox");
    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");

    itemsPerPageLabel.addStyleName("pagedtable-label");
    itemsPerPageSelect.addStyleName("pagedtable-combobox");
    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.addComponent(itemsPerPageLabel);
    pageSize.addComponent(itemsPerPageSelect);
    pageSize.setComponentAlignment(itemsPerPageLabel, Alignment.MIDDLE_LEFT);
    pageSize.setComponentAlignment(itemsPerPageSelect, Alignment.MIDDLE_LEFT);
    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, Sizeable.Unit.PERCENTAGE);
    controlBar.setExpandRatio(pageSize, 1);

    if (container != null) {
        first.setEnabled(container.getStartIndex() > 0);
        previous.setEnabled(container.getStartIndex() > 0);
        next.setEnabled(container.getStartIndex() < container.getRealSize() - getPageLength());
        last.setEnabled(container.getStartIndex() < container.getRealSize() - getPageLength());
    }

    addListener(new PageChangeListener() {
        private boolean inMiddleOfValueChange;

        @Override
        public void pageChanged(PagedTableChangeEvent event) {
            if (!inMiddleOfValueChange) {
                inMiddleOfValueChange = true;
                first.setEnabled(container.getStartIndex() > 0);
                previous.setEnabled(container.getStartIndex() > 0);
                next.setEnabled(container.getStartIndex() < container.getRealSize() - getPageLength());
                last.setEnabled(container.getStartIndex() < container.getRealSize() - getPageLength());
                currentPageTextField.setValue(String.valueOf(getCurrentPage()));
                totalPagesLabel.setValue(Integer.toString(getTotalAmountOfPages()));
                itemsPerPageSelect.setValue(getPageLength());
                inMiddleOfValueChange = false;
            }
        }
    });
    return controlBar;
}

From source file:org.bubblecloud.ilves.comment.CommentAddComponent.java

License:Open Source License

/**
 * The default constructor which instantiates Vaadin
 * component hierarchy.//from ww  w .  j av  a 2  s  . c o  m
 */
public CommentAddComponent() {

    final User user = DefaultSiteUI.getSecurityProvider().getUserFromSession();

    final String contextPath = VaadinService.getCurrentRequest().getContextPath();
    final Site site = Site.getCurrent();

    final Company company = site.getSiteContext().getObject(Company.class);
    final EntityManager entityManager = site.getSiteContext().getObject(EntityManager.class);

    final Panel panel = new Panel(site.localize("panel-add-comment"));
    setCompositionRoot(panel);

    final VerticalLayout mainLayout = new VerticalLayout();
    panel.setContent(mainLayout);
    mainLayout.setMargin(true);
    mainLayout.setSpacing(true);

    final TextArea commentMessageField = new TextArea(site.localize("field-comment-message"));
    mainLayout.addComponent(commentMessageField);
    commentMessageField.setWidth(100, Unit.PERCENTAGE);
    commentMessageField.setRows(3);
    commentMessageField.setMaxLength(255);

    final Button addCommentButton = new Button(site.localize("button-add-comment"));
    mainLayout.addComponent(addCommentButton);
    if (user == null) {
        commentMessageField.setEnabled(false);
        commentMessageField.setInputPrompt(site.localize("message-please-login-to-comment"));
        addCommentButton.setEnabled(false);
    }

    addCommentButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            final String commentMessage = commentMessageField.getValue();
            if (StringUtils.isEmpty(commentMessage)) {
                return;
            }
            final Comment comment = new Comment(company, user, contextPath, commentMessage);
            entityManager.getTransaction().begin();
            try {
                entityManager.persist(comment);
                entityManager.getTransaction().commit();
                commentMessageField.setValue("");
                if (commentListComponent != null) {
                    commentListComponent.refresh();
                }
            } finally {
                if (entityManager.getTransaction().isActive()) {
                    entityManager.getTransaction().rollback();
                }
            }
        }
    });

}

From source file:org.bubblecloud.ilves.ui.anonymous.login.ForgotPasswordFlowlet.java

License:Apache License

@Override
public void initialize() {
    pinProperty = new ObjectProperty<String>(null, String.class);
    emailAddressProperty = new ObjectProperty<String>(null, String.class);

    final List<FieldDescriptor> fieldDescriptors = new ArrayList<FieldDescriptor>();

    fieldDescriptors.add(new FieldDescriptor("pin", getSite().localize("input-password-reset-pin"),
            TextField.class, null, 150, null, String.class, null, true, true, true));
    fieldDescriptors.add(new FieldDescriptor("emailAddress", getSite().localize("input-email-address"),
            TextField.class, null, 150, null, String.class, null, false, true, true)
                    .addValidator(new EmailValidator("Email address is not valid.")));

    editor = new ValidatingEditor(fieldDescriptors);

    final Button resetPasswordButton = new Button(getSite().localize("button-reset-password"));
    resetPasswordButton.addClickListener(new ClickListener() {
        /** The default serial version ID. */
        private static final long serialVersionUID = 1L;

        @Override//w  w w .  j a  va 2  s  .  c o m
        public void buttonClick(final ClickEvent event) {
            editor.commit();
            final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class);
            final Company company = getSite().getSiteContext().getObject(Company.class);

            final User user = UserDao.getUser(entityManager, company, (String) emailAddressProperty.getValue());
            if (user == null) {
                Notification.show(getSite().localize("message-user-email-address-not-registered"),
                        Notification.Type.WARNING_MESSAGE);
                return;
            }

            final List<EmailPasswordReset> emailPasswordResets = UserDao
                    .getEmailPasswordResetByEmailAddress(entityManager, user);
            final Date now = new Date();

            for (final EmailPasswordReset emailPasswordReset : emailPasswordResets) {
                if (now.getTime() - emailPasswordReset.getCreated().getTime() < 24 * 60 * 60 * 1000) {
                    Notification.show(getSite().localize("message-password-reset-email-already-sent"),
                            Notification.Type.ERROR_MESSAGE);
                    return;
                } else {
                    entityManager.getTransaction().begin();
                    try {
                        entityManager.remove(emailPasswordReset);
                        entityManager.getTransaction().commit();
                    } catch (final Exception e) {
                        if (entityManager.getTransaction().isActive()) {
                            entityManager.getTransaction().rollback();
                        }
                        throw new SiteException("Error removing old email password reset.", e);
                    }
                }
            }

            try {
                final String pin = (String) pinProperty.getValue();
                final byte[] pinAndSaltBytes = (user.getEmailAddress() + ":" + pin).getBytes("UTF-8");
                final MessageDigest md = MessageDigest.getInstance("SHA-256");
                final byte[] pinAndSaltDigest = md.digest(pinAndSaltBytes);

                final EmailPasswordReset emailPasswordReset = new EmailPasswordReset();
                emailPasswordReset.setUser(user);
                emailPasswordReset.setPinHash(StringUtil.toHexString(pinAndSaltDigest));
                emailPasswordReset.setCreated(now);

                entityManager.getTransaction().begin();
                try {
                    entityManager.persist(emailPasswordReset);
                    entityManager.getTransaction().commit();
                } catch (final Exception e) {
                    if (entityManager.getTransaction().isActive()) {
                        entityManager.getTransaction().rollback();
                    }
                    throw new SiteException("Error saving email password reset", e);
                }

                final String url = company.getUrl() + "#!reset/" + emailPasswordReset.getEmailPasswordResetId();

                final Thread emailThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        EmailUtil.send(PropertiesUtil.getProperty("site", "smtp-host"), user.getEmailAddress(),
                                company.getSupportEmailAddress(), "Password Reset Link",
                                "Password reset has been requested for your user account."
                                        + "You can perform the reset using the following link: " + url);
                    }
                });
                emailThread.start();

                Notification.show(
                        getSite().localize("message-password-reset-email-sent")
                                + getSite().localize("message-your-password-reset-pin-is") + pin,
                        Notification.Type.WARNING_MESSAGE);

                final HttpServletRequest request = ((VaadinServletRequest) VaadinService.getCurrentRequest())
                        .getHttpServletRequest();
                LOGGER.info("Password reset email sent to " + user.getEmailAddress() + " (IP: "
                        + request.getRemoteHost() + ":" + request.getRemotePort() + ")");

                getFlow().back();
            } catch (final Exception e) {
                LOGGER.error("Error preparing password reset.", e);
                Notification.show(getSite().localize("message-password-reset-prepare-error"),
                        Notification.Type.WARNING_MESSAGE);
            }
            reset();
        }
    });

    editor.addListener(new ValidatingEditorStateListener() {
        @Override
        public void editorStateChanged(final ValidatingEditor source) {
            if (source.isValid()) {
                resetPasswordButton.setEnabled(true);
            } else {
                resetPasswordButton.setEnabled(false);
            }
        }
    });

    reset();

    final VerticalLayout panel = new VerticalLayout();
    panel.addComponent(editor);
    panel.addComponent(resetPasswordButton);
    panel.setSpacing(true);

    final HorizontalLayout mainLayout = new HorizontalLayout();
    mainLayout.addComponent(panel);

    setViewContent(mainLayout);
}

From source file:org.bubblecloud.ilves.ui.anonymous.login.RegisterFlowlet.java

License:Apache License

@Override
public void initialize() {
    originalPasswordProperty = new ObjectProperty<String>(null, String.class);
    verifiedPasswordProperty = new ObjectProperty<String>(null, String.class);

    final List<FieldDescriptor> fieldDescriptors = new ArrayList<FieldDescriptor>();

    final PasswordValidator passwordValidator = new PasswordValidator(getSite(), originalPasswordProperty,
            "password2");

    //fieldDescriptors.addAll(SiteFields.getFieldDescriptors(Customer.class));

    for (final FieldDescriptor fieldDescriptor : SiteFields.getFieldDescriptors(Customer.class)) {
        if (fieldDescriptor.getId().equals("adminGroup")) {
            continue;
        }// w  w  w  .ja  v a2s . c  om
        if (fieldDescriptor.getId().equals("memberGroup")) {
            continue;
        }
        if (fieldDescriptor.getId().equals("created")) {
            continue;
        }
        if (fieldDescriptor.getId().equals("modified")) {
            continue;
        }
        fieldDescriptors.add(fieldDescriptor);
    }

    //fieldDescriptors.remove(fieldDescriptors.size() - 1);
    //fieldDescriptors.remove(fieldDescriptors.size() - 1);
    fieldDescriptors
            .add(new FieldDescriptor("password1", getSite().localize("input-password"), PasswordField.class,
                    null, 150, null, String.class, null, false, true, true).addValidator(passwordValidator));
    fieldDescriptors.add(new FieldDescriptor("password2", getSite().localize("input-password-verification"),
            PasswordField.class, null, 150, null, String.class, null, false, true, true)
                    .addValidator(new PasswordVerificationValidator(getSite(), originalPasswordProperty)));

    editor = new ValidatingEditor(fieldDescriptors);
    passwordValidator.setEditor(editor);

    final Button registerButton = new Button(getSite().localize("button-register"));
    registerButton.setStyleName(ValoTheme.BUTTON_PRIMARY);
    registerButton.addClickListener(new ClickListener() {
        /** The default serial version ID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            editor.commit();
            customer.setCreated(new Date());
            customer.setModified(customer.getCreated());
            final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class);
            final Company company = getSite().getSiteContext().getObject(Company.class);

            final PostalAddress invoicingAddress = new PostalAddress();
            invoicingAddress.setAddressLineOne("?");
            invoicingAddress.setAddressLineTwo("?");
            invoicingAddress.setAddressLineThree("?");
            invoicingAddress.setCity("?");
            invoicingAddress.setPostalCode("?");
            invoicingAddress.setCountry("?");
            final PostalAddress deliveryAddress = new PostalAddress();
            deliveryAddress.setAddressLineOne("?");
            deliveryAddress.setAddressLineTwo("?");
            deliveryAddress.setAddressLineThree("?");
            deliveryAddress.setCity("?");
            deliveryAddress.setPostalCode("?");
            deliveryAddress.setCountry("?");
            customer.setInvoicingAddress(invoicingAddress);
            customer.setDeliveryAddress(deliveryAddress);

            if (UserDao.getUser(entityManager, company, customer.getEmailAddress()) != null) {
                Notification.show(getSite().localize("message-user-email-address-registered"),
                        Notification.Type.WARNING_MESSAGE);
                return;
            }

            final HttpServletRequest request = ((VaadinServletRequest) VaadinService.getCurrentRequest())
                    .getHttpServletRequest();

            try {
                final byte[] passwordAndSaltBytes = (customer.getEmailAddress() + ":"
                        + ((String) originalPasswordProperty.getValue())).getBytes("UTF-8");
                final MessageDigest md = MessageDigest.getInstance("SHA-256");
                final byte[] passwordAndSaltDigest = md.digest(passwordAndSaltBytes);

                customer.setOwner(company);
                final User user = new User(company, customer.getFirstName(), customer.getLastName(),
                        customer.getEmailAddress(), customer.getPhoneNumber(),
                        StringUtil.toHexString(passwordAndSaltDigest));

                SecurityService.addUser(getSite().getSiteContext(), user,
                        UserDao.getGroup(entityManager, company, "user"));

                if (SiteModuleManager.isModuleInitialized(CustomerModule.class)) {
                    SecurityService.addCustomer(getSite().getSiteContext(), customer, user);
                }

                final String url = company.getUrl() + "#!validate/" + user.getUserId();

                final Thread emailThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        EmailUtil.send(PropertiesUtil.getProperty("site", "smtp-host"), user.getEmailAddress(),
                                company.getSupportEmailAddress(), "Email Validation",
                                "Please validate your email by browsing to this URL: " + url);
                    }
                });
                emailThread.start();

                LOGGER.info("User registered " + user.getEmailAddress() + " (IP: " + request.getRemoteHost()
                        + ":" + request.getRemotePort() + ")");
                Notification.show(getSite().localize("message-registration-success"),
                        Notification.Type.HUMANIZED_MESSAGE);

                getFlow().back();
            } catch (final Exception e) {
                LOGGER.error("Error adding user. (IP: " + request.getRemoteHost() + ":"
                        + request.getRemotePort() + ")", e);
                Notification.show(getSite().localize("message-registration-error"),
                        Notification.Type.WARNING_MESSAGE);
            }
            reset();
        }
    });

    editor.addListener(new ValidatingEditorStateListener() {
        @Override
        public void editorStateChanged(final ValidatingEditor source) {
            if (source.isValid()) {
                registerButton.setEnabled(true);
            } else {
                registerButton.setEnabled(false);
            }
        }
    });

    reset();

    final VerticalLayout panel = new VerticalLayout();
    panel.addComponent(editor);
    panel.addComponent(registerButton);
    panel.setSpacing(true);

    final HorizontalLayout mainLayout = new HorizontalLayout();
    mainLayout.setMargin(true);
    mainLayout.addComponent(panel);

    final Panel mainPanel = new Panel();
    mainPanel.setSizeUndefined();
    mainPanel.setContent(mainLayout);

    setViewContent(mainPanel);
}

From source file:org.bubblecloud.ilves.ui.user.AccountFlowlet.java

License:Apache License

@Override
public void initialize() {
    final GridLayout gridLayout = new GridLayout(1, 6);
    gridLayout.setRowExpandRatio(0, 0.0f);
    gridLayout.setRowExpandRatio(1, 0.0f);
    gridLayout.setRowExpandRatio(2, 0.0f);
    gridLayout.setRowExpandRatio(3, 0.0f);
    gridLayout.setRowExpandRatio(4, 0.0f);
    gridLayout.setRowExpandRatio(5, 1.0f);

    gridLayout.setSizeFull();//w ww .j av  a  2  s.c  o  m
    gridLayout.setMargin(false);
    gridLayout.setSpacing(true);
    gridLayout.setRowExpandRatio(4, 1f);
    setViewContent(gridLayout);

    final HorizontalLayout userAccountTitle = new HorizontalLayout();
    userAccountTitle.setMargin(new MarginInfo(false, false, false, false));
    userAccountTitle.setSpacing(true);
    final Embedded userAccountTitleIcon = new Embedded(null, getSite().getIcon("view-icon-user"));
    userAccountTitleIcon.setWidth(32, Unit.PIXELS);
    userAccountTitleIcon.setHeight(32, Unit.PIXELS);
    userAccountTitle.addComponent(userAccountTitleIcon);
    final Label userAccountTitleLabel = new Label("<h2>User Account</h2>", ContentMode.HTML);
    userAccountTitle.addComponent(userAccountTitleLabel);
    gridLayout.addComponent(userAccountTitle, 0, 0);

    final Button editUserButton = new Button("Edit User Account");
    editUserButton.setIcon(getSite().getIcon("button-icon-edit"));
    gridLayout.addComponent(editUserButton, 0, 2);
    editUserButton.addClickListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            final User entity = ((SecurityProviderSessionImpl) getSite().getSecurityProvider())
                    .getUserFromSession();
            final UserAccountFlowlet customerView = getFlow().getFlowlet(UserAccountFlowlet.class);
            customerView.edit(entity, false);
            getFlow().forward(UserAccountFlowlet.class);
        }
    });

    final Company company = getSite().getSiteContext().getObject(Company.class);
    if (company.isOpenIdLogin()) {
        final VerticalLayout mainPanel = new VerticalLayout();
        mainPanel.setCaption("Choose OpenID Provider:");
        gridLayout.addComponent(mainPanel, 0, 1);
        final HorizontalLayout openIdLayout = new HorizontalLayout();
        mainPanel.addComponent(openIdLayout);
        openIdLayout.setMargin(new MarginInfo(false, false, true, false));
        openIdLayout.setSpacing(true);
        final String returnViewName = "openidlink";
        final Map<String, String> urlIconMap = OpenIdUtil.getOpenIdProviderUrlIconMap();
        for (final String url : urlIconMap.keySet()) {
            openIdLayout.addComponent(OpenIdUtil.getLoginButton(url, urlIconMap.get(url), returnViewName));
        }
    }

    if (SiteModuleManager.isModuleInitialized(CustomerModule.class)) {
        final List<FieldDescriptor> fieldDefinitions = SiteFields.getFieldDescriptors(Customer.class);

        final List<FilterDescriptor> filterDefinitions = new ArrayList<FilterDescriptor>();
        filterDefinitions.add(new FilterDescriptor("companyName", "companyName", "Company Name",
                new TextField(), 101, "=", String.class, ""));
        filterDefinitions.add(new FilterDescriptor("lastName", "lastName", "Last Name", new TextField(), 101,
                "=", String.class, ""));

        final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class);
        entityContainer = new EntityContainer<Customer>(entityManager, true, false, false, Customer.class, 1000,
                new String[] { "companyName", "lastName" }, new boolean[] { false, false }, "customerId");

        for (final FieldDescriptor fieldDefinition : fieldDefinitions) {
            entityContainer.addContainerProperty(fieldDefinition.getId(), fieldDefinition.getValueType(),
                    fieldDefinition.getDefaultValue(), fieldDefinition.isReadOnly(),
                    fieldDefinition.isSortable());
        }

        final HorizontalLayout titleLayout = new HorizontalLayout();
        titleLayout.setMargin(new MarginInfo(true, false, false, false));
        titleLayout.setSpacing(true);
        final Embedded titleIcon = new Embedded(null, getSite().getIcon("view-icon-customer"));
        titleIcon.setWidth(32, Unit.PIXELS);
        titleIcon.setHeight(32, Unit.PIXELS);
        titleLayout.addComponent(titleIcon);
        final Label titleLabel = new Label("<h2>Customer Accounts</h2>", ContentMode.HTML);
        titleLayout.addComponent(titleLabel);
        gridLayout.addComponent(titleLayout, 0, 3);

        final Table table = new Table();
        table.setPageLength(5);
        entityGrid = new Grid(table, entityContainer);
        entityGrid.setFields(fieldDefinitions);
        entityGrid.setFilters(filterDefinitions);
        //entityGrid.setFixedWhereCriteria("e.owner.companyId=:companyId");

        table.setColumnCollapsed("created", true);
        table.setColumnCollapsed("modified", true);
        table.setColumnCollapsed("company", true);
        gridLayout.addComponent(entityGrid, 0, 5);

        final HorizontalLayout customerButtonsLayout = new HorizontalLayout();
        gridLayout.addComponent(customerButtonsLayout, 0, 4);
        customerButtonsLayout.setMargin(false);
        customerButtonsLayout.setSpacing(true);

        final Button editCustomerDetailsButton = new Button("Edit Customer Details");
        customerButtonsLayout.addComponent(editCustomerDetailsButton);
        editCustomerDetailsButton.setEnabled(false);
        editCustomerDetailsButton.setIcon(getSite().getIcon("button-icon-edit"));
        editCustomerDetailsButton.addClickListener(new ClickListener() {
            /**
             * Serial version UID.
             */
            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(final ClickEvent event) {
                if (entityGrid.getSelectedItemId() == null) {
                    return;
                }
                final Customer entity = entityContainer.getEntity(entityGrid.getSelectedItemId());
                final CustomerFlowlet customerView = getFlow().forward(CustomerFlowlet.class);
                customerView.edit(entity, false);
            }
        });

        final Button editCustomerMembersButton = new Button("Edit Customer Members");
        customerButtonsLayout.addComponent(editCustomerMembersButton);
        editCustomerMembersButton.setEnabled(false);
        editCustomerMembersButton.setIcon(getSite().getIcon("button-icon-edit"));
        editCustomerMembersButton.addClickListener(new ClickListener() {
            /**
             * Serial version UID.
             */
            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(final ClickEvent event) {
                if (entityGrid.getSelectedItemId() == null) {
                    return;
                }
                final Customer entity = entityContainer.getEntity(entityGrid.getSelectedItemId());
                final GroupFlowlet view = getFlow().forward(GroupFlowlet.class);
                view.edit(entity.getMemberGroup(), false);
            }
        });

        final Button editCustomerAdminsButton = new Button("Edit Customer Admins");
        customerButtonsLayout.addComponent(editCustomerAdminsButton);
        editCustomerAdminsButton.setEnabled(false);
        editCustomerAdminsButton.setIcon(getSite().getIcon("button-icon-edit"));
        editCustomerAdminsButton.addClickListener(new ClickListener() {
            /**
             * Serial version UID.
             */
            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(final ClickEvent event) {
                if (entityGrid.getSelectedItemId() == null) {
                    return;
                }
                final Customer entity = entityContainer.getEntity(entityGrid.getSelectedItemId());
                final GroupFlowlet view = getFlow().forward(GroupFlowlet.class);
                view.edit(entity.getAdminGroup(), false);
            }
        });

        table.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(final Property.ValueChangeEvent event) {
                editCustomerDetailsButton.setEnabled(table.getValue() != null);
                editCustomerMembersButton.setEnabled(table.getValue() != null);
                editCustomerAdminsButton.setEnabled(table.getValue() != null);
            }
        });

    }
}