Java tutorial
/* * 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.ui.Button; import com.vaadin.ui.FormLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Layout; 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.FindAnyEntityParameter; import org.azrul.langkuik.dao.HibernateGenericDAO; import org.azrul.langkuik.framework.PageParameter; import org.azrul.langkuik.framework.webgui.breadcrumb.BreadCrumbBuilder; import org.azrul.langkuik.framework.webgui.breadcrumb.History; import org.azrul.langkuik.framework.relationship.RelationManagerFactory; 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 <C> */ public class PlainTableView<C> extends VerticalView { private final Class<C> classOfBean; private final int noBeansPerPage; private final DataAccessObject<C> dao; private final PageParameter pageParameter; public PlainTableView(Class<C> classOfBean, PageParameter pageParameter) { this(classOfBean, 3, pageParameter); } public PlainTableView(Class<C> classOfBean, int noBeansPerPage, PageParameter pageParameter) { this.classOfBean = classOfBean; this.noBeansPerPage = noBeansPerPage; this.pageParameter = pageParameter; this.dao = new HibernateGenericDAO<>(pageParameter.getEntityManagerFactory(), classOfBean); } @Override public void enter(final ViewChangeListener.ViewChangeEvent vcevent) { setCurrentView(vcevent.getViewName()); 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 = 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); } /*@Override public void enter(final ViewChangeListener.ViewChangeEvent vcevent) { setCurrentView(vcevent.getViewName()); this.removeAllComponents(); //Build bread crumb BreadCrumbBuilder.buildBreadCrumb(vcevent.getNavigator(),pageParameter.getBreadcrumb(), pageParameter.getHistory()); //set form FormLayout form = new FormLayout(); //Construct all data type T layout VerticalLayout dataTableLayout = new VerticalLayout(); //Page label final Label pageLabel = new Label(); //Collect all visible and searchable fields final Map<String, Field> fieldsToBeDisplayedInTable = new HashMap<>(); final BeanFieldGroup binder = new BeanFieldGroup(classOfBean); final Map<String, com.vaadin.ui.Field> searchableFields = new HashMap<>(); for (Field field : classOfBean.getDeclaredFields()) { if (field.isAnnotationPresent(WebField.class)) { WebField myf = (WebField) field.getAnnotation(WebField.class); if (myf.displayInTable() == true) { fieldsToBeDisplayedInTable.put(field.getName(), field); } if (field.isAnnotationPresent(org.hibernate.search.annotations.Field.class)) { if (myf.choices().length > 0) { com.vaadin.ui.ComboBox searchComboBox = new com.vaadin.ui.ComboBox(myf.name()); searchComboBox.setImmediate(true); binder.bind(searchComboBox, field.getName()); for (Choice choice : myf.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()); } } searchComboBox.setId(searchComboBox.getCaption()); dataTableLayout.addComponent(searchComboBox); searchableFields.put(field.getName(), searchComboBox); } else { com.vaadin.ui.Field searchField = binder.buildAndBind(myf.name(), field.getName()); if (field.getType().equals(Date.class)) { DateField dateField = (DateField) searchField; dateField.setDateFormat(pageParameter.getConfig().get("dateFormat")); dateField.setWidth(100f, Unit.PIXELS); } dataTableLayout.addComponent(searchField); searchField.setId(searchField.getCaption()); searchableFields.put(field.getName(), searchField); } } } } //Get all data of of type T Collection<C> tableData = dao.search(null, classOfBean, currentTableDataIndex, noBeansPerPage); if (tableData.isEmpty()) { tableData.add(dao.createNew()); } totalTableData = dao.countSearch(null, classOfBean); //Put all data of type T into a table to be chosen final WebEntityItemContainer<C> tableDataIT = new WebEntityItemContainer<>(tableData); //put seach form in search data layout (if there is there are searchable fields) if (!searchableFields.isEmpty()) { final GridLayout searchBox = new GridLayout(); searchBox.setColumns(2); Button searchBtn = new Button("Search", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { //reset previous searches searchTerms.clear(); currentTableDataIndex = 0; //read search terms from search form try { for (Map.Entry<String, com.vaadin.ui.Field> entry : searchableFields.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)) { searchTerms.add(new SearchTerm(entry.getKey(), classOfBean.getDeclaredField(entry.getKey()), searchField.getValue())); } } else { searchTerms.add(new SearchTerm(entry.getKey(), classOfBean.getDeclaredField(entry.getKey()), searchField.getValue())); } } } } catch (NoSuchFieldException | SecurityException ex) { Logger.getLogger(PlainTableView.class.getName()).log(Level.SEVERE, null, ex); } //do query Collection<C> tableData = dao.search(searchTerms, classOfBean, orderBy, asc, currentTableDataIndex, noBeansPerPage); if (tableData.isEmpty()) { tableData = new ArrayList<C>(); tableData.add(dao.createNew()); } totalTableData = dao.countSearch(searchTerms, classOfBean); tableDataIT.setBeans(tableData); tableDataIT.refreshItems(); currentTableDataIndex = 0; int lastPage = (int) Math.floor(totalTableData / noBeansPerPage); if (totalTableData % noBeansPerPage == 0) { lastPage--; } int currentUpdatedPage = currentTableDataIndex / noBeansPerPage; pageLabel.setCaption(" " + (currentUpdatedPage + 1) + " of " + (lastPage + 1) + " "); } }); searchBox.addComponent(searchBtn); searchBtn.setId(searchBtn.getCaption()); dataTableLayout.addComponent(searchBox); } //Construct table for choice data final Table dataTable = new Table(null); dataTable.setContainerDataSource(tableDataIT); tableDataIT.refreshItems(); //sort displyable fields by rank Map<Integer,String> columns = new HashMap<>(); for (Field field : fieldsToBeDisplayedInTable.values()){ WebField myf = field.getAnnotation(WebField.class); columns.put(myf.rank(), field.getName()); } //display rows in table dataTable.setVisibleColumns(columns.values().toArray()); dataTable.setImmediate(true); dataTable.setSelectable(true); dataTable.setMultiSelect(true); dataTable.setHeight(200f, Unit.PIXELS); for (Map.Entry<String, Field> entry : fieldsToBeDisplayedInTable.entrySet()) { Field field = entry.getValue(); String fieldName = entry.getKey(); //set date format for table if (field.getType().equals(Date.class)) { dataTable.setConverter(fieldName, new StringToDateConverter() { @Override public DateFormat getFormat(Locale locale) { return new SimpleDateFormat(pageParameter.getConfig().get("dateFormat")); } }); } else { if (field.isAnnotationPresent(WebField.class)) { final WebField myf = field.getAnnotation(WebField.class); if (myf.choices().length > 0) { final Map<Object, Object> modelToPresentationMap = new HashMap<>(); final Map<Object, Object> presentationToModelMap = new HashMap<>(); for (Choice choice : myf.choices()) { if (choice.value() == -1) { modelToPresentationMap.put(choice.textValue(), choice.display()); presentationToModelMap.put(choice.display(), choice.textValue()); } else { modelToPresentationMap.put(choice.value(), choice.display()); presentationToModelMap.put(choice.display(), choice.value()); } } dataTable.setConverter(fieldName, new Converter<String, Object>() { @Override public Object convertToModel(String value, Class<? extends Object> targetType, Locale locale) throws Converter.ConversionException { return presentationToModelMap.get(value); } @Override public String convertToPresentation(Object value, Class<? extends String> targetType, Locale locale) throws Converter.ConversionException { return (String) modelToPresentationMap.get(value); } @Override public Class<Object> getModelType() { return (Class<Object>) (new Object()).getClass(); } @Override public Class<String> getPresentationType() { return (Class<String>) "".getClass(); } }); } } } } //create navigation button int lastPage = (int) Math.floor(totalTableData / noBeansPerPage); if (totalTableData % noBeansPerPage == 0) { lastPage--; } int currentUpdatedPage = currentTableDataIndex / noBeansPerPage; pageLabel.setCaption(" " + (currentUpdatedPage + 1) + " of " + (lastPage + 1) + " "); dataTableLayout.addComponent(dataTable); HorizontalLayout nav = new HorizontalLayout(); nav.addComponent(new Button("<<", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { int lastPage = (int) Math.floor(totalTableData / noBeansPerPage); if (totalTableData % noBeansPerPage == 0) { lastPage--; } if (currentTableDataIndex > 0) { currentTableDataIndex = 0; tableDataIT.setBeans(dao.search(searchTerms, classOfBean, orderBy, asc, currentTableDataIndex, noBeansPerPage)); tableDataIT.refreshItems(); } int currentUpdatedPage = currentTableDataIndex / noBeansPerPage; pageLabel.setCaption(" " + (currentUpdatedPage + 1) + " of " + (lastPage + 1) + " "); } })); nav.addComponent(new Button("<", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { int lastPage = (int) Math.floor(totalTableData / noBeansPerPage); if (totalTableData % noBeansPerPage == 0) { lastPage--; } if (currentTableDataIndex > 0) { currentTableDataIndex -= noBeansPerPage; tableDataIT.setBeans(dao.search(searchTerms, classOfBean, orderBy, asc, currentTableDataIndex, noBeansPerPage)); tableDataIT.refreshItems(); } int currentUpdatedPage = currentTableDataIndex / noBeansPerPage; pageLabel.setCaption(" " + (currentUpdatedPage + 1) + " of " + (lastPage + 1) + " "); } })); nav.addComponent(pageLabel); nav.addComponent(new Button(">", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { int lastPage = (int) Math.floor(totalTableData / noBeansPerPage); if (totalTableData % noBeansPerPage == 0) { lastPage--; } int currentPage = currentTableDataIndex / noBeansPerPage; if (currentPage < lastPage) { currentTableDataIndex += noBeansPerPage; tableDataIT.setBeans(dao.search(searchTerms, classOfBean, orderBy, asc, currentTableDataIndex, noBeansPerPage)); tableDataIT.refreshItems(); } int currentUpdatedPage = currentTableDataIndex / noBeansPerPage; pageLabel.setCaption(" " + (currentUpdatedPage + 1) + " of " + (lastPage + 1) + " "); } })); nav.addComponent(new Button(">>", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { int lastPage = (int) Math.floor(totalTableData / noBeansPerPage); if (totalTableData % noBeansPerPage == 0) { lastPage--; } int currentPage = currentTableDataIndex / noBeansPerPage; if (currentPage < lastPage) { currentTableDataIndex = lastPage * noBeansPerPage; tableDataIT.setBeans(dao.search(searchTerms, classOfBean, orderBy, asc, currentTableDataIndex, noBeansPerPage)); tableDataIT.refreshItems(); } pageLabel.setCaption(" " + (lastPage + 1) + " of " + (lastPage + 1) + " "); } })); dataTableLayout.addComponent(nav); form.addComponent(dataTableLayout); //Handle sorting // Handle the header clicks dataTable.addHeaderClickListener(new Table.HeaderClickListener() { @Override public void headerClick(Table.HeaderClickEvent event) { String column = (String) event.getPropertyId(); if (orderBy.equals(column)) { asc = !asc; } orderBy = column; Collection<C> tableData = dao.search(searchTerms, classOfBean, orderBy, asc, currentTableDataIndex, noBeansPerPage); if (tableData.isEmpty()) { tableData.add(dao.createNew()); } tableDataIT.setBeans(tableData); tableDataIT.refreshItems(); //totalTableData = dao.countSearch(null, classOfBean); } }); // Disable the default sorting behavior dataTable.setSortEnabled(false); //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.getValue(); if (!currentBeans.isEmpty()) { C currentBean = currentBeans.iterator().next(); if (currentBean != null) { 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, "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.getValue(); 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); }*/ }