Example usage for com.vaadin.ui FormLayout addComponent

List of usage examples for com.vaadin.ui FormLayout addComponent

Introduction

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

Prototype

@Override
public void addComponent(Component c) 

Source Link

Document

Add a component into this container.

Usage

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

@Override
public void enter(final ViewChangeListener.ViewChangeEvent vcevent) {
    setCurrentView(vcevent.getViewName());
    //reset form// w w w . j a  v 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 {/*from  w  w w .j a v a2 s  .  c o  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;//  w  w  w .  j  a v  a  2  s . co  m
    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 w w w .j av a  2  s  .  com
    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.bitpimp.VaadinCurrencyConverter.MyVaadinApplication.java

License:Apache License

@Override
protected void init(VaadinRequest request) {
    // Set the window or tab title
    getPage().setTitle("Yahoo Currency Converter");

    // Create the content root layout for the UI
    final FormLayout content = new FormLayout();
    content.setMargin(true);//  w w w  .  j av  a2s.  com
    final Panel panel = new Panel(content);
    panel.setWidth("500");
    panel.setHeight("400");
    final VerticalLayout root = new VerticalLayout();
    root.addComponent(panel);
    root.setComponentAlignment(panel, Alignment.MIDDLE_CENTER);
    root.setSizeFull();
    root.setMargin(true);

    setContent(root);

    content.addComponent(new Embedded("",
            new ExternalResource("https://vaadin.com/vaadin-theme/images/vaadin/vaadin-logo-color.png")));
    content.addComponent(new Embedded("",
            new ExternalResource("http://images.wikia.com/logopedia/images/e/e4/YahooFinanceLogo.png")));

    // Display the greeting
    final Label heading = new Label("<b>Simple Currency Converter " + "Using YQL/Yahoo Finance Service</b>",
            ContentMode.HTML);
    heading.setWidth(null);
    content.addComponent(heading);

    // Build the set of fields for the converter form
    final TextField fromField = new TextField("From Currency", "AUD");
    fromField.setRequired(true);
    fromField.addValidator(new StringLengthValidator(CURRENCY_CODE_REQUIRED, 3, 3, false));
    content.addComponent(fromField);

    final TextField toField = new TextField("To Currency", "USD");
    toField.setRequired(true);
    toField.addValidator(new StringLengthValidator(CURRENCY_CODE_REQUIRED, 3, 3, false));
    content.addComponent(toField);

    final TextField resultField = new TextField("Result");
    resultField.setEnabled(false);
    content.addComponent(resultField);

    final TextField timeField = new TextField("Time");
    timeField.setEnabled(false);
    content.addComponent(timeField);

    final Button submitButton = new Button("Submit", new ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            // Do the conversion
            final String result = converter.convert(fromField.getValue().toUpperCase(),
                    toField.getValue().toUpperCase());
            if (result != null) {
                resultField.setValue(result);
                timeField.setValue(new Date().toString());
            }
        }
    });
    content.addComponent(submitButton);

    // Configure the error handler for the UI
    UI.getCurrent().setErrorHandler(new DefaultErrorHandler() {
        @Override
        public void error(com.vaadin.server.ErrorEvent event) {
            // Find the final cause
            String cause = "<b>The operation failed :</b><br/>";
            Throwable th = Throwables.getRootCause(event.getThrowable());
            if (th != null)
                cause += th.getClass().getName() + "<br/>";

            // Display the error message in a custom fashion
            content.addComponent(new Label(cause, ContentMode.HTML));

            // Do the default error handling (optional)
            doDefault(event);
        }
    });
}

From source file:org.esn.esobase.view.tab.SystemSettingsTab.java

public SystemSettingsTab(DBService service_) {
    this.service = service_;

    FormLayout fl = new FormLayout();
    isAutoSyncEnabledBox = new CheckBox("??? ");
    fl.addComponent(isAutoSyncEnabledBox);
    HorizontalLayout hl = new HorizontalLayout();
    Button saveButton = new Button("");
    saveButton.addClickListener(new Button.ClickListener() {

        @Override/*  w  w  w .  ja v a 2s.  c  o  m*/
        public void buttonClick(Button.ClickEvent event) {
            service.setIsAutoSynchronizationEnabled(isAutoSyncEnabledBox.getValue());
            LoadData();
            Notification notification = new Notification("?? ? ?",
                    Notification.Type.HUMANIZED_MESSAGE);
            notification.setDelayMsec(2000);
            notification.show(isAutoSyncEnabledBox.getUI().getPage());
        }
    });
    Button cancelButton = new Button("");
    cancelButton.addClickListener(new Button.ClickListener() {

        @Override
        public void buttonClick(Button.ClickEvent event) {
            LoadData();
        }
    });
    hl.addComponent(cancelButton);
    hl.addComponent(saveButton);
    fl.addComponent(hl);
    this.addComponent(fl);
    LoadData();
}

From source file:org.ikasan.dashboard.ui.framework.window.IkasanMessageDialog.java

License:BSD License

/**
 * Helper method to initialise this object.
 * //from   w ww.  ja  va  2  s.c  om
 * @param message
 */
protected void init(String message) {
    super.setModal(true);
    super.setResizable(false);
    super.center();

    FormLayout layout = new FormLayout();
    layout.setMargin(true);
    layout.addComponent(new Label(message));

    Button okButton = new Button("OK");
    okButton.setStyleName(ValoTheme.BUTTON_SMALL);

    okButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            action.exectuteAction();
            close();
        }
    });

    Button cancelButton = new Button("Cancel");
    cancelButton.setStyleName(ValoTheme.BUTTON_SMALL);

    cancelButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            action.ignoreAction();
            close();
        }
    });

    HorizontalLayout wrapper = new HorizontalLayout();
    wrapper.setWidth(100, Unit.PERCENTAGE);
    HorizontalLayout hlayout = new HorizontalLayout();
    wrapper.addComponent(hlayout);
    wrapper.setComponentAlignment(hlayout, Alignment.MIDDLE_CENTER);
    hlayout.addComponent(okButton);
    hlayout.addComponent(cancelButton);

    layout.addComponent(wrapper);

    super.setContent(layout);
}

From source file:org.investovator.ui.dataplayback.admin.DataPlaybackEngineAdminDashboard.java

License:Open Source License

public Component setupGameConfigBox() {
    FormLayout layout = new FormLayout();
    layout.setCaption("Game Configuration");
    layout.addStyleName("center-caption");

    GameTypes config = DataPlaybackEngineStates.gameConfig;

    //show the game description
    Label gameDescription = new Label(config.getDescription());
    layout.addComponent(gameDescription);
    gameDescription.setContentMode(ContentMode.HTML);
    gameDescription.setWidth(320, Unit.PIXELS);
    gameDescription.setCaption("Game: ");

    //add the player type
    Label playerType = new Label();
    layout.addComponent(playerType);/*  ww  w . j a v a 2  s.  c om*/
    playerType.setCaption("Player Type: ");
    playerType.setValue(player.getName());

    //show the attributes
    Label attributes = new Label(config.getInterestedAttributes().toString());
    layout.addComponent(attributes);
    attributes.setContentMode(ContentMode.HTML);
    attributes.setCaption("Attributes: ");

    //matching attribute
    Label matchingAttr = new Label(config.getAttributeToMatch().toString());
    layout.addComponent(matchingAttr);
    matchingAttr.setContentMode(ContentMode.HTML);
    matchingAttr.setCaption("Played On: ");

    return layout;

}

From source file:org.investovator.ui.dataplayback.admin.DataPlaybackEngineAdminDashboard.java

License:Open Source License

public Component setupGameStatsBox() {
    FormLayout layout = new FormLayout();
    layout.setCaption("Game Stats");
    layout.addStyleName("center-caption");

    //show game runtime
    final Label runTime = new Label();
    //push the changes
    UI.getCurrent().access(new Runnable() {
        @Override//from  w ww .j a va 2 s  .  c o  m
        public void run() {
            TimeZone defaultTz = TimeZone.getDefault();
            TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
            SimpleDateFormat sDate = new SimpleDateFormat("HH:mm:ss");
            runTime.setValue(sDate.format(new Date(player.getGameRuntime())));
            TimeZone.setDefault(defaultTz);
            getUI().push();

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    runTime.setCaption("Up Time: ");
    layout.addComponent(runTime);
    //start the time updating thread
    new Thread() {
        public void run() {
            //update forever
            while (true) {
                UI.getCurrent().access(new Runnable() {
                    @Override
                    public void run() {
                        TimeZone defaultTz = TimeZone.getDefault();
                        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
                        SimpleDateFormat sDate = new SimpleDateFormat("HH:mm:ss");
                        runTime.setValue(sDate.format(new Date(player.getGameRuntime())));
                        TimeZone.setDefault(defaultTz);
                        getUI().push();
                    }
                });

                //wait before updating
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }.start();

    //show market turnover
    Label turnover = new Label(Float.toString(player.getMarketTurnover()));
    turnover.setCaption("Market Turnover: ");
    layout.addComponent(turnover);

    //show total trades
    Label totalTrades = new Label(Integer.toString(player.getTotalTrades()));
    totalTrades.setCaption("Total Trades: ");
    layout.addComponent(totalTrades);

    return layout;
}

From source file:org.investovator.ui.dataplayback.user.dashboard.dailysummary.DailySummaryMultiPlayerMainView.java

License:Open Source License

public Component setUpAccountInfoForm() {
    FormLayout form = new FormLayout();

    try {/*from ww  w.java  2 s  .  c o m*/
        if (this.userName == null) {

            int bal = player.getInitialCredit();
            Label accountBalance = new Label(Integer.toString(bal));
            this.accBalance = accountBalance;
            accountBalance.setCaption("Account Balance");
            form.addComponent(accountBalance);

            int max = player.getMaxOrderSize();
            Label maxOrderSize = new Label(Integer.toString(max));
            maxOrderSize.setCaption("Max. Order Size");
            form.addComponent(maxOrderSize);
        } else {
            Double bal = player.getMyPortfolio(this.userName).getCashBalance();
            Label accountBalance = new Label(bal.toString());
            this.accBalance = accountBalance;
            accountBalance.setCaption("Account Balance");
            form.addComponent(accountBalance);

            int max = player.getMaxOrderSize();
            Label maxOrderSize = new Label(Integer.toString(max));
            maxOrderSize.setCaption("Max. Order Size");
            form.addComponent(maxOrderSize);
        }
    } catch (UserJoinException e) {
        e.printStackTrace();
    }

    return form;
}