Example usage for com.vaadin.ui Button setId

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

Introduction

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

Prototype

@Override
    public void setId(String id) 

Source Link

Usage

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

private void populateTabletServersTable(final Table table, Set<EnvironmentContainerHost> containerHosts,
        final boolean masters) {
    table.removeAllItems();//  w w  w.  j av  a 2s  .  c om
    for (final EnvironmentContainerHost containerHost : containerHosts) {
        final Button checkBtn = new Button(CHECK_BUTTON_CAPTION);
        checkBtn.setId(containerHost.getIpByInterfaceName("eth0") + "-accumuloCheck");
        final Button destroyBtn = new Button(DESTROY_BUTTON_CAPTION);
        destroyBtn.setId(containerHost.getIpByInterfaceName("eth0") + "-accumuloDestroy");
        final Label resultHolder = new Label();
        resultHolder.setId(containerHost.getIpByInterfaceName("eth0") + "accumuloResult");

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

        addGivenComponents(availableOperations, checkBtn, destroyBtn);
        addStyleName(checkBtn, destroyBtn, availableOperations);

        table.addItem(new Object[] { containerHost.getHostname(), containerHost.getIpByInterfaceName("eth0"),
                filterNodeRole(NodeType.ACCUMULO_TABLET_SERVER.name()), resultHolder, availableOperations },
                null);

        checkBtn.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                PROGRESS_ICON.setVisible(true);
                disableButtons(checkBtn, destroyBtn);
                executorService.execute(new CheckTask(accumulo, tracker, accumuloClusterConfig.getClusterName(),
                        containerHost.getHostname(), new CompleteEvent() {
                            public void onComplete(String result) {
                                synchronized (PROGRESS_ICON) {
                                    resultHolder.setValue(parseStatus(result, NodeType.ACCUMULO_TABLET_SERVER));
                                    enableButtons(checkBtn, destroyBtn);
                                    PROGRESS_ICON.setVisible(false);
                                }
                            }
                        }));
            }
        });

        destroyBtn.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                if (accumuloClusterConfig.getSlaves().size() == 1) {
                    show("This is last tablet server in cluster, please destroy whole cluster");
                    return;
                }

                ConfirmationDialog alert = new ConfirmationDialog(
                        String.format("Do you want to destroy the %s node?", containerHost.getHostname()),
                        "Yes", "No");
                alert.getOk().addClickListener(new Button.ClickListener() {
                    @Override
                    public void buttonClick(Button.ClickEvent clickEvent) {
                        UUID trackID = accumulo.destroyNode(accumuloClusterConfig.getClusterName(),
                                containerHost.getHostname(), NodeType.ACCUMULO_TABLET_SERVER);

                        ProgressWindow window = new ProgressWindow(executorService, tracker, trackID,
                                AccumuloClusterConfig.PRODUCT_KEY);
                        window.getWindow().addCloseListener(new Window.CloseListener() {
                            @Override
                            public void windowClose(Window.CloseEvent closeEvent) {
                                refreshClustersInfo();
                            }
                        });
                        contentRoot.getUI().addWindow(window.getWindow());
                    }
                });
                contentRoot.getUI().addWindow(alert.getAlert());
            }
        });
    }
}

From source file:io.subutai.plugin.accumulo.ui.wizard.ConfigurationStep.java

public ConfigurationStep(final Accumulo accumulo, final Hadoop hadoop, final Zookeeper zookeeper,
        final EnvironmentManager environmentManager, final Wizard wizard) {

    this.environmentManager = environmentManager;
    this.wizard = wizard;
    this.hadoop = hadoop;
    this.zookeeper = zookeeper;
    this.accumulo = accumulo;

    if (wizard.getConfig().getSetupType() == SetupType.OVER_HADOOP_N_ZK) {
        //hadoop combo
        final ComboBox hadoopClustersCombo = getCombo("Hadoop cluster");
        hadoopClustersCombo.setId("hadoopClusterscb");

        //zookeeper combo
        final ComboBox zkClustersCombo = getCombo("Zookeeper cluster");
        zkClustersCombo.setId("zkClustersCombo");

        //master nodes
        final ComboBox masterNodeCombo = getCombo("Master node");
        masterNodeCombo.setId("masterNodeCombo");
        final ComboBox gcNodeCombo = getCombo("GC node");
        gcNodeCombo.setId("gcNodeCombo");
        final ComboBox monitorNodeCombo = getCombo("Monitor node");
        monitorNodeCombo.setId("monitorNodeCombo");

        //accumulo init controls
        TextField clusterNameTxtFld = getTextField("Cluster name", "Cluster name", 20);
        clusterNameTxtFld.setId("clusterNameTxtFld");
        TextField instanceNameTxtFld = getTextField("Instance name", "Instance name", 20);
        instanceNameTxtFld.setId("instanceNameTxtFld");
        TextField passwordTxtFld = getTextField("Password", "Password", 20);
        passwordTxtFld.setId("passwordTxtFld");

        //tracers
        final TwinColSelect tracersSelect = getTwinSelect("Tracers", "hostname", "Available Nodes",
                "Selected Nodes", 4);
        tracersSelect.setId("TracersSelect");
        //slave nodes
        final TwinColSelect slavesSelect = getTwinSelect("Slaves", "hostname", "Available Nodes",
                "Selected Nodes", 4);
        slavesSelect.setId("SlavesSelect");

        //get existing hadoop clusters
        List<HadoopClusterConfig> hadoopClusters = hadoop.getClusters();

        //fill hadoopClustersCombo with hadoop cluster infos
        for (HadoopClusterConfig hadoopClusterInfo : hadoopClusters) {
            hadoopClustersCombo.addItem(hadoopClusterInfo);
            hadoopClustersCombo.setItemCaption(hadoopClusterInfo, hadoopClusterInfo.getClusterName());
        }// www  .j  a  va2s .co  m

        //try to find hadoop cluster info based on one saved in the configuration
        if (wizard.getConfig().getHadoopClusterName() != null) {
            hadoop.getCluster(wizard.getConfig().getHadoopClusterName());
        }

        //select if saved found
        if (!hadoopClusters.isEmpty()) {
            //select first one if saved not found
            hadoopClustersCombo.setValue(hadoopClusters.iterator().next());
            fillZookeeperComboBox(zkClustersCombo, zookeeper,
                    hadoopClusters.iterator().next().getEnvironmentId());
        }

        // fill selection controls with hadoop nodes
        if (hadoopClustersCombo.getValue() != null) {
            HadoopClusterConfig hadoopInfo = (HadoopClusterConfig) hadoopClustersCombo.getValue();

            wizard.getConfig().setHadoopClusterName(hadoopInfo.getClusterName());

            setComboDS(masterNodeCombo, hadoopInfo.getAllNodes(), new HashSet<String>());
            setComboDS(gcNodeCombo, hadoopInfo.getAllNodes(), new HashSet<String>());
            setComboDS(monitorNodeCombo, hadoopInfo.getAllNodes(), new HashSet<String>());

            setTwinSelectDS(tracersSelect, getSlaveContainerHosts(Sets.newHashSet(hadoopInfo.getAllNodes())));
            setTwinSelectDS(slavesSelect, getSlaveContainerHosts(Sets.newHashSet(hadoopInfo.getAllNodes())));
        }

        //on hadoop cluster change reset all controls and config
        hadoopClustersCombo.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                if (event.getProperty().getValue() != null) {
                    HadoopClusterConfig hadoopInfo = (HadoopClusterConfig) event.getProperty().getValue();
                    //reset relevant controls
                    setComboDS(masterNodeCombo, hadoopInfo.getAllNodes(), new HashSet<String>());
                    setComboDS(gcNodeCombo, hadoopInfo.getAllNodes(), new HashSet<String>());
                    setComboDS(monitorNodeCombo, hadoopInfo.getAllNodes(), new HashSet<String>());

                    setTwinSelectDS(tracersSelect,
                            getSlaveContainerHosts(Sets.newHashSet(hadoopInfo.getAllNodes())));
                    setTwinSelectDS(slavesSelect,
                            getSlaveContainerHosts(Sets.newHashSet(hadoopInfo.getAllNodes())));
                    //reset relevant properties
                    wizard.getConfig().setMasterNode(null);
                    wizard.getConfig().setGcNode(null);
                    wizard.getConfig().setMonitor(null);
                    wizard.getConfig().setTracers(null);
                    wizard.getConfig().setSlaves(null);
                    wizard.getConfig().setHadoopClusterName(hadoopInfo.getClusterName());
                    fillZookeeperComboBox(zkClustersCombo, zookeeper, hadoopInfo.getEnvironmentId());
                }
            }
        });

        //restore master node if back button is pressed
        if (wizard.getConfig().getMasterNode() != null) {
            masterNodeCombo.setValue(wizard.getConfig().getMasterNode());
        }
        //restore gc node if back button is pressed
        if (wizard.getConfig().getGcNode() != null) {
            gcNodeCombo.setValue(wizard.getConfig().getGcNode());
        }
        //restore monitor node if back button is pressed
        if (wizard.getConfig().getMonitor() != null) {
            monitorNodeCombo.setValue(wizard.getConfig().getMonitor());
        }

        //add value change handler
        masterNodeCombo.addValueChangeListener(new Property.ValueChangeListener() {
            public void valueChange(Property.ValueChangeEvent event) {
                if (event.getProperty().getValue() != null) {
                    String masterNode = (String) event.getProperty().getValue();
                    wizard.getConfig().setMasterNode(masterNode);
                }
            }
        });
        //add value change handler
        gcNodeCombo.addValueChangeListener(new Property.ValueChangeListener() {

            public void valueChange(Property.ValueChangeEvent event) {
                if (event.getProperty().getValue() != null) {
                    String gcNode = (String) event.getProperty().getValue();
                    wizard.getConfig().setGcNode(gcNode);
                }
            }
        });
        //add value change handler
        monitorNodeCombo.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                if (event.getProperty().getValue() != null) {
                    String monitor = (String) event.getProperty().getValue();
                    wizard.getConfig().setMonitor(monitor);
                }
            }
        });

        //restore tracers if back button is pressed
        if (!CollectionUtil.isCollectionEmpty(wizard.getConfig().getTracers())) {
            tracersSelect.setValue(wizard.getConfig().getTracers());
        }
        //restore slaves if back button is pressed
        if (!CollectionUtil.isCollectionEmpty(wizard.getConfig().getSlaves())) {
            slavesSelect.setValue(wizard.getConfig().getSlaves());
        }

        clusterNameTxtFld.setValue(wizard.getConfig().getInstanceName());
        clusterNameTxtFld.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                wizard.getConfig().setClusterName(event.getProperty().getValue().toString().trim());
            }
        });

        instanceNameTxtFld.setValue(wizard.getConfig().getInstanceName());
        instanceNameTxtFld.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                wizard.getConfig().setInstanceName(event.getProperty().getValue().toString().trim());
            }
        });

        passwordTxtFld.setValue(wizard.getConfig().getPassword());
        passwordTxtFld.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                wizard.getConfig().setPassword(event.getProperty().getValue().toString().trim());
            }
        });

        //add value change handler
        tracersSelect.addValueChangeListener(new Property.ValueChangeListener() {

            public void valueChange(Property.ValueChangeEvent event) {
                if (event.getProperty().getValue() != null) {
                    Set<String> nodes = new HashSet<>();
                    Set<EnvironmentContainerHost> nodeList = (Set<EnvironmentContainerHost>) event.getProperty()
                            .getValue();
                    for (EnvironmentContainerHost host : nodeList) {
                        nodes.add(host.getId());
                    }
                    wizard.getConfig().setTracers(nodes);
                }
            }
        });
        //add value change handler
        slavesSelect.addValueChangeListener(new Property.ValueChangeListener() {
            public void valueChange(Property.ValueChangeEvent event) {
                if (event.getProperty().getValue() != null) {
                    Set<String> nodes = new HashSet<>();
                    Set<EnvironmentContainerHost> nodeList = (Set<EnvironmentContainerHost>) event.getProperty()
                            .getValue();
                    for (EnvironmentContainerHost host : nodeList) {
                        nodes.add(host.getId());
                    }
                    wizard.getConfig().setSlaves(nodes);
                }
            }
        });

        Button next = new Button("Next");
        next.setId("confNext2");
        next.addStyleName("default");
        //check valid configuration
        next.addClickListener(new Button.ClickListener() {

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

                if (Strings.isNullOrEmpty(wizard.getConfig().getClusterName())) {
                    show("Please, enter cluster name");
                } else if (Strings.isNullOrEmpty(wizard.getConfig().getZookeeperClusterName())) {
                    show("Please, select Zookeeper cluster");
                } else if (Strings.isNullOrEmpty(wizard.getConfig().getHadoopClusterName())) {
                    show("Please, select Hadoop cluster");
                } else if (wizard.getConfig().getMasterNode() == null) {
                    show("Please, select master node");
                } else if (Strings.isNullOrEmpty(wizard.getConfig().getInstanceName())) {
                    show("Please, specify instance name");
                } else if (Strings.isNullOrEmpty(wizard.getConfig().getPassword())) {
                    show("Please, specify password");
                } else if (wizard.getConfig().getGcNode() == null) {
                    show("Please, select gc node");
                } else if (wizard.getConfig().getMonitor() == null) {
                    show("Please, select monitor");
                } else if (CollectionUtil.isCollectionEmpty(wizard.getConfig().getTracers())) {
                    show("Please, select tracer(s)");
                } else if (CollectionUtil.isCollectionEmpty(wizard.getConfig().getSlaves())) {
                    show("Please, select slave(s)");
                } else {
                    wizard.next();
                }
            }
        });

        Button back = new Button("Back");
        back.setId("confBack2");
        back.addStyleName("default");
        back.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                wizard.back();
            }
        });

        setSizeFull();

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

        VerticalLayout layout = new VerticalLayout();
        layout.setSpacing(true);
        layout.addComponent(new Label("Please, specify installation settings"));
        layout.addComponent(content);

        HorizontalLayout masters = new HorizontalLayout();
        masters.setMargin(new MarginInfo(true, false, false, false));
        masters.setSpacing(true);
        masters.addComponent(hadoopClustersCombo);
        masters.addComponent(zkClustersCombo);
        masters.addComponent(masterNodeCombo);
        masters.addComponent(gcNodeCombo);
        masters.addComponent(monitorNodeCombo);

        HorizontalLayout credentials = new HorizontalLayout();
        credentials.setMargin(new MarginInfo(true, false, false, false));
        credentials.setSpacing(true);
        credentials.addComponent(clusterNameTxtFld);
        credentials.addComponent(instanceNameTxtFld);
        credentials.addComponent(passwordTxtFld);

        HorizontalLayout buttons = new HorizontalLayout();
        buttons.setMargin(new MarginInfo(true, false, false, false));
        buttons.setSpacing(true);
        buttons.addComponent(back);
        buttons.addComponent(next);

        content.addComponent(masters);
        content.addComponent(credentials);
        content.addComponent(tracersSelect);
        content.addComponent(slavesSelect);
        content.addComponent(buttons);

        setContent(layout);
    }
}

From source file:io.subutai.plugin.accumulo.ui.wizard.VerificationStep.java

public VerificationStep(final Accumulo accumulo, final Hadoop hadoop, final ExecutorService executorService,
        final Tracker tracker, EnvironmentManager environmentManager, final Wizard wizard) {

    setSizeFull();/*from   www .j  a v  a  2 s.  co m*/

    GridLayout grid = new GridLayout(1, 5);
    grid.setSpacing(true);
    grid.setMargin(true);
    grid.setSizeFull();

    Label confirmationLbl = new Label("<strong>Please verify the installation settings "
            + "(you may change them by clicking on Back button)</strong><br/>");
    confirmationLbl.setContentMode(ContentMode.HTML);

    ConfigView cfgView = new ConfigView("Installation configuration");
    cfgView.addStringCfg("Cluster Name", wizard.getConfig().getClusterName());
    cfgView.addStringCfg("Instance name", wizard.getConfig().getInstanceName());
    cfgView.addStringCfg("Password", wizard.getConfig().getPassword());
    cfgView.addStringCfg("Hadoop cluster", wizard.getConfig().getHadoopClusterName());
    cfgView.addStringCfg("Zookeeper cluster", wizard.getConfig().getZookeeperClusterName());

    if (wizard.getConfig().getSetupType() == SetupType.OVER_HADOOP_N_ZK) {
        try {
            Environment hadoopEnvironment = environmentManager.loadEnvironment(
                    hadoop.getCluster(wizard.getConfig().getHadoopClusterName()).getEnvironmentId());
            EnvironmentContainerHost master = hadoopEnvironment
                    .getContainerHostById(wizard.getConfig().getMasterNode());
            EnvironmentContainerHost gc = hadoopEnvironment
                    .getContainerHostById(wizard.getConfig().getGcNode());
            EnvironmentContainerHost monitor = hadoopEnvironment
                    .getContainerHostById(wizard.getConfig().getMonitor());
            Set<EnvironmentContainerHost> tracers = hadoopEnvironment
                    .getContainerHostsByIds(wizard.getConfig().getTracers());
            Set<EnvironmentContainerHost> slaves = hadoopEnvironment
                    .getContainerHostsByIds(wizard.getConfig().getSlaves());

            cfgView.addStringCfg("Master node", master.getHostname());
            cfgView.addStringCfg("GC node", gc.getHostname());
            cfgView.addStringCfg("Monitor node", monitor.getHostname());
            for (EnvironmentContainerHost containerHost : tracers) {
                cfgView.addStringCfg("Tracers", containerHost.getHostname());
            }
            for (EnvironmentContainerHost containerHost : slaves) {
                cfgView.addStringCfg("Slaves", containerHost.getHostname());
            }
        } catch (EnvironmentNotFoundException | ContainerHostNotFoundException e) {
            LOGGER.error("Error applying operations on environment/container", e);
        }
    } else {
        cfgView.addStringCfg("Number of Hadoop slaves",
                wizard.getHadoopClusterConfig().getCountOfSlaveNodes() + "");
        cfgView.addStringCfg("Hadoop replication factor",
                wizard.getHadoopClusterConfig().getReplicationFactor() + "");
        cfgView.addStringCfg("Hadoop domain name", wizard.getHadoopClusterConfig().getDomainName() + "");
        cfgView.addStringCfg("Number of tracers", wizard.getConfig().getNumberOfTracers() + "");
        cfgView.addStringCfg("Number of slaves", wizard.getConfig().getNumberOfSlaves() + "");
    }

    Button install = new Button("Install");
    install.setId("installBtn");
    install.addStyleName("default");
    install.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            UUID trackID;
            if (wizard.getConfig().getSetupType() == SetupType.OVER_HADOOP_N_ZK) {
                trackID = accumulo.installCluster(wizard.getConfig());
            } else {
                trackID = accumulo.installCluster(wizard.getConfig());
            }
            ProgressWindow window = new ProgressWindow(executorService, tracker, trackID,
                    AccumuloClusterConfig.PRODUCT_KEY);
            window.getWindow().addCloseListener(new Window.CloseListener() {
                @Override
                public void windowClose(Window.CloseEvent closeEvent) {
                    wizard.init();
                }
            });
            getUI().addWindow(window.getWindow());
        }
    });

    Button back = new Button("Back");
    back.setId("verBack");
    back.addStyleName("default");
    back.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            wizard.back();
        }
    });

    HorizontalLayout buttons = new HorizontalLayout();
    buttons.addComponent(back);
    buttons.addComponent(install);

    grid.addComponent(confirmationLbl, 0, 0);

    grid.addComponent(cfgView.getCfgTable(), 0, 1, 0, 3);

    grid.addComponent(buttons, 0, 4);

    setContent(grid);
}

From source file:io.subutai.plugin.accumulo.ui.wizard.WelcomeStep.java

public WelcomeStep(final Wizard wizard) {

    setSizeFull();//from www.j a  v a2s .c o m

    GridLayout grid = new GridLayout(10, 6);
    grid.setSpacing(true);
    grid.setMargin(true);
    grid.setSizeFull();

    Label welcomeMsg = new Label("<center><h2>Welcome to Accumulo Installation Wizard!</h2>");
    welcomeMsg.setContentMode(ContentMode.HTML);
    grid.addComponent(welcomeMsg, 3, 1, 6, 2);

    Label logoImg = new Label();
    // Image as a file resource
    logoImg.setIcon(new FileResource(FileUtil.getFile(AccumuloPortalModule.MODULE_IMAGE, this)));
    logoImg.setContentMode(ContentMode.HTML);
    logoImg.setHeight(56, Unit.PIXELS);
    logoImg.setWidth(220, Unit.PIXELS);
    grid.addComponent(logoImg, 1, 3, 2, 5);

    Button startOverHadoopNZK = new Button("Start over Hadoop & ZK installation");
    startOverHadoopNZK.setId("startOverHadoopNZK");
    startOverHadoopNZK.addStyleName("default");
    grid.addComponent(startOverHadoopNZK, 4, 4, 4, 4);
    grid.setComponentAlignment(startOverHadoopNZK, Alignment.BOTTOM_RIGHT);

    startOverHadoopNZK.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            wizard.init();
            wizard.getConfig().setSetupType(SetupType.OVER_HADOOP_N_ZK);
            wizard.next();
        }
    });

    setContent(grid);
}

From source file:org.azrul.langkuik.framework.customtype.attachment.AttachmentCustomTypeUICreator.java

@Override
public Component createUIForForm(final C currentBean, final Class<? extends CustomType> attachmentClass,
        final String pojoFieldName, final BeanView beanView, final DataAccessObject<C> conatainerClassDao,
        final DataAccessObject<? extends CustomType> customTypeDao,
        final RelationManagerFactory relationManagerFactory, final Configuration config,
        final ComponentState componentState, final Window window) {
    final FormLayout form = new FormLayout();

    final DataAccessObject<AttachmentCustomType> attachmentDao = ((DataAccessObject<AttachmentCustomType>) customTypeDao);
    final Collection<AttachmentCustomType> attachments = attachmentDao.find(currentBean, pojoFieldName, null,
            true, 0, Integer.parseInt(config.get("uploadCountLimit")));

    final WebEntityItemContainer attachmentIC = new WebEntityItemContainer(attachmentClass);
    if (!attachments.isEmpty()) {
        attachmentIC.addAll(attachments);
    }//w w  w . j  a v a  2  s  .  c  o m
    final ListSelect attachmentList = new ListSelect("", attachmentIC);
    createAtachmentList(attachmentList, attachments, config, beanView, form);

    final String relativePath = currentBean.getClass().getCanonicalName() + File.separator
            + conatainerClassDao.getIdentifierValue(currentBean);
    final String fullPath = config.get("attachmentRepository") + File.separator + relativePath;
    MyUploadHandler<C> uploadFinishHandler = new MyUploadHandler<>(currentBean,
            Integer.parseInt(config.get("uploadCountLimit").trim()), pojoFieldName, fullPath, relativePath,
            attachmentList, attachmentIC, customTypeDao, attachmentClass, relationManagerFactory);

    //File upload/download/delete buttons
    HorizontalLayout attachmentButtons = new HorizontalLayout();
    attachmentButtons.setSpacing(true);

    UploadStateWindow uploadStateWindow = new UploadStateWindow();
    MultiFileUpload fileUpload = new MultiFileUpload(uploadFinishHandler, uploadStateWindow);
    uploadFinishHandler.setFileUpload(fileUpload);

    fileUpload.getSmartUpload().setEnabled(true);
    fileUpload.getSmartUpload().setMaxFileSize(Integer.parseInt(config.get("uploadSizeLimit").trim()));
    fileUpload.getSmartUpload().setUploadButtonCaptions("Upload files", "Upload files");
    fileUpload.getSmartUpload().setId("Upload files");
    fileUpload.setId("Upload files2");

    Button deleteAttachmentBtn = new Button("Delete file", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            Collection<AttachmentCustomType> attachments = (Collection<AttachmentCustomType>) attachmentList
                    .getValue();
            if (!attachments.isEmpty()) {
                customTypeDao.unlinkAndDelete(attachments, currentBean, pojoFieldName,
                        relationManagerFactory.create(currentBean.getClass(), attachmentClass));
                Collection<AttachmentCustomType> a = attachmentDao.find(currentBean, pojoFieldName, null, true,
                        0, Integer.parseInt(config.get("uploadCountLimit")));
                attachmentIC.removeAllItems();
                attachmentIC.addAll(a);
                attachmentIC.refreshItems();
            }
        }
    });
    deleteAttachmentBtn.setId(deleteAttachmentBtn.getCaption());

    Button downloadAttachmentBtn = new Button("Download file", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {

            Collection<AttachmentCustomType> attachments = (Collection<AttachmentCustomType>) attachmentList
                    .getValue();
            if (!attachments.isEmpty()) {
                AttachmentCustomType attachment = attachments.iterator().next();
                final String fullPath = config.get("attachmentRepository") + File.separator
                        + attachment.getRelativeLocation() + File.separator + attachment.getFileName();
                FileResource res = new FileResource(new File(fullPath));
                beanView.setViewResource("DOWNLOAD", res);
                ResourceReference rr = ResourceReference.create(res, beanView, "DOWNLOAD");
                Page.getCurrent().open(rr.getURL(), null);
            }
        }
    });
    downloadAttachmentBtn.setId(downloadAttachmentBtn.getCaption());

    Button closeWindowBtn = new Button("Close", new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            window.close();
        }
    });
    closeWindowBtn.setId(closeWindowBtn.getCaption());

    if (componentState.equals(ComponentState.EDITABLE)) {
        attachmentButtons.addComponent(fileUpload);
        attachmentButtons.addComponent(deleteAttachmentBtn);
    }

    if (componentState.equals(ComponentState.EDITABLE) || componentState.equals(ComponentState.READ_ONLY)) {
        attachmentButtons.addComponent(downloadAttachmentBtn);
    }

    attachmentButtons.addComponent(closeWindowBtn);

    form.addComponent(attachmentButtons);
    form.setMargin(true);
    //beanView.addComponent(form);
    return form;
}

From source file:org.azrul.langkuik.framework.webgui.BeanView.java

@Override
public void enter(final ViewChangeListener.ViewChangeEvent vcevent) {
    setCurrentView(vcevent.getViewName());
    //reset form//from   w  w w.  jav  a  2 s  .c  o m
    this.removeAllComponents();

    //determine user details
    UserDetails userDetails = null;
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        userDetails = (UserDetails) auth.getPrincipal();
    } else {
        return;
    }

    final Set<String> currentUserRoles = new HashSet<>();
    for (GrantedAuthority grantedAuth : userDetails.getAuthorities()) {
        currentUserRoles.add(grantedAuth.getAuthority());
    }

    //determine entity rights 
    EntityRight entityRight = null;

    EntityUserMap[] entityUserMaps = ((WebEntity) currentBean.getClass().getAnnotation(WebEntity.class))
            .userMap();
    for (EntityUserMap e : entityUserMaps) {
        if (currentUserRoles.contains(e.role()) || ("*").equals(e.role())) {
            entityRight = e.right();
            break;
        }
    }
    if (entityRight == null) { //if entityRight=EntityRight.NONE, still allow to go through because field level might be accessible
        //Not accessible
        return;
    }

    //create bean utils
    final BeanUtils beanUtils = new BeanUtils();

    //rebuild pageParameter.getBreadcrumb()
    BreadCrumbBuilder.buildBreadCrumb(vcevent.getNavigator(), pageParameter.getBreadcrumb(),
            pageParameter.getHistory());

    //rebuild components
    if (currentBean == null) {
        return;
    }

    //refresh current item
    C newBean = dao.refresh(currentBean);
    if (newBean != null) {
        currentBean = newBean;
    }

    final BeanFieldGroup fieldGroup = new BeanFieldGroup(currentBean.getClass());
    fieldGroup.setItemDataSource(currentBean);
    final FormLayout form = new FormLayout();
    Map<String, Map<Integer, FieldContainer>> groups = beanUtils.createGroupsFromBean(currentBean.getClass());

    //render form according to tab
    if (groups.size() == 1) {
        createForm(entityRight, currentUserRoles, groups, fieldGroup, pageParameter.getCustomTypeDaos(),
                vcevent.getNavigator(), form);
    } else {
        TabSheet tabSheet = new TabSheet();
        for (String group : groups.keySet()) {
            if (("All").equals(group)) {
                createForm(entityRight, currentUserRoles, groups, group, fieldGroup,
                        pageParameter.getCustomTypeDaos(), vcevent.getNavigator(), form);
            } else {
                FormLayout tab = new FormLayout();
                createForm(entityRight, currentUserRoles, groups, group, fieldGroup,
                        pageParameter.getCustomTypeDaos(), vcevent.getNavigator(), tab);
                tabSheet.addTab(tab, group);

            }
        }
        form.addComponent(tabSheet);
    }

    //Navigation and actions
    HorizontalLayout navButtons = new HorizontalLayout();
    navButtons.setSpacing(true);

    Button saveAndBackBtn = new Button("Save and back", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            try {
                fieldGroup.commit();
                currentBean = (C) fieldGroup.getItemDataSource().getBean();
                currentBean = saveBean(currentBean, parentBean, beanUtils, currentUserRoles);
                if (!pageParameter.getHistory().isEmpty()) {
                    String currentView = pageParameter.getHistory().pop().getViewHandle();
                    String lastView = pageParameter.getHistory().peek().getViewHandle();
                    vcevent.getNavigator().removeView(currentView);
                    vcevent.getNavigator().navigateTo(lastView);
                }
            } catch (FieldGroup.CommitException ex) {
                handleFieldsError(fieldGroup);
            }
        }

    });
    navButtons.addComponent(saveAndBackBtn);
    saveAndBackBtn.setId(saveAndBackBtn.getCaption());

    form.addComponent(navButtons);
    form.setMargin(new MarginInfo(true));
    this.addComponent(form);
}

From source file:org.azrul.langkuik.framework.webgui.BeanView.java

private void createForm(EntityRight entityRight, final Set<String> currentUserRoles,
        final Map<String, Map<Integer, FieldContainer>> groups, String group, final BeanFieldGroup fieldGroup,
        final List<DataAccessObject<?>> customTypeDaos, final Navigator nav, final FormLayout form)
        throws FieldGroup.BindException, UnsupportedOperationException {
    //create bean utils
    final BeanUtils beanUtils = new BeanUtils();

    //select which group we want
    Map<Integer, FieldContainer> fieldContainerMap = null;
    if (group == null) {
        fieldContainerMap = groups.entrySet().iterator().next().getValue();
    } else {//w  w w  .j  a va 2 s.  co  m
        fieldContainerMap = groups.get(group);
    }

    //collect all activechoices
    Map<com.vaadin.ui.ComboBox, ActiveChoiceTarget> activeChoicesWithFieldAsKey = new HashMap<>();
    Map<String, com.vaadin.ui.ComboBox> activeChoicesFieldWithHierarchyAsKey = new HashMap<>();

    //collect all cutsom types
    List<Class> customTypes = new ArrayList<>();
    for (DataAccessObject<?> ctDao : customTypeDaos) {
        customTypes.add(ctDao.getType());
    }
    //deal with every field
    everyField: for (Map.Entry<Integer, FieldContainer> entry : fieldContainerMap.entrySet()) {
        final FieldContainer fieldContainer = entry.getValue();
        final ComponentState effectiveFieldState = beanUtils
                .calculateEffectiveComponentState(fieldContainer.getPojoField(), currentUserRoles, entityRight);

        //Create form
        if (ComponentState.INVISIBLE.equals(effectiveFieldState)) {
            continue everyField; //Continue with next field
        }

        //deal with normal form element
        com.vaadin.ui.Field uifield = null;
        //deal with plain choices
        if (fieldContainer.getWebField().choices().length > 0) {
            //deal with choices
            com.vaadin.ui.ComboBox formComboBox = new com.vaadin.ui.ComboBox(
                    fieldContainer.getWebField().name());
            formComboBox.setImmediate(true);
            fieldGroup.bind(formComboBox, fieldContainer.getPojoField().getName());
            for (Choice choice : fieldContainer.getWebField().choices()) {
                if (choice.value() == -1) {
                    formComboBox.addItem(choice.textValue());
                    formComboBox.setItemCaption(choice.textValue(), choice.display());
                } else {
                    formComboBox.addItem(choice.value());
                    formComboBox.setItemCaption(choice.value(), choice.display());
                }
            }
            form.addComponent(formComboBox);
            uifield = formComboBox;
            //deal with active choices
        } else if (fieldContainer.getWebField().activeChoice().enumTree() != EmptyEnum.class) {
            //collect active choices - 
            com.vaadin.ui.ComboBox formComboBox = new com.vaadin.ui.ComboBox(
                    fieldContainer.getWebField().name());
            formComboBox.setImmediate(true);
            fieldGroup.bind(formComboBox, fieldContainer.getPojoField().getName());
            String hierarchy = fieldContainer.getWebField().activeChoice().hierarchy();
            Class<ActiveChoiceEnum> enumTree = (Class<ActiveChoiceEnum>) fieldContainer.getWebField()
                    .activeChoice().enumTree();
            ActiveChoiceTarget activeChoiceTarget = ActiveChoiceUtils.build(enumTree, hierarchy);
            for (String choice : activeChoiceTarget.getSourceChoices()) {
                formComboBox.addItem(choice);
                activeChoicesWithFieldAsKey.put(formComboBox, activeChoiceTarget);
                activeChoicesFieldWithHierarchyAsKey.put(hierarchy, formComboBox);
            }

            form.addComponent(formComboBox);
            uifield = formComboBox;

            //deal with relationship
        } else if (fieldContainer.getPojoField().isAnnotationPresent(OneToMany.class)
                || fieldContainer.getPojoField().isAnnotationPresent(ManyToOne.class)
                || fieldContainer.getPojoField().isAnnotationPresent(ManyToMany.class)) {

            //special relationship: deal with custom type form element
            int state = 0;
            Class classOfField = null;
            while (true) {
                if (state == 0) {
                    if (Collection.class.isAssignableFrom(fieldContainer.getPojoField().getType())) {
                        classOfField = (Class) ((ParameterizedType) fieldContainer.getPojoField()
                                .getGenericType()).getActualTypeArguments()[0];
                        state = 1;
                    } else {
                        state = 3;
                        break;
                    }
                }
                if (state == 1) {
                    if (CustomType.class.isAssignableFrom(classOfField)) {
                        state = 2;
                        break;
                    } else {
                        state = 3;
                        break;
                    }
                }
            }

            if (state == 2) { //Custom type
                Button openCustom = new Button("Manage " + fieldContainer.getWebField().name(),
                        new Button.ClickListener() {
                            @Override
                            public void buttonClick(ClickEvent event) {
                                try {
                                    fieldGroup.commit();
                                    currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                    currentBean = saveBean(currentBean, parentBean, beanUtils,
                                            currentUserRoles);
                                    fieldGroup.setItemDataSource(currentBean);
                                    //field class
                                    Class iclassOfField = (Class) ((ParameterizedType) fieldContainer
                                            .getPojoField().getGenericType()).getActualTypeArguments()[0];

                                    //find a custom type dao
                                    DataAccessObject<? extends CustomType> chosenCTDao = null;
                                    for (DataAccessObject cdao : customTypeDaos) {
                                        if (cdao.getType().isAssignableFrom(iclassOfField)) {
                                            chosenCTDao = cdao;
                                            break;
                                        }
                                    }

                                    //deal with windows
                                    final Window window = new Window();
                                    final AttachmentCustomTypeUICreator<C> attachmentCustomTypeUICreator = new AttachmentCustomTypeUICreator();
                                    Component customTypeComponent = attachmentCustomTypeUICreator
                                            .createUIForForm(currentBean, iclassOfField,
                                                    fieldContainer.getPojoField().getName(), BeanView.this, dao,
                                                    chosenCTDao, pageParameter.getRelationManagerFactory(),
                                                    pageParameter.getConfig(), effectiveFieldState, window);
                                    customTypeComponent
                                            .setCaption("Manage " + fieldContainer.getWebField().name());
                                    customTypeComponent.setId(customTypeComponent.getCaption());
                                    window.setCaption(customTypeComponent.getCaption());
                                    window.setId(window.getCaption());
                                    window.setContent(customTypeComponent);
                                    window.setModal(true);

                                    BeanView.this.getUI().addWindow(window);
                                } catch (CommitException ex) {
                                    handleFieldsError(fieldGroup);
                                }
                            }
                        });
                openCustom.setId(openCustom.getCaption());
                form.addComponent(openCustom);

            } else { //relationship
                try {
                    fieldContainer.getPojoField().setAccessible(true);
                    final WebField webField = fieldContainer.getPojoField().getAnnotation(WebField.class);
                    Button relationshipButton = null;
                    if (fieldContainer.getPojoField().isAnnotationPresent(OneToMany.class)) {
                        relationshipButton = new Button("Manage " + webField.name(),
                                new Button.ClickListener() {
                                    @Override
                                    public void buttonClick(Button.ClickEvent event) {
                                        try {
                                            fieldGroup.commit();
                                            currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                            currentBean = saveBean(currentBean, parentBean, beanUtils,
                                                    currentUserRoles);

                                            Class classOfField = (Class) ((ParameterizedType) fieldContainer
                                                    .getPojoField().getGenericType())
                                                            .getActualTypeArguments()[0];
                                            EditorTableView view = new EditorTableView(currentBean,
                                                    fieldContainer.getPojoField().getName(),
                                                    effectiveFieldState, classOfField, ChoiceType.CHOOSE_MANY,
                                                    pageParameter);
                                            String targetView = "BEAN_VIEW_" + UUID.randomUUID().toString();
                                            History his = new History(targetView, "Manage " + webField.name());
                                            pageParameter.getHistory().push(his);
                                            nav.addView(targetView, view);
                                            nav.navigateTo(targetView);
                                        } catch (CommitException ex) {
                                            handleFieldsError(fieldGroup);
                                        }
                                    }
                                });

                    } else if (fieldContainer.getPojoField().isAnnotationPresent(ManyToOne.class)) {
                        relationshipButton = new Button("Manage " + webField.name(),
                                new Button.ClickListener() {
                                    @Override
                                    public void buttonClick(Button.ClickEvent event) {
                                        try {
                                            fieldGroup.commit();
                                            currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                            fieldGroup.commit();
                                            currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                            currentBean = saveBean(currentBean, parentBean, beanUtils,
                                                    currentUserRoles);

                                            EditorTableView view = new EditorTableView(currentBean,
                                                    fieldContainer.getPojoField().getName(),
                                                    effectiveFieldState,
                                                    fieldContainer.getPojoField().getType(),
                                                    ChoiceType.CHOOSE_ONE, pageParameter);
                                            String targetView = "BEAN_VIEW_" + UUID.randomUUID().toString();
                                            History his = new History(targetView, "Manage " + webField.name());
                                            pageParameter.getHistory().push(his);
                                            nav.addView(targetView, view);
                                            nav.navigateTo(targetView);
                                        } catch (CommitException ex) {
                                            handleFieldsError(fieldGroup);
                                        }
                                    }
                                });
                    } else if (fieldContainer.getPojoField().isAnnotationPresent(ManyToMany.class)) {
                        relationshipButton = new Button("Manage " + webField.name(),
                                new Button.ClickListener() {
                                    @Override
                                    public void buttonClick(Button.ClickEvent event) {
                                        try {
                                            fieldGroup.commit();
                                            currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                            fieldGroup.commit();
                                            currentBean = (C) fieldGroup.getItemDataSource().getBean();
                                            currentBean = saveBean(currentBean, parentBean, beanUtils,
                                                    currentUserRoles);

                                            Class classOfField = (Class) ((ParameterizedType) fieldContainer
                                                    .getPojoField().getGenericType())
                                                            .getActualTypeArguments()[0];
                                            EditorTableView view = new EditorTableView(currentBean,
                                                    fieldContainer.getPojoField().getName(),
                                                    effectiveFieldState, classOfField, ChoiceType.CHOOSE_MANY,
                                                    pageParameter);

                                            String targetView = "BEAN_VIEW_" + UUID.randomUUID().toString();
                                            History his = new History(targetView, "Manage " + webField.name());
                                            pageParameter.getHistory().push(his);
                                            nav.addView(targetView, view);
                                            nav.navigateTo(targetView);
                                        } catch (CommitException ex) {
                                            handleFieldsError(fieldGroup);
                                        }
                                    }
                                });
                    }
                    relationshipButton.setId(relationshipButton.getCaption());
                    form.addComponent(relationshipButton);
                } catch (IllegalArgumentException ex) {
                    Logger.getLogger(BeanView.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            //deal with id
        } else if (fieldContainer.getPojoField().isAnnotationPresent(Id.class)) {
            com.vaadin.ui.Field formField = fieldGroup.buildAndBind(fieldContainer.getWebField().name(),
                    fieldContainer.getPojoField().getName());
            if (Number.class.isAssignableFrom(fieldContainer.getPojoField().getType())) {
                ((TextField) formField).setConverter(
                        new NumberBasedIDConverter((Class<Number>) fieldContainer.getPojoField().getType()));
            }

            form.addComponent(formField);
            uifield = formField;

            //deal with nominal form element
        } else {
            com.vaadin.ui.Field formField = fieldGroup.buildAndBind(fieldContainer.getWebField().name(),
                    fieldContainer.getPojoField().getName());
            if (fieldContainer.getPojoField().getType().equals(Date.class)) {
                //deal with date
                DateField dateField = (DateField) formField;
                dateField.setDateFormat(pageParameter.getConfig().get("dateFormat"));
                dateField.setWidth(100f, Unit.PIXELS);
            } else if (fieldContainer.getPojoField().getType().equals(BigDecimal.class)) {
                TextField bdField = (TextField) formField;
                bdField.setConverter(new StringToBigDecimalConverter());
            }

            form.addComponent(formField);
            uifield = formField;
        }

        if (uifield != null) {
            //deal with read only
            if (ComponentState.READ_ONLY.equals(effectiveFieldState)) {
                uifield.setReadOnly(true);
            } else {
                uifield.setReadOnly(false);
                if (fieldContainer.getWebField().required() == true) {
                    uifield.setRequired(true);
                }
            }

            //set null presentation
            if (uifield instanceof AbstractTextField) {
                AbstractTextField textField = (AbstractTextField) uifield;
                textField.setNullRepresentation("");
            }

            //set debug id
            uifield.setId(uifield.getCaption());
        }
    }

    //deal with active choice
    for (final com.vaadin.ui.ComboBox sourceField : activeChoicesWithFieldAsKey.keySet()) {
        final ActiveChoiceTarget target = activeChoicesWithFieldAsKey.get(sourceField);
        final com.vaadin.ui.ComboBox targetField = activeChoicesFieldWithHierarchyAsKey
                .get(target.getTargetHierarchy());
        sourceField.addValueChangeListener(new ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                List<String> targetValues = target.getTargets().get(sourceField.getValue());
                if (targetValues != null && !targetValues.isEmpty() && targetField != null) {
                    targetField.removeAllItems();
                    for (String targetValue : targetValues) {
                        targetField.addItem(targetValue);
                    }
                }
            }
        });

    }
}

From source file:org.azrul.langkuik.framework.webgui.EditorTableView.java

public void enter(final ViewChangeListener.ViewChangeEvent vcevent) {
    setCurrentView(vcevent.getViewName());
    this.removeAllComponents();

    //get user roles
    UserDetails userDetails = null;//from   www .  j  a v a2 s  . c  om
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        userDetails = (UserDetails) auth.getPrincipal();
    } else {
        return;
    }
    Set<String> currentUserRoles = new HashSet<>();
    for (GrantedAuthority grantedAuth : userDetails.getAuthorities()) {
        currentUserRoles.add(grantedAuth.getAuthority());
    }

    //determine entity rights 
    EntityRight entityRight = null;

    EntityUserMap[] entityUserMaps = classOfBean.getAnnotation(WebEntity.class).userMap();
    for (EntityUserMap e : entityUserMaps) {
        if (currentUserRoles.contains(e.role()) || ("*").equals(e.role())) {
            entityRight = e.right();
            break;
        }
    }
    if (entityRight == null) { //if entityRight=EntityRight.NONE, still allow to go through because field level might be accessible
        //Not accessible
        return;
    }

    //create bean utils
    BeanUtils beanUtils = new BeanUtils();

    //creat bread crumb
    BreadCrumbBuilder.buildBreadCrumb(vcevent.getNavigator(), pageParameter.getBreadcrumb(),
            pageParameter.getHistory());

    //create form
    FormLayout form = new FormLayout();
    FindAnyEntityParameter<C> searchQuery = new FindAnyEntityParameter<>(classOfBean);
    FindEntityCollectionParameter<P, C> entityCollectionQuery = new FindEntityCollectionParameter<>(parentBean,
            parentToBeanField,
            pageParameter.getRelationManagerFactory().create((Class<P>) parentBean.getClass(), classOfBean));

    final SearchDataTableLayout<C> allDataTableLayout = new SearchDataTableLayout<>(searchQuery, classOfBean,
            dao, noBeansPerPage, pageParameter.getCustomTypeDaos(), pageParameter.getConfig(), currentUserRoles,
            entityRight);
    final CollectionDataTableLayout<P, C> beanTableLayout = new CollectionDataTableLayout<>(
            entityCollectionQuery, classOfBean, dao, noBeansPerPage, pageParameter.getCustomTypeDaos(),
            pageParameter.getConfig(), currentUserRoles, entityRight);

    //handle associate existing data
    final Window window = new Window("Associate");
    window.setId(window.getCaption());
    window.setContent(allDataTableLayout);
    window.setModal(true);

    HorizontalLayout popupButtonLayout = new HorizontalLayout();

    Button associateToCurrentBtn = new Button("Associate to current", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            Collection<C> allDataList = allDataTableLayout.getTableValues();
            beanTableLayout.associateEntities(allDataList, choiceType);
            window.close();
        }
    });
    associateToCurrentBtn.setId(associateToCurrentBtn.getCaption());
    popupButtonLayout.addComponent(associateToCurrentBtn);

    Button closeBtn = new Button("Close", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            window.close();
        }
    });
    popupButtonLayout.addComponent(closeBtn);
    closeBtn.setId(closeBtn.getCaption());

    popupButtonLayout.setSpacing(true);
    MarginInfo marginInfo = new MarginInfo(true);

    allDataTableLayout.setMargin(marginInfo);
    allDataTableLayout.addComponent(popupButtonLayout);
    if (parentToBeanFieldState.equals(ComponentState.EDITABLE)) {
        Button associateExistingBtn = new Button("Associate existing", new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {

                EditorTableView.this.getUI().addWindow(window);
            }
        });
        form.addComponent(associateExistingBtn);
        associateExistingBtn.setId(associateExistingBtn.getCaption());
    }
    form.addComponent(beanTableLayout);

    //Navigation and actions
    HorizontalLayout buttonLayout = new HorizontalLayout();
    if (beanUtils.isCreatable(classOfBean, currentUserRoles)
            && parentToBeanFieldState.equals(ComponentState.EDITABLE)) {
        Button addNewBtn = new Button("Add new", new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                C currentBean = dao.createNew(true);//dao.createAndSave(parentBean, parentToBeanField, pageParameter.getRelationManagerFactory().create((Class<P>) parentBean.getClass(), classOfBean));
                BeanView<P, C> beanView = new BeanView<P, C>(currentBean, parentBean, parentToBeanField,
                        pageParameter);
                String targetView = "CHOOSE_ONE_TABLE_VIEW_" + UUID.randomUUID().toString();
                WebEntity myObject = (WebEntity) currentBean.getClass().getAnnotation(WebEntity.class);
                History his = new History(targetView, "Add new " + myObject.name());
                pageParameter.getHistory().push(his);
                vcevent.getNavigator().addView(targetView, beanView);
                vcevent.getNavigator().navigateTo(targetView);

            }
        });
        buttonLayout.addComponent(addNewBtn);
        addNewBtn.setId(addNewBtn.getCaption());
    }

    if (beanUtils.isEditable(classOfBean, currentUserRoles)
            || beanUtils.isViewable(classOfBean, currentUserRoles)) {
        Button manageBtn = new Button("Manage", new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                C currentBean = beanTableLayout.getTableValues().iterator().next();
                if (currentBean != null) {
                    BeanView<P, C> beanView = new BeanView<P, C>(currentBean, parentBean, parentToBeanField,
                            pageParameter);
                    String targetView = "CHOOSE_ONE_TABLE_VIEW_" + UUID.randomUUID().toString();
                    WebEntity myObject = (WebEntity) currentBean.getClass().getAnnotation(WebEntity.class);
                    History his = new History(targetView, "Manage " + myObject.name());
                    pageParameter.getHistory().push(his);
                    vcevent.getNavigator().addView(targetView, beanView);
                    vcevent.getNavigator().navigateTo(targetView);
                }
            }
        });
        buttonLayout.addComponent(manageBtn);
        manageBtn.setId(manageBtn.getCaption());
    }

    if (parentToBeanFieldState.equals(ComponentState.EDITABLE)) {

        if (beanUtils.isCreatable(classOfBean, currentUserRoles)
                && parentToBeanFieldState.equals(ComponentState.EDITABLE)) {
            Button deleteBtn = new Button("Delete", new Button.ClickListener() {
                @Override
                public void buttonClick(Button.ClickEvent event) {
                    final Collection<C> currentBeans = (Collection<C>) beanTableLayout.getTableValues();
                    if (!currentBeans.isEmpty()) {
                        ConfirmDialog.show(EditorTableView.this.getUI(), "Please Confirm:",
                                "Are you really sure you want to delete these entries?", "I am", "Not quite",
                                new ConfirmDialog.Listener() {
                                    @Override
                                    public void onClose(ConfirmDialog dialog) {
                                        if (dialog.isConfirmed()) {
                                            EditorTableView.this.parentBean = beanTableLayout
                                                    .deleteData(currentBeans);
                                        }
                                    }
                                });
                    }
                }
            });
            buttonLayout.addComponent(deleteBtn);
            deleteBtn.setId(deleteBtn.getCaption());
        }
    }

    Button saveAndBackBtn = new Button("Save and back", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            //parentDao.save(parentBean);
            if (!pageParameter.getHistory().isEmpty()) {
                String currentView = pageParameter.getHistory().pop().getViewHandle();
                String lastView = pageParameter.getHistory().peek().getViewHandle();
                vcevent.getNavigator().removeView(currentView);
                vcevent.getNavigator().navigateTo(lastView);
            }
        }
    });
    buttonLayout.addComponent(saveAndBackBtn);
    saveAndBackBtn.setId(saveAndBackBtn.getCaption());

    buttonLayout.setSpacing(true);
    form.addComponent(buttonLayout);
    this.addComponent(form);
}

From source file:org.azrul.langkuik.framework.webgui.PlainTableView.java

@Override
public void enter(final ViewChangeListener.ViewChangeEvent vcevent) {
    setCurrentView(vcevent.getViewName());
    this.removeAllComponents();

    //determine user details
    UserDetails userDetails = null;//from ww w . j  a va2  s  .c  o m
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        userDetails = (UserDetails) auth.getPrincipal();
    } else {
        return;
    }

    final Set<String> currentUserRoles = new HashSet<>();
    for (GrantedAuthority grantedAuth : userDetails.getAuthorities()) {
        currentUserRoles.add(grantedAuth.getAuthority());
    }

    //determine entity rights 
    EntityRight entityRight = null;

    EntityUserMap[] entityUserMaps = classOfBean.getAnnotation(WebEntity.class).userMap();
    for (EntityUserMap e : entityUserMaps) {
        if (currentUserRoles.contains(e.role()) || ("*").equals(e.role())) {
            entityRight = e.right();
            break;
        }
    }
    if (entityRight == null) { //if entityRight=EntityRight.NONE, still allow to go through because field level might be accessible
        //Not accessible
        return;
    }

    //Build bread crumb
    BreadCrumbBuilder.buildBreadCrumb(vcevent.getNavigator(), pageParameter.getBreadcrumb(),
            pageParameter.getHistory());
    FindAnyEntityParameter<C> searchQuery = new FindAnyEntityParameter<>(classOfBean);

    //set form
    FormLayout form = new FormLayout();
    final SearchDataTableLayout<C> dataTable = new SearchDataTableLayout<>(searchQuery, classOfBean, dao,
            noBeansPerPage, pageParameter.getCustomTypeDaos(), pageParameter.getConfig(), currentUserRoles,
            entityRight);
    form.addComponent(dataTable);

    //Handle navigations and actions
    HorizontalLayout buttonLayout = new HorizontalLayout();

    //        Button addNewBtn = new Button("Add new",
    //                new Button.ClickListener() {
    //                    @Override
    //                    public void buttonClick(Button.ClickEvent event
    //                    ) {
    //                        C currentBean = dao.createAndSave();
    //                        BeanView<Object, C> beanView = new BeanView<Object, C>(currentBean,null, pageParameter.getRelationManagerFactory(), pageParameter.getEntityManagerFactory(), pageParameter.getHistory(), pageParameter.getBreadcrumb(), pageParameter.getConfig(), pageParameter.getCustomTypeDaos());
    //                        String targetView = "CHOOSE_ONE_TABLE_VIEW_" + UUID.randomUUID().toString();
    //                        WebEntity myObject = (WebEntity) currentBean.getClass().getAnnotation(WebEntity.class);
    //                        History his = new History(targetView, "Add new " + myObject.name());
    //                        pageParameter.getHistory().push(his);
    //                        vcevent.getNavigator().addView(targetView, beanView);
    //                        vcevent.getNavigator().navigateTo(targetView);
    //
    //                    }
    //                });
    //        buttonLayout.addComponent(addNewBtn);
    //        addNewBtn.setId(addNewBtn.getCaption());

    Button manageBtn = new Button("Manage", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            Collection<C> currentBeans = (Collection<C>) dataTable.getTableValues();
            if (!currentBeans.isEmpty()) {
                C currentBean = currentBeans.iterator().next();
                if (currentBean != null) {
                    BeanView<Object, C> beanView = new BeanView<>(currentBean, null, null, pageParameter);
                    String targetView = "CHOOSE_ONE_TABLE_VIEW_" + UUID.randomUUID().toString();
                    WebEntity myObject = (WebEntity) currentBean.getClass().getAnnotation(WebEntity.class);
                    History his = new History(targetView, "Manage " + myObject.name());
                    pageParameter.getHistory().push(his);
                    vcevent.getNavigator().addView(targetView, beanView);
                    vcevent.getNavigator().navigateTo(targetView);
                }
            }

        }
    });
    buttonLayout.addComponent(manageBtn);
    manageBtn.setId(manageBtn.getCaption());

    Button deleteBtn = new Button("Delete", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            final Collection<C> currentBeans = (Collection<C>) dataTable.getTableValues();
            if (!currentBeans.isEmpty()) {
                ConfirmDialog.show(PlainTableView.this.getUI(), "Please Confirm:",
                        "Are you really sure you want to delete these entries?", "I am", "Not quite",
                        new ConfirmDialog.Listener() {
                            public void onClose(ConfirmDialog dialog) {
                                if (dialog.isConfirmed()) {
                                    //                                        dao.delete(currentBeans);
                                    //                                        Collection<C> data = dao.search(searchTerms, classOfBean, currentTableDataIndex, noBeansPerPage);
                                    //                                        if (data.isEmpty()) {
                                    //                                            data = new ArrayList<C>();
                                    //                                            data.add(dao.createNew());
                                    //                                        }
                                    //                                        tableDataIT.setBeans(data);
                                    //                                        tableDataIT.refreshItems();
                                    //                                        totalTableData = dao.countSearch(searchTerms, classOfBean);
                                    //                                        final Label pageLabel = new Label();
                                    //                                        int lastPage = (int) Math.floor(totalTableData / noBeansPerPage);
                                    //                                        if (totalTableData % noBeansPerPage == 0) {
                                    //                                            lastPage--;
                                    //                                        }
                                    //                                        int currentUpdatedPage = currentTableDataIndex / noBeansPerPage;
                                    //                                        pageLabel.setCaption(" " + (currentUpdatedPage + 1) + " of " + (lastPage + 1) + " ");
                                }
                            }
                        });
            }

        }
    });
    buttonLayout.addComponent(deleteBtn);
    deleteBtn.setId(deleteBtn.getCaption());

    buttonLayout.setSpacing(true);
    form.addComponent(buttonLayout);

    Button backBtn = new Button("Back", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            if (!pageParameter.getHistory().isEmpty()) {
                String currentView = pageParameter.getHistory().pop().getViewHandle();
                String lastView = pageParameter.getHistory().peek().getViewHandle();
                vcevent.getNavigator().removeView(currentView);
                vcevent.getNavigator().navigateTo(lastView);
            }
        }
    });
    form.addComponent(backBtn);
    backBtn.setId(backBtn.getCaption());
    this.addComponent(form);
}

From source file:org.azrul.langkuik.framework.webgui.SearchDataTableLayout.java

protected void createSearchPanel(final Class<C> classOfBean, final Configuration config,
        final Set<String> currentUserRoles, final EntityRight entityRight)
        throws UnsupportedOperationException, SecurityException, FieldGroup.BindException {
    final BeanFieldGroup fieldGroup = new BeanFieldGroup(classOfBean);
    final FindAnyEntityParameter searchQuery = (FindAnyEntityParameter) parameter;

    //collect all activechoices
    Map<com.vaadin.ui.ComboBox, ActiveChoiceTarget> activeChoicesWithFieldAsKey = new HashMap<>();
    Map<String, com.vaadin.ui.ComboBox> activeChoicesFieldWithHierarchyAsKey = new HashMap<>();

    BeanUtils beanUtils = new BeanUtils();
    Map<Integer, FieldContainer> fieldContainers = beanUtils.getOrderedFieldsByRank(classOfBean);

    final Map<Integer, com.vaadin.ui.Field> searchableFieldsByRank = new TreeMap<>();
    final Map<String, com.vaadin.ui.Field> searchableFieldsByName = new TreeMap<>();

    //Construct search form
    for (FieldContainer fieldContainer : fieldContainers.values()) {
        Field pojoField = fieldContainer.getPojoField();
        WebField webField = fieldContainer.getWebField();

        if (pojoField.isAnnotationPresent(org.hibernate.search.annotations.Field.class)) {
            if (webField.choices().length > 0) {
                //deal with choices

                com.vaadin.ui.ComboBox searchComboBox = new com.vaadin.ui.ComboBox(webField.name());

                searchComboBox.setImmediate(true);
                fieldGroup.bind(searchComboBox, pojoField.getName());
                for (Choice choice : webField.choices()) {
                    if (choice.value() == -1) {
                        searchComboBox.addItem(choice.textValue());
                        searchComboBox.setItemCaption(choice.textValue(), choice.display());
                    } else {
                        searchComboBox.addItem(choice.value());
                        searchComboBox.setItemCaption(choice.value(), choice.display());
                    }/*  ww  w .  j  av a  2  s  . c  om*/
                }

                //allDataSearchForm.addComponent(searchComboBox);
                searchableFieldsByRank.put(webField.rank(), searchComboBox);
                searchableFieldsByName.put(pojoField.getName(), searchComboBox);
            } else if (webField.activeChoice().enumTree() != EmptyEnum.class) {
                //collect active choices - 
                com.vaadin.ui.ComboBox searchComboBox = new com.vaadin.ui.ComboBox(webField.name());
                searchComboBox.setImmediate(true);
                fieldGroup.bind(searchComboBox, pojoField.getName());
                String hierarchy = webField.activeChoice().hierarchy();
                Class<ActiveChoiceEnum> enumTree = (Class<ActiveChoiceEnum>) webField.activeChoice().enumTree();
                ActiveChoiceTarget activeChoiceTarget = ActiveChoiceUtils.build(enumTree, hierarchy);
                for (String choice : activeChoiceTarget.getSourceChoices()) {
                    searchComboBox.addItem(choice);
                    activeChoicesWithFieldAsKey.put(searchComboBox, activeChoiceTarget);
                    activeChoicesFieldWithHierarchyAsKey.put(hierarchy, searchComboBox);
                }
                searchableFieldsByRank.put(webField.rank(), searchComboBox);
                searchableFieldsByName.put(pojoField.getName(), searchComboBox);

            } else {
                com.vaadin.ui.Field searchField = fieldGroup.buildAndBind(webField.name(), pojoField.getName());
                if (pojoField.getType().equals(Date.class)) {
                    DateField dateField = (DateField) searchField;
                    dateField.setDateFormat(config.get("dateFormat"));
                    dateField.setWidth(100f, Sizeable.Unit.PIXELS);
                }

                //allDataSearchForm.addComponent(searchField);
                searchableFieldsByRank.put(webField.rank(), searchField);
                searchableFieldsByName.put(pojoField.getName(), searchField);
            }
        }

    }

    //build form
    int rowCount = (int) (Math.ceil(searchableFieldsByRank.size() / 2));
    rowCount = rowCount < 1 ? 1 : rowCount;
    GridLayout allDataSearchForm = new GridLayout(2, rowCount);
    allDataSearchForm.setSpacing(true);
    for (com.vaadin.ui.Field searchField : searchableFieldsByRank.values()) {
        allDataSearchForm.addComponent(searchField);
        searchField.setId(searchField.getCaption());
    }

    this.addComponent(allDataSearchForm);

    //deal with active choice
    for (final com.vaadin.ui.ComboBox sourceField : activeChoicesWithFieldAsKey.keySet()) {
        final ActiveChoiceTarget target = activeChoicesWithFieldAsKey.get(sourceField);
        final com.vaadin.ui.ComboBox targetField = activeChoicesFieldWithHierarchyAsKey
                .get(target.getTargetHierarchy());
        sourceField.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                List<String> targetValues = target.getTargets().get(sourceField.getValue());
                if (targetValues != null && !targetValues.isEmpty() && targetField != null) {
                    targetField.removeAllItems();
                    for (String targetValue : targetValues) {
                        targetField.addItem(targetValue);
                    }
                }
            }
        });

    }

    //search button
    Button searchBtn = new Button("Search", new Button.ClickListener() {

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

            //reset previous searches
            searchQuery.getSearchTerms().clear();
            //read search terms from form
            try {
                for (Map.Entry<String, com.vaadin.ui.Field> entry : searchableFieldsByName.entrySet()) {
                    com.vaadin.ui.Field searchField = entry.getValue();
                    if (searchField.getValue() != null) {
                        if (searchField.getValue() instanceof String) {
                            String searchTerm = ((String) searchField.getValue()).trim();
                            if (!"".equals(searchTerm)) {
                                searchQuery.getSearchTerms().add(new SearchTerm(entry.getKey(),
                                        classOfBean.getDeclaredField(entry.getKey()), searchField.getValue()));
                            }
                        } else {
                            searchQuery.getSearchTerms().add(new SearchTerm(entry.getKey(),
                                    classOfBean.getDeclaredField(entry.getKey()), searchField.getValue()));
                        }
                    }
                }
            } catch (NoSuchFieldException | SecurityException ex) {
                Logger.getLogger(SearchDataTableLayout.class.getName()).log(Level.SEVERE, null, ex);
            }
            //do query
            Collection<C> allData = dao.runQuery(parameter, orderBy, asc, currentTableIndex, itemCountPerPage);
            if (allData.isEmpty()) {
                allData = new ArrayList<>();
                allData.add(dao.createNew());
            }
            bigTotal = dao.countQueryResult(parameter);
            itemContainer.setBeans(allData);
            itemContainer.refreshItems();
            table.setPageLength(itemCountPerPage);
            table.setPageLength(itemCountPerPage);
            currentTableIndex = 0;
            int lastPage = (int) Math.floor(bigTotal / itemCountPerPage);
            if (bigTotal % itemCountPerPage == 0) {
                lastPage--;
            }
            int currentUpdatedPage = currentTableIndex / itemCountPerPage;
            pageLabel.setCaption(" " + (currentUpdatedPage + 1) + " of " + (lastPage + 1) + " ");
        }
    });
    searchBtn.setId(searchBtn.getCaption());
    this.addComponent(searchBtn);
}