org.azrul.langkuik.framework.webgui.EditorTableView.java Source code

Java tutorial

Introduction

Here is the source code for org.azrul.langkuik.framework.webgui.EditorTableView.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.azrul.langkuik.framework.webgui;

import org.azrul.langkuik.dao.DataAccessObject;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.ui.Button;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Layout;
import com.vaadin.ui.Window;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.persistence.EntityManagerFactory;
import org.azrul.langkuik.annotations.EntityUserMap;
import org.azrul.langkuik.annotations.WebEntity;
import org.azrul.langkuik.configs.Configuration;
import org.azrul.langkuik.dao.HibernateGenericDAO;
import org.azrul.langkuik.framework.webgui.breadcrumb.BreadCrumbBuilder;
import org.azrul.langkuik.dao.FindAnyEntityParameter;
import org.azrul.langkuik.dao.FindEntityCollectionParameter;
import org.azrul.langkuik.framework.PageParameter;
import org.azrul.langkuik.framework.webgui.breadcrumb.History;
import org.azrul.langkuik.framework.relationship.RelationManagerFactory;
import org.azrul.langkuik.security.constant.ComponentState;
import org.azrul.langkuik.security.role.EntityRight;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.vaadin.dialogs.ConfirmDialog;

/**
 *
 * @author azrulm
 * @param <P>
 * @param <C>
 */
public class EditorTableView<P, C> extends VerticalView {

    private P parentBean;
    private String parentToBeanField;
    private ComponentState parentToBeanFieldState;
    private final Class<C> classOfBean;
    private final int noBeansPerPage;
    private final DataAccessObject<C> dao;
    private final DataAccessObject<P> parentDao;
    private final List<DataAccessObject<?>> customTypeDaos;
    private ChoiceType choiceType;
    private PageParameter pageParameter;

    public EditorTableView(P parentBean, String parentToBeanField, ComponentState parentToBeanFieldState,
            Class<C> classOfBean, ChoiceType choiceType, PageParameter pageParameter) {
        this(parentBean, parentToBeanField, parentToBeanFieldState, classOfBean, choiceType, 3, pageParameter);
    }

    public EditorTableView(P parentBean, String parentToBeanField, ComponentState parentToBeanFieldState,
            Class<C> classOfBean, ChoiceType choiceType, int noBeansPerPage, PageParameter pageParameter) {
        this.parentBean = parentBean;
        this.parentToBeanField = parentToBeanField;
        this.classOfBean = classOfBean;
        this.noBeansPerPage = noBeansPerPage;
        this.dao = new HibernateGenericDAO<>(pageParameter.getEntityManagerFactory(), classOfBean);
        this.parentDao = new HibernateGenericDAO<>(pageParameter.getEntityManagerFactory(),
                (Class<P>) parentBean.getClass());

        this.choiceType = choiceType;
        this.customTypeDaos = pageParameter.getCustomTypeDaos();
        this.parentToBeanFieldState = parentToBeanFieldState;
        this.pageParameter = pageParameter;
    }

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

        //get user roles
        UserDetails userDetails = null;
        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);
    }
}