Example usage for com.vaadin.ui Button addListener

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

Introduction

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

Prototype

@Override
    public Registration addListener(Component.Listener listener) 

Source Link

Usage

From source file:org.vaadin.addons.serverpush.samples.chat.ChatLayout.java

License:Apache License

public ChatLayout(final User user, final User from) {
    setSizeFull();//from  w ww . jav a  2s  .  c o  m
    Table table = new Table();
    table.setSizeFull();
    table.setContainerDataSource(new MessageContainer(user, from));
    table.addListener(new Container.ItemSetChangeListener() {
        public void containerItemSetChange(Container.ItemSetChangeEvent event) {
            ((Pushable) getApplication()).push();
        }
    });
    table.setVisibleColumns(new String[] { "from", "to", "received", "message" });

    addComponent(table);

    HorizontalLayout hl = new HorizontalLayout();
    hl.setWidth("100%");
    final TextArea textArea = new TextArea();
    textArea.setRows(5);
    textArea.setSizeFull();
    textArea.setWordwrap(true);
    textArea.setValue("");
    hl.addComponent(textArea);

    Button sendButton = new Button("Send");
    sendButton.setWidth("120px");
    sendButton.setImmediate(true);
    sendButton.addListener(new Button.ClickListener() {
        public void buttonClick(Button.ClickEvent event) {
            Message msg = new Message();
            msg.setFrom(from);
            msg.setTo(user);
            msg.setMessage(textArea.getValue().toString());
            MessageManager.getInstance().addMessage(msg);
            textArea.setValue("");
        }
    });
    hl.addComponent(sendButton);
    hl.setComponentAlignment(sendButton, Alignment.BOTTOM_RIGHT);
    hl.setExpandRatio(textArea, 1);
    addComponent(hl);

    setExpandRatio(table, 1);
}

From source file:org.vaadin.addons.sitekit.viewlet.administrator.company.CompaniesFlowlet.java

License:Apache License

@Override
public void initialize() {
    entityManager = getSite().getSiteContext().getObject(EntityManager.class);

    gridLayout = new GridLayout(1, 2);
    gridLayout.setSizeFull();/*from   ww  w . j  av  a  2 s.  co m*/
    gridLayout.setMargin(false);
    gridLayout.setSpacing(true);
    gridLayout.setRowExpandRatio(1, 1f);
    setViewContent(gridLayout);

    final List<FieldDescriptor> fieldDefinitions = SiteFields.getFieldDescriptors(Company.class);

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

    entityContainer = new EntityContainer<Company>(entityManager, true, false, false, Company.class, 1000,
            new String[] { "companyName" }, new boolean[] { false }, "companyId");
    for (final FieldDescriptor fieldDefinition : fieldDefinitions) {
        entityContainer.addContainerProperty(fieldDefinition.getId(), fieldDefinition.getValueType(),
                fieldDefinition.getDefaultValue(), fieldDefinition.isReadOnly(), fieldDefinition.isSortable());
    }

    final Table table = new Table();
    entityGrid = new Grid(table, entityContainer);
    entityGrid.setFields(fieldDefinitions);
    entityGrid.setFilters(filterDefinitions);

    table.setColumnCollapsed("created", true);
    table.setColumnCollapsed("modified", true);
    table.setColumnCollapsed("company", true);
    table.setColumnCollapsed("emailPasswordReset", true);
    table.setColumnCollapsed("openIdLogin", true);
    table.setColumnCollapsed("maxFailedLoginCount", true);
    table.setColumnCollapsed("salesEmailAddress", true);
    table.setColumnCollapsed("supportEmailAddress", true);
    table.setColumnCollapsed("invoicingEmailAddress", true);
    gridLayout.addComponent(entityGrid, 0, 1);

    final HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.setSizeUndefined();
    gridLayout.addComponent(buttonLayout, 0, 0);

    final Button addButton = new Button("Add");
    addButton.setIcon(getSite().getIcon("button-icon-add"));
    addButton.setWidth(100, UNITS_PIXELS);
    buttonLayout.addComponent(addButton);

    addButton.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            final Company company = new Company();
            company.setCreated(new Date());
            company.setModified(company.getCreated());
            company.setInvoicingAddress(new PostalAddress());
            company.setDeliveryAddress(new PostalAddress());
            final CompanyFlowlet companyView = getFlow().forward(CompanyFlowlet.class);
            companyView.edit(company, true);
        }
    });

    final Button editButton = new Button("Edit");
    editButton.setIcon(getSite().getIcon("button-icon-edit"));
    editButton.setWidth(100, UNITS_PIXELS);
    buttonLayout.addComponent(editButton);
    editButton.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            final Company entity = entityContainer.getEntity(entityGrid.getSelectedItemId());
            final CompanyFlowlet companyView = getFlow().forward(CompanyFlowlet.class);
            companyView.edit(entity, false);
        }
    });

    final Button removeButton = new Button("Remove");
    removeButton.setIcon(getSite().getIcon("button-icon-remove"));
    removeButton.setWidth(100, UNITS_PIXELS);
    buttonLayout.addComponent(removeButton);
    removeButton.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            entityContainer.removeItem(entityGrid.getSelectedItemId());
            entityContainer.commit();
        }
    });

}

From source file:org.vaadin.addons.sitekit.viewlet.administrator.customer.CustomersFlowlet.java

License:Apache License

@Override
public void initialize() {
    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", "firstName" }, new boolean[] { true, true, true },
            "customerId");

    for (final FieldDescriptor fieldDefinition : fieldDefinitions) {
        entityContainer.addContainerProperty(fieldDefinition.getId(), fieldDefinition.getValueType(),
                fieldDefinition.getDefaultValue(), fieldDefinition.isReadOnly(), fieldDefinition.isSortable());
    }//  www  . j  a v a 2  s.com

    final GridLayout gridLayout = new GridLayout(1, 2);
    gridLayout.setSizeFull();
    gridLayout.setMargin(false);
    gridLayout.setSpacing(true);
    gridLayout.setRowExpandRatio(1, 1f);
    setViewContent(gridLayout);

    final HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.setSizeUndefined();
    gridLayout.addComponent(buttonLayout, 0, 0);

    final Table table = new Table();
    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, 1);

    final Button addButton = new Button("Add");
    addButton.setIcon(getSite().getIcon("button-icon-add"));
    addButton.setWidth(100, UNITS_PIXELS);
    buttonLayout.addComponent(addButton);

    addButton.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            final Customer customer = new Customer();
            customer.setCreated(new Date());
            customer.setModified(customer.getCreated());
            customer.setInvoicingAddress(new PostalAddress());
            customer.setDeliveryAddress(new PostalAddress());
            customer.setOwner((Company) getSite().getSiteContext().getObject(Company.class));
            final CustomerFlowlet customerView = getFlow().forward(CustomerFlowlet.class);
            customerView.edit(customer, true);
        }
    });

    final Button editButton = new Button("Edit");
    editButton.setIcon(getSite().getIcon("button-icon-edit"));
    editButton.setWidth(100, UNITS_PIXELS);
    buttonLayout.addComponent(editButton);
    editButton.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

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

    final Button removeButton = new Button("Remove");
    removeButton.setIcon(getSite().getIcon("button-icon-remove"));
    removeButton.setWidth(100, UNITS_PIXELS);
    buttonLayout.addComponent(removeButton);
    removeButton.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            entityContainer.removeItem(entityGrid.getSelectedItemId());
            entityContainer.commit();
        }
    });

}

From source file:org.vaadin.addons.sitekit.viewlet.administrator.directory.UserDirectoriesFlowlet.java

License:Apache License

@Override
public void initialize() {
    final List<FieldDescriptor> fieldDefinitions = new ArrayList<FieldDescriptor>(
            SiteFields.getFieldDescriptors(UserDirectory.class));

    for (final FieldDescriptor fieldDescriptor : fieldDefinitions) {
        if (fieldDescriptor.getId().equals("loginPassword")) {
            fieldDefinitions.remove(fieldDescriptor);
            break;
        }/*from   w  w  w .  j a v  a2s .c  o m*/
    }

    final List<FilterDescriptor> filterDefinitions = new ArrayList<FilterDescriptor>();

    final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class);
    entityContainer = new EntityContainer<UserDirectory>(entityManager, true, false, false, UserDirectory.class,
            1000, new String[] { "address", "port" }, new boolean[] { true, true }, "userDirectoryId");

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

    final GridLayout gridLayout = new GridLayout(1, 2);
    gridLayout.setSizeFull();
    gridLayout.setMargin(false);
    gridLayout.setSpacing(true);
    gridLayout.setRowExpandRatio(1, 1f);
    setViewContent(gridLayout);

    final HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.setSizeUndefined();
    gridLayout.addComponent(buttonLayout, 0, 0);

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

    table.setColumnCollapsed("loginDn", true);
    table.setColumnCollapsed("userEmailAttribute", true);
    table.setColumnCollapsed("userSearchBaseDn", true);
    table.setColumnCollapsed("groupSearchBaseDn", true);
    table.setColumnCollapsed("remoteLocalGroupMapping", true);
    table.setColumnCollapsed("created", true);
    table.setColumnCollapsed("modified", true);
    table.setColumnCollapsed("company", true);
    gridLayout.addComponent(entityGrid, 0, 1);

    final Button addButton = new Button("Add");
    addButton.setIcon(getSite().getIcon("button-icon-add"));
    addButton.setWidth(100, UNITS_PIXELS);
    buttonLayout.addComponent(addButton);

    addButton.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            final UserDirectory userDirectory = new UserDirectory();
            userDirectory.setCreated(new Date());
            userDirectory.setModified(userDirectory.getCreated());
            userDirectory.setOwner((Company) getSite().getSiteContext().getObject(Company.class));
            final UserDirectoryFlowlet userDirectoryView = getFlow().forward(UserDirectoryFlowlet.class);
            userDirectoryView.edit(userDirectory, true);
        }
    });

    final Button editButton = new Button("Edit");
    editButton.setIcon(getSite().getIcon("button-icon-edit"));
    editButton.setWidth(100, UNITS_PIXELS);
    buttonLayout.addComponent(editButton);
    editButton.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            final UserDirectory entity = entityContainer.getEntity(entityGrid.getSelectedItemId());
            final UserDirectoryFlowlet userDirectoryView = getFlow().forward(UserDirectoryFlowlet.class);
            userDirectoryView.edit(entity, false);
        }
    });

    final Button removeButton = new Button("Remove");
    removeButton.setIcon(getSite().getIcon("button-icon-remove"));
    removeButton.setWidth(100, UNITS_PIXELS);
    buttonLayout.addComponent(removeButton);
    removeButton.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            entityContainer.removeItem(entityGrid.getSelectedItemId());
            entityContainer.commit();
        }
    });

}

From source file:org.vaadin.addons.sitekit.viewlet.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.addListener(new ClickListener() {
        /** The default serial version ID. */
        private static final long serialVersionUID = 1L;

        @Override//from w ww  .jav a 2  s  .  co 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.vaadin.addons.sitekit.viewlet.anonymous.login.LoginFlowlet.java

License:Apache License

@SuppressWarnings("serial")
@Override//from   ww  w.j  av a 2s .com
public void initialize() {

    final VerticalLayout layout = new VerticalLayout();
    layout.setSpacing(true);

    final Company company = getSite().getSiteContext().getObject(Company.class);
    if (company.isOpenIdLogin()) {
        final Panel openIdPanel = new Panel();
        openIdPanel.setStyleName(Reindeer.PANEL_LIGHT);
        openIdPanel.setCaption("OpenID Login");
        layout.addComponent(openIdPanel);
        final HorizontalLayout openIdLayout = new HorizontalLayout();
        openIdPanel.setContent(openIdLayout);
        openIdLayout.setMargin(new MarginInfo(false, false, true, false));
        openIdLayout.setSpacing(true);
        final String returnViewName = "openidlogin";
        final Map<String, String> urlIconMap = OpenIdUtil.getOpenIdProviderUrlIconMap();
        for (final String url : urlIconMap.keySet()) {
            openIdLayout.addComponent(OpenIdUtil.getLoginButton(url, urlIconMap.get(url), returnViewName));
        }
    }

    loginForm = new LoginForm() {
        @Override
        public String getLoginHTML() {
            return super.getLoginHTML().replace("<input class='v-textfield v-widget' style='display:block;'",
                    "<input class='v-textfield v-widget' style='margin-bottom:10px; display:block;'");
        }
    };

    loginForm.setLoginButtonCaption(getSite().localize("button-login"));
    loginForm.setUsernameCaption(getSite().localize("input-user-name"));
    loginForm.setPasswordCaption(getSite().localize("input-user-password"));
    loginForm.addListener(this);

    layout.addComponent(loginForm);

    final Button registerButton = new Button(getSite().localize("button-register") + " >>");
    registerButton.addListener(new ClickListener() {
        @Override
        public void buttonClick(final ClickEvent event) {
            getFlow().forward(RegisterFlowlet.class);
        }
    });
    layout.addComponent(registerButton);

    if (company.isEmailPasswordReset()) {
        final Button forgotPasswordButton = new Button(getSite().localize("button-forgot-password") + " >>");
        forgotPasswordButton.addListener(new ClickListener() {
            @Override
            public void buttonClick(final ClickEvent event) {
                getFlow().forward(ForgotPasswordFlowlet.class);
            }
        });
        layout.addComponent(forgotPasswordButton);
    }

    setViewContent(layout);

}

From source file:org.vaadin.addons.sitekit.viewlet.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;
        }//from w ww  . j  ava 2 s .  co  m
        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.addListener(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();
            final PostalAddress deliveryAddress = new PostalAddress();
            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));

                if (UserDao.getGroup(entityManager, company, "user") == null) {
                    UserDao.addGroup(entityManager, new Group(company, "user", "Default user group."));
                }

                UserDao.addUser(entityManager, user, UserDao.getGroup(entityManager, company, "user"));
                CustomerDao.saveCustomer(entityManager, customer);
                UserDao.addGroupMember(entityManager, customer.getAdminGroup(), user);
                UserDao.addGroupMember(entityManager, customer.getMemberGroup(), 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.addComponent(panel);

    setViewContent(mainLayout);
}

From source file:org.vaadin.addons.sitekit.viewlet.user.AccountFlowlet.java

License:Apache License

@Override
public void initialize() {
    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());
    }//from  www  . jav a 2 s  . c  o  m

    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();
    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, UNITS_PIXELS);
    userAccountTitleIcon.setHeight(32, UNITS_PIXELS);
    userAccountTitle.addComponent(userAccountTitleIcon);
    final Label userAccountTitleLabel = new Label("<h2>User Account</h2>", Label.CONTENT_XHTML);
    userAccountTitle.addComponent(userAccountTitleLabel);
    gridLayout.addComponent(userAccountTitle, 0, 0);

    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, UNITS_PIXELS);
    titleIcon.setHeight(32, UNITS_PIXELS);
    titleLayout.addComponent(titleIcon);
    final Label titleLabel = new Label("<h2>Customer Accounts</h2>", Label.CONTENT_XHTML);
    titleLayout.addComponent(titleLabel);
    gridLayout.addComponent(titleLayout, 0, 3);

    final Table table = new Table();
    table.setPageLength(10);
    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 Button editUserButton = new Button("Edit User Account");
    editUserButton.setIcon(getSite().getIcon("button-icon-edit"));
    gridLayout.addComponent(editUserButton, 0, 2);
    editUserButton.addListener(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 Panel openIdPanel = new Panel();
        openIdPanel.setStyleName(Reindeer.PANEL_LIGHT);
        openIdPanel.setCaption("Choose OpenID Provider:");
        gridLayout.addComponent(openIdPanel, 0, 1);
        final HorizontalLayout openIdLayout = new HorizontalLayout();
        openIdPanel.setContent(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));
        }
    }

    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.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            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.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            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.addListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            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);
        }
    });

}

From source file:org.vaadin.dialogs.DefaultConfirmDialogFactory.java

License:Mozilla Public License

public ConfirmDialog create(final String caption, final String message, final String okCaption,
        final String cancelCaption) {

    // Create a confirm dialog
    final ConfirmDialog confirm = new ConfirmDialog();
    confirm.setCaption(caption != null ? caption : DEFAULT_CAPTION);

    // Close listener implementation
    confirm.addListener(new Window.CloseListener() {

        private static final long serialVersionUID = 1971800928047045825L;

        public void windowClose(CloseEvent ce) {

            // Only process if still enabled
            if (confirm.isEnabled()) {
                confirm.setEnabled(false); // avoid double processing
                confirm.setConfirmed(false);
                if (confirm.getListener() != null) {
                    confirm.getListener().onClose(confirm);
                }/*from  w  w  w .j  a  v  a 2 s.  c  o m*/
            }
        }
    });

    // Create content
    VerticalLayout c = (VerticalLayout) confirm.getContent();
    c.setSizeFull();
    c.setSpacing(true);

    // Panel for scrolling lengthty messages.
    Panel scroll = new Panel(new VerticalLayout());
    scroll.setScrollable(true);
    c.addComponent(scroll);
    scroll.setWidth("100%");
    scroll.setHeight("100%");
    scroll.setStyleName(Reindeer.PANEL_LIGHT);
    c.setExpandRatio(scroll, 1f);

    // Always HTML, but escape
    Label text = new Label("", Label.CONTENT_RAW);
    scroll.addComponent(text);
    confirm.setMessageLabel(text);
    confirm.setMessage(message);

    HorizontalLayout buttons = new HorizontalLayout();
    c.addComponent(buttons);
    buttons.setSpacing(true);

    buttons.setHeight(format(BUTTON_HEIGHT) + "em");
    buttons.setWidth("100%");
    Label spacerLeft = new Label("");
    buttons.addComponent(spacerLeft);
    spacerLeft.setWidth("100%");
    buttons.setExpandRatio(spacerLeft, 1f);

    final Button cancel = new Button(cancelCaption != null ? cancelCaption : DEFAULT_CANCEL_CAPTION);
    cancel.setData(false);
    cancel.setClickShortcut(KeyCode.ESCAPE, null);
    buttons.addComponent(cancel);

    confirm.setCancelButton(cancel);

    final Button ok = new Button(okCaption != null ? okCaption : DEFAULT_OK_CAPTION);
    ok.setData(true);
    ok.setClickShortcut(KeyCode.ENTER, null);
    ok.focus();
    buttons.addComponent(ok);
    confirm.setOkButton(ok);

    Label spacerRight = new Label("");
    buttons.addComponent(spacerRight);
    spacerRight.setWidth("100%");
    buttons.setExpandRatio(spacerRight, 1f);
    // Create a listener for buttons
    Button.ClickListener cb = new Button.ClickListener() {
        private static final long serialVersionUID = 3525060915814334881L;

        public void buttonClick(ClickEvent event) {
            // Copy the button date to window for passing through either
            // "OK" or "CANCEL". Only process id still enabled.
            if (confirm.isEnabled()) {
                confirm.setEnabled(false); // Avoid double processing

                confirm.setConfirmed(event.getButton() == ok);

                // We need to cast this way, because of the backward
                // compatibility issue in 6.4 series.
                Component parent = confirm.getParent();
                if (parent instanceof Window) {
                    try {
                        Method m = Window.class.getDeclaredMethod("removeWindow", Window.class);
                        m.invoke(parent, confirm);
                    } catch (Exception e) {
                        throw new RuntimeException(
                                "Failed to remove confirmation dialog from the parent window.", e);
                    }
                }

                // This has to be invoked as the window.close
                // event is not fired when removed.
                if (confirm.getListener() != null) {
                    confirm.getListener().onClose(confirm);
                }
            }

        }

    };
    cancel.addListener(cb);
    ok.addListener(cb);

    // Approximate the size of the dialog
    double[] dim = getDialogDimensions(message, ConfirmDialog.CONTENT_TEXT_WITH_NEWLINES);
    confirm.setWidth(format(dim[0]) + "em");
    confirm.setHeight(format(dim[1]) + "em");
    confirm.setResizable(false);

    return confirm;
}

From source file:org.vaadin.example.MyVaadinApplication.java

License:Apache License

@Override
public void init() {
    window = new Window("My Vaadin Application");
    setMainWindow(window);//from   ww  w.ja  va2s .c  om

    HorizontalSplitPanel horizontalSplitPanel = new HorizontalSplitPanel();
    horizontalSplitPanel.setSplitPosition(30);
    window.setContent(horizontalSplitPanel);

    VerticalLayout verticalLayout = new VerticalLayout();

    final PojoOne pojoOne = new PojoOne();
    pojoOne.setName("My pojo one");
    Button button = new Button("Edit pojo one");
    button.addListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            editPojo(pojoOne);
        }
    });
    verticalLayout.addComponent(button);

    final PojoTwo pojoTwo = new PojoTwo();
    button = new Button("Edit pojo two");
    pojoTwo.setName("My second pojo");

    button.addListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            editPojo(pojoTwo);
        }
    });
    verticalLayout.addComponent(button);

    horizontalSplitPanel.setFirstComponent(verticalLayout);

    form.setLayout(layout);
    form.setFormFieldFactory(preCreatedFieldsHelper);
    form.setVisible(false);
    horizontalSplitPanel.setSecondComponent(form);

}