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:es.mdef.clientmanager.ui.GestionClientesUI.java

License:Apache License

CssLayout buildMenu() {
    // Add items/*  w ww  .ja v a 2 s  . c om*/
    menuItems.put("common", "Common UI Elements");
    menu.setSizeFull();
    menu.addComponent(getMenuTitleComponent());

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

    // TODO Actualizar nombre de usuario cuando se logee con exito
    final MenuBar.MenuItem userMenuItem = settings.addItem(getNombreUsuario(),
            new ThemeResource("icons/usuario.svg"), null);

    userMenuItem.addItem("Cambiar contrasea", new MenuBar.Command() {
        @Override
        public void menuSelected(MenuBar.MenuItem selectedItem) {
            ChangePasswordWindow changePasswordWindow = new ChangePasswordWindow();
            changePasswordWindow.center();
            addWindow(changePasswordWindow);
        }
    });
    userMenuItem.addSeparator();
    userMenuItem.addItem("Salir", new MenuBar.Command() {
        @Override
        public void menuSelected(MenuBar.MenuItem selectedItem) {
            SecurityContextHolder.clearContext();

            //UI.getCurrent().close();
            Navigator navigator = UI.getCurrent().getNavigator();
            navigator.navigateTo("");
        }
    });
    menu.addComponent(settings);

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

    final Button clientesButton = new Button("Clientes", new Button.ClickListener() {
        @Override
        public void buttonClick(final Button.ClickEvent event) {
            navigator.navigateTo(CLIENT_LIST_VIEW);
        }
    });

    clientesButton.setHtmlContentAllowed(true);
    clientesButton.setPrimaryStyleName("valo-menu-item");
    clientesButton.setIcon(new ThemeResource("icons/clientes2.svg"));
    menuItemsLayout.addComponent(clientesButton);

    final Button budgetButton = new Button("Presupuesto", new Button.ClickListener() {
        @Override
        public void buttonClick(final Button.ClickEvent event) {
            navigator.navigateTo(BUDGETS_VIEW);
        }
    });

    budgetButton.setHtmlContentAllowed(true);
    budgetButton.setPrimaryStyleName("valo-menu-item");
    budgetButton.setIcon(new ThemeResource("icons/money.svg"));
    menuItemsLayout.addComponent(budgetButton);

    final Button subscripcionButton = new Button("Suscripciones", new Button.ClickListener() {
        @Override
        public void buttonClick(final Button.ClickEvent event) {
            navigator.navigateTo(PROVIDERS_VIEW);
        }
    });

    subscripcionButton.setHtmlContentAllowed(true);
    subscripcionButton.setPrimaryStyleName("valo-menu-item");
    subscripcionButton.setIcon(new ThemeResource("icons/suscripciones.svg"));
    menuItemsLayout.addComponent(subscripcionButton);

    return menu;
}

From source file:eu.hurion.hello.vaadin.shiro.application.HelloScreen.java

License:Apache License

public HelloScreen(final HerokuShiroApplication app) {
    setSizeFull();//w  w  w .j  av a 2s .co  m
    final Subject currentUser = SecurityUtils.getSubject();

    final Panel welcomePanel = new Panel();
    final FormLayout content = new FormLayout();
    final Label label = new Label("Logged in as " + currentUser.getPrincipal().toString());
    logout = new Button("logout");
    logout.addClickListener(new HerokuShiroApplication.LogoutListener(app));

    content.addComponent(label);
    content.addComponent(logout);
    welcomePanel.setContent(content);
    welcomePanel.setWidth("400px");
    welcomePanel.setHeight("200px");
    addComponent(welcomePanel);
    setComponentAlignment(welcomePanel, Alignment.MIDDLE_CENTER);

    final HorizontalLayout footer = new HorizontalLayout();
    footer.setHeight("50px");
    addComponent(footer);

    final Button adminButton = new Button("For admin only");
    adminButton.setEnabled(currentUser.hasRole("admin"));
    adminButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(final Button.ClickEvent event) {
            Notification.show("you're an admin");
        }
    });
    content.addComponent(adminButton);

    final Button userButton = new Button("For users with permission 1");
    userButton.setEnabled(currentUser.isPermitted("permission_1"));
    userButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(final Button.ClickEvent event) {
            Notification.show("you've got permission 1");
        }
    });
    content.addComponent(userButton);

}

From source file:eu.lod2.DeleteGraphs.java

License:Apache License

/**
 * Takes the currently marked graphs in the table and destroys the graphs. Asks for confirmation first.
 * Resets the entire table after selection.
 * @param event : the clickevent that fired the call
 *///  w  ww .ja v a 2s.  c o m
private void deletegraphs(ClickEvent event) {
    Button yesOption = showConfirmDialog(
            "Warning! This function will result in the complete and irretrievable removal of the selected graphs.\n\n "
                    + "Do you wish to continue?");
    final DeleteGraphs panel = this;

    yesOption.addListener(new Button.ClickListener() {
        public void buttonClick(Button.ClickEvent event) {
            try {
                panel.doDeleteGraphs();
            } catch (Exception e) {
                getWindow().showNotification("Graph removal failed",
                        "Remove the graphs. " + "Received " + e.getClass().getSimpleName()
                                + " error with message: " + e.getMessage(),
                        Window.Notification.TYPE_ERROR_MESSAGE);
            }
        }
    });
}

From source file:eu.lod2.DeleteGraphs.java

License:Apache License

private Button showConfirmDialog(String message) {
    final Window notifier = new Window("Are you sure?");
    notifier.setWidth("400px");
    notifier.setModal(true);/*  w w  w  .j  ava2  s.co  m*/

    VerticalLayout layout = (VerticalLayout) notifier.getContent();
    layout.setMargin(true);
    layout.setSpacing(true);

    Label messageLabel = new Label(message);
    notifier.addComponent(messageLabel);

    Button yes = new Button("Yes", new ClickListener() {
        public void buttonClick(ClickEvent event) {
            notifier.getParent().removeWindow(notifier);
        }
    });
    Button no = new Button("No", new Button.ClickListener() {
        public void buttonClick(Button.ClickEvent event) {
            notifier.getParent().removeWindow(notifier);
        }
    });

    HorizontalLayout buttons = new HorizontalLayout();
    buttons.addComponent(yes);
    buttons.addComponent(no);
    notifier.addComponent(buttons);

    getWindow().addWindow(notifier);

    return yes;
}

From source file:gq.vaccum121.ui.LoginScreen.java

License:Apache License

private void initLayout() {
    FormLayout loginForm = new FormLayout();
    loginForm.setSizeUndefined();/*from w  w  w.  j  a  va  2  s  .c  om*/
    userName = new TextField("Username");
    passwordField = new PasswordField("Password");
    login = new Button("Login");
    loginForm.addComponent(userName);
    loginForm.addComponent(passwordField);
    loginForm.addComponent(login);
    login.addStyleName(ValoTheme.BUTTON_PRIMARY);
    login.setDisableOnClick(true);
    login.setClickShortcut(ShortcutAction.KeyCode.ENTER);
    login.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            login();
        }
    });

    VerticalLayout loginLayout = new VerticalLayout();
    loginLayout.setSizeUndefined();

    loginFailedLabel = new Label();
    loginLayout.addComponent(loginFailedLabel);
    loginLayout.setComponentAlignment(loginFailedLabel, Alignment.BOTTOM_CENTER);
    loginFailedLabel.setSizeUndefined();
    loginFailedLabel.addStyleName(ValoTheme.LABEL_FAILURE);
    loginFailedLabel.setVisible(false);

    loggedOutLabel = new Label("Good bye!");
    loginLayout.addComponent(loggedOutLabel);
    loginLayout.setComponentAlignment(loggedOutLabel, Alignment.BOTTOM_CENTER);
    loggedOutLabel.setSizeUndefined();
    loggedOutLabel.addStyleName(ValoTheme.LABEL_SUCCESS);
    loggedOutLabel.setVisible(false);

    loginLayout.addComponent(loginForm);
    loginLayout.setComponentAlignment(loginForm, Alignment.TOP_CENTER);

    VerticalLayout rootLayout = new VerticalLayout(loginLayout);
    rootLayout.setSizeFull();
    rootLayout.setComponentAlignment(loginLayout, Alignment.MIDDLE_CENTER);
    setCompositionRoot(rootLayout);
    setSizeFull();
}

From source file:io.mateu.ui.vaadin.framework.MyUI.java

License:Apache License

/**
 * construye una opcin del men//w  w  w . ja v  a2s.  com
 *
 */
private void addMenu(AbstractArea area, MenuEntry e) {

    Button b = null;

    if (e instanceof AbstractMenu) {
        b = new Button(e.getName(), new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                setAreaActual(area);
                setMenuActual(e);
                Page.getCurrent().open("#!" + getApp().getAreaId(area) + "/" + getApp().getMenuId(e) + "/menu",
                        (event.isAltKey() || event.isCtrlKey()) ? "_blank" : Page.getCurrent().getWindowName());
            }
        });
        b.setCaption(b.getCaption() + " <span class=\"valo-menu-badge\">"
                + ((AbstractMenu) e).getEntries().size() + "</span>");
    }

    if (e instanceof AbstractAction) {

        b = new Button(e.getName(), new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                setAreaActual(area);
                setMenuActual(e);
                ((AbstractAction) e).setModifierPressed(event.isAltKey() || event.isCtrlKey()).run();
            }
        });

    }

    if (b != null) {
        b.setCaptionAsHtml(true);
        b.setPrimaryStyleName(ValoTheme.MENU_ITEM);

        //b.setIcon(testIcon.get());  // sin iconos en el men
        menuItemsLayout.addComponent(b);

        botonesMenu.put(e, b);

    }

}

From source file:life.qbic.components.OfferGeneratorTab.java

License:Open Source License

/**
 * adds all the listeners to the offer generator tab
 * @param db: database instance to query
 * @param managerTabs: TabSheet holding the three tabs (Offer Generator, Offer Manager and Package Manager)
 * @param selectedProjectComboBox: ComboBox for selecting the project for the offer to generate
 * @param completeButton: button to complete the offer
 * @param addPackLayout: vertical layout which holds the twin select for selecting the packages, the package
 *                     description panel and the button to complete the offer
 * @param selectPackagesTwinColSelect: TwinSelect to select the packages for the current offer
 * @param packageDescriptionPanel: panel holding the descriptions labels for the selected packages
 * @param packageDescriptionLabel: label holding the description for the packages
 * @param twinColSelectFilter: text field for filtering the left side of the TwinColSelect
 *//*  w ww  . j  a v a 2s.  c o m*/
private static void addListeners(Database db, TabSheet managerTabs, ComboBox selectedProjectComboBox,
        Button completeButton, VerticalLayout addPackLayout, TwinColSelect selectPackagesTwinColSelect,
        Panel packageDescriptionPanel, Label packageDescriptionLabel, TextField twinColSelectFilter) {

    final float[] totalPrice = new float[1];
    final String[] descriptionText = new String[1];
    final String[][] offerGeneratorPackageNames = new String[1][1];
    final String[][] offerGeneratorPackageIds = new String[1][1];

    selectedProjectComboBox.addValueChangeListener(new Property.ValueChangeListener() {

        /**
         *
         */
        private static final long serialVersionUID = 6871999698387032993L;

        @Override
        public void valueChange(Property.ValueChangeEvent event) {
            if (selectedProjectComboBox.getValue() == null) {
                displayNotification("oO! No project selected!",
                        "Please select a project to proceed, otherwise we are going to have a situation here! ;)",
                        "error");
            } else {
                addPackLayout.addComponent(twinColSelectFilter);
                addPackLayout.addComponent(selectPackagesTwinColSelect);
                addPackLayout.addComponent(packageDescriptionPanel);
                addPackLayout.addComponent(completeButton);
            }
        }
    });

    selectPackagesTwinColSelect.addValueChangeListener(new Property.ValueChangeListener() {

        /**
         *
         */
        private static final long serialVersionUID = -5813954665588509117L;

        @Override
        public void valueChange(Property.ValueChangeEvent event) {

            // get the packages (package_id: package_name) as comma separated string and remove the leading and trailing bracket
            String selectedPackages = selectPackagesTwinColSelect.getValue().toString().substring(1);
            selectedPackages = selectedPackages.substring(0, selectedPackages.length() - 1);

            // in case there is no package selected, we do nothing
            if (selectedPackages.length() == 0) {
                return;
            }

            // init the arrays holding the package names and package ids
            offerGeneratorPackageNames[0] = selectedPackages.split(",");
            offerGeneratorPackageIds[0] = selectedPackages.split(",");

            // split the package id and the package name
            for (int i = 0; i < offerGeneratorPackageNames[0].length; i++) {
                offerGeneratorPackageIds[0][i] = offerGeneratorPackageIds[0][i].split(": ", 2)[0];
                offerGeneratorPackageNames[0][i] = offerGeneratorPackageNames[0][i].split(": ", 2)[1];
            }

            // TODO: value change listener does not trigger if the last element from the twin col select gets deselected
            System.out.println("packages in twin col select:");
            System.out.println(selectPackagesTwinColSelect.getValue());

            // there is a package for the current project, so we enable the complete offer button
            if (selectPackagesTwinColSelect.getValue() != null) {
                completeButton.setEnabled(true);
            } else {
                completeButton.setEnabled(false);
            }

            assert offerGeneratorPackageNames[0].length == offerGeneratorPackageIds[0].length;

            // iterate over all of the packages for the current offer and add their price and description to the view
            descriptionText[0] = "";
            totalPrice[0] = 0;
            for (int i = 0; i < offerGeneratorPackageNames[0].length; i++) {

                int currentPackageId = Integer.valueOf(offerGeneratorPackageIds[0][i].trim());

                // calculate the total offer price
                try {
                    totalPrice[0] += Float.parseFloat(db.getPriceFromPackageId(currentPackageId, "internal"));
                } catch (NullPointerException e) {
                    displayNotification("Package price is null!",
                            "The package price of the package " + offerGeneratorPackageIds[0][i] + ": "
                                    + offerGeneratorPackageNames[0][i] + " is null. Please remove the "
                                    + "package from the offer or update the "
                                    + "package price on the package manager tab. Otherwise "
                                    + "bad stuff is expected to happen..",
                            "error");
                }

                // get the description for the current package
                descriptionText[0] = descriptionText[0] + "<tr><td><p><b>" + offerGeneratorPackageIds[0][i]
                        + ": " + offerGeneratorPackageNames[0][i] + "</b><br>"
                        + db.getPackageDescriptionFromPackageId(currentPackageId)
                        + "</td><td align='right' valign='top'>"
                        + db.getPriceFromPackageId(currentPackageId, "internal") + "</td>" + "</p></tr>";

                // add the description and the total price to the view
                if (offerGeneratorPackageNames[0][i].length() != 0)
                    packageDescriptionLabel.setValue(
                            "<table width='100%'><tr><td><p style='color:red;'><b>Package Name and Description</b></p>"
                                    + "</td><td align='right'><p style='color:red;'><b>Price</b></p></td></tr><tr> </tr>"
                                    + descriptionText[0]
                                    + "<tr><td><p style='color:red;'><b>Grand Total</b> (excl. Taxes)</p></td><td align='right'>"
                                    + "<p style='color:red;'><b>" + totalPrice[0]
                                    + "</b></p></td></tr></table>");
                else
                    packageDescriptionLabel.setValue("No description available!");
            }
        }

    });

    completeButton.addClickListener(new Button.ClickListener() {

        /**
         *
         */
        private static final long serialVersionUID = 8181926819540586585L;

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

            // get some fields for the current offer
            String offerProjectReference = selectedProjectComboBox.getValue().toString();
            String dateToday = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String offerNumber = dateToday + "_" + offerProjectReference;
            String offerFacility = db.getPIFromProjectRef(offerProjectReference);
            String offerName = db.getShortTitleFromProjectRef(offerProjectReference);
            String offerDescription = db.getLongDescFromProjectRef(offerProjectReference);

            // register the new offer in the database; NOTE: internal has no functionality anymore, so we simply set it to
            // true
            int offerId = db.registerNewOffer(offerNumber, offerProjectReference, offerFacility, offerName,
                    offerDescription, totalPrice[0], new Date(), "temp", true);

            // TODO: if a liferay instance is running uncomment this and remove the call to db.registerNewOffer above
            /*        offerId =
                        db.registerNewOffer(offerNumber, offerProjectReference, offerFacility, offerName,
                            offerDescription, totalPrice, dNow,
                            LiferayAndVaadinUtils.getUser().getScreenName(), externalPriceSelectedCheckBox.getValue());
                    */

            // iterate over the packages from the current offer and insert them also in the database
            for (String packageId : offerGeneratorPackageIds[0]) {
                int currentPackageId = Integer.valueOf(packageId);
                float packageUnitPrice = Float.valueOf(db.getPriceFromPackageId(currentPackageId, "internal"));
                db.insertOrUpdateOffersPackages(offerId, currentPackageId, packageUnitPrice);
            }

            displayNotification("Perfect! Offer successfully saved in the Database!",
                    "Next step is to modify, finalize and send it to the customer. Keep in mind that the "
                            + "description of the offer is still missing. Please go ahead and complete it. Fingers crossed!",
                    "success");

            // change view to offer manager
            managerTabs.setSelectedTab(1);
        }
    });
}

From source file:life.qbic.components.OfferManagerTab.java

License:Open Source License

/**
 * adds the listeners to the offer manager tab
 * @param db: database instance to query
 * @param updateStatusComboBox: combo box for selecting the status of the offer
 * @param updateButton: button for updating the status of the offer
 * @param deleteOfferButton: button for deleting an offer
 * @param generateOfferButton: button for printing an offer
 * @param container: sql container holding the data from the database
 * @param exportTableButton: button for exporting the grid as csv
 *///  ww  w .  ja v  a  2  s.  c  o m
private static void addListeners(Database db, ComboBox updateStatusComboBox, Button updateButton,
        Button deleteOfferButton, Button generateOfferButton, SQLContainer container,
        Button exportTableButton) {

    // several lists holding the package names, descriptions, prices, etc. for the current offer
    // TODO: change to one list of packageBeans
    List<String> packageNames = qOfferManager.getPackageNames();
    List<String> packageDescriptions = qOfferManager.getPackageDescriptions();
    List<String> packageCounts = qOfferManager.getPackageCounts();
    List<String> packageUnitPrices = qOfferManager.getPackageUnitPrices();
    List<String> packageTotalPrices = qOfferManager.getPackageTotalPrices();

    offerManagerGrid.addSelectionListener(selectionEvent -> {

        // Get selection from the selection model
        Object selected = ((Grid.SingleSelectionModel) offerManagerGrid.getSelectionModel()).getSelectedRow();

        if (selected != null) {

            // check if any of the packages in the current offer has no package_grp (e.g. "Bioinformatics Analysis",
            // "Project Management", etc.) associated with it and display a warning for the user
            ArrayList<String> packageIdsWithoutPackageGroup = db.getPackageIdsWithoutPackageGroup(
                    container.getItem(selected).getItemProperty("offer_id").getValue().toString());
            if (packageIdsWithoutPackageGroup.size() > 0) {
                String firstPackageName = db.getPackageNameFromPackageId(packageIdsWithoutPackageGroup.get(0));
                displayNotification("Package not associated to package group", "The package " + firstPackageName
                        + " with id " + packageIdsWithoutPackageGroup.get(0)
                        + " has no package group associated with it. Please consider assigning the package to a "
                        + "package group.", "warning");
            }

            updateStatusComboBox.select(db.getOfferStatus(
                    container.getItem(selected).getItemProperty("offer_id").getValue().toString()));

            // enable the print offer button
            generateOfferButton.setEnabled(true);

            Notification.show("Selected " + db.getOfferStatus(
                    container.getItem(selected).getItemProperty("offer_id").getValue().toString()));

            detailsLayout.removeAllComponents();
            try {
                detailsLayout.addComponent(createOfferManagerTabPackageComponent(container,
                        container.getItem(selected).getItemProperty("offer_id").getValue().toString(), "All"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    updateButton.addClickListener(new Button.ClickListener() {

        /**
         *
         */
        private static final long serialVersionUID = 8910018717791341602L;

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

            if (offerManagerGrid.getSelectedRow() == null) {
                displayNotification("oOps! Forgot something?!",
                        "Please make sure that you select an offer to update.", "error");
            } else if (updateStatusComboBox.getValue() == null) {
                displayNotification("oOps! Forgot something?!",
                        "Please make sure that you select an option for status update.", "error");
            } else {
                // update the status of the offer (sent, accepted, declined, etc.)
                db.updateStatus(updateStatusComboBox.getValue().toString(),
                        offerManagerGrid.getSelectedRow().toString());

                container.refresh();
            }
        }
    });

    deleteOfferButton.addClickListener((Button.ClickListener) event -> {

        Object selectedRow = offerManagerGrid.getSelectedRow();
        if (selectedRow == null) {
            displayNotification("No offer selected!", "Please select an offer to delete.", "error");
            return;
        }

        int selectedOfferId = (int) offerManagerGrid.getContainerDataSource().getItem(selectedRow)
                .getItemProperty("offer_id").getValue();

        db.deleteOffer(selectedOfferId);

        // since refreshing the rows doesn't work properly; we force an update of the grid by setting the sort direction
        // of the package name column
        offerManagerGrid.sort("offer_id", SortDirection.ASCENDING);
        displayNotification("Offer deleted", "Offer " + selectedOfferId + " " + "successfully deleted.",
                "success");

    });

    packageGroupComboBox.addValueChangeListener((Property.ValueChangeListener) event -> {

        Object selected = ((Grid.SingleSelectionModel) offerManagerGrid.getSelectionModel()).getSelectedRow();

        if (selected == null) {
            displayNotification("No offer selected.", "Please select an offer to display", "error");
            return;
        }

        // e.g. "All", "Sequencing", or "Project Management"
        String selectedPackageGroup = packageGroupComboBox.getValue().toString();

        // change the view to display only the packages for the selected package group
        detailsLayout.removeAllComponents();
        try {
            detailsLayout.addComponent(createOfferManagerTabPackageComponent(container,
                    container.getItem(selected).getItemProperty("offer_id").getValue().toString(),
                    selectedPackageGroup));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });

    // adds the file creation and the export functionality to the print offer button
    try {
        setupOfferFileExportFunctionality(db, generateOfferButton, container, packageNames, packageDescriptions,
                packageCounts, packageUnitPrices, packageTotalPrices);
    } catch (IOException e) {
        displayNotification("Whoops, something went wrong.", "A file could not be found, please try" + "again.",
                "error");
        e.printStackTrace();
    }

    try {
        setupTableExportFunctionality(container, exportTableButton);
    } catch (IOException e) {
        displayNotification("Whoops, something went wrong.", "A file could not be found, please try" + "again.",
                "error");
        e.printStackTrace();
    }
}

From source file:life.qbic.components.OfferManagerTabPackageComponent.java

License:Open Source License

/**
 * adds the listeners to the package component of the offer manager tab
 * @param offerGridContainer: sql container holding the data for the offers
 * @param selectedOfferID: id of the selected offer
 * @param db: database instance to query
 * @param packageQuantityComboBox: combo box for selecting the package quantity
 * @param updateQuantityButton: button for updating the package quantity
 * @param removePackageButton: button for removing a package from the current offer
 * @param packagesAvailableForOfferComboBox: combo box for selecting the available packages to add to the current offer
 * @param addPackageButton: button for adding a package
 * @param packsContainer: sql container holding the data for the packages
 *///from  w w w  . j av  a  2  s.  c  o  m
private static void addListeners(SQLContainer offerGridContainer, String selectedOfferID, Database db,
        ComboBox packageQuantityComboBox, Button updateQuantityButton, Button removePackageButton,
        ComboBox packagesAvailableForOfferComboBox, Button addPackageButton, SQLContainer packsContainer,
        ComboBox externalInternalPriceComboBox, Button externalInternalPriceButton) {

    selectedPacksInOfferGrid.addSelectionListener(new SelectionEvent.SelectionListener() {

        /**
         *
         */
        private static final long serialVersionUID = -1061272471352530723L;

        @Override
        public void select(SelectionEvent event) {

            Object selectedPackageId = selectedPacksInOfferGrid.getSelectedRow();
            if (selectedPackageId != null) {
                int packageCount = db.getPackageCount(selectedOfferID, selectedPackageId.toString());
                if (packageCount > 0)
                    packageQuantityComboBox.select(packageCount);
            }
        }
    });

    updateQuantityButton.addClickListener(new Button.ClickListener() {

        /**
         *
         */
        private static final long serialVersionUID = 8910018717791341602L;

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

            if (selectedPacksInOfferGrid.getSelectedRow() == null) {
                displayNotification("oOps! Forgot something?!",
                        "Please make sure that you select a package to update.", "error");
                return;
            }

            if (packageQuantityComboBox.getValue() == null) {
                displayNotification("oOps! Forgot something?!",
                        "Please make sure that you select an option for the package quantity.", "error");
            } else {

                String rowId = selectedPacksInOfferGrid.getSelectedRow().toString();
                Object rowContainerId = packsContainer.getIdByIndex(Integer.parseInt(rowId) - 1);
                String packageId = packsContainer.getContainerProperty(rowContainerId, "package_id").getValue()
                        .toString();

                String packageGroup;
                try {
                    packageGroup = packsContainer.getContainerProperty(rowContainerId, "package_grp").getValue()
                            .toString();
                } catch (NullPointerException e) {
                    packageGroup = "";
                }
                int packageCount = Integer.parseInt(packageQuantityComboBox.getValue().toString());
                float packageDiscount = 1.0f;
                // the package discount should only be applied to the sequencing packages
                if (Objects.equals(packageGroup, "Sequencing")) {
                    // get the package discount based on the number of samples
                    packageDiscount = discountPerSampleSize.get(packageCount);
                }

                Property packagePriceTypeProperty = packsContainer.getContainerProperty(rowContainerId,
                        "package_price_type");
                String packagePriceType;
                if (packagePriceTypeProperty.getValue() == null) {
                    packagePriceType = "internal";
                } else {
                    packagePriceType = packagePriceTypeProperty.getValue().toString();
                }

                // update the database
                db.updatePackageQuantityAndRecalcalculatePrice(packageQuantityComboBox.getValue().toString(),
                        selectedOfferID, packageId, packagePriceType, packageDiscount);

                packsContainer.refresh();
                offerGridContainer.refresh();
            }

            // update the array lists holding the information about the packages of the current offer
            updatePackageArrays(packsContainer);
        }
    });

    removePackageButton.addClickListener((Button.ClickListener) event -> {

        Object selectedRow = selectedPacksInOfferGrid.getSelectedRow();
        if (selectedRow == null) {
            displayNotification("No package selected!", "Please select an package to remove from the offer.",
                    "error");
            return;
        }

        int selectedPackageID = (int) selectedPacksInOfferGrid.getContainerDataSource().getItem(selectedRow)
                .getItemProperty("package_id").getValue();

        db.removePackageFromOffer(selectedPackageID, Integer.parseInt(selectedOfferID));
        packsContainer.refresh();

        // update the array lists holding the information about the packages of the current offer
        updatePackageArrays(packsContainer);

        // recalculate the total offer price and update the database
        updateOfferPrice(selectedOfferID, packsContainer);

        offerGridContainer.refresh();

        displayNotification("Package removed",
                "Package " + selectedPackageID + " successfully removed from " + "offer.", "success");
    });

    addPackageButton.addClickListener((Button.ClickListener) event -> {

        Object packageToAdd = packagesAvailableForOfferComboBox.getValue();
        if (packageToAdd == null) {
            displayNotification("No package selected!", "Please select an package to add to the offer.",
                    "error");
            return;
        }

        // the package id and name is stored in the combobox as such: <package_id>: <package_name>
        String packageName = packageToAdd.toString().split(": ", 2)[1];
        int packageId = Integer.parseInt(packageToAdd.toString().split(": ", 2)[0]);

        // get the package price as string, so we can check whether it's null
        String packageUnitPrice = db.getPriceFromPackageId(packageId, "internal");
        if (packageUnitPrice == null) {
            displayNotification("Price is null!", "The price for the current package is null, please fix the "
                    + "database entry before adding the package!", "error");
            return;
        }

        // check if the package is already used for the offer
        boolean packageIsAlreadyInOffer = db.checkForPackageInOffer(Integer.parseInt(selectedOfferID),
                packageId);
        if (packageIsAlreadyInOffer) {
            displayNotification("Package already in offer!", "The package you tried to add is already used in "
                    + "the offer. Please update the quantity instead.", "error");
            return;
        }

        db.insertOrUpdateOffersPackages(Integer.parseInt(selectedOfferID), packageId,
                Float.parseFloat(packageUnitPrice));
        packsContainer.refresh();

        // update the array lists holding the information about the packages of the current offer
        updatePackageArrays(packsContainer);

        // recalculate the total offer price and update the database
        updateOfferPrice(selectedOfferID, packsContainer);

        offerGridContainer.refresh();
        displayNotification("Package added",
                "Package " + packageName + " successfully added to the " + "offer.", "success");
    });

    externalInternalPriceButton.addClickListener(event -> {

        if (selectedPacksInOfferGrid.getSelectedRow() == null) {
            displayNotification("oOps! Forgot something?!",
                    "Please make sure that you select a package to update.", "error");
            return;
        }

        if (externalInternalPriceComboBox.getValue() == null) {
            displayNotification("oOps! Forgot something?!",
                    "Please make sure that you select an option for the package price type.", "error");
        } else {

            String rowId = selectedPacksInOfferGrid.getSelectedRow().toString();
            Object rowContainerId = packsContainer.getIdByIndex(Integer.parseInt(rowId) - 1);
            String packageId = packsContainer.getContainerProperty(rowContainerId, "package_id").getValue()
                    .toString();

            // database entry is an enum ["internal", "external_academic" and "external_commercial"], so we need to
            // adjust the value we want to insert
            String packagePriceType = externalInternalPriceComboBox.getValue().toString();
            packagePriceType = packagePriceType.toLowerCase().replace(" ", "_");

            // check if we have a price for the selected package price type in the database
            if (packsContainer.getContainerProperty(rowContainerId, "package_price_" + packagePriceType)
                    .getValue() == null) {
                displayNotification("Package price is null", "The " + packagePriceType + " for package "
                        + packageId
                        + " is null. Please update the package in the package manager tab. Otherwise the price "
                        + "will be null", "error");
                return;
            }

            // update the package price type
            db.updatePackagePriceTypeForPackage(selectedOfferID, packageId, packagePriceType);

            // due to a lack of time we simply use the updatePackageQuantityAndRecalcalculatePrice function to
            // recalculate the prices, although the quantity has not changed
            // TODO: write function to recalculate the price without the quantity to save some computation power
            String packageDiscountString = packsContainer
                    .getContainerProperty(rowContainerId, "package_discount").getValue().toString()
                    .split("%")[0];
            String packageCount = packsContainer.getContainerProperty(rowContainerId, "package_count")
                    .getValue().toString();

            db.updatePackageQuantityAndRecalcalculatePrice(packageCount, selectedOfferID, packageId,
                    packagePriceType, 1 - Float.valueOf(packageDiscountString) / 100);

            packsContainer.refresh();
            offerGridContainer.refresh();

        }
    });
}

From source file:life.qbic.components.PackageManagerTab.java

License:Open Source License

/**
 * adds the listeners to the three buttons
 * @param db: database instance to query
 * @param addPackageButton: button for creating a new package
 * @param updatePackageGroupComboBox: combo box for selecting the package group
 * @param updateSelectedPackageButton: button for updating a package
 * @param deleteSelectedPackageButton: button for deleting a package
 * @param container: SQLContainer holding the data from the database
 * @param packageGrid: grid holding the packages
 * @param exportTableButton: button for exporting the grid as csv
 *///from   ww  w .java 2s .c  o m
private static void addListeners(Database db, Button addPackageButton, ComboBox updatePackageGroupComboBox,
        Button updateSelectedPackageButton, Button deleteSelectedPackageButton, SQLContainer container,
        RefreshableGrid packageGrid, Button exportTableButton) {

    addPackageButton.addClickListener(new Button.ClickListener() {

        /**
         *
         */
        private static final long serialVersionUID = 8181926819540586585L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            DBManager.getDatabaseInstance().addNewPackage("*** New Package - double click to edit ***");
            displayNotification("New Package Added",
                    "Please edit the package details! If the details are not complete, incompatibility "
                            + "issues are expected to happen.",
                    "success");
            packageGrid.clearSortOrder();
            packageGrid.sort("package_name", SortDirection.ASCENDING);
        }
    });

    updateSelectedPackageButton.addClickListener((Button.ClickListener) event -> {

        if (packageGrid.getSelectedRow() == null) {
            displayNotification("oOps! Forgot something?!",
                    "Please make sure that you select a package to update.", "error");
        } else if (updatePackageGroupComboBox.getValue() == null) {
            displayNotification("oOps! Forgot something?!",
                    "Please make sure that you select an option for the package group.", "error");
        } else {
            String selectedPackageGroup = updatePackageGroupComboBox.getValue().toString();
            String packageId = packageGrid.getSelectedRow().toString();
            db.updatePackageGroupForPackage(selectedPackageGroup, packageId);
            container.refresh();
        }
    });

    deleteSelectedPackageButton.addClickListener((Button.ClickListener) event -> {
        Object selectedRow = packageGrid.getSelectedRow();
        if (selectedRow == null) {
            displayNotification("No package selected!", "Please select a package to delete.", "error");
            return;
        }

        int selectedPackageId = (int) packageGrid.getContainerDataSource().getItem(selectedRow)
                .getItemProperty("package_id").getValue();

        // check if package is used in a offer
        boolean isPackageSelected = db.isPackageSelectedForAnyOffer(selectedPackageId);
        if (isPackageSelected) {
            // get the first offer_id from the offers where the package is in use
            int offerId = db.getFirstOfferIdForPackageId(selectedPackageId);
            displayNotification("Package in use", "Package " + selectedPackageId + " is used by offer "
                    + offerId + " ! Please remove the package from the offer before deleting it.", "error");
            return;
        }

        db.deletePackage(selectedPackageId);
        // since refreshing the rows doesn't work properly; we force an update of the grid by setting the sort direction
        // of the package name column
        packageGrid.sort("package_name", SortDirection.ASCENDING);
        displayNotification("Package deleted", "Package " + selectedPackageId + " successfully deleted.",
                "success");
    });

    // setup the export as .csv file functionality
    String exportPackagesFileName = pathOnServer + "packages.csv";
    fileDownloader = new FileDownloader(new FileResource(new File(exportPackagesFileName))) {
        @Override
        public boolean handleConnectorRequest(VaadinRequest request, VaadinResponse response, String path)
                throws IOException {
            createExportContent(container, exportPackagesFileName, fileDownloader);
            return super.handleConnectorRequest(request, response, path);
        }
    };
    fileDownloader.extend(exportTableButton);

}