Example usage for com.vaadin.ui Button.ClickListener Button.ClickListener

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

Introduction

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

Prototype

Button.ClickListener

Source Link

Usage

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

License:Open Source License

/**
 * The default constructor which instantiates Vaadin
 * component hierarchy./* www.  j a  v  a  2s .co 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.module.content.RenderFlowlet.java

License:Apache License

public RenderFlowlet(final Content content) {
    this.content = content;
    topEditButton = getSite().getButton("edit");
    topEditButton.addClickListener(new Button.ClickListener() {
        @Override/* w w w.  j  a  va  2 s . com*/
        public void buttonClick(Button.ClickEvent event) {
            final ContentFlowlet contentFlowlet = getFlow().getFlowlet(ContentFlowlet.class);
            contentFlowlet.edit(content, false);
            ((AbstractFlowViewlet) getFlow()).getTopRightLayout().removeComponent(topEditButton);
            ((AbstractFlowViewlet) getFlow()).refreshPathLabels();
            getFlow().forward(ContentFlowlet.class);
        }
    });
}

From source file:org.bubblecloud.ilves.site.view.valo.DefaultValoView.java

License:Apache License

private CssLayout buildMenu() {

    final HorizontalLayout topLayout = new HorizontalLayout();
    topLayout.setWidth("100%");
    topLayout.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);
    topLayout.addStyleName("valo-menu-title");
    menu.addComponent(topLayout);// w ww. j  a v  a  2  s .  c  o m

    final Button showMenu = new Button("Menu", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            if (menu.getStyleName().contains("valo-menu-visible")) {
                menu.removeStyleName("valo-menu-visible");
            } else {
                menu.addStyleName("valo-menu-visible");
            }
        }
    });
    showMenu.addStyleName(ValoTheme.BUTTON_PRIMARY);
    showMenu.addStyleName(ValoTheme.BUTTON_SMALL);
    showMenu.addStyleName("valo-menu-toggle");
    showMenu.setIcon(FontAwesome.LIST);
    menu.addComponent(showMenu);

    final Label title = new Label("<h3>" + Site.getCurrent().localize(getViewVersion().getTitle()) + "</h3>",
            ContentMode.HTML);
    title.setSizeUndefined();
    topLayout.addComponent(title);
    topLayout.setExpandRatio(title, 1);

    final MenuBar settings = new MenuBar();
    settings.addStyleName("user-menu");

    final String user = Site.getCurrent().getSecurityProvider().getUser();
    final String userMenuCaption;
    final Resource userMenuIcon;
    if (user == null) {
        userMenuCaption = Site.getCurrent().localize("page-link-login");
        userMenuIcon = new ThemeResource("ilves_logo.png");
    } else {
        final URL gravatarUrl = GravatarUtil.getGravatarUrl(user, 64);
        userMenuIcon = new ExternalResource(gravatarUrl);
        userMenuCaption = ((SecurityProviderSessionImpl) Site.getCurrent().getSecurityProvider())
                .getUserFromSession().getFirstName();
    }

    final MenuBar.MenuItem settingsItem = settings.addItem(userMenuCaption, userMenuIcon, null);
    if (user != null) {
        settingsItem.addItem(Site.getCurrent().localize("page-link-account"), new MenuBar.Command() {
            @Override
            public void menuSelected(MenuBar.MenuItem selectedItem) {
                UI.getCurrent().getNavigator().navigateTo("account");
            }
        });
        settingsItem.addSeparator();
        settingsItem.addItem(Site.getCurrent().localize("button-logout"), new MenuBar.Command() {
            @Override
            public void menuSelected(MenuBar.MenuItem selectedItem) {
                LoginService.logout(Site.getCurrent().getSiteContext());
                final Company company = Site.getCurrent().getSiteContext().getObject(Company.class);
                getUI().getPage().setLocation(company.getUrl());
                getSession().getSession().invalidate();
                getSession().close();
            }
        });
    } else {
        settingsItem.addItem(Site.getCurrent().localize("page-link-login"), new MenuBar.Command() {
            @Override
            public void menuSelected(MenuBar.MenuItem selectedItem) {
                UI.getCurrent().getNavigator().navigateTo("login");
            }
        });
    }
    menu.addComponent(settings);

    menuItemsLayout.setPrimaryStyleName("valo-menuitems");
    menu.addComponent(menuItemsLayout);

    final Site site = Site.getCurrent();
    final NavigationVersion navigationVersion = site.getCurrentNavigationVersion();

    for (final String pageName : navigationVersion.getRootPages()) {
        final ViewVersion pageVersion = site.getCurrentViewVersion(pageName);
        if (pageVersion == null) {
            throw new SiteException("Unknown page: " + pageName);
        }
        if (pageVersion.getViewerRoles().length > 0) {
            boolean roleMatch = false;
            for (final String role : pageVersion.getViewerRoles()) {
                if (site.getSecurityProvider().getRoles().contains(role)) {
                    roleMatch = true;
                    break;
                }
            }
            if (!roleMatch) {
                continue;
            }
        }

        if (navigationVersion.hasChildPages(pageName)) {

            final String localizedPageName = pageVersion.isDynamic() ? pageName
                    : site.localize("page-link-" + pageName);

            final Label label = new Label(localizedPageName, ContentMode.HTML);
            label.setPrimaryStyleName("valo-menu-subtitle");
            label.addStyleName("h4");
            label.setSizeUndefined();
            menuItemsLayout.addComponent(label);

            final List<String> childPages = navigationVersion.getChildPages(pageName);
            for (final String childPage : childPages) {
                addMenuLink(navigationVersion, childPage);
            }

            label.setValue(
                    label.getValue() + " <span class=\"valo-menu-badge\">" + childPages.size() + "</span>");
        } else {
            addMenuLink(navigationVersion, pageName);
        }
    }

    return menu;
}

From source file:org.bubblecloud.ilves.site.view.valo.DefaultValoView.java

License:Apache License

private void addMenuLink(final NavigationVersion navigationVersion, final String pageName) {
    final Site site = Site.getCurrent();
    final ViewVersion pageVersion = site.getCurrentViewVersion(pageName);
    if (pageVersion == null) {
        throw new SiteException("Unknown page: " + pageName);
    }/*from  w w  w  .jav a  2s  . c o  m*/
    if (pageVersion.getViewerRoles().length > 0) {
        boolean roleMatch = false;
        for (final String role : pageVersion.getViewerRoles()) {
            if (site.getSecurityProvider().getRoles().contains(role)) {
                roleMatch = true;
                break;
            }
        }
        if (!roleMatch) {
            return;
        }
    }

    final String localizedPageName = pageVersion.isDynamic() ? pageName
            : site.localize("page-link-" + pageName);
    final Resource iconResource = pageVersion.isDynamic()
            ? navigationVersion.hasChildPages(pageName) ? site.getIcon("page-icon-folder")
                    : site.getIcon("page-icon-page")
            : site.getIcon("page-icon-" + pageName);

    Button b = new Button(localizedPageName, new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            UI.getCurrent().getNavigator().navigateTo(pageName);
        }
    });

    b.setHtmlContentAllowed(true);
    b.setPrimaryStyleName("valo-menu-item");
    b.setIcon(iconResource);
    menuItemsLayout.addComponent(b);

}

From source file:org.bubblecloud.ilves.ui.user.privilege.PrivilegesFlowlet.java

License:Apache License

@Override
protected void initialize() {
    final HorizontalLayout titleLayout = new HorizontalLayout();
    titleLayout.setMargin(new MarginInfo(true, false, true, false));
    titleLayout.setSpacing(true);/*from   w  w w.ja  v  a 2  s .com*/
    final Embedded titleIcon = new Embedded(null, getSite().getIcon("view-icon-privileges"));
    titleIcon.setWidth(32, Unit.PIXELS);
    titleIcon.setHeight(32, Unit.PIXELS);
    titleLayout.addComponent(titleIcon);
    titleLabel = new Label("<h1>" + getSite().localize("view-privileges") + "</h1>", ContentMode.HTML);
    titleLayout.addComponent(titleLabel);

    matrixLayout = new VerticalLayout();
    matrixLayout.setSpacing(true);
    matrixLayout.setMargin(false);

    final HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    saveButton = getSite().getButton("save");
    buttonLayout.addComponent(saveButton);
    saveButton.addClickListener(new Button.ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final Button.ClickEvent event) {
            saveGroupMatrix();
            saveUserMatrix();
            PrivilegeCache.flush((Company) Site.getCurrent().getSiteContext().getObject(Company.class));
        }
    });
    discardButton = getSite().getButton("discard");
    buttonLayout.addComponent(discardButton);
    discardButton.addClickListener(new Button.ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final Button.ClickEvent event) {
            refreshGroupMatrix();
            refreshUserMatrix();
        }
    });

    final CssLayout panel = new CssLayout();
    panel.addComponent(titleLayout);
    panel.addComponent(matrixLayout);
    panel.addComponent(buttonLayout);

    setCompositionRoot(panel);
}

From source file:org.groom.review.ui.flows.ReviewFileDiffFlowlet.java

License:Apache License

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

    gridLayout = new GridLayout(1, 2);
    gridLayout.setSpacing(true);/*  w w  w . j a  v a2  s .  c om*/
    gridLayout.setSizeFull();
    gridLayout.setColumnExpandRatio(0, 1f);
    gridLayout.setRowExpandRatio(1, 1f);
    setViewContent(gridLayout);

    selectionChangeListener = new AceEditor.SelectionChangeListener() {
        @Override
        public void selectionChanged(AceEditor.SelectionChangeEvent e) {

        }
    };

    //gridLayout.addComponent(editor, 0, 0);

    if (getFlow().getFlowlet(ReviewFlowlet.class) != null) {
        final HorizontalLayout buttonLayout = new HorizontalLayout();
        buttonLayout.setSpacing(true);
        gridLayout.addComponent(buttonLayout, 0, 0);

        final Button previousButton = new Button(getSite().localize("button-previous-diff"));
        previousButton.setClickShortcut(ShortcutAction.KeyCode.ARROW_LEFT);
        previousButton.setHtmlContentAllowed(true);
        buttonLayout.addComponent(previousButton);
        previousButton.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent clickEvent) {
                final ReviewFlowlet view = getFlow().getFlowlet(ReviewFlowlet.class);
                view.previous(path);
            }
        });

        final Button nextButton = new Button(getSite().localize("button-next-diff"));
        nextButton.setClickShortcut(ShortcutAction.KeyCode.ARROW_RIGHT);
        nextButton.setHtmlContentAllowed(true);
        buttonLayout.addComponent(nextButton);
        nextButton.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent clickEvent) {
                final ReviewFlowlet view = getFlow().getFlowlet(ReviewFlowlet.class);
                view.next(path);
            }
        });

        final Button scrollToPreviousChangeButton = new Button(
                getSite().localize("button-scroll-to-previous-change"));
        scrollToPreviousChangeButton.setClickShortcut(ShortcutAction.KeyCode.ARROW_UP);
        scrollToPreviousChangeButton.setHtmlContentAllowed(true);
        buttonLayout.addComponent(scrollToPreviousChangeButton);
        scrollToPreviousChangeButton.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent clickEvent) {
                int cursorLine = getScrolledTowRow();

                for (int i = cursorLine; i >= 0; i--) {
                    cursorLine = i;
                    if (blames.get(i).getType() == LineChangeType.NONE) {
                        break;
                    }
                }
                for (int i = cursorLine; i >= 0; i--) {
                    cursorLine = i;
                    if (i == 0 | blames.get(i).getType() != LineChangeType.NONE) {
                        break;
                    }
                }
                for (int i = cursorLine; i >= 0; i--) {
                    if (i == 0) {
                        final ReviewFlowlet view = getFlow().getFlowlet(ReviewFlowlet.class);
                        //view.previous(path);
                        scrollToRow(0);
                        break;
                    }
                    if (blames.get(i).getType() == LineChangeType.NONE) {
                        scrollToRow(i + 1);
                        break;
                    }
                }
            }
        });

        final Button scrollToNextChangeButton = new Button(getSite().localize("button-scroll-to-next-change"));
        scrollToNextChangeButton.setClickShortcut(ShortcutAction.KeyCode.ARROW_DOWN);
        scrollToNextChangeButton.setHtmlContentAllowed(true);
        buttonLayout.addComponent(scrollToNextChangeButton);
        scrollToNextChangeButton.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent clickEvent) {
                int cursorLine = getScrolledTowRow();

                for (int i = cursorLine; i < blames.size(); i++) {
                    cursorLine = i;
                    if (blames.get(i).getType() == LineChangeType.NONE) {
                        break;
                    }
                }
                for (int i = cursorLine; i < blames.size(); i++) {
                    if (i == blames.size() - 1) {
                        final ReviewFlowlet view = getFlow().getFlowlet(ReviewFlowlet.class);
                        //view.next(path);
                        scrollToRow(i);
                        break;
                    }
                    if (blames.get(i).getType() != LineChangeType.NONE) {
                        scrollToRow(i);
                        break;
                    }
                }
            }
        });

        final Button scrollToCursorButton = new Button("Scroll to Cursor");
        scrollToCursorButton.setHtmlContentAllowed(true);
        buttonLayout.addComponent(scrollToCursorButton);
        scrollToCursorButton.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent clickEvent) {
                if (editor.getSelection() == null || editor.getCursorPosition() < 0) {
                    return;
                }
                int cursor = editor.getCursorPosition();
                if (fileDiff.getReviewStatus() != null) {
                    final int cursorLine = findLine(editor.getValue(), cursor);
                    scrollToRow(cursorLine);
                }
            }
        });

        groomButton = getSite().getButton("groom");
        groomButton.setClickShortcut(ShortcutAction.KeyCode.ENTER);
        groomButton.setHtmlContentAllowed(true);
        buttonLayout.addComponent(groomButton);
        groomButton.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent clickEvent) {
                if (editor.getSelection() == null || editor.getCursorPosition() < 0) {
                    return;
                }
                int cursor = editor.getCursorPosition();
                if (fileDiff.getReviewStatus() != null) {
                    final int cursorLine = findLine(editor.getValue(), cursor);
                    final BlameLine blame = blames.get(cursorLine);

                    final CommentDialog commentDialog = new CommentDialog(new CommentDialog.DialogListener() {
                        @Override
                        public void onOk(final String message, final int severity) {
                            final ReviewStatus reviewStatus = fileDiff.getReviewStatus();
                            final Review review = reviewStatus.getReview();
                            final Date date = new Date();
                            if (message.trim().length() > 0) {
                                final Comment comment = new Comment(review, reviewStatus.getReviewer(),
                                        blame.getHash(), fileDiff.getPath(), blame.getFinalLine(), cursorLine,
                                        severity, message, blame.getAuthorName(), blame.getCommitterName(),
                                        date, date);
                                ReviewDao.saveComment(entityManager, comment);
                                addComment(comment);
                                final Company company = getSite().getSiteContext().getObject(Company.class);
                                final Thread emailThread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        String severity;
                                        switch (comment.getSeverity()) {
                                        case 1:
                                            severity = "Kudo";
                                            break;
                                        case -1:
                                            severity = "Warning";
                                            break;
                                        case -2:
                                            severity = "Red Flag";
                                            break;
                                        default:
                                            severity = Integer.toString(comment.getSeverity());
                                            if (!severity.startsWith("-")) {
                                                severity = "+" + severity;
                                            }
                                        }
                                        EmailUtil.send(blame.getAuthorEmail(),
                                                reviewStatus.getReviewer().getEmailAddress(),
                                                severity + " from review '" + review.getTitle() + "'",
                                                "Reviewer: " + reviewStatus.getReviewer().getFirstName() + " "
                                                        + reviewStatus.getReviewer().getLastName() + "\n"
                                                        + "Commit: " + blame.getHash() + "\n" + "File: "
                                                        + fileDiff.getPath() + "\n" + "Original Line: "
                                                        + blame.getOriginalLine() + "\n" + "Diff line: "
                                                        + cursorLine + "\n" + blame.getType() + ":"
                                                        + blame.getLine() + "\n" + "Message: " + message);
                                    }
                                });
                                emailThread.start();
                            }
                        }

                        public void onCancel() {
                            //To change body of implemented methods use File | Settings | File Templates.
                        }
                    });
                    int cursorPosition = editor.getCursorPosition();
                    commentDialog.setCaption("Please enter groom text for " + blame.getAuthorName()
                            + " at line: " + (cursorLine + 1));
                    UI.getCurrent().addWindow(commentDialog);
                    commentDialog.getTextArea().focus();

                }
            }
        });

    }
}

From source file:org.hbrs.nosql.mongoweb.gui.views.UseCaseC.java

@Override
protected void setUp() {
    MongoDBConnector mongo = new MongoDBConnector();

    VerticalLayout vl = new VerticalLayout();

    //CRUD Operations
    Label lbCreate = new Label("Create:");
    addComponent(lbCreate);// w  w w. ja  v a2s .  com

    HorizontalLayout hlCreate = new HorizontalLayout();
    TextField tfCreate = new TextField("Neues Dokument:");
    hlCreate.addComponent(tfCreate);
    Button btSaveCreate = new Button("Speichern");
    btSaveCreate.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            if (!tfCreate.getValue().equals("")) {
                String doc = tfCreate.getValue();
                mongo.insertNewDocumnet(doc);
            }
        }
    });

    hlCreate.addComponent(btSaveCreate);

    addComponent(hlCreate);

    //Read: All

    //Update:
    // https://www.mkyong.com/mongodb/java-mongodb-update-document/
    // http://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/

    //Delete: Attributes or Documents

    setMargin(true);
    setSpacing(true);
}

From source file:org.hbrs.nosql.mongoweb.gui.views.UseCaseU.java

@Override
protected void setUp() {
    MongoDBConnector mongo = new MongoDBConnector();

    VerticalLayout vl = new VerticalLayout();

    //CRUD Operations
    Label lbCreate = new Label("Update:");
    addComponent(lbCreate);/*from ww w  .  j  a  v a 2 s . co m*/

    HorizontalLayout hlCreate = new HorizontalLayout();
    TextField tfCreate = new TextField("Neues Dokument:");
    hlCreate.addComponent(tfCreate);
    Button btSaveCreate = new Button("Speichern");
    btSaveCreate.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            if (!tfCreate.getValue().equals("")) {
                String doc = tfCreate.getValue();
                mongo.insertNewDocumnet(doc);
            }
        }
    });

    hlCreate.addComponent(btSaveCreate);

    addComponent(hlCreate);

    //Read: All

    //Update:
    // https://www.mkyong.com/mongodb/java-mongodb-update-document/
    // http://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/

    //Delete: Attributes or Documents

    setMargin(true);
    setSpacing(true);
}

From source file:org.investovator.ui.dataplayback.user.dashboard.dailysummary.DailySummaryMultiPlayerMainView.java

License:Open Source License

@Override
public HorizontalLayout getBuySellForumButtons(final ComboBox stocksList, final TextField quantity,
        final NativeSelect orderSide) {
    HorizontalLayout buttonsBar = new HorizontalLayout();
    final Button buySellButton = new Button("Buy");
    buySellButton.addClickListener(new Button.ClickListener() {
        @Override//from   ww w. j  ava 2  s.c o  m
        public void buttonClick(Button.ClickEvent clickEvent) {

            //check for invalid orders
            boolean invalidOrder = false;
            String numericRegex = "^[0-9]+$";
            //conditions to check
            if (stocksList.getValue() == null || quantity.getValue() == null
                    || !quantity.getValue().toString().matches(numericRegex)) {
                invalidOrder = true;

            }
            //if this is a sell order
            else if (((OrderType) orderSide.getValue()) == OrderType.SELL) {
                //check if te user has this stock
                BeanContainer<String, PortfolioBean> beans = (BeanContainer<String, PortfolioBean>) portfolioTable
                        .getContainerDataSource();

                if (!beans.containsId(stocksList.getValue().toString())) {
                    invalidOrder = true;
                }
            }

            if (invalidOrder) {
                Notification.show("Invalid Order");
                return;
            }

            try {
                Boolean status = player.executeOrder(stocksList.getValue().toString(),
                        Integer.parseInt(quantity.getValue().toString()), ((OrderType) orderSide.getValue()),
                        userName);
                //if the transaction was a success
                if (status) {
                    updatePortfolioTable(stocksList.getValue().toString());
                    //update the account balance
                    updateAccountBalance();
                } else {

                    Notification.show(status.toString());
                }
            } catch (InvalidOrderException e) {
                Notification.show(e.getMessage());
            } catch (UserJoinException e) {
                e.printStackTrace();
            }

        }
    });

    orderSide.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            if (valueChangeEvent.getProperty().getValue() == OrderType.BUY) {
                buySellButton.setCaption("Buy");
            } else if (valueChangeEvent.getProperty().getValue() == OrderType.SELL) {
                buySellButton.setCaption("Sell");
            }
        }
    });

    buttonsBar.addComponent(buySellButton);

    return buttonsBar;
}

From source file:org.investovator.ui.dataplayback.user.dashboard.dailysummary.DailySummarySinglePlayerMainView.java

License:Open Source License

@Override
public HorizontalLayout getBuySellForumButtons(final ComboBox stocksList, final TextField quantity,
        final NativeSelect orderSide) {

    HorizontalLayout buttonsBar = new HorizontalLayout();
    final Button buySellButton = new Button("Buy");
    buySellButton.addClickListener(new Button.ClickListener() {
        @Override/*from www . j  a v a2s  .  c om*/
        public void buttonClick(Button.ClickEvent clickEvent) {

            //check for invalid orders
            boolean invalidOrder = false;
            String numericRegex = "^[0-9]+$";
            //conditions to check
            if (stocksList.getValue() == null || quantity.getValue() == null
                    || !quantity.getValue().toString().matches(numericRegex)) {
                invalidOrder = true;

            }
            //if this is a sell order
            else if (((OrderType) orderSide.getValue()) == OrderType.SELL) {
                //check if te user has this stock
                BeanContainer<String, PortfolioBean> beans = (BeanContainer<String, PortfolioBean>) portfolioTable
                        .getContainerDataSource();

                if (!beans.containsId(stocksList.getValue().toString())) {
                    invalidOrder = true;
                }
            }

            if (invalidOrder) {
                Notification.show("Invalid Order");
                return;
            }

            try {
                Boolean status = player.executeOrder(stocksList.getValue().toString(),
                        Integer.parseInt(quantity.getValue().toString()), ((OrderType) orderSide.getValue()),
                        userName);
                //if the transaction was a success
                if (status) {
                    updatePortfolioTable(stocksList.getValue().toString());

                    updateAccountBalance();
                } else {

                    Notification.show(status.toString());
                }
            } catch (InvalidOrderException e) {
                Notification.show(e.getMessage());
            } catch (UserJoinException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }

        }
    });
    orderSide.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            if (valueChangeEvent.getProperty().getValue() == OrderType.BUY) {
                buySellButton.setCaption("Buy");
            } else if (valueChangeEvent.getProperty().getValue() == OrderType.SELL) {
                buySellButton.setCaption("Sell");
            }
        }
    });

    Button nextDayB = new Button("Next day");
    nextDayB.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {

            player.playNextDay();
            updateProfitChart(player.getCurrentTime());

            //push the changes
            UI.getCurrent().access(new Runnable() {
                @Override
                public void run() {
                    getUI().push();
                }
            });

        }
    });

    buttonsBar.addComponent(nextDayB);

    buttonsBar.addComponent(buySellButton);

    return buttonsBar;
}