Example usage for com.vaadin.ui CheckBox CheckBox

List of usage examples for com.vaadin.ui CheckBox CheckBox

Introduction

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

Prototype

public CheckBox(String caption) 

Source Link

Document

Creates a new checkbox with a set caption.

Usage

From source file:eu.maxschuster.vaadin.localstorage.test.LocalStorageUI.java

License:Apache License

@Override
protected void init(VaadinRequest request) {

    final LocalStorageItemCallback callback = new LocalStorageItemCallback() {

        /*/*from  w w w .j ava2 s  .com*/
         * (non-Javadoc)
         * @see eu.maxschuster.vaadin.localstorage.shared.LocalStorageItemCallback#onSussess(java.lang.String, java.lang.String, java.lang.String)
         */
        @Override
        public void onSuccess(LocalStorageItem item) {
            appendToLog("Success:\n" + item);
        }

        /*
         * (non-Javadoc)
         * @see eu.maxschuster.vaadin.localstorage.shared.LocalStorageItemCallback#onError()
         */
        @Override
        public void onError(String key) {
            appendToLog("ERROR for item \"" + key + "\" (simulateNotSupported="
                    + LocalStorage.getCurrent().isSimulateNotSupported() + ")");
        }

    };

    final ItemUpdateListener itemUpdateListener = new ItemUpdateListener() {

        @Override
        public void onUpdate(ItemUpdateEvent event) {
            appendToLog("Update (type=" + event.getType() + "):\n" + event.getItem());
        }

    };

    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    layout.setSizeFull();
    setContent(layout);

    final HorizontalLayout topLayout = new HorizontalLayout();
    topLayout.setSpacing(true);
    layout.addComponent(topLayout);
    layout.setExpandRatio(topLayout, 0);

    Button button = new Button("Start", new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {

            appendToLog("Start localStorage test:");

            LocalStorage localStorage = LocalStorage.getCurrent();

            localStorage.setItem("remove", "REMOVE ME!");

            localStorage.setItem("test", "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", callback);

            localStorage.removeItem("remove");

            localStorage.setItem("test", "Duis commodo.", callback);

            localStorage.getItem("test", callback);

            localStorage.getItem("remove", callback);

        }
    });
    topLayout.addComponent(button);

    Button clearButton = new Button("Clear localStorage", new Button.ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            LocalStorage.getCurrent().clear(callback);
        }

    });

    CheckBox fireUpdateCheckBox = new CheckBox("Fire update events");
    fireUpdateCheckBox.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            Boolean value = (Boolean) event.getProperty().getValue();
            if (value)
                LocalStorage.getCurrent().addItemUpdateListener(itemUpdateListener);
            else
                LocalStorage.getCurrent().removeItemUpdateListener(itemUpdateListener);
        }

    });

    CheckBox simulateNotSupportedCheckbox = new CheckBox("Simulate not supported");
    simulateNotSupportedCheckbox.addValueChangeListener(new ValueChangeListener() {
        @Override
        public void valueChange(ValueChangeEvent event) {
            LocalStorage.getCurrent().setSimulateNotSupported((Boolean) event.getProperty().getValue());
        }
    });

    topLayout.addComponents(clearButton, fireUpdateCheckBox, simulateNotSupportedCheckbox);

    log.setSizeFull();
    log.setReadOnly(true);
    layout.addComponent(log);
    layout.setExpandRatio(log, 1);

}

From source file:facs.components.UserAdmin.java

License:Open Source License

public UserAdmin(User user) {

    Date dNow = new Date();
    SimpleDateFormat ft = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
    System.out.println(ft.format(dNow) + "  INFO  Calendar User Manager accessed! - User: "
            + LiferayAndVaadinUtils.getUser().getScreenName());

    Label infoLabel = new Label(
            DBManager.getDatabaseInstance().getUserNameByUserID(LiferayAndVaadinUtils.getUser().getScreenName())
                    + "  " + LiferayAndVaadinUtils.getUser().getScreenName());
    infoLabel.addStyleName("h4");

    CheckBox isAdmin = new CheckBox("user has admin panel access");
    isAdmin.setEnabled(false);/*from w  w w  .j a  va2 s .  c  o  m*/

    String buttonGroupUpdateTitle = "Edit Group";
    Button updateUserGroup = new Button(buttonGroupUpdateTitle);
    updateUserGroup.setIcon(FontAwesome.EDIT);
    updateUserGroup.setSizeFull();
    updateUserGroup.setDescription("Click here to update the group of the user!");

    String buttonWorkgroupUpdateTitle = "Edit Workgroup";
    Button updateUserWorkgroup = new Button(buttonWorkgroupUpdateTitle);
    updateUserWorkgroup.setIcon(FontAwesome.EDIT);
    updateUserWorkgroup.setSizeFull();
    updateUserWorkgroup.setDescription("Click here to update the workgroup of the user!");

    String buttonUpdateTitle = "Update (user role & group for device)";
    Button updateUserRightsAndRoles = new Button(buttonUpdateTitle);
    updateUserRightsAndRoles.setIcon(FontAwesome.WRENCH);
    updateUserRightsAndRoles.setSizeFull();
    updateUserRightsAndRoles.setDescription("Click here to update the user's role and group for a device!");

    String buttonTitle = "Refresh";
    Button refresh = new Button(buttonTitle);
    refresh.setIcon(FontAwesome.REFRESH);
    refresh.setSizeFull();
    refresh.setDescription("Click here to reload the data from the database!");
    refresh.addStyleName(ValoTheme.BUTTON_FRIENDLY);

    // String buttonTitleSave = "Save";
    // Button save = new Button(buttonTitleSave);
    // save.setIcon(FontAwesome.SAVE);
    // save.setSizeFull();
    // save.setDescription("Click here to save all changes!");
    // save.addStyleName(ValoTheme.BUTTON_BORDERLESS);

    userDevice = new ListSelect("Devices");
    userDevice.addItems(DBManager.getDatabaseInstance().getDeviceNames());
    userDevice.setRows(6);
    userDevice.setNullSelectionAllowed(false);
    userDevice.setSizeFull();
    userDevice.setImmediate(true);
    /*
     * userDevice.addValueChangeListener(e -> Notification.show("Device:",
     * String.valueOf(e.getProperty().getValue()), Type.TRAY_NOTIFICATION));
     */
    userGroup = new ListSelect("User Groups");
    userGroup.addItems(DBManager.getDatabaseInstance().getUserGroups());
    userGroup.addItem("N/A");
    userGroup.setRows(6);
    userGroup.setNullSelectionAllowed(false);
    userGroup.setSizeFull();
    userGroup.setImmediate(true);
    /*
     * userGroup.addValueChangeListener(e -> Notification.show("User Group:",
     * String.valueOf(e.getProperty().getValue()), Type.TRAY_NOTIFICATION));
     */
    userRole = new ListSelect("User Roles");
    userRole.addItems(DBManager.getDatabaseInstance().getUserRoles());
    userRole.addItem("N/A");
    userRole.setRows(6);
    userRole.setNullSelectionAllowed(false);
    userRole.setSizeFull();
    userRole.setImmediate(true);
    /*
     * userRole.addValueChangeListener(e -> Notification.show("User Role:",
     * String.valueOf(e.getProperty().getValue()), Type.TRAY_NOTIFICATION));
     */
    userWorkgroup = new ListSelect("Workgroups");
    userWorkgroup.addItems(DBManager.getDatabaseInstance().getUserWorkgroups());
    userWorkgroup.setRows(6);
    userWorkgroup.setNullSelectionAllowed(false);
    userWorkgroup.setSizeFull();
    userWorkgroup.setImmediate(true);
    /*
     * userRole.addValueChangeListener(e -> Notification.show("User Role:",
     * String.valueOf(e.getProperty().getValue()), Type.TRAY_NOTIFICATION));
     */

    Button updateUser = new Button(buttonTitle);
    updateUser.setIcon(FontAwesome.WRENCH);
    updateUser.setDescription("Click here to update your user role and group!");

    refresh.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -3610721151565496269L;

        @Override
        public void buttonClick(ClickEvent event) {
            refreshDataSources();
        }
    });

    updateUser.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -3610721151565496909L;

        @Override
        public void buttonClick(ClickEvent event) {
            refreshDataSources();
        }
    });

    updateUserWorkgroup.addClickListener(new ClickListener() {

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

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                Object selectedRow = ((SingleSelectionModel) usersGrid.getSelectionModel()).getSelectedRow();

                if (selectedRow == null || userWorkgroup.getValue().equals(null)) {
                    Notification("Something's missing!",
                            "Please make sure that you selected the user and workgroup! Make sure they are highligthed.",
                            "error");
                } else {
                    DBManager.getDatabaseInstance().adminUpdatesUserWorkgroup(
                            DBManager.getDatabaseInstance()
                                    .getUserGroupIDByName(userWorkgroup.getValue().toString()),
                            DBManager.getDatabaseInstance().getUserLDAPIDbyID(selectedRow.toString()));

                    // log changes in 'user_log' table
                    DBManager.getDatabaseInstance().logEverything(
                            LiferayAndVaadinUtils.getUser().getScreenName(), "Admin edited Workgroup");

                    Notification("Successfully Updated",
                            "Selected values are updated in the database. If it was a mistake, please remind that there is no 'undo' functionality yet.",
                            "success");

                }
            } catch (Exception e) {
                Notification("Something's missing!",
                        "Please make sure that you selected the user and workgroup! Make sure they are highligthed.",
                        "error");
            }
            refreshDataSources();
        }
    });

    updateUserGroup.addClickListener(new ClickListener() {

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

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                Object selectedRow = ((SingleSelectionModel) usersGrid.getSelectionModel()).getSelectedRow();

                if (selectedRow == null || userWorkgroup.getValue().equals(null)) {
                    Notification("Something's missing!",
                            "Please make sure that you selected the user and group! Make sure they are highligthed.",
                            "error");
                } else {
                    DBManager.getDatabaseInstance().adminUpdatesUserGroup(
                            DBManager.getDatabaseInstance()
                                    .getUserGroupIDByName(userGroup.getValue().toString()),
                            DBManager.getDatabaseInstance().getUserIDbyLDAPID(selectedRow.toString()));

                    // log changes in 'user_log' table
                    DBManager.getDatabaseInstance().logEverything(
                            LiferayAndVaadinUtils.getUser().getScreenName(), "Admin edited User Group");

                    Notification("Successfully Updated",
                            "Selected values are updated in the database. If it was a mistake, please remind that there is no 'undo' functionality yet.",
                            "success");

                }
            } catch (Exception e) {
                Notification("Something's missing!",
                        "Please make sure that you selected the user and group! Make sure they are highligthed.",
                        "error");
            }
            refreshDataSources();
        }
    });

    updateUserRightsAndRoles.addClickListener(new ClickListener() {

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

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                Object selectedRow = ((SingleSelectionModel) usersGrid.getSelectionModel()).getSelectedRow();

                if (selectedRow == null || userDevice.getValue().equals(null)
                        || userRole.getValue().equals(null)) {
                    Notification("Something's missing!",
                            "Please make sure that you selected the user, device and role! Each list has to have one highligthed option.",
                            "error");
                } else {
                    DBManager.getDatabaseInstance().adminUpdatesUserRoleForDevice(
                            DBManager.getDatabaseInstance().getUserRoleIDbyDesc(userRole.getValue().toString()),
                            DBManager.getDatabaseInstance().getUserIDbyLDAPID(
                                    DBManager.getDatabaseInstance().getUserLDAPIDbyID(selectedRow.toString())),
                            DBManager.getDatabaseInstance()
                                    .getDeviceIDByName(userDevice.getValue().toString()));

                    // log changes in 'user_log' table
                    DBManager.getDatabaseInstance().logEverything(
                            LiferayAndVaadinUtils.getUser().getScreenName(),
                            "Admin edited Device, Role, Group");

                    Notification("Successfully Updated",
                            "Selected values are updated in the database. If it was a mistake, please remind that there is no 'undo' functionality yet.",
                            "success");

                }
            } catch (Exception e) {
                Notification("Something's missing!",
                        "Please make sure that you selected the user, device and role! Each list has to have one highligthed option.",
                        "error");
            }
            refreshDataSources();
        }
    });

    try {
        TableQuery tq = new TableQuery("user", DBManager.getDatabaseInstanceAlternative());
        tq.setVersionColumn("OPTLOCK");
        SQLContainer container = new SQLContainer(tq);

        // System.out.println("Print Container: " + container.size());
        container.setAutoCommit(isEnabled());

        usersGrid = new Grid(container);

        FieldGroup fieldGroup = usersGrid.getEditorFieldGroup();
        fieldGroup.addCommitHandler(new FieldGroup.CommitHandler() {
            /**
             * 
             */
            private static final long serialVersionUID = 3799806709907688919L;

            @Override
            public void preCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException {

            }

            @Override
            public void postCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException {

                Notification("Successfully Updated",
                        "Selected values are updated in the database. If it was a mistake, please remind that there is no 'undo' functionality yet.",
                        "success");

                refreshGrid();
            }

            private void refreshGrid() {
                container.refresh();
            }

        });

        usersGrid.addSelectionListener(selectionEvent -> { // Java 8
            // Get selection from the selection model
            Object selected = ((SingleSelectionModel) usersGrid.getSelectionModel()).getSelectedRow();

            if (selected != null) {

                // userDevice.select(bookAdmin.getSelectedTab().getCaption());
                userWorkgroup.select(DBManager.getDatabaseInstance().getUserWorkgroupByUserId(usersGrid
                        .getContainerDataSource().getItem(selected).getItemProperty("user_id").toString()));
                userGroup.select(DBManager.getDatabaseInstance().getUserRoleByUserId(usersGrid
                        .getContainerDataSource().getItem(selected).getItemProperty("user_id").toString()));

                userDevice.addValueChangeListener(new ValueChangeListener() {

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

                    @Override
                    public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
                        userRole.select(
                                DBManager.getDatabaseInstance().getUserGroupDescriptionByUserID(
                                        usersGrid.getContainerDataSource().getItem(selected)
                                                .getItemProperty("user_id").toString(),
                                        userDevice.getValue().toString()));

                    }
                });

                isAdmin.setValue(DBManager.getDatabaseInstance().hasAdminPanelAccess(usersGrid
                        .getContainerDataSource().getItem(selected).getItemProperty("user_id").toString()));

                Notification.show("Selected "
                        + usersGrid.getContainerDataSource().getItem(selected).getItemProperty("user_id"));
            } else
                Notification.show("Nothing selected");
        });

    } catch (Exception e) {
        // TODO Auto-generated catch block
        Notification("Something went wrong!",
                "Unable to update/connect the database. There may be a connection problem, please check your internet connection settings then try it again.",
                "error");
        e.printStackTrace();
    }

    /*
     * // only admins are allowed to see the admin panel ;) if (!DBManager.getDatabaseInstance()
     * .getUserAdminPanelAccessByLDAPId(LiferayAndVaadinUtils.getUser().getScreenName())
     * .equals("1")) { VerticalLayout errorLayout = new VerticalLayout();
     * infoLabel.setValue("ACCESS DENIED"); errorLayout.addComponent(infoLabel);
     * showErrorNotification( "Access Denied!",
     * "Sorry, you're not allowed to see anything here, at least your username told us so. Do you need assistance? Please contact 'info@qbic.uni-tuebingen.de'."
     * ); setCompositionRoot(errorLayout); return; }
     */

    this.setCaption("User Manager");

    final TabSheet userAdmin = new TabSheet();
    userAdmin.addStyleName(ValoTheme.TABSHEET_FRAMED);
    userAdmin.addTab(usersGrid());
    /*
     * userAdmin.addSelectedTabChangeListener(new SelectedTabChangeListener() {
     * 
     * @Override public void selectedTabChange(SelectedTabChangeEvent event) {
     * 
     * } });
     */

    gridLayout.setWidth("100%");

    // add components to the grid layout
    // gridLayout.addComponent(infoLabel, 0, 0, 3, 0);
    gridLayout.addComponent(userAdmin, 0, 1, 5, 1);
    gridLayout.addComponent(refresh, 0, 2);
    gridLayout.addComponent(isAdmin, 5, 2);
    // gridLayout.addComponent(save);

    gridLayout.addComponent(userWorkgroup, 0, 4);
    gridLayout.addComponent(userDevice, 1, 4);
    gridLayout.addComponent(userRole, 2, 4, 4, 4);
    gridLayout.addComponent(userGroup, 5, 4);
    gridLayout.addComponent(updateUserWorkgroup, 0, 5);
    gridLayout.addComponent(updateUserRightsAndRoles, 1, 5, 4, 5);
    gridLayout.addComponent(updateUserGroup, 5, 5);
    // gridLayout.addComponent(newContainerGrid, 1, 4);

    gridLayout.setSpacing(true);
    gridLayout.setSizeFull();
    setCompositionRoot(gridLayout);

}

From source file:fr.univlorraine.mondossierweb.views.ListeInscritsView.java

License:Apache License

public void initListe() {
    //On vrifie le droit d'accder  la vue
    if (UI.getCurrent() instanceof MainUI && userController.isEnseignant()) {
        // initialisation de la vue
        removeAllComponents();/*from w w  w  .j  a va 2  s.co m*/
        listeEtapes = null;
        listeGroupes = null;

        // Style 
        setMargin(true);
        setSpacing(true);
        setSizeFull();

        // Rcupration de l'objet de la SE dont on doit afficher les inscrits
        code = MainUI.getCurrent().getCodeObjListInscrits();
        typeFavori = MainUI.getCurrent().getTypeObjListInscrits();
        libelleObj = "";
        if (typeIsVet() && MainUI.getCurrent().getEtapeListeInscrits() != null) {
            libelleObj = MainUI.getCurrent().getEtapeListeInscrits().getLibelle();
        }
        if (typeIsElp() && MainUI.getCurrent().getElpListeInscrits() != null) {
            libelleObj = MainUI.getCurrent().getElpListeInscrits().getLibelle();
        }

        // Si l'objet est renseign
        if (code != null && typeFavori != null) {

            //Panel contenant les filtres d'affichage et le bouton de mise en favori
            HorizontalLayout panelLayout = new HorizontalLayout();
            panelLayout.setSizeFull();
            panelLayout.addStyleName("small-font-element");

            // Layout contenant les filtres
            FormLayout formInscritLayout = new FormLayout();
            formInscritLayout.setStyleName(ValoTheme.FORMLAYOUT_LIGHT);
            formInscritLayout.setSpacing(true);
            formInscritLayout.setMargin(true);

            panelFormInscrits = new Panel(code + " " + libelleObj);

            //Affichage d'une liste droulante contenant la liste des annes
            List<String> lannees = MainUI.getCurrent().getListeAnneeInscrits();
            if (lannees != null && lannees.size() > 0) {
                listeAnnees = new ComboBox(applicationContext.getMessage(NAME + ".annee", null, getLocale()));
                listeAnnees.setPageLength(5);
                listeAnnees.setTextInputAllowed(false);
                listeAnnees.setNullSelectionAllowed(false);
                listeAnnees.setWidth("150px");
                for (String annee : lannees) {
                    listeAnnees.addItem(annee);
                    int anneenplusun = Integer.parseInt(annee) + 1;
                    listeAnnees.setItemCaption(annee, annee + "/" + anneenplusun);
                }
                listeAnnees.setValue(MainUI.getCurrent().getAnneeInscrits());

                //Gestion de l'vnement sur le changement d'anne
                listeAnnees.addValueChangeListener(new ValueChangeListener() {
                    @Override
                    public void valueChange(ValueChangeEvent event) {
                        String selectedValue = (String) event.getProperty().getValue();

                        //faire le changement
                        Map<String, String> parameterMap = new HashMap<>();
                        parameterMap.put("code", code);
                        parameterMap.put("type", typeFavori);

                        //rcupration de la nouvelle liste
                        if (typeIsVet()) {
                            listeInscritsController.recupererLaListeDesInscrits(parameterMap, selectedValue,
                                    MainUI.getCurrent());
                        }
                        if (typeIsElp()) {
                            listeInscritsController.recupererLaListeDesInscritsELP(parameterMap, selectedValue,
                                    MainUI.getCurrent());
                        }

                        //update de l'affichage
                        initListe();
                    }
                });
                formInscritLayout.addComponent(listeAnnees);

            }

            //Si on affiche la liste des inscrits  un ELP
            //on doit affiche l'tape d'appartenance et ventuellement les groupes
            //Affichage d'une liste droulante contenant la liste des annes
            if (typeIsElp()) {
                List<VersionEtape> letapes = MainUI.getCurrent().getListeEtapesInscrits();
                if (letapes != null && letapes.size() > 0) {
                    listeEtapes = new ComboBox(
                            applicationContext.getMessage(NAME + ".etapes", null, getLocale()));
                    listeEtapes.setPageLength(5);
                    listeEtapes.setNullSelectionAllowed(false);
                    listeEtapes.setTextInputAllowed(false);
                    listeEtapes.setRequired(false);
                    listeEtapes.setWidth("400px");
                    listeEtapes.addItem(TOUTES_LES_ETAPES_LABEL);
                    listeEtapes.setItemCaption(TOUTES_LES_ETAPES_LABEL, TOUTES_LES_ETAPES_LABEL);
                    for (VersionEtape etape : letapes) {
                        String idEtape = etape.getId().getCod_etp() + "/" + etape.getId().getCod_vrs_vet();
                        listeEtapes.addItem(idEtape);
                        listeEtapes.setItemCaption(idEtape, "[" + idEtape + "] " + etape.getLib_web_vet());
                    }

                    if (MainUI.getCurrent().getEtapeInscrits() != null) {
                        listeEtapes.setValue(MainUI.getCurrent().getEtapeInscrits());
                    } else {

                        listeEtapes.setValue(TOUTES_LES_ETAPES_LABEL);
                    }

                    //Gestion de l'vnement sur le changement d'tape
                    listeEtapes.addValueChangeListener(new ValueChangeListener() {
                        @Override
                        public void valueChange(ValueChangeEvent event) {
                            String vetSelectionnee = (String) event.getProperty().getValue();
                            if (vetSelectionnee.equals(TOUTES_LES_ETAPES_LABEL)) {
                                vetSelectionnee = null;
                            }
                            MainUI.getCurrent().setEtapeInscrits(vetSelectionnee);

                            //faire le changement
                            String groupeSelectionne = ((listeGroupes != null
                                    && listeGroupes.getValue() != null) ? (String) listeGroupes.getValue()
                                            : null);
                            if (groupeSelectionne != null && groupeSelectionne.equals(TOUS_LES_GROUPES_LABEL)) {
                                groupeSelectionne = null;
                            }
                            filtrerInscrits(vetSelectionnee, groupeSelectionne);

                        }
                    });
                    formInscritLayout.addComponent(listeEtapes);

                }

                List<ElpDeCollection> lgroupes = MainUI.getCurrent().getListeGroupesInscrits();
                if (lgroupes != null && lgroupes.size() > 0) {
                    listeGroupes = new ComboBox();
                    listeGroupes.setPageLength(5);
                    listeGroupes.setNullSelectionAllowed(false);
                    listeGroupes.setTextInputAllowed(false);
                    listeGroupes.setRequired(false);
                    listeGroupes.setStyleName(ValoTheme.COMBOBOX_BORDERLESS);
                    listeGroupes.setWidth("348px");
                    listeGroupes.addItem(TOUS_LES_GROUPES_LABEL);
                    listeGroupes.setItemCaption(TOUS_LES_GROUPES_LABEL, TOUS_LES_GROUPES_LABEL);
                    for (ElpDeCollection edc : lgroupes) {
                        for (CollectionDeGroupes cdg : edc.getListeCollection()) {
                            for (Groupe groupe : cdg.getListeGroupes()) {
                                listeGroupes.addItem(groupe.getCleGroupe());
                                listeGroupes.setItemCaption(groupe.getCleGroupe(), groupe.getLibGroupe());

                            }
                        }
                    }
                    if (MainUI.getCurrent().getGroupeInscrits() != null) {
                        listeGroupes.setValue(MainUI.getCurrent().getGroupeInscrits());
                    } else {
                        listeGroupes.setValue(TOUS_LES_GROUPES_LABEL);
                    }

                    //Gestion de l'vnement sur le changement de groupe
                    listeGroupes.addValueChangeListener(new ValueChangeListener() {
                        @Override
                        public void valueChange(ValueChangeEvent event) {
                            String grpSelectionnee = (String) event.getProperty().getValue();
                            if (grpSelectionnee.equals(TOUS_LES_GROUPES_LABEL)) {
                                grpSelectionnee = null;
                            }
                            MainUI.getCurrent().setGroupeInscrits(grpSelectionnee);

                            //faire le changement
                            String etapeSelectionnee = ((listeEtapes != null && listeEtapes.getValue() != null)
                                    ? (String) listeEtapes.getValue()
                                    : null);
                            if (etapeSelectionnee != null
                                    && etapeSelectionnee.equals(TOUTES_LES_ETAPES_LABEL)) {
                                etapeSelectionnee = null;
                            }
                            filtrerInscrits(etapeSelectionnee, grpSelectionnee);

                        }
                    });

                    HorizontalLayout gpLayout = new HorizontalLayout();
                    gpLayout.setCaption(applicationContext.getMessage(NAME + ".groupes", null, getLocale()));
                    gpLayout.setMargin(false);
                    gpLayout.setSpacing(false);
                    gpLayout.addComponent(listeGroupes);
                    Button btnDetailGpe = new Button();
                    btnDetailGpe.setWidth("52px");
                    btnDetailGpe.setHeight("32px");
                    btnDetailGpe.setStyleName(ValoTheme.BUTTON_PRIMARY);
                    btnDetailGpe.setIcon(FontAwesome.SEARCH);
                    btnDetailGpe.setDescription(
                            applicationContext.getMessage(NAME + ".detail.groupes", null, getLocale()));
                    btnDetailGpe.addClickListener(e -> {
                        String vet = null;
                        if (listeEtapes != null && listeEtapes.getValue() != null
                                && !listeEtapes.getValue().equals(TOUTES_LES_ETAPES_LABEL)) {
                            vet = listeEtapes.getItemCaption(listeEtapes.getValue());
                        }
                        DetailGroupesWindow dgw = new DetailGroupesWindow(lgroupes,
                                panelFormInscrits.getCaption(), vet, (String) listeAnnees.getValue());
                        UI.getCurrent().addWindow(dgw);
                    });
                    gpLayout.addComponent(btnDetailGpe);

                    formInscritLayout.addComponent(gpLayout);

                }
            }
            panelLayout.addComponent(formInscritLayout);
            panelLayout.setComponentAlignment(formInscritLayout, Alignment.MIDDLE_LEFT);

            //Cration du favori pour l'objet concern pas la liste des inscrits
            List<Favoris> lfav = favorisController.getFavoris();
            FavorisPK favpk = new FavorisPK();
            favpk.setLogin(userController.getCurrentUserName());
            favpk.setIdfav(code);
            favpk.setTypfav(typeFavori);
            Favoris favori = new Favoris();
            favori.setId(favpk);
            //Cration du bouton pour ajouter l'objet aux favoris
            favoriLayout = new VerticalLayout();
            favoriLayout.setSizeFull();
            favoriLayout.setMargin(true);
            favoriLayout.setSpacing(true);
            btnAjoutFavori = new Button(
                    applicationContext.getMessage(NAME + ".btn.ajoutFavori", null, getLocale()));
            btnAjoutFavori.setIcon(FontAwesome.STAR_O);
            btnAjoutFavori.addStyleName(ValoTheme.BUTTON_PRIMARY);
            btnAjoutFavori.setDescription(
                    applicationContext.getMessage(NAME + ".btn.ajoutFavori", null, getLocale()));
            btnAjoutFavori.addClickListener(e -> {

                //creation du favori en base sur le clic du bouton
                favorisController.saveFavori(favori);

                //On cache le bouton de mise en favori
                btnAjoutFavori.setVisible(false);

                //Affichage d'un message de confirmation
                Notification.show(
                        applicationContext.getMessage(NAME + ".message.favoriAjoute", null, getLocale()),
                        Type.TRAY_NOTIFICATION);
            });

            //Ajout du bouton  l'interface
            favoriLayout.addComponent(btnAjoutFavori);
            favoriLayout.setComponentAlignment(btnAjoutFavori, Alignment.TOP_RIGHT);
            if (typeIsElp()) {
                btnMasquerFiltre = new Button(
                        applicationContext.getMessage(NAME + ".btn.btnMasquerFiltre", null, getLocale()));
                btnMasquerFiltre.setIcon(FontAwesome.CHEVRON_CIRCLE_UP);
                btnMasquerFiltre.addStyleName(ValoTheme.BUTTON_FRIENDLY);
                btnMasquerFiltre.setDescription(
                        applicationContext.getMessage(NAME + ".btn.btnMasquerFiltre", null, getLocale()));
                btnMasquerFiltre.addClickListener(e -> {
                    panelFormInscrits.setContent(null);
                    if (btnDisplayFiltres != null) {
                        btnDisplayFiltres.setVisible(true);
                    }
                });
                favoriLayout.addComponent(btnMasquerFiltre);
                favoriLayout.setComponentAlignment(btnMasquerFiltre, Alignment.BOTTOM_RIGHT);
            }
            panelLayout.addComponent(favoriLayout);
            panelLayout.setComponentAlignment(favoriLayout, Alignment.TOP_RIGHT);

            //Si l'objet est dj en favori
            if (lfav != null && lfav.contains(favori)) {

                //On affiche pas le bouton de mise en favori
                btnAjoutFavori.setVisible(false);
            }

            panelFormInscrits.setContent(panelLayout);
            addComponent(panelFormInscrits);

            //Rcupration de la liste des inscrits
            linscrits = MainUI.getCurrent().getListeInscrits();

            refreshListeCodind(new BeanItemContainer<>(Inscrit.class, linscrits));

            //Test si la liste contient des tudiants
            if (linscrits != null && linscrits.size() > 0 && listecodind != null && listecodind.size() > 0) {
                infoLayout = new VerticalLayout();
                infoLayout.setSizeFull();

                //Layout avec le nb d'inscrit, le bouton trombinoscope et le bouton d'export
                HorizontalLayout resumeLayout = new HorizontalLayout();
                resumeLayout.setWidth("100%");
                resumeLayout.setHeight("50px");

                //Label affichant le nb d'inscrits
                infoNbInscrit = new Label(
                        applicationContext.getMessage(NAME + ".message.nbinscrit", null, getLocale()) + " : "
                                + linscrits.size());

                leftResumeLayout = new HorizontalLayout();
                leftResumeLayout.addComponent(infoNbInscrit);
                leftResumeLayout.setComponentAlignment(infoNbInscrit, Alignment.MIDDLE_LEFT);

                Button infoDescriptionButton = new Button();
                infoDescriptionButton.setStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
                infoDescriptionButton.setIcon(FontAwesome.INFO_CIRCLE);
                infoDescriptionButton.setDescription(applicationContext
                        .getMessage(NAME + ".message.info.predescription", null, getLocale()));
                infoDescriptionButton.addClickListener(e -> {
                    String message = "";
                    if (typeIsVet()) {
                        message = applicationContext.getMessage(NAME + ".message.info.vetdescription", null,
                                getLocale());
                    }
                    if (typeIsElp()) {
                        message = applicationContext.getMessage(NAME + ".message.info.elpdescription", null,
                                getLocale());
                    }

                    HelpBasicWindow hbw = new HelpBasicWindow(message,
                            applicationContext.getMessage("helpWindow.defaultTitle", null, getLocale()));
                    UI.getCurrent().addWindow(hbw);
                });
                leftResumeLayout.addComponent(infoDescriptionButton);
                leftResumeLayout.setComponentAlignment(infoDescriptionButton, Alignment.MIDDLE_LEFT);

                //Bouton export trombinoscope
                btnExportTrombi = new Button();
                btnExportTrombi.setIcon(FontAwesome.FILE_PDF_O);
                btnExportTrombi.setStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
                btnExportTrombi.addStyleName("button-icon");
                btnExportTrombi.addStyleName("red-button-icon");
                btnExportTrombi.setDescription(
                        applicationContext.getMessage(NAME + ".pdf.trombinoscope.link", null, getLocale()));

                //methode qui permet de generer l'export  la demande
                //Cration du nom du fichier
                String nomFichier = applicationContext.getMessage("pdf.trombinoscope.title", null,
                        Locale.getDefault()) + "_" + panelFormInscrits.getCaption() + ".pdf";
                nomFichier = nomFichier.replaceAll(" ", "_");
                StreamResource resource = new StreamResource(new StreamResource.StreamSource() {
                    @Override
                    public InputStream getStream() {

                        //recuperation de l'anne slectionne et du libell de l'ELP
                        String annee = (String) listeAnnees.getValue();
                        String libObj = panelFormInscrits.getCaption();

                        //cration du trombi en pdf
                        return listeInscritsController.getPdfStream(linscrits, listecodind, libObj, annee);
                    }
                }, nomFichier);
                resource.setMIMEType("application/force-download;charset=UTF-8");
                resource.setCacheTime(0);

                //On ajoute le FD sur le bouton d'export
                if (PropertyUtils.isPushEnabled()) {
                    new MyFileDownloader(resource).extend(btnExportTrombi);
                } else {
                    FileDownloader fdpdf = new FileDownloader(resource);
                    fdpdf.setOverrideContentType(false);
                    fdpdf.extend(btnExportTrombi);
                }

                leftResumeLayout.addComponent(btnExportTrombi);
                leftResumeLayout.setComponentAlignment(btnExportTrombi, Alignment.MIDDLE_LEFT);
                //if(!afficherTrombinoscope){

                //On cache le bouton d'export pdf
                btnExportTrombi.setVisible(false);
                //}

                //Bouton export liste excel
                btnExportExcel = new Button();
                btnExportExcel.setIcon(FontAwesome.FILE_EXCEL_O);
                btnExportExcel.setStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
                btnExportExcel.addStyleName("button-icon");
                btnExportExcel
                        .setDescription(applicationContext.getMessage(NAME + ".excel.link", null, getLocale()));
                String nomFichierXls = applicationContext.getMessage("excel.listeinscrits.title", null,
                        Locale.getDefault()) + "_" + panelFormInscrits.getCaption() + ".xls";
                nomFichierXls = nomFichierXls.replaceAll(" ", "_");

                StreamResource resourceXls = new StreamResource(new StreamResource.StreamSource() {

                    @Override
                    public InputStream getStream() {

                        //recuperation de l'anne slectionne et du libell de l'ELP
                        String annee = (String) listeAnnees.getValue();
                        String libObj = panelFormInscrits.getCaption();

                        //cration du trombi en pdf
                        return listeInscritsController.getXlsStream(linscrits, listecodind, listeGroupes,
                                libObj, annee, typeFavori);
                    }
                }, nomFichierXls);
                resourceXls.setMIMEType("application/force-download;charset=UTF-8");
                resourceXls.setCacheTime(0);
                //On ajoute le FD sur le bouton d'export
                if (PropertyUtils.isPushEnabled()) {
                    new MyFileDownloader(resourceXls).extend(btnExportExcel);
                } else {
                    FileDownloader fd = new FileDownloader(resourceXls);
                    fd.setOverrideContentType(false);
                    fd.extend(btnExportExcel);
                }

                //if(!afficherTrombinoscope){
                //On change le bouton d'export pdf par le bouton export excel
                leftResumeLayout.replaceComponent(btnExportTrombi, btnExportExcel);
                //}

                resumeLayout.addComponent(leftResumeLayout);

                //Middle layout avec les bouton de collapse des colonnes
                middleResumeLayout = new HorizontalLayout();
                middleResumeLayout.setSizeFull();
                middleResumeLayout.addStyleName("small-font-element");
                middleResumeLayout.setSpacing(true);

                if (!typeIsVet()) {
                    collapseEtp = new CheckBox(
                            applicationContext.getMessage(NAME + ".collapseEtp.title", null, getLocale()));
                    collapseEtp.setValue(true);
                    collapseEtp.addValueChangeListener(e -> {
                        inscritstable.setColumnCollapsed("etape", !collapseEtp.getValue());
                    });
                    collapseEtp.setDescription(applicationContext.getMessage(NAME + ".collapseEtp.description",
                            null, getLocale()));
                    middleResumeLayout.addComponent(collapseEtp);
                    middleResumeLayout.setComponentAlignment(collapseEtp, Alignment.MIDDLE_CENTER);
                }
                collapseResultatsS1 = new CheckBox(
                        applicationContext.getMessage(NAME + ".collapseResultatsS1.title", null, getLocale()));
                collapseResultatsS1.setValue(false);
                collapseResultatsS1.addValueChangeListener(e -> {
                    inscritstable.setColumnCollapsed("notes1", !collapseResultatsS1.getValue());
                });
                collapseResultatsS1.setDescription(applicationContext
                        .getMessage(NAME + ".collapseResultatsS1.description", null, getLocale()));
                middleResumeLayout.addComponent(collapseResultatsS1);
                middleResumeLayout.setComponentAlignment(collapseResultatsS1, Alignment.MIDDLE_CENTER);

                collapseResultatsS2 = new CheckBox(
                        applicationContext.getMessage(NAME + ".collapseResultatsS2.title", null, getLocale()));
                collapseResultatsS2.setValue(false);
                collapseResultatsS2.addValueChangeListener(e -> {
                    inscritstable.setColumnCollapsed("notes2", !collapseResultatsS2.getValue());
                });
                collapseResultatsS2.setDescription(applicationContext
                        .getMessage(NAME + ".collapseResultatsS2.description", null, getLocale()));
                middleResumeLayout.addComponent(collapseResultatsS2);
                middleResumeLayout.setComponentAlignment(collapseResultatsS2, Alignment.MIDDLE_CENTER);

                resumeLayout.addComponent(middleResumeLayout);

                HorizontalLayout buttonResumeLayout = new HorizontalLayout();
                buttonResumeLayout.setSizeFull();
                buttonResumeLayout.setSpacing(true);
                //Bouton pour afficher les filtres
                btnDisplayFiltres = new Button();
                btnDisplayFiltres.setWidth("52px");
                btnDisplayFiltres.setHeight("32px");
                btnDisplayFiltres.setStyleName(ValoTheme.BUTTON_FRIENDLY);
                btnDisplayFiltres.setIcon(FontAwesome.FILTER);
                btnDisplayFiltres.setDescription(
                        applicationContext.getMessage(NAME + ".btn.displayFilters", null, getLocale()));
                btnDisplayFiltres.addClickListener(e -> {
                    panelFormInscrits.setContent(panelLayout);
                    btnDisplayFiltres.setVisible(false);
                });
                buttonResumeLayout.addComponent(btnDisplayFiltres);
                buttonResumeLayout.setComponentAlignment(btnDisplayFiltres, Alignment.MIDDLE_RIGHT);
                buttonResumeLayout.setExpandRatio(btnDisplayFiltres, 1);
                btnDisplayFiltres.setVisible(false);

                //Bouton trombinoscope
                btnTrombi = new Button(
                        applicationContext.getMessage(NAME + ".message.trombinoscope", null, getLocale()));
                if (listeInscritsController.isPhotoProviderOperationnel()) {
                    btnTrombi.setIcon(FontAwesome.GROUP);
                    buttonResumeLayout.addComponent(btnTrombi);

                    //Gestion du clic sur le bouton trombinoscope
                    btnTrombi.addClickListener(e -> {

                        //Si on doit afficher une fentre de loading pendant l'excution
                        if (PropertyUtils.isPushEnabled() && PropertyUtils.isShowLoadingIndicator()) {
                            //affichage de la pop-up de loading
                            MainUI.getCurrent().startBusyIndicator();

                            //Execution de la mthode en parallle dans un thread
                            executorService.execute(new Runnable() {
                                public void run() {
                                    MainUI.getCurrent().access(new Runnable() {
                                        @Override
                                        public void run() {
                                            executeDisplayTrombinoscope();
                                            //close de la pop-up de loading
                                            MainUI.getCurrent().stopBusyIndicator();
                                        }
                                    });
                                }
                            });

                        } else {
                            //On ne doit pas afficher de fentre de loading, on excute directement la mthode
                            executeDisplayTrombinoscope();
                        }

                    });
                    buttonResumeLayout.setComponentAlignment(btnTrombi, Alignment.MIDDLE_RIGHT);
                }

                //Bouton de retour  l'affichage de la liste
                btnRetourListe = new Button(
                        applicationContext.getMessage(NAME + ".message.retourliste", null, getLocale()));
                btnRetourListe.setIcon(FontAwesome.BARS);
                buttonResumeLayout.addComponent(btnRetourListe);
                //if(!afficherTrombinoscope){
                btnRetourListe.setVisible(false);
                //}

                //Gestion du clic sur le bouton de  retour  l'affichage de la liste
                btnRetourListe.addClickListener(e -> {
                    afficherTrombinoscope = false;
                    btnExportTrombi.setVisible(false);
                    leftResumeLayout.replaceComponent(btnExportTrombi, btnExportExcel);
                    btnTrombi.setVisible(true);
                    btnRetourListe.setVisible(false);
                    dataLayout.removeAllComponents();
                    dataLayout.addComponent(inscritstable);
                    middleResumeLayout.setVisible(true);

                });
                buttonResumeLayout.setComponentAlignment(btnRetourListe, Alignment.MIDDLE_RIGHT);

                resumeLayout.addComponent(buttonResumeLayout);

                infoLayout.addComponent(resumeLayout);

                //Layout qui contient la liste des inscrits et le trombinoscope
                dataLayout = new VerticalLayout();
                dataLayout.setSizeFull();

                //Table contenant la liste des inscrits
                inscritstable = new Table(null, new BeanItemContainer<>(Inscrit.class, linscrits));

                inscritstable.addStyleName("table-without-column-selector");
                inscritstable.setSizeFull();
                inscritstable.setVisibleColumns(new String[0]);

                String[] fields = INS_FIELDS_ELP;
                if (typeIsVet()) {
                    fields = INS_FIELDS_VET;
                }
                for (String fieldName : fields) {
                    inscritstable.setColumnHeader(fieldName,
                            applicationContext.getMessage(NAME + ".table." + fieldName, null, getLocale()));
                }

                inscritstable.addGeneratedColumn("cod_etu", new CodEtuColumnGenerator());
                inscritstable.setColumnHeader("cod_etu",
                        applicationContext.getMessage(NAME + ".table.cod_etu", null, getLocale()));
                inscritstable.addGeneratedColumn("email", new MailColumnGenerator());
                inscritstable.setColumnHeader("email",
                        applicationContext.getMessage(NAME + ".table.email", null, getLocale()));
                inscritstable.addGeneratedColumn("notes1", new Session1ColumnGenerator());
                inscritstable.setColumnHeader("notes1",
                        applicationContext.getMessage(NAME + ".table.notes1", null, getLocale()));
                inscritstable.addGeneratedColumn("notes2", new Session2ColumnGenerator());
                inscritstable.setColumnHeader("notes2",
                        applicationContext.getMessage(NAME + ".table.notes2", null, getLocale()));

                //Si on est sur un ELP
                if (typeIsElp()) {
                    //on affiche l'tape de rattachement
                    inscritstable.addGeneratedColumn("etape", new EtapeColumnGenerator());
                    inscritstable.setColumnHeader("etape",
                            applicationContext.getMessage(NAME + ".table.etape", null, getLocale()));
                }

                String[] fields_to_display = INS_FIELDS_TO_DISPLAY_ELP;
                if (typeIsVet()) {
                    fields_to_display = INS_FIELDS_TO_DISPLAY_VET;
                }

                inscritstable.setVisibleColumns((Object[]) fields_to_display);

                inscritstable.setColumnCollapsingAllowed(true);
                inscritstable.setColumnReorderingAllowed(false);

                //On masque les colonnes de notes par dfaut
                inscritstable.setColumnCollapsed("notes1", true);
                inscritstable.setColumnCollapsed("notes2", true);

                inscritstable.setSelectable(false);
                inscritstable.setImmediate(true);
                inscritstable.addStyleName("scrollabletable");
                //Si on n'a pas dj demand  afficher le trombinoscope
                //if(!afficherTrombinoscope){
                //la layout contient la table
                dataLayout.addComponent(inscritstable);
                //}

                //Layout contenant le gridLayout correspondant au trombinoscope
                verticalLayoutForTrombi = new VerticalLayout();
                verticalLayoutForTrombi.setSizeFull();
                verticalLayoutForTrombi.addStyleName("v-scrollablepanel");

                //Cration du trombinoscope
                displayTrombinoscope();

                verticalLayoutForTrombi.addComponent(trombiLayout);
                verticalLayoutForTrombi.setSizeFull();
                verticalLayoutForTrombi.setHeight(null);

                //Si on a demand  afficher le trombinoscope
                /*if(afficherTrombinoscope){
                   //Le layout contient le trombi  afficher
                   dataLayout.addComponent(verticalLayoutForTrombi);
                }*/
                infoLayout.addComponent(dataLayout);
                infoLayout.setExpandRatio(dataLayout, 1);
                addComponent(infoLayout);
                setExpandRatio(infoLayout, 1);

                //Si on a demand  afficher le trombinoscope
                if (afficherTrombinoscope) {
                    //On execute la procdure d'affichage du trombinoscope
                    executeDisplayTrombinoscope();
                }
            } else {
                Label infoAucuninscrit = new Label(
                        applicationContext.getMessage(NAME + ".message.aucuninscrit", null, getLocale()));
                addComponent(infoAucuninscrit);
                setComponentAlignment(infoAucuninscrit, Alignment.TOP_CENTER);
                setExpandRatio(infoAucuninscrit, 1);
            }

        }
    }
}

From source file:fr.univlorraine.mondossierweb.views.RechercheRapideView.java

License:Apache License

/**
 * Initialise la vue//  www  . jav a2s .  c  o m
 */
@PostConstruct
public void init() {

    //On vrifie le droit d'accder  la vue
    if (userController.isEnseignant()) {

        /* Style */
        setMargin(true);
        setSpacing(true);

        mainVerticalLayout = new VerticalLayout();
        champRechercheLayout = new HorizontalLayout();
        mainVerticalLayout.setImmediate(true);
        mainVerticalLayout.setSizeFull();

        //BOUTON DE RECHERCHE
        btnRecherche = new Button(
                applicationContext.getMessage("buttonChercher.label", null, Locale.getDefault()));
        btnRecherche.setIcon(FontAwesome.SEARCH);
        btnRecherche.setEnabled(true);
        btnRecherche.addClickListener(e -> search(false));

        //Init connexion  ES, pour gain perf au premiere lettre tapes
        if (ElasticSearchService.initConnexion(true)) {

            //CHAMP DE RECHERCHE
            champRecherche = new AutoComplete();
            champRecherche.setWidth(700, Unit.PIXELS); //540
            champRecherche.setEnabled(true);
            champRecherche.setImmediate(true);
            champRecherche.focus();
            champRecherche.setTextChangeEventMode(TextChangeEventMode.EAGER);
            champRecherche.addTextChangeListener(new TextChangeListener() {
                @Override
                public void textChange(TextChangeEvent event) {
                    if (event.getText() != null) {
                        resetButton.setIcon(FontAwesome.TIMES);
                    }
                    champRecherche.showChoices(quickSearch(event.getText()), mainVerticalLayout, btnRecherche,
                            false);

                }
            });
            champRecherche.setImmediate(true);
            champRecherche.addShortcutListener(
                    new ShortcutListener("Enter Shortcut", ShortcutAction.KeyCode.ENTER, null) {
                        @Override
                        public void handleAction(Object sender, Object target) {
                            if (target == champRecherche) {
                                //Si on tait sur une ligne propose sous le champ de recherche
                                if (champRecherche.getSelectedItem() > 0) {
                                    //On remplie d'abord le champ avec la ligne slectionne
                                    champRecherche.setValue(champRecherche.getChoices()
                                            .getItem(champRecherche.getSelectedItem()).getItemProperty("lib")
                                            .getValue().toString());
                                }
                                search(false);
                            }
                        }
                    });

            champRecherche.addShortcutListener(
                    new ShortcutListener("Bottom Arrow", ShortcutAction.KeyCode.ARROW_DOWN, null) {
                        @Override
                        public void handleAction(Object sender, Object target) {
                            if (target == champRecherche) {
                                if (champRecherche != null && champRecherche.getChoices() != null
                                        && champRecherche.getChoices().getItemIds() != null) {
                                    champRecherche.getChoicesPopup().setVisible(true);
                                    champRecherche.getChoices().setValue(champRecherche.getNextItem());

                                }
                            }
                        }
                    });

            champRecherche.addShortcutListener(
                    new ShortcutListener("Top Arrow", ShortcutAction.KeyCode.ARROW_UP, null) {
                        @Override
                        public void handleAction(Object sender, Object target) {
                            if (target == champRecherche) {
                                if (champRecherche.getChoices().getItemIds() != null) {
                                    champRecherche.getChoicesPopup().setVisible(true);
                                    Integer champSelectionne = champRecherche.getPreviousItem();
                                    if (champSelectionne > 0) {
                                        champRecherche.getChoices().setValue(champSelectionne);
                                    } else {
                                        champRecherche.getChoices().setValue(null);
                                    }

                                }
                            }
                        }
                    });

            //champRecherche.addBlurListener(e -> champRecherche.getChoicesPopup().setVisible(false));

            HorizontalLayout layoutBordure = new HorizontalLayout();
            layoutBordure.setWidth("100px");
            champRechercheLayout.addComponent(layoutBordure);
            champRechercheLayout.setComponentAlignment(layoutBordure, Alignment.MIDDLE_LEFT);

            /*champRechercheLayout.addComponent(search1);
            champRechercheLayout.setComponentAlignment(search1, Alignment.MIDDLE_LEFT);*/

            champRechercheLayout.addComponent(champRecherche);
            champRechercheLayout.setComponentAlignment(champRecherche, Alignment.MIDDLE_LEFT);

            //BOUTON RESET
            champRecherche.addStyleName("textfield-resetable");
            resetButton = new Button();
            resetButton.setIcon(FontAwesome.TIMES);
            resetButton.setStyleName(ValoTheme.BUTTON_BORDERLESS);
            resetButton.addStyleName("btn-reset");
            resetButton.addClickListener(e -> {
                champRecherche.setValue("");
                //search1.setValue("");
                resetButton.setIcon(FontAwesome.TIMES);
                champRecherche.focus();
            });
            champRechercheLayout.addComponent(resetButton);
            champRechercheLayout.setComponentAlignment(resetButton, Alignment.MIDDLE_LEFT);

            //Ajout du bouton de recherche au layout
            champRechercheLayout.addComponent(btnRecherche);
            mainVerticalLayout.addComponent(champRechercheLayout);
            mainVerticalLayout.setComponentAlignment(champRechercheLayout, Alignment.MIDDLE_LEFT);
            champRechercheLayout.setMargin(true);

            casesAcocherComposantes = new CheckBox("Composantes");
            casesAcocherComposantes.setValue(true);
            casesAcocherComposantes.setStyleName(ValoTheme.CHECKBOX_SMALL);
            casesAcocherComposantes.addValueChangeListener(e -> tuneSearch());
            casesAcocherVet = new CheckBox("Etapes");
            casesAcocherVet.setValue(true);
            casesAcocherVet.setStyleName(ValoTheme.CHECKBOX_SMALL);
            casesAcocherVet.addValueChangeListener(e -> tuneSearch());
            casesAcocherElp = new CheckBox("Elments pdagogiques");
            casesAcocherElp.setValue(true);
            casesAcocherElp.setStyleName(ValoTheme.CHECKBOX_SMALL);
            casesAcocherElp.addValueChangeListener(e -> tuneSearch());
            casesAcocherEtudiant = new CheckBox("Etudiants");
            casesAcocherEtudiant.setValue(true);
            casesAcocherEtudiant.setStyleName(ValoTheme.CHECKBOX_SMALL);
            casesAcocherEtudiant.addValueChangeListener(e -> tuneSearch());

            HorizontalLayout checkBoxLayout = new HorizontalLayout();
            checkBoxLayout.setMargin(true);
            checkBoxLayout.setSpacing(true);
            checkBoxLayout.addComponent(casesAcocherComposantes);
            checkBoxLayout.addComponent(casesAcocherVet);
            checkBoxLayout.addComponent(casesAcocherElp);
            checkBoxLayout.addComponent(casesAcocherEtudiant);

            mainVerticalLayout.addComponent(checkBoxLayout);

            //TABLE DE RESULTATS
            rrContainer = new HierarchicalContainer();
            rrContainer.addContainerProperty("lib", String.class, "");
            rrContainer.addContainerProperty("code", String.class, "");
            rrContainer.addContainerProperty("info", String.class, "");
            rrContainer.addContainerProperty("type", String.class, "");
            tableResultats = new TreeTable();
            tableResultats.setSizeFull();
            tableResultats.setSelectable(false);
            tableResultats.setMultiSelect(false);
            tableResultats.setImmediate(true);
            columnHeaders = new String[FIELDS_ORDER.length];
            for (int fieldIndex = 0; fieldIndex < FIELDS_ORDER.length; fieldIndex++) {
                columnHeaders[fieldIndex] = applicationContext
                        .getMessage("result.table." + FIELDS_ORDER[fieldIndex], null, Locale.getDefault());
            }
            tableResultats.addGeneratedColumn("lib", new DisplayNameColumnGenerator());
            tableResultats.addGeneratedColumn("type", new DisplayTypeColumnGenerator());
            tableResultats.setContainerDataSource(rrContainer);
            tableResultats.setVisibleColumns(FIELDS_ORDER);
            tableResultats.setColumnHeaders(columnHeaders);
            /*mainVerticalLayout.addComponent(searchBoxFilter);
            mainVerticalLayout.setComponentAlignment(searchBoxFilter, Alignment.MIDDLE_RIGHT);*/
            VerticalLayout tableVerticalLayout = new VerticalLayout();
            tableVerticalLayout.setMargin(new MarginInfo(false, true, true, true));
            tableVerticalLayout.setSizeFull();
            tableVerticalLayout.addComponent(tableResultats);
            mainVerticalLayout.addComponent(tableVerticalLayout);
            mainVerticalLayout.setExpandRatio(tableVerticalLayout, 1);
            tableResultats.setVisible(false);

            addComponent(mainVerticalLayout);
            setSizeFull();
        } else {

            //Message fonctionnalit indisponible
            addComponent(
                    new Label(applicationContext.getMessage(NAME + ".indisponible.message", null, getLocale()),
                            ContentMode.HTML));
        }
    }
}

From source file:info.magnolia.ui.admincentral.shellapp.pulse.item.detail.PulseItemCategoryNavigator.java

License:Open Source License

private void initCheckbox(PulseItemCategory... categories) {
    final String caption = i18n.translate("pulse.items.groupby");
    groupByCheckBox = new CheckBox(StringUtils.abbreviate(caption, 15));
    groupByCheckBox.addStyleName("navigator-grouping");
    groupByCheckBox.setImmediate(true);/* ww  w  .  ja v a  2s  .c  om*/
    groupByCheckBox.setVisible(false);
    // tooltip
    groupByCheckBox.setDescription(caption);

    if (showGroupBy) {
        addComponent(groupByCheckBox);
        for (final PulseItemCategory category : categories) {
            if (category == PulseItemCategory.ALL_MESSAGES) {
                enableGroupBy(true);
            }
        }
    }
}

From source file:io.subutai.plugin.accumulo.ui.manager.Manager.java

public Manager(final ExecutorService executorService, final Accumulo accumulo, Hadoop hadoop,
        final Zookeeper zookeeper, Tracker tracker, EnvironmentManager environmentManager)
        throws NamingException {

    this.executorService = executorService;
    this.accumulo = accumulo;
    this.hadoop = hadoop;
    this.zookeeper = zookeeper;
    this.tracker = tracker;
    this.environmentManager = environmentManager;

    contentRoot = new GridLayout();
    contentRoot.setSpacing(true);/*from  w  w  w  .  j  a v a  2s  . c o m*/
    contentRoot.setMargin(true);
    contentRoot.setSizeFull();
    contentRoot.setRows(10);
    contentRoot.setColumns(1);

    //tables go here
    mastersTable = createTableTemplate("Masters");
    mastersTable.setId("MastersTable");
    tracersTable = createTableTemplate("Tracers");
    tracersTable.setId("TracersTable");
    slavesTable = createTableTemplate("Tablet Servers");
    slavesTable.setId("Slavestable");

    HorizontalLayout controlsContent = new HorizontalLayout();
    controlsContent.setSpacing(true);
    controlsContent.setHeight(100, Sizeable.Unit.PERCENTAGE);

    Label clusterNameLabel = new Label("Select the cluster");
    controlsContent.addComponent(clusterNameLabel);
    controlsContent.setComponentAlignment(clusterNameLabel, Alignment.MIDDLE_CENTER);

    ComboBox clustersCombo = getClusterCombo();
    controlsContent.addComponent(clustersCombo);
    controlsContent.setComponentAlignment(clustersCombo, Alignment.MIDDLE_CENTER);

    refreshClustersBtn = getRefreshClustersButton();
    controlsContent.addComponent(refreshClustersBtn);
    controlsContent.setComponentAlignment(refreshClustersBtn, Alignment.MIDDLE_CENTER);

    checkAllBtn = getCheckAllButton();
    controlsContent.addComponent(checkAllBtn);
    controlsContent.setComponentAlignment(checkAllBtn, Alignment.MIDDLE_CENTER);

    startClusterBtn = getStartAllButton();
    controlsContent.addComponent(startClusterBtn);
    controlsContent.setComponentAlignment(startClusterBtn, Alignment.MIDDLE_CENTER);

    stopClusterBtn = getStopAllButton();
    controlsContent.addComponent(stopClusterBtn);
    controlsContent.setComponentAlignment(stopClusterBtn, Alignment.MIDDLE_CENTER);

    destroyClusterBtn = getDestroyClusterButton();
    controlsContent.addComponent(destroyClusterBtn);
    controlsContent.setComponentAlignment(destroyClusterBtn, Alignment.MIDDLE_CENTER);

    addTracerBtn = getAddTracerNodeButton();
    controlsContent.addComponent(addTracerBtn);
    controlsContent.setComponentAlignment(addTracerBtn, Alignment.MIDDLE_CENTER);

    addTabletServerButton = getAddSlaveButton();
    controlsContent.addComponent(addTabletServerButton);
    controlsContent.setComponentAlignment(addTabletServerButton, Alignment.MIDDLE_CENTER);

    //auto scale button
    autoScaleBtn = new CheckBox(AUTO_SCALE_BUTTON_CAPTION);
    autoScaleBtn.setValue(false);
    autoScaleBtn.addStyleName("default");
    controlsContent.addComponent(autoScaleBtn);
    controlsContent.setComponentAlignment(autoScaleBtn, Alignment.MIDDLE_CENTER);
    autoScaleBtn.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(final Property.ValueChangeEvent event) {
            if (accumuloClusterConfig == null) {
                show("Select cluster");
            } else {
                boolean value = (Boolean) event.getProperty().getValue();
                accumuloClusterConfig.setAutoScaling(value);
                try {
                    accumulo.saveConfig(accumuloClusterConfig);
                } catch (ClusterException e) {
                    show(e.getMessage());
                }
            }
        }
    });

    addStyleName(refreshClustersBtn, checkAllBtn, startClusterBtn, stopClusterBtn, destroyClusterBtn,
            addTracerBtn, addTabletServerButton);

    PROGRESS_ICON.setVisible(false);
    PROGRESS_ICON.setId("indicator");
    controlsContent.addComponent(PROGRESS_ICON);
    controlsContent.setComponentAlignment(PROGRESS_ICON, Alignment.MIDDLE_CENTER);

    contentRoot.addComponent(controlsContent, 0, 0);
    contentRoot.addComponent(mastersTable, 0, 1, 0, 3);
    contentRoot.addComponent(tracersTable, 0, 4, 0, 6);
    contentRoot.addComponent(slavesTable, 0, 7, 0, 9);
}

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

License:Open Source License

/**
 * creates the tab for creating new packages
 * @return vaadin component//from   www . j a v  a2 s  .  c o m
 * @throws SQLException:
 */
static Component createPackageManagerTab() throws SQLException {

    Database db = qOfferManager.getDb();

    VerticalLayout packManVerticalLayout = new VerticalLayout();
    packManVerticalLayout.setMargin(true);
    packManVerticalLayout.setSpacing(true);
    packManVerticalLayout.setSizeFull();

    HorizontalLayout packManHorizontalLayout = new HorizontalLayout();
    packManHorizontalLayout.setSpacing(true);

    Button addPackageButton = new Button("New Package");
    addPackageButton.setIcon(FontAwesome.PLUS);
    addPackageButton.setDescription("Click here to add a new package but don't forget to update the details.");

    ComboBox updatePackageGroupComboBox = new ComboBox("Select package group");
    updatePackageGroupComboBox.addItems("Sequencing", "Project Management", "Bioinformatics Analysis",
            "Mass spectrometry", "Other");
    updatePackageGroupComboBox.setDescription(
            "Select a package group for the currently selected package and hit the " + "update button.");

    Button updateSelectedPackageButton = new Button("Update");
    updateSelectedPackageButton.setIcon(FontAwesome.SPINNER);
    updateSelectedPackageButton.setDescription("Click here to update the currently selected package.");

    Button deleteSelectedPackageButton = new Button("Delete");
    deleteSelectedPackageButton.setIcon(FontAwesome.TRASH_O);
    deleteSelectedPackageButton.setDescription("Click here to delete the currently selected package.");

    Button exportTableButton = new Button("Export as .csv");
    exportTableButton.setIcon(FontAwesome.DOWNLOAD);
    exportTableButton.setDescription("Click here to export the table as .csv file.");

    CheckBox calculatePricesAutomaticallyCheckBox = new CheckBox("Auto-calculate external prices");
    calculatePricesAutomaticallyCheckBox
            .setDescription("Click here to enable/disable the automatic calculation of the "
                    + "external prices based on the internal prices.");
    calculatePricesAutomaticallyCheckBox.setValue(true);

    TableQuery tq = new TableQuery("packages", DBManager.getDatabaseInstanceAlternative());
    tq.setVersionColumn("OPTLOCK");

    SQLContainer container = new SQLContainer(tq);
    container.setAutoCommit(true);

    GeneratedPropertyContainer gpcontainer = new GeneratedPropertyContainer(container);

    // create the column holding the offer_ids where the package is being used in
    // TODO: offer_ids currently not in use; since it's extremely slow..
    /*
        gpcontainer.addGeneratedProperty("offer_ids",
            new PropertyValueGenerator<String>() {
              @Override
              public String getValue(Item item, Object itemId,
                         Object propertyId) {
            
    int package_id = (Integer) item.getItemProperty("package_id").getValue();
            
    // query offers_packages for all offer_ids of the current package
    ArrayList<String> offerIds = db.getOfferIdsForPackage(package_id);
            
    return String.join(",", offerIds);
              }
            
              @Override
              public Class<String> getType() {
    return String.class;
              }
            });
    */

    RefreshableGrid packageGrid = new RefreshableGrid(gpcontainer);

    // add the filters to the grid
    GridCellFilter filter = new GridCellFilter(packageGrid);
    filter.setTextFilter("package_id", true, true);
    filter.setTextFilter("package_name", true, false);
    filter.setTextFilter("package_facility", true, false);
    filter.setTextFilter("package_description", true, false);
    filter.setTextFilter("package_group", true, false);
    filter.setTextFilter("package_unit_type", true, false);
    filter.setComboBoxFilter("package_group", Arrays.asList("Bioinformatics Analysis", "Mass spectrometry",
            "Project Management", "Sequencing", "Other"));

    packageGrid.getColumn("package_id").setHeaderCaption("Id").setWidth(100);
    packageGrid.getColumn("package_name").setHeaderCaption("Name");
    packageGrid.getColumn("package_facility").setHeaderCaption("Facility");
    packageGrid.getColumn("package_description").setHeaderCaption("Description").setWidth(300);
    packageGrid.getColumn("package_group").setHeaderCaption("Package Group").setEditable(false);
    packageGrid.getColumn("package_price_internal").setHeaderCaption("Internal Price ()");
    packageGrid.getColumn("package_price_external_academic").setHeaderCaption("Ext. Academical Price ()");
    packageGrid.getColumn("package_price_external_commercial").setHeaderCaption("Ext. Commercial Price ()");
    // TODO: offer_ids currently not in use; since it's extremely slow..
    //packageGrid.getColumn("offer_ids").setHeaderCaption("Offer Id's");
    packageGrid.getColumn("package_unit_type").setHeaderCaption("Unit Type");

    /*
    // TODO: offer_ids currently not in use; since it's extremely slow..
    packageGrid.setColumnOrder("package_id", "package_name", "package_description", "package_group", "package_facility",
        "package_price_internal", "package_price_external_academic", "package_price_external_commercial",
        "package_unit_type", "offer_ids");*/

    packageGrid.setColumnOrder("package_id", "package_name", "package_description", "package_group",
            "package_facility", "package_price_internal", "package_price_external_academic",
            "package_price_external_commercial", "package_unit_type");

    packageGrid.removeColumn("added_by");
    packageGrid.removeColumn("package_grp");
    packageGrid.removeColumn("package_date");
    packageGrid.removeColumn("last_edited");

    packageGrid.sort("package_name", SortDirection.ASCENDING);
    packageGrid.setWidth("100%");
    packageGrid.setSelectionMode(Grid.SelectionMode.SINGLE);
    packageGrid.setEditorEnabled(true);

    addAutomaticPriceCalculation(calculatePricesAutomaticallyCheckBox, container, packageGrid);

    // add tooltips to the cells
    packageGrid.setCellDescriptionGenerator((Grid.CellDescriptionGenerator) cell -> {
        if (cell.getValue() == null)
            return null;
        return cell.getValue().toString();
    });

    // add tooltips to the header row
    for (Grid.Column column : packageGrid.getColumns()) {
        Grid.HeaderCell cell = packageGrid.getDefaultHeaderRow().getCell(column.getPropertyId());
        String htmlWithTooltip = String.format("<span title=\"%s\">%s</span>", cell.getText(), cell.getText());
        cell.setHtml(htmlWithTooltip);
    }

    addListeners(db, addPackageButton, updatePackageGroupComboBox, updateSelectedPackageButton,
            deleteSelectedPackageButton, container, packageGrid, exportTableButton);

    packManHorizontalLayout.addComponent(addPackageButton);
    packManHorizontalLayout.addComponent(updatePackageGroupComboBox);
    packManHorizontalLayout.addComponent(updateSelectedPackageButton);
    packManHorizontalLayout.addComponent(deleteSelectedPackageButton);
    packManHorizontalLayout.addComponent(exportTableButton);
    packManHorizontalLayout.addComponent(calculatePricesAutomaticallyCheckBox);

    packManHorizontalLayout.setComponentAlignment(addPackageButton, Alignment.BOTTOM_CENTER);
    packManHorizontalLayout.setComponentAlignment(updatePackageGroupComboBox, Alignment.MIDDLE_CENTER);
    packManHorizontalLayout.setComponentAlignment(updateSelectedPackageButton, Alignment.BOTTOM_CENTER);
    packManHorizontalLayout.setComponentAlignment(deleteSelectedPackageButton, Alignment.BOTTOM_CENTER);
    packManHorizontalLayout.setComponentAlignment(calculatePricesAutomaticallyCheckBox,
            Alignment.MIDDLE_CENTER);
    packManHorizontalLayout.setComponentAlignment(exportTableButton, Alignment.BOTTOM_CENTER);

    packManVerticalLayout.addComponent(packageGrid);
    packManVerticalLayout.addComponent(packManHorizontalLayout);

    return packManVerticalLayout;
}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.execution.ExecutionWizardStep.java

License:Apache License

@Override
public Component getContent() {
    Panel form = new Panel(TRANSLATOR.translate("step.detail"));
    if (getExecutionStep().getExecutionStart() == null) {
        //Set the start date.
        getExecutionStep().setExecutionStart(new Date());
    }//from w w w  . j av a2s .  com
    FormLayout layout = new FormLayout();
    form.setContent(layout);
    form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT);
    BeanFieldGroup binder = new BeanFieldGroup(getExecutionStep().getStep().getClass());
    binder.setItemDataSource(getExecutionStep().getStep());
    TextArea text = new TextArea(TRANSLATOR.translate("general.text"));
    text.setConverter(new ByteToStringConverter());
    binder.bind(text, "text");
    text.setSizeFull();
    layout.addComponent(text);
    Field notes = binder.buildAndBind(TRANSLATOR.translate("general.notes"), "notes", TextArea.class);
    notes.setSizeFull();
    layout.addComponent(notes);
    if (getExecutionStep().getExecutionStart() != null) {
        start = new DateField(TRANSLATOR.translate("start.date"));
        start.setResolution(Resolution.SECOND);
        start.setDateFormat(VMSettingServer.getSetting("date.format").getStringVal());
        start.setValue(getExecutionStep().getExecutionStart());
        start.setReadOnly(true);
        layout.addComponent(start);
    }
    if (getExecutionStep().getExecutionEnd() != null) {
        end = new DateField(TRANSLATOR.translate("end.date"));
        end.setDateFormat(VMSettingServer.getSetting("date.format").getStringVal());
        end.setResolution(Resolution.SECOND);
        end.setValue(getExecutionStep().getExecutionEnd());
        end.setReadOnly(true);
        layout.addComponent(end);
    }
    binder.setReadOnly(true);
    //Space to record result
    if (getExecutionStep().getResultId() != null) {
        result.setValue(getExecutionStep().getResultId().getResultName());
    }
    layout.addComponent(result);
    if (reviewer) {//Space to record review
        if (getExecutionStep().getReviewResultId() != null) {
            review.setValue(getExecutionStep().getReviewResultId().getReviewName());
        }
        layout.addComponent(review);
    }
    //Add Reviewer name
    if (getExecutionStep().getReviewer() != null) {
        TextField reviewerField = new TextField(TRANSLATOR.translate("general.reviewer"));
        reviewerField.setValue(getExecutionStep().getReviewer().getFirstName() + " "
                + getExecutionStep().getReviewer().getLastName());
        reviewerField.setReadOnly(true);
        layout.addComponent(reviewerField);
    }
    if (getExecutionStep().getReviewDate() != null) {
        reviewDate = new DateField(TRANSLATOR.translate("review.date"));
        reviewDate.setDateFormat(VMSettingServer.getSetting("date.format").getStringVal());
        reviewDate.setResolution(Resolution.SECOND);
        reviewDate.setValue(getExecutionStep().getReviewDate());
        reviewDate.setReadOnly(true);
        layout.addComponent(reviewDate);
    }
    if (VMSettingServer.getSetting("show.expected.result").getBoolVal()) {
        TextArea expectedResult = new TextArea(TRANSLATOR.translate("expected.result"));
        expectedResult.setConverter(new ByteToStringConverter());
        binder.bind(expectedResult, "expectedResult");
        expectedResult.setSizeFull();
        layout.addComponent(expectedResult);
    }
    //Add the fields
    fields.clear();
    getExecutionStep().getStep().getDataEntryList().forEach(de -> {
        switch (de.getDataEntryType().getId()) {
        case 1://String
            TextField tf = new TextField(TRANSLATOR.translate(de.getEntryName()));
            tf.setRequired(true);
            tf.setData(de.getEntryName());
            if (VMSettingServer.getSetting("show.expected.result").getBoolVal()) {
                //Add expected result
                DataEntryProperty stringCase = DataEntryServer.getProperty(de, "property.match.case");
                DataEntryProperty r = DataEntryServer.getProperty(de, "property.expected.result");
                if (r != null && !r.getPropertyValue().equals("null")) {
                    String error = TRANSLATOR.translate("expected.result") + ": " + r.getPropertyValue();
                    tf.setRequiredError(error);
                    tf.setRequired(DataEntryServer.getProperty(de, "property.required").getPropertyValue()
                            .equals("true"));
                    tf.addValidator((Object val) -> {
                        //We have an expected result and a match case requirement
                        if (stringCase != null && stringCase.getPropertyValue().equals("true")
                                ? !((String) val).equals(r.getPropertyValue())
                                : !((String) val).equalsIgnoreCase(r.getPropertyValue())) {
                            throw new InvalidValueException(error);
                        }
                    });
                }
            }
            fields.add(tf);
            //Set value if already recorded
            updateValue(tf);
            layout.addComponent(tf);
            break;
        case 2://Numeric
            NumberField field = new NumberField(TRANSLATOR.translate(de.getEntryName()));
            field.setSigned(true);
            field.setUseGrouping(true);
            field.setGroupingSeparator(',');
            field.setDecimalSeparator('.');
            field.setConverter(new StringToDoubleConverter());
            field.setRequired(
                    DataEntryServer.getProperty(de, "property.required").getPropertyValue().equals("true"));
            field.setData(de.getEntryName());
            Double min = null, max = null;
            for (DataEntryProperty prop : de.getDataEntryPropertyList()) {
                String value = prop.getPropertyValue();
                if (prop.getPropertyName().equals("property.max")) {
                    try {
                        max = Double.parseDouble(value);
                    } catch (NumberFormatException ex) {
                        //Leave as null
                    }
                } else if (prop.getPropertyName().equals("property.min")) {
                    try {
                        min = Double.parseDouble(value);
                    } catch (NumberFormatException ex) {
                        //Leave as null
                    }
                }
            }
            //Add expected result
            if (VMSettingServer.getSetting("show.expected.result").getBoolVal()
                    && (min != null || max != null)) {
                String error = TRANSLATOR.translate("error.out.of.range") + " "
                        + (min == null ? " " : (TRANSLATOR.translate("property.min") + ": " + min)) + " "
                        + (max == null ? "" : (TRANSLATOR.translate("property.max") + ": " + max));
                field.setRequiredError(error);
                field.addValidator(new DoubleRangeValidator(error, min, max));
            }
            fields.add(field);
            //Set value if already recorded
            updateValue(field);
            layout.addComponent(field);
            break;
        case 3://Boolean
            CheckBox cb = new CheckBox(TRANSLATOR.translate(de.getEntryName()));
            cb.setData(de.getEntryName());
            cb.setRequired(
                    DataEntryServer.getProperty(de, "property.required").getPropertyValue().equals("true"));
            if (VMSettingServer.getSetting("show.expected.result").getBoolVal()) {
                DataEntryProperty r = DataEntryServer.getProperty(de, "property.expected.result");
                if (r != null) {
                    //Add expected result
                    String error = TRANSLATOR.translate("expected.result") + ": " + r.getPropertyValue();
                    cb.addValidator((Object val) -> {
                        if (!val.toString().equals(r.getPropertyValue())) {
                            throw new InvalidValueException(error);
                        }
                    });
                }
            }
            fields.add(cb);
            //Set value if already recorded
            updateValue(cb);
            layout.addComponent(cb);
            break;
        case 4://Attachment
            Label l = new Label(TRANSLATOR.translate(de.getEntryName()));
            layout.addComponent(l);
            break;
        default:
            LOG.log(Level.SEVERE, "Unexpected field type: {0}", de.getDataEntryType().getId());
        }
    });
    //Add the Attachments
    HorizontalLayout attachments = new HorizontalLayout();
    attachments.setCaption(TRANSLATOR.translate("general.attachment"));
    HorizontalLayout comments = new HorizontalLayout();
    comments.setCaption(TRANSLATOR.translate("general.comments"));
    HorizontalLayout issues = new HorizontalLayout();
    issues.setCaption(TRANSLATOR.translate("general.issue"));
    int commentCounter = 0;
    int issueCounter = 0;
    for (ExecutionStepHasIssue ei : getExecutionStep().getExecutionStepHasIssueList()) {
        issueCounter++;
        Button a = new Button("Issue #" + issueCounter);
        a.setIcon(VaadinIcons.BUG);
        a.addClickListener((Button.ClickEvent event) -> {
            displayIssue(new IssueServer(ei.getIssue()));
        });
        a.setEnabled(!step.getLocked());
        issues.addComponent(a);
    }
    for (ExecutionStepHasAttachment attachment : getExecutionStep().getExecutionStepHasAttachmentList()) {
        switch (attachment.getAttachment().getAttachmentType().getType()) {
        case "comment": {
            //Comments go in a different section
            commentCounter++;
            Button a = new Button("Comment #" + commentCounter);
            a.setIcon(VaadinIcons.CLIPBOARD_TEXT);
            a.addClickListener((Button.ClickEvent event) -> {
                if (!step.getLocked()) {
                    //Prompt if user wants this removed
                    MessageBox mb = getDeletionPrompt(attachment);
                    mb.open();
                } else {
                    displayComment(new AttachmentServer(attachment.getAttachment().getAttachmentPK()));
                }
            });
            a.setEnabled(!step.getLocked());
            comments.addComponent(a);
            break;
        }
        default: {
            Button a = new Button(attachment.getAttachment().getFileName());
            a.setEnabled(!step.getLocked());
            a.setIcon(VaadinIcons.PAPERCLIP);
            a.addClickListener((Button.ClickEvent event) -> {
                if (!step.getLocked()) {
                    //Prompt if user wants this removed
                    MessageBox mb = getDeletionPrompt(attachment);
                    mb.open();
                } else {
                    displayAttachment(new AttachmentServer(attachment.getAttachment().getAttachmentPK()));
                }
            });
            attachments.addComponent(a);
            break;
        }
        }
    }
    if (attachments.getComponentCount() > 0) {
        layout.addComponent(attachments);
    }
    if (comments.getComponentCount() > 0) {
        layout.addComponent(comments);
    }
    if (issues.getComponentCount() > 0) {
        layout.addComponent(issues);
    }
    //Add the menu
    HorizontalLayout hl = new HorizontalLayout();
    attach = new Button(TRANSLATOR.translate("add.attachment"));
    attach.setIcon(VaadinIcons.PAPERCLIP);
    attach.addClickListener((Button.ClickEvent event) -> {
        //Show dialog to upload file.
        Window dialog = new VMWindow(TRANSLATOR.translate("attach.file"));
        VerticalLayout vl = new VerticalLayout();
        MultiFileUpload multiFileUpload = new MultiFileUpload() {
            @Override
            protected void handleFile(File file, String fileName, String mimeType, long length) {
                try {
                    LOG.log(Level.FINE, "Received file {1} at: {0}",
                            new Object[] { file.getAbsolutePath(), fileName });
                    //Process the file
                    //Create the attachment
                    AttachmentServer a = new AttachmentServer();
                    a.addFile(file, fileName);
                    //Overwrite the default file name set in addFile. It'll be a temporary file name
                    a.setFileName(fileName);
                    a.write2DB();
                    //Now add it to this Execution Step
                    if (getExecutionStep().getExecutionStepHasAttachmentList() == null) {
                        getExecutionStep().setExecutionStepHasAttachmentList(new ArrayList<>());
                    }
                    getExecutionStep().addAttachment(a);
                    getExecutionStep().write2DB();
                    w.updateCurrentStep();
                } catch (Exception ex) {
                    LOG.log(Level.SEVERE, "Error creating attachment!", ex);
                }
            }
        };
        multiFileUpload.setCaption(TRANSLATOR.translate("select.files.attach"));
        vl.addComponent(multiFileUpload);
        dialog.setContent(vl);
        dialog.setHeight(25, Sizeable.Unit.PERCENTAGE);
        dialog.setWidth(25, Sizeable.Unit.PERCENTAGE);
        ValidationManagerUI.getInstance().addWindow(dialog);
    });
    hl.addComponent(attach);
    bug = new Button(TRANSLATOR.translate("create.issue"));
    bug.setIcon(VaadinIcons.BUG);
    bug.addClickListener((Button.ClickEvent event) -> {
        displayIssue(new IssueServer());
    });
    hl.addComponent(bug);
    comment = new Button(TRANSLATOR.translate("add.comment"));
    comment.setIcon(VaadinIcons.CLIPBOARD_TEXT);
    comment.addClickListener((Button.ClickEvent event) -> {
        AttachmentServer as = new AttachmentServer();
        //Get comment type
        AttachmentType type = AttachmentTypeServer.getTypeForExtension("comment");
        as.setAttachmentType(type);
        displayComment(as);
    });
    hl.addComponent(comment);
    step.update();
    attach.setEnabled(!step.getLocked());
    bug.setEnabled(!step.getLocked());
    comment.setEnabled(!step.getLocked());
    result.setEnabled(!step.getLocked());
    layout.addComponent(hl);
    return layout;
}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.ValidationManagerUI.java

License:Apache License

private void createRequirementSpecNodeMenu(ContextMenu menu) {
    MenuItem create = menu.addItem(TRANSLATOR.translate("create.requiremnet"), VaadinIcons.PLUS,
            (MenuItem selectedItem) -> {
                Requirement r = new Requirement();
                r.setRequirementSpecNode((RequirementSpecNode) tree.getValue());
                displayRequirement(r, true);
            });//  w  w  w  .  j  av  a2  s.co  m
    create.setEnabled(checkRight("requirement.modify"));
    MenuItem edit = menu.addItem(TRANSLATOR.translate("edit.req.spec.node"), EDIT_ICON,
            (MenuItem selectedItem) -> {
                displayRequirementSpecNode((RequirementSpecNode) tree.getValue(), true);
            });
    edit.setEnabled(checkRight("requirement.modify"));
    MenuItem importRequirement = menu.addItem(TRANSLATOR.translate("import.requirement"), IMPORT_ICON,
            (MenuItem selectedItem) -> {// Create a sub-window and set the content
                Window subWindow = new VMWindow(TRANSLATOR.translate("import.requirement"));
                VerticalLayout subContent = new VerticalLayout();
                subWindow.setContent(subContent);

                //Add a checkbox to know if file has headers or not
                CheckBox cb = new CheckBox(TRANSLATOR.translate("file.has.header"));

                FileUploader receiver = new FileUploader();
                Upload upload = new Upload(TRANSLATOR.translate("upload.excel"), receiver);
                upload.addSucceededListener((Upload.SucceededEvent event1) -> {
                    try {
                        subWindow.close();
                        //TODO: Display the excel file (partially), map columns and import
                        //Process the file
                        RequirementImporter importer = new RequirementImporter(receiver.getFile(),
                                (RequirementSpecNode) tree.getValue());

                        importer.importFile(cb.getValue());
                        importer.processImport();
                        buildProjectTree(tree.getValue());
                        updateScreen();
                    } catch (RequirementImportException ex) {
                        LOG.log(Level.SEVERE, TRANSLATOR.translate("import.error"), ex);
                        Notification.show(TRANSLATOR.translate("import.unsuccessful"),
                                Notification.Type.ERROR_MESSAGE);
                    } catch (VMException ex) {
                        LOG.log(Level.SEVERE, null, ex);
                    }
                });
                upload.addFailedListener((Upload.FailedEvent event1) -> {
                    LOG.log(Level.SEVERE, "Upload unsuccessful!\n{0}", event1.getReason());
                    Notification.show(TRANSLATOR.translate("upload.unsuccessful"),
                            Notification.Type.ERROR_MESSAGE);
                    subWindow.close();
                });
                subContent.addComponent(cb);
                subContent.addComponent(upload);
                // Open it in the UI
                addWindow(subWindow);
            });
    importRequirement.setEnabled(checkRight("requirement.modify"));
}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.ValidationManagerUI.java

License:Apache License

private void createTestCaseMenu(ContextMenu menu) {
    MenuItem create = menu.addItem(TRANSLATOR.translate("create.step"), VaadinIcons.PLUS,
            (MenuItem selectedItem) -> {
                TestCase tc = (TestCase) tree.getValue();
                Step s = new Step();
                s.setStepSequence(tc.getStepList().size() + 1);
                s.setTestCase(tc);/*from w ww .  j  a  v  a2s .  c  om*/
                displayStep(s, true);
            });
    create.setEnabled(checkRight("requirement.modify"));
    MenuItem edit = menu.addItem(TRANSLATOR.translate("edit.test.case"), EDIT_ICON, (MenuItem selectedItem) -> {
        displayTestCase((TestCase) tree.getValue(), true);
    });
    edit.setEnabled(checkRight("testcase.modify"));
    MenuItem importSteps = menu.addItem(TRANSLATOR.translate("import.step"), IMPORT_ICON,
            (MenuItem selectedItem) -> { // Create a sub-window and set the content
                Window subWindow = new VMWindow(TRANSLATOR.translate("import.test.case.step"));
                VerticalLayout subContent = new VerticalLayout();
                subWindow.setContent(subContent);

                //Add a checkbox to know if file has headers or not
                CheckBox cb = new CheckBox(TRANSLATOR.translate("file.has.header"));

                FileUploader receiver = new FileUploader();
                Upload upload = new Upload(TRANSLATOR.translate("upload.excel"), receiver);
                upload.addSucceededListener((Upload.SucceededEvent event1) -> {
                    try {
                        subWindow.close();
                        //TODO: Display the excel file (partially), map columns and import
                        //Process the file
                        TestCase tc = (TestCase) tree.getValue();
                        StepImporter importer = new StepImporter(receiver.getFile(), tc);
                        importer.importFile(cb.getValue());
                        importer.processImport();
                        SortedMap<Integer, Step> map = new TreeMap<>();
                        tc.getStepList().forEach((s) -> {
                            map.put(s.getStepSequence(), s);
                        });
                        //Now update the sequence numbers
                        int count = 0;
                        for (Entry<Integer, Step> entry : map.entrySet()) {
                            entry.getValue().setStepSequence(++count);
                            try {
                                new StepJpaController(DataBaseManager.getEntityManagerFactory())
                                        .edit(entry.getValue());
                            } catch (Exception ex) {
                                LOG.log(Level.SEVERE, null, ex);
                            }
                        }
                        buildProjectTree(new TestCaseServer(tc.getTestCasePK()).getEntity());
                        updateScreen();
                    } catch (TestCaseImportException ex) {
                        LOG.log(Level.SEVERE, TRANSLATOR.translate("import.error"), ex);
                        Notification.show(TRANSLATOR.translate("import.unsuccessful"),
                                Notification.Type.ERROR_MESSAGE);
                    }
                });
                upload.addFailedListener((Upload.FailedEvent event1) -> {
                    LOG.log(Level.SEVERE, "Upload unsuccessful!\n{0}", event1.getReason());
                    Notification.show(TRANSLATOR.translate("upload.unsuccessful"),
                            Notification.Type.ERROR_MESSAGE);
                    subWindow.close();
                });
                subContent.addComponent(cb);
                subContent.addComponent(upload);
                // Open it in the UI
                addWindow(subWindow);
            });
    importSteps.setEnabled(checkRight("requirement.modify"));
    MenuItem export = menu.addItem(TRANSLATOR.translate("general.export"), VaadinIcons.DOWNLOAD,
            (MenuItem selectedItem) -> {
                TestCase tc = (TestCase) tree.getValue();
                UI.getCurrent().addWindow(TestCaseExporter.getTestCaseExporter(Arrays.asList(tc)));
            });
    export.setEnabled(checkRight("testcase.view"));
    addExecutionDashboard(menu);
}