com.vaadin.event.Action - java examples

Here are the examples of the java api com.vaadin.event.Action taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

32 Examples 7

19 View Complete Implementation : CmsAppView.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * @see com.vaadin.event.Action.Handler#handleAction(com.vaadin.event.Action, java.lang.Object, java.lang.Object)
 */
public void handleAction(Action action, Object sender, Object target) {
    if ((m_appActions != null) && m_appActions.containsKey(action)) {
        m_appActions.get(action).run();
    } else if (m_defaultActions.containsKey(action)) {
        m_defaultActions.get(action).run();
    }
}

19 View Complete Implementation : CmsAppView.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Displays the selected app.<p>
 */
public clreplaced CmsAppView implements ViewChangeListener, I_CmsWindowCloseListener, I_CmsAppView, Handler, BrowserWindowResizeListener {

    /**
     * Enum representing caching status of a view.<p>
     */
    public static enum CacheStatus {

        /**
         * Cache view.
         */
        cache,
        /**
         * Cache view one time only.
         */
        cacheOnce,
        /**
         * Don't cache view.
         */
        noCache
    }

    /**
     * Used in case the requested app can not be displayed to the current user.<p>
     */
    protected clreplaced NotAvailableApp implements I_CmsWorkplaceApp {

        /**
         * @see org.opencms.ui.apps.I_CmsWorkplaceApp#initUI(org.opencms.ui.apps.I_CmsAppUIContext)
         */
        public void initUI(I_CmsAppUIContext context) {
            Label label = new Label(CmsVaadinUtils.getMessageText(Messages.GUI_APP_NOT_AVAILABLE_0));
            label.addStyleName(ValoTheme.LABEL_H2);
            label.addStyleName(OpenCmsTheme.LABEL_ERROR);
            VerticalLayout content = new VerticalLayout();
            content.setMargin(true);
            content.addComponent(label);
            context.setAppContent(content);
        }

        /**
         * @see org.opencms.ui.apps.I_CmsWorkplaceApp#onStateChange(java.lang.String)
         */
        public void onStateChange(String state) {
        // nothing to do
        }
    }

    /**
     * The history back action.
     */
    private static final Action ACTION_HISTORY_BACK = new ShortcutAction("Alt+ArrowLeft", ShortcutAction.KeyCode.ARROW_LEFT, new int[] { ShortcutAction.ModifierKey.ALT });

    /**
     * The history forward action.
     */
    private static final Action ACTION_HISTORY_FORWARD = new ShortcutAction("Alt+ArrowRight", ShortcutAction.KeyCode.ARROW_RIGHT, new int[] { ShortcutAction.ModifierKey.ALT });

    /**
     * The serial version id.
     */
    private static final long serialVersionUID = -8128528863875050216L;

    /**
     * Logger instance for this clreplaced.
     */
    private static final Log LOG = CmsLog.getLog(CmsAppView.clreplaced);

    /**
     * The current app.
     */
    private I_CmsWorkplaceApp m_app;

    /**
     * The app shortcut actions.
     */
    private Map<Action, Runnable> m_appActions;

    /**
     * The app configuration.
     */
    private I_CmsWorkplaceAppConfiguration m_appConfig;

    /**
     * The app layout component.
     */
    private CmsAppViewLayout m_appLayout;

    /**
     * The cache status.
     */
    private CacheStatus m_cacheStatus = CacheStatus.noCache;

    /**
     * The default shortcut actions.
     */
    private Map<Action, Runnable> m_defaultActions;

    /**
     * The requires restore from cache flag.
     */
    private boolean m_requiresRestore;

    /**
     * Constructor.<p>
     *
     * @param appConfig the app configuration
     */
    public CmsAppView(I_CmsWorkplaceAppConfiguration appConfig) {
        m_appConfig = appConfig;
        m_defaultActions = new HashMap<Action, Runnable>();
        m_defaultActions.put(ACTION_HISTORY_BACK, new Runnable() {

            public void run() {
                ((CmsAppWorkplaceUi) UI.getCurrent()).historyBack();
            }
        });
        m_defaultActions.put(ACTION_HISTORY_FORWARD, new Runnable() {

            public void run() {
                ((CmsAppWorkplaceUi) UI.getCurrent()).historyForward();
            }
        });
    }

    /**
     * @see com.vaadin.navigator.ViewChangeListener#afterViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent)
     */
    public void afterViewChange(ViewChangeEvent event) {
        if (m_app instanceof ViewChangeListener) {
            ((ViewChangeListener) m_app).afterViewChange(event);
        }
    }

    /**
     * @see com.vaadin.navigator.ViewChangeListener#beforeViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent)
     */
    public boolean beforeViewChange(ViewChangeEvent event) {
        disableGlobalShortcuts();
        if (m_appLayout != null) {
            m_appLayout.closePopupViews();
        }
        if (m_app instanceof ViewChangeListener) {
            return ((ViewChangeListener) m_app).beforeViewChange(event);
        }
        return true;
    }

    /**
     * @see com.vaadin.server.Page.BrowserWindowResizeListener#browserWindowResized(com.vaadin.server.Page.BrowserWindowResizeEvent)
     */
    public void browserWindowResized(BrowserWindowResizeEvent event) {
        if (m_appLayout != null) {
            m_appLayout.browserWindowResized(event);
        }
    }

    /**
     * @see org.opencms.ui.I_CmsAppView#disableGlobalShortcuts()
     */
    public void disableGlobalShortcuts() {
        UI.getCurrent().removeActionHandler(this);
    }

    /**
     * @see org.opencms.ui.I_CmsAppView#enableGlobalShortcuts()
     */
    public void enableGlobalShortcuts() {
        // to avoid multiple action handler registration, remove this first
        UI.getCurrent().removeActionHandler(this);
        UI.getCurrent().addActionHandler(this);
    }

    /**
     * @see org.opencms.ui.I_CmsAppView#enter(java.lang.String)
     */
    public void enter(String newState) {
        injectAdditionalStyles();
        if (newState.startsWith(NavigationState.PARAM_SEPARATOR)) {
            newState = newState.substring(1);
        }
        if ((m_appLayout != null) && (m_appConfig != null)) {
            m_appLayout.setAppreplacedle(m_appConfig.getName(UI.getCurrent().getLocale()));
        }
        m_app.onStateChange(newState);
        if (m_app instanceof I_CmsHreplacedhortcutActions) {
            m_appActions = ((I_CmsHreplacedhortcutActions) m_app).getShortcutActions();
        }
        UI.getCurrent().addActionHandler(this);
    }

    /**
     * @see com.vaadin.navigator.View#enter(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent)
     */
    public void enter(ViewChangeEvent event) {
        String newState = event.getParameters();
        enter(newState);
    }

    /**
     * @see com.vaadin.event.Action.Handler#getActions(java.lang.Object, java.lang.Object)
     */
    public Action[] getActions(Object target, Object sender) {
        if (m_appActions != null) {
            Set<Action> actions = new HashSet<Action>(m_defaultActions.keySet());
            actions.addAll(m_appActions.keySet());
            return actions.toArray(new Action[actions.size()]);
        }
        return m_defaultActions.keySet().toArray(new Action[m_defaultActions.size()]);
    }

    /**
     * Gets the cache status of the view.<p>
     *
     * @return the cache status of the view
     */
    public CacheStatus getCacheStatus() {
        return m_cacheStatus;
    }

    /**
     * @see org.opencms.ui.I_CmsAppView#getComponent()
     */
    public CmsAppViewLayout getComponent() {
        if (m_app == null) {
            return reinitComponent();
        }
        return m_appLayout;
    }

    /**
     * @see org.opencms.ui.I_CmsAppView#getName()
     */
    public String getName() {
        return m_appConfig.getId();
    }

    /**
     * @see com.vaadin.event.Action.Handler#handleAction(com.vaadin.event.Action, java.lang.Object, java.lang.Object)
     */
    public void handleAction(Action action, Object sender, Object target) {
        if ((m_appActions != null) && m_appActions.containsKey(action)) {
            m_appActions.get(action).run();
        } else if (m_defaultActions.containsKey(action)) {
            m_defaultActions.get(action).run();
        }
    }

    /**
     * @see org.opencms.ui.I_CmsAppView#isCachable()
     */
    public boolean isCachable() {
        return (m_app instanceof I_CmsCachableApp) && ((I_CmsCachableApp) m_app).isCachable();
    }

    /**
     * @see org.opencms.ui.components.I_CmsWindowCloseListener#onWindowClose()
     */
    public void onWindowClose() {
        if (m_app instanceof I_CmsWindowCloseListener) {
            ((I_CmsWindowCloseListener) m_app).onWindowClose();
        }
        disableGlobalShortcuts();
    }

    /**
     * @see org.opencms.ui.I_CmsAppView#reinitComponent()
     */
    public CmsAppViewLayout reinitComponent() {
        if (m_app != null) {
            beforeViewChange(new ViewChangeEvent(CmsAppWorkplaceUi.get().getNavigator(), this, this, m_appConfig.getId(), ""));
        }
        if (!m_appConfig.getVisibility(A_CmsUI.getCmsObject()).isActive()) {
            m_app = new NotAvailableApp();
        } else {
            m_app = m_appConfig.getAppInstance();
        }
        m_appLayout = new CmsAppViewLayout(m_appConfig.getId());
        m_appLayout.setAppreplacedle(m_appConfig.getName(UI.getCurrent().getLocale()));
        m_app.initUI(m_appLayout);
        return m_appLayout;
    }

    /**
     * @see org.opencms.ui.I_CmsAppView#requiresRestore()
     */
    public boolean requiresRestore() {
        return m_requiresRestore;
    }

    /**
     * Restores the view from cache.<p>
     */
    public void restoreFromCache() {
        ((I_CmsCachableApp) m_app).onRestoreFromCache();
        m_requiresRestore = false;
    }

    /**
     * Sets the cache status.
     *
     * @param status the new cache status
     */
    public void setCacheStatus(CacheStatus status) {
        m_cacheStatus = status;
    }

    /**
     * @see org.opencms.ui.I_CmsAppView#setRequiresRestore(boolean)
     */
    public void setRequiresRestore(boolean restored) {
        m_requiresRestore = restored;
    }

    /**
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "appView " + getName() + System.idenreplacedyHashCode(this) + " (" + m_app + ")";
    }

    /**
     * Inject external stylesheets.
     */
    private void injectAdditionalStyles() {
        try {
            Collection<String> stylesheets = OpenCms.getWorkplaceAppManager().getAdditionalStyleSheets();
            for (String stylesheet : stylesheets) {
                A_CmsUI.get().getPage().addDependency(new Dependency(Type.STYLESHEET, stylesheet));
            }
        } catch (Exception e) {
            LOG.warn(e.getLocalizedMessage(), e);
        }
    }
}

19 View Complete Implementation : CmsOkCancelActionHandler.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * @see com.vaadin.event.Action.Handler#handleAction(com.vaadin.event.Action, java.lang.Object, java.lang.Object)
 */
public void handleAction(Action action, Object sender, Object target) {
    if (ENTER_ACTION.equals(action)) {
        ok();
    } else if (ESC_ACTION.equals(action)) {
        cancel();
    }
}

19 View Complete Implementation : CmsSourceEditor.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * The plain text editor.<p>
 */
@SuppressWarnings("deprecation")
public clreplaced CmsSourceEditor implements I_CmsEditor, I_CmsWindowCloseListener, ViewChangeListener, I_CmsHreplacedhortcutActions {

    /**
     * Stores the editor settings.<p>
     */
    public static clreplaced EditorSettings implements I_CmsAppSettings {

        /**
         * JSON key constant.
         */
        private static final String BRACKETS = "brackets";

        /**
         * JSON key constant.
         */
        private static final String FONTSIZE = "fontsize";

        /**
         * JSON key constant.
         */
        private static final String HIGHLIGHTING = "highlighting";

        /**
         * JSON key constant.
         */
        private static final String TABS = "tabs";

        /**
         * JSON key constant.
         */
        private static final String WRAPPING = "wrapping";

        /**
         * The auto close brackets flag.
         */
        boolean m_closeBrackets = true;

        /**
         * The font size.
         */
        String m_fontSize = "16px";

        /**
         * The highlighting flag.
         */
        boolean m_highlighting = true;

        /**
         * The line wrapping flag.
         */
        boolean m_lineWrapping;

        /**
         * The tab visibility flag.
         */
        boolean m_tabsVisible = true;

        /**
         * @see org.opencms.ui.apps.I_CmsAppSettings#getSettingsString()
         */
        public String getSettingsString() {
            JSONObject json = new JSONObject();
            try {
                json.put(BRACKETS, m_closeBrackets);
                json.put(HIGHLIGHTING, m_highlighting);
                json.put(WRAPPING, m_lineWrapping);
                json.put(FONTSIZE, m_fontSize);
                json.put(TABS, m_tabsVisible);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return json.toString();
        }

        /**
         * @see org.opencms.ui.apps.I_CmsAppSettings#restoreSettings(java.lang.String)
         */
        public void restoreSettings(String storedSettings) {
            try {
                JSONObject json = new JSONObject(storedSettings);
                if (json.has(BRACKETS)) {
                    m_closeBrackets = json.getBoolean(BRACKETS);
                }
                if (json.has(HIGHLIGHTING)) {
                    m_highlighting = json.getBoolean(HIGHLIGHTING);
                }
                if (json.has(WRAPPING)) {
                    m_lineWrapping = json.getBoolean(WRAPPING);
                }
                if (json.has(TABS)) {
                    m_tabsVisible = json.getBoolean(TABS);
                }
                if (json.has(FONTSIZE)) {
                    m_fontSize = json.getString(FONTSIZE);
                }
            } catch (JSONException e) {
            // LOG.error("Failed to restore file explorer settings from '" + storedSettings + "'", e);
            }
        }
    }

    /**
     * Exit shortcut.
     */
    private static final Action ACTION_EXIT = new ShortcutAction("Ctrl+Shift+X", ShortcutAction.KeyCode.X, new int[] { ShortcutAction.ModifierKey.CTRL, ShortcutAction.ModifierKey.SHIFT });

    /**
     * Exit shortcut, (using Apple CMD as modifier).
     */
    private static final Action ACTION_EXIT_CMD = new ShortcutAction("CMD+Shift+X", ShortcutAction.KeyCode.X, new int[] { ShortcutAction.ModifierKey.META, ShortcutAction.ModifierKey.SHIFT });

    /**
     * Save shortcut.
     */
    private static final Action ACTION_SAVE = new ShortcutAction("Ctrl+S", ShortcutAction.KeyCode.S, new int[] { ShortcutAction.ModifierKey.CTRL });

    /**
     * Save shortcut, (using Apple CMD as modifier).
     */
    private static final Action ACTION_SAVE_CMD = new ShortcutAction("CMD+S", ShortcutAction.KeyCode.S, new int[] { ShortcutAction.ModifierKey.META });

    /**
     * Save & Exit shortcut.
     */
    private static final Action ACTION_SAVE_AND_EXIT = new ShortcutAction("Ctrl+Shift+S", ShortcutAction.KeyCode.S, new int[] { ShortcutAction.ModifierKey.CTRL, ShortcutAction.ModifierKey.SHIFT });

    /**
     * Save & Exit shortcut, (using Apple CMD as modifier).
     */
    private static final Action ACTION_SAVE_AND_EXIT_CMD = new ShortcutAction("CMD+Shift+S", ShortcutAction.KeyCode.S, new int[] { ShortcutAction.ModifierKey.META, ShortcutAction.ModifierKey.SHIFT });

    /**
     * The available font sizes.
     */
    private static final String[] FONT_SIZES = new String[] { "8px", "10px", "12px", "14px", "16px", "18px", "20px" };

    /**
     * The serial version id.
     */
    private static final long serialVersionUID = 726920483145397926L;

    /**
     * The editor back link.
     */
    String m_backLink;

    /**
     * The code mirror instance.
     */
    CmsCodeMirror m_codeMirror;

    /**
     * The bundle editor shortcuts.
     */
    Map<Action, Runnable> m_shortcutActions;

    /**
     * The content changed flag.
     */
    private boolean m_changed;

    /**
     * The cleared flag.
     */
    private boolean m_cleared;

    /**
     * The exit button.
     */
    private Button m_exit;

    /**
     * The current file.
     */
    private LockedFile m_file;

    /**
     * The save button.
     */
    private Button m_save;

    /**
     * The save and exit button.
     */
    private Button m_saveAndExit;

    /**
     * Constructor.<p>
     */
    public CmsSourceEditor() {
        m_shortcutActions = new HashMap<Action, Runnable>();
        Runnable save = new Runnable() {

            public void run() {
                save();
            }
        };
        m_shortcutActions.put(ACTION_SAVE, save);
        m_shortcutActions.put(ACTION_SAVE_CMD, save);
        Runnable saveExit = new Runnable() {

            public void run() {
                saveAndExit();
            }
        };
        m_shortcutActions.put(ACTION_SAVE_AND_EXIT, saveExit);
        m_shortcutActions.put(ACTION_SAVE_AND_EXIT_CMD, saveExit);
        Runnable exit = new Runnable() {

            public void run() {
                exit();
            }
        };
        m_shortcutActions.put(ACTION_EXIT, exit);
        m_shortcutActions.put(ACTION_EXIT_CMD, exit);
    }

    /**
     * @see com.vaadin.navigator.ViewChangeListener#afterViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent)
     */
    public void afterViewChange(ViewChangeEvent event) {
    // nothing to do
    }

    /**
     * @see com.vaadin.navigator.ViewChangeListener#beforeViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent)
     */
    public boolean beforeViewChange(final ViewChangeEvent event) {
        if (m_changed) {
            CmsConfirmationDialog.show(CmsVaadinUtils.getMessageText(org.opencms.ui.apps.Messages.GUI_EDITOR_CLOSE_CAPTION_0), CmsVaadinUtils.getMessageText(org.opencms.ui.apps.Messages.GUI_EDITOR_CLOSE_TEXT_0), new Runnable() {

                public void run() {
                    clear();
                    event.getNavigator().navigateTo(event.getViewName());
                }
            });
            return false;
        }
        if (!m_cleared) {
            clear();
        }
        return true;
    }

    /**
     * Returns the syntax highlighting type for the currently edited resource.<p>
     *
     * @param resource the resource to edit
     *
     * @return the syntax highlighting type
     */
    public CodeMirrorLanguage getHighlightMode(CmsResource resource) {
        if (resource != null) {
            // determine resource type
            int type = resource.getTypeId();
            if (CmsResourceTypeJsp.isJspTypeId(type)) {
                // JSP file
                return CodeMirrorLanguage.JSP;
            }
            if (CmsResourceTypeXmlContent.isXmlContent(resource) || CmsResourceTypeXmlPage.isXmlPage(resource)) {
                // XML content file or XML page file
                return CodeMirrorLanguage.XML;
            }
            // all other files will be matched according to their suffix
            int dotIndex = resource.getName().lastIndexOf('.');
            if (dotIndex != -1) {
                String suffix = resource.getName().substring(dotIndex + 1).toLowerCase();
                for (CodeMirrorLanguage lang : CodeMirrorLanguage.values()) {
                    if (lang.isSupportedFileType(suffix)) {
                        return lang;
                    }
                }
            }
        }
        // return HTML type as default
        return CodeMirrorLanguage.HTML;
    }

    /**
     * @see org.opencms.ui.editors.I_CmsEditor#getPriority()
     */
    public int getPriority() {
        return 10;
    }

    /**
     * @see org.opencms.ui.apps.I_CmsHreplacedhortcutActions#getShortcutActions()
     */
    public Map<Action, Runnable> getShortcutActions() {
        return m_shortcutActions;
    }

    /**
     * @see org.opencms.ui.editors.I_CmsEditor#initUI(org.opencms.ui.apps.I_CmsAppUIContext, org.opencms.file.CmsResource, java.lang.String, java.util.Map)
     */
    public void initUI(I_CmsAppUIContext context, CmsResource resource, String backLink, Map<String, String> params) {
        CmsMessages messages = Messages.get().getBundle(UI.getCurrent().getLocale());
        context.showInfoArea(false);
        context.setAppreplacedle(messages.key(Messages.GUI_SOURCE_EDITOR_replacedLE_0));
        CmsAppWorkplaceUi.setWindowreplacedle(CmsVaadinUtils.getMessageText(org.opencms.ui.apps.Messages.GUI_CONTENT_EDITOR_replacedLE_2, resource.getName(), CmsResource.getParentFolder(A_CmsUI.getCmsObject().getSitePath(resource))));
        m_backLink = backLink;
        m_codeMirror = new CmsCodeMirror();
        m_codeMirror.setSizeFull();
        context.setAppContent(m_codeMirror);
        context.enableDefaultToolbarButtons(false);
        m_saveAndExit = CmsToolBar.createButton(FontOpenCms.SAVE_EXIT, messages.key(Messages.GUI_BUTTON_SAVE_AND_EXIT_0), true);
        m_saveAndExit.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                saveAndExit();
            }
        });
        m_saveAndExit.setEnabled(false);
        context.addToolbarButton(m_saveAndExit);
        m_save = CmsToolBar.createButton(FontOpenCms.SAVE, messages.key(Messages.GUI_BUTTON_SAVE_0), true);
        m_save.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                save();
            }
        });
        m_save.setEnabled(false);
        context.addToolbarButton(m_save);
        Button undo = CmsToolBar.createButton(FontOpenCms.UNDO, messages.key(Messages.GUI_BUTTON_UNDO_0), true);
        context.addToolbarButton(undo);
        Button redo = CmsToolBar.createButton(FontOpenCms.REDO, messages.key(Messages.GUI_BUTTON_REDO_0), true);
        context.addToolbarButton(redo);
        m_codeMirror.registerUndoRedo(undo, redo);
        Button search = CmsToolBar.createButton(FontOpenCms.SEARCH, messages.key(Messages.GUI_BUTTON_SEARCH_0), true);
        context.addToolbarButton(search);
        Button replace = CmsToolBar.createButton(FontOpenCms.SEARCH_REPLACE, messages.key(Messages.GUI_BUTTON_REPLACE_0), true);
        context.addToolbarButton(replace);
        m_codeMirror.registerSearchReplace(search, replace);
        EditorSettings settings;
        try {
            settings = OpenCms.getWorkplaceAppManager().getAppSettings(A_CmsUI.getCmsObject(), EditorSettings.clreplaced);
        } catch (Exception e) {
            settings = new EditorSettings();
        }
        final Button toggleHighlight = CmsToolBar.createButton(FontOpenCms.HIGHLIGHT, messages.key(Messages.GUI_BUTTON_TOGGLE_HIGHLIGHTING_0));
        toggleHighlight.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                Button b = event.getButton();
                boolean pressed = b.getStyleName().contains(OpenCmsTheme.BUTTON_PRESSED);
                if (pressed) {
                    b.removeStyleName(OpenCmsTheme.BUTTON_PRESSED);
                } else {
                    b.addStyleName(OpenCmsTheme.BUTTON_PRESSED);
                }
                m_codeMirror.setHighlighting(!pressed);
            }
        });
        if (settings.m_highlighting) {
            m_codeMirror.setHighlighting(true);
            toggleHighlight.addStyleName(OpenCmsTheme.BUTTON_PRESSED);
        } else {
            m_codeMirror.setHighlighting(false);
        }
        context.addToolbarButtonRight(toggleHighlight);
        final Button toggleLineWrap = CmsToolBar.createButton(FontOpenCms.WRAP_LINES, messages.key(Messages.GUI_BUTTON_TOGGLE_LINE_WRAPPING_0));
        toggleLineWrap.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                Button b = event.getButton();
                boolean pressed = b.getStyleName().contains(OpenCmsTheme.BUTTON_PRESSED);
                if (pressed) {
                    b.removeStyleName(OpenCmsTheme.BUTTON_PRESSED);
                } else {
                    b.addStyleName(OpenCmsTheme.BUTTON_PRESSED);
                }
                m_codeMirror.setLineWrapping(!pressed);
            }
        });
        if (settings.m_lineWrapping) {
            m_codeMirror.setLineWrapping(true);
            toggleLineWrap.addStyleName(OpenCmsTheme.BUTTON_PRESSED);
        } else {
            m_codeMirror.setLineWrapping(false);
        }
        context.addToolbarButtonRight(toggleLineWrap);
        final Button toggleBrackets = CmsToolBar.createButton(FontOpenCms.BRACKETS, messages.key(Messages.GUI_BUTTON_TOBBLE_BRACKET_AUTOCLOSE_0));
        toggleBrackets.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                Button b = event.getButton();
                boolean pressed = b.getStyleName().contains(OpenCmsTheme.BUTTON_PRESSED);
                if (pressed) {
                    b.removeStyleName(OpenCmsTheme.BUTTON_PRESSED);
                } else {
                    b.addStyleName(OpenCmsTheme.BUTTON_PRESSED);
                }
                m_codeMirror.setCloseBrackets(!pressed);
            }
        });
        if (settings.m_closeBrackets) {
            m_codeMirror.setCloseBrackets(true);
            toggleBrackets.addStyleName(OpenCmsTheme.BUTTON_PRESSED);
        } else {
            m_codeMirror.setCloseBrackets(false);
        }
        context.addToolbarButtonRight(toggleBrackets);
        final Button toggleTabs = CmsToolBar.createButton(FontOpenCms.INVISIBLE_CHARS, messages.key(Messages.GUI_BUTTON_TOGGLE_TAB_VISIBILITY_0));
        toggleTabs.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                Button b = event.getButton();
                boolean pressed = b.getStyleName().contains(OpenCmsTheme.BUTTON_PRESSED);
                if (pressed) {
                    b.removeStyleName(OpenCmsTheme.BUTTON_PRESSED);
                } else {
                    b.addStyleName(OpenCmsTheme.BUTTON_PRESSED);
                }
                m_codeMirror.setTabsVisible(!pressed);
            }
        });
        if (settings.m_tabsVisible) {
            m_codeMirror.setTabsVisible(true);
            toggleTabs.addStyleName(OpenCmsTheme.BUTTON_PRESSED);
        } else {
            m_codeMirror.setTabsVisible(false);
        }
        context.addToolbarButtonRight(toggleTabs);
        ComboBox modeSelect = new ComboBox();
        modeSelect.setWidth("115px");
        modeSelect.addStyleName(OpenCmsTheme.TOOLBAR_FIELD);
        modeSelect.addStyleName(OpenCmsTheme.REQUIRED_BUTTON);
        modeSelect.setNullSelectionAllowed(false);
        modeSelect.setImmediate(true);
        modeSelect.setNewItemsAllowed(false);
        for (CodeMirrorLanguage lang : CodeMirrorLanguage.values()) {
            modeSelect.addItem(lang);
            modeSelect.sereplacedemCaption(lang, lang.name());
        }
        CodeMirrorLanguage lang = getHighlightMode(resource);
        modeSelect.setValue(lang);
        m_codeMirror.setLanguage(lang);
        modeSelect.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            public void valueChange(ValueChangeEvent event) {
                m_codeMirror.setLanguage((CodeMirrorLanguage) event.getProperty().getValue());
            }
        });
        context.addToolbarButtonRight(modeSelect);
        ComboBox fontSizeSelect = new ComboBox();
        fontSizeSelect.setWidth("75px");
        fontSizeSelect.addStyleName(OpenCmsTheme.TOOLBAR_FIELD);
        fontSizeSelect.addStyleName(OpenCmsTheme.REQUIRED_BUTTON);
        fontSizeSelect.setNullSelectionAllowed(false);
        fontSizeSelect.setImmediate(true);
        fontSizeSelect.setNewItemsAllowed(false);
        for (int i = 0; i < FONT_SIZES.length; i++) {
            fontSizeSelect.addItem(FONT_SIZES[i]);
        }
        fontSizeSelect.setValue(settings.m_fontSize);
        fontSizeSelect.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            public void valueChange(ValueChangeEvent event) {
                m_codeMirror.setFontSize((String) event.getProperty().getValue());
            }
        });
        context.addToolbarButtonRight(fontSizeSelect);
        m_codeMirror.setFontSize(settings.m_fontSize);
        m_exit = CmsToolBar.createButton(FontOpenCms.EXIT, messages.key(Messages.GUI_BUTTON_CANCEL_0), true);
        m_exit.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                exit();
            }
        });
        context.addToolbarButtonRight(m_exit);
        try {
            m_file = LockedFile.lockResource(A_CmsUI.getCmsObject(), resource);
            String content = new String(m_file.getFile().getContents(), m_file.getEncoding());
            m_codeMirror.setValue(content);
        } catch (Exception e) {
            CmsErrorDialog.showErrorDialog(e);
        }
        m_codeMirror.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            public void valueChange(ValueChangeEvent event) {
                onChange((String) event.getProperty().getValue());
            }
        });
    }

    /**
     * @see org.opencms.ui.editors.I_CmsEditor#matchesResource(org.opencms.file.CmsResource, boolean)
     */
    public boolean matchesResource(CmsResource resource, boolean plainText) {
        I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(resource);
        return matchesType(type, plainText);
    }

    /**
     * @see org.opencms.ui.editors.I_CmsEditor#matchesType(org.opencms.file.types.I_CmsResourceType, boolean)
     */
    public boolean matchesType(I_CmsResourceType type, boolean plainText) {
        return !((type instanceof CmsResourceTypeBinary) || (type instanceof CmsResourceTypeImage));
    }

    /**
     * @see org.opencms.ui.editors.I_CmsEditor#newInstance()
     */
    public I_CmsEditor newInstance() {
        return new CmsSourceEditor();
    }

    /**
     * @see org.opencms.ui.components.I_CmsWindowCloseListener#onWindowClose()
     */
    public void onWindowClose() {
        clear();
    }

    /**
     * Unlocks the edited file before leaving the editor.<p>
     */
    void clear() {
        m_cleared = true;
        m_changed = false;
        m_file.tryUnlock();
        OpenCms.getWorkplaceAppManager().storeAppSettings(A_CmsUI.getCmsObject(), EditorSettings.clreplaced, getCurrentSettings());
    }

    /**
     * Exits the editor without saving.<p>
     * Will ask to confirm exit on changed contents.<p>
     */
    void exit() {
        if (m_changed) {
            CmsConfirmationDialog.show(CmsVaadinUtils.getMessageText(org.opencms.ui.apps.Messages.GUI_EDITOR_CLOSE_CAPTION_0), CmsVaadinUtils.getMessageText(org.opencms.ui.apps.Messages.GUI_EDITOR_CLOSE_TEXT_0), new Runnable() {

                public void run() {
                    exitInternal();
                }
            });
        } else {
            exitInternal();
        }
    }

    /**
     * Exits the editor without saving.<p>
     */
    void exitInternal() {
        clear();
        CmsEditor.openBackLink(m_backLink);
    }

    /**
     * Called on content change.<p>
     *
     * @param value the changed content value
     */
    void onChange(String value) {
        m_changed = true;
        m_save.setEnabled(true);
        m_saveAndExit.setEnabled(true);
    }

    /**
     * Saves the current editor content.<p>
     */
    void save() {
        try {
            byte[] content = m_codeMirror.getValue().getBytes(m_file.getEncoding());
            m_file.getFile().setContents(content);
            A_CmsUI.getCmsObject().writeFile(m_file.getFile());
            m_changed = false;
            m_save.setEnabled(false);
            m_saveAndExit.setEnabled(false);
        } catch (Exception e) {
            CmsErrorDialog.showErrorDialog(e);
        }
    }

    /**
     * Saves the current editor content and leaves the editor.<p>
     */
    void saveAndExit() {
        save();
        exit();
    }

    /**
     * Returns the current editor settings.<p>
     *
     * @return the current editor settings
     */
    private EditorSettings getCurrentSettings() {
        EditorSettings result = new EditorSettings();
        result.m_closeBrackets = m_codeMirror.isCloseBrackets();
        result.m_lineWrapping = m_codeMirror.isLineWrapping();
        result.m_highlighting = m_codeMirror.isHighlighting();
        result.m_tabsVisible = m_codeMirror.isTabsVisible();
        result.m_fontSize = m_codeMirror.getFontSize();
        return result;
    }
}

19 View Complete Implementation : PIPSQLResolverEditorWindow.java
Copyright Apache License 2.0
Author : apache
@Override
public void handleAction(Action action, Object sender, Object target) {
    if (action == ADD_ATTRIBUTE) {
        if (sender.equals(this.tableRequiredAttributes)) {
            this.editAttribute(self.tableRequiredAttributes, null);
        } else {
            this.editAttribute(self.tableAttributes, null);
        }
        return;
    }
    if (action == EDIT_ATTRIBUTE) {
        replacedert target instanceof ResolverAttribute;
        if (sender.equals(this.tableRequiredAttributes)) {
            this.editAttribute(self.tableRequiredAttributes, (ResolverAttribute) target);
        } else {
            this.editAttribute(self.tableAttributes, (ResolverAttribute) target);
        }
        return;
    }
    if (action == CLONE_ATTRIBUTE) {
        replacedert target instanceof ResolverAttribute;
        try {
            // 
            // Which table?
            // 
            if (sender.equals(this.tableRequiredAttributes)) {
                // 
                // Clone the attribute giving it a new
                // field name.
                // 
                ResolverAttribute clone = new ResolverAttribute(this.fieldPrefix, this.getNextField(), (ResolverAttribute) target);
                // 
                // Add it to the container
                // 
                this.fieldsContainer.addBean(clone);
                // 
                // Reset the page length so we can see it and have room
                // to add another.
                // 
                this.tableRequiredAttributes.setPageLength(this.fieldsContainer.size() + 1);
                // 
                // Select it
                // 
                this.tableRequiredAttributes.select(clone);
            } else {
                // 
                // Clone the attribute giving it a new
                // field name.
                // 
                ResolverAttribute clone = new ResolverAttribute(this.parameterPrefix, this.getNextParameter(), (ResolverAttribute) target);
                // 
                // Add it to the container
                // 
                this.parametersContainer.addBean(clone);
                // 
                // Reset the page length so we can see it and have room
                // to add another.
                // 
                this.tableAttributes.setPageLength(this.parametersContainer.size() + 1);
                // 
                // Select it
                // 
                this.tableAttributes.select(clone);
            }
            // 
            // We have changed
            // 
            this.fireFormChangedEvent();
        } catch (Exception e) {
            logger.error("Failed to clone: " + e);
        }
        return;
    }
    if (action == REMOVE_ATTRIBUTE) {
        replacedert target instanceof ResolverAttribute;
        // 
        // Help method to remove the attribute
        // 
        this.removeAttribute((ResolverAttribute) target);
        // 
        // Which table?
        // 
        if (sender.equals(this.tableRequiredAttributes)) {
            // 
            // Now remove it from the table
            // 
            this.tableRequiredAttributes.removeItem(target);
        } else {
            // 
            // Now remove it from the table
            // 
            this.tableAttributes.removeItem(target);
        }
        // 
        // we have changed
        // 
        this.fireFormChangedEvent();
        return;
    }
}

19 View Complete Implementation : TBSLApplication.java
Copyright GNU General Public License v3.0
Author : AskNowQA
/**
 * The Application's "main" clreplaced
 */
@SuppressWarnings("serial")
public clreplaced TBSLApplication extends Application implements ParameterHandler {

    private MainView mainView;

    Action action_query = new ShortcutAction("Ctrl+Q", ShortcutAction.KeyCode.Q, new int[] { ShortcutAction.ModifierKey.CTRL });

    private String endpoint;

    private String question;

    @Override
    public void init() {
        // Create the application data instance
        UserSession sessionData = new UserSession(this);
        // Register it as a listener in the application context
        getContext().addTransactionListener(sessionData);
        setTheme("custom");
        ViewHandler.initialize(this);
        SessionHandler.initialize(this);
        Permissions.initialize(this, new JPAPermissionManager());
        Window mainWindow = new Window("AutoSPARQL TBSL");
        mainWindow.addParameterHandler(this);
        setMainWindow(mainWindow);
        mainView = new MainView();
        mainWindow.setContent(mainView);
        mainWindow.setSizeFull();
        setLogoutURL("http://aksw.org");
        mainWindow.addActionHandler(new Action.Handler() {

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == action_query) {
                    onShowLearnedQuery();
                }
            }

            @Override
            public Action[] getActions(Object target, Object sender) {
                return new Action[] { action_query };
            }
        });
    }

    private void onShowLearnedQuery() {
        String learnedSPARQLQuery = UserSession.getManager().getLearnedSPARQLQuery();
        VerticalLayout layout = new VerticalLayout();
        final Window w = new Window("Learned SPARQL Query", layout);
        w.setWidth("300px");
        w.setSizeUndefined();
        w.setPositionX(200);
        w.setPositionY(100);
        getMainWindow().addWindow(w);
        w.addListener(new Window.CloseListener() {

            @Override
            public void windowClose(CloseEvent e) {
                getMainWindow().removeWindow(w);
            }
        });
        Label queryLabel = new Label(learnedSPARQLQuery, Label.CONTENT_PREFORMATTED);
        queryLabel.setWidth(null);
        layout.addComponent(queryLabel);
        Label nlLabel = new Label(UserSession.getManager().getNLRepresentation(learnedSPARQLQuery));
        layout.addComponent(nlLabel);
    }

    @Override
    public void terminalError(Terminal.ErrorEvent event) {
        // Call the default implementation.
        super.terminalError(event);
    // Some custom behaviour.
    // if (getMainWindow() != null) {
    // getMainWindow().showNotification(
    // "An unchecked exception occured!",
    // event.getThrowable().toString(),
    // Notification.TYPE_ERROR_MESSAGE);
    // }
    }

    @Override
    public void handleParameters(Map<String, String[]> parameters) {
        String[] endpointArray = parameters.get(URLParameters.ENDPOINT);
        if (endpointArray != null && endpointArray.length == 1) {
            endpoint = endpointArray[0];
            System.out.println("URL param: " + endpoint);
        }
        String[] questionArray = parameters.get(URLParameters.QUESTION);
        if (questionArray != null && endpointArray.length == 1) {
            question = questionArray[0];
            System.out.println("URL param: " + question);
        }
        if (endpoint != null && question != null) {
            mainView.initWithParams(endpoint, question);
        }
    }
}

19 View Complete Implementation : PIPSQLResolverEditorWindow.java
Copyright MIT License
Author : att
@Override
public void handleAction(Action action, Object sender, Object target) {
    if (action == ADD_ATTRIBUTE) {
        if (sender.equals(this.tableRequiredAttributes)) {
            this.editAttribute(self.tableRequiredAttributes, null);
        } else {
            this.editAttribute(self.tableAttributes, null);
        }
        return;
    }
    if (action == EDIT_ATTRIBUTE) {
        replacedert (target instanceof ResolverAttribute);
        if (sender.equals(this.tableRequiredAttributes)) {
            this.editAttribute(self.tableRequiredAttributes, (ResolverAttribute) target);
        } else {
            this.editAttribute(self.tableAttributes, (ResolverAttribute) target);
        }
        return;
    }
    if (action == CLONE_ATTRIBUTE) {
        replacedert (target instanceof ResolverAttribute);
        try {
            // 
            // Which table?
            // 
            if (sender.equals(this.tableRequiredAttributes)) {
                // 
                // Clone the attribute giving it a new
                // field name.
                // 
                ResolverAttribute clone = new ResolverAttribute(this.fieldPrefix, this.getNextField(), (ResolverAttribute) target);
                // 
                // Add it to the container
                // 
                this.fieldsContainer.addBean(clone);
                // 
                // Reset the page length so we can see it and have room
                // to add another.
                // 
                this.tableRequiredAttributes.setPageLength(this.fieldsContainer.size() + 1);
                // 
                // Select it
                // 
                this.tableRequiredAttributes.select(clone);
            } else {
                // 
                // Clone the attribute giving it a new
                // field name.
                // 
                ResolverAttribute clone = new ResolverAttribute(this.parameterPrefix, this.getNextParameter(), (ResolverAttribute) target);
                // 
                // Add it to the container
                // 
                this.parametersContainer.addBean(clone);
                // 
                // Reset the page length so we can see it and have room
                // to add another.
                // 
                this.tableAttributes.setPageLength(this.parametersContainer.size() + 1);
                // 
                // Select it
                // 
                this.tableAttributes.select(clone);
            }
            // 
            // We have changed
            // 
            this.fireFormChangedEvent();
        } catch (Exception e) {
            logger.error("Failed to clone: " + e);
        }
        return;
    }
    if (action == REMOVE_ATTRIBUTE) {
        replacedert (target instanceof ResolverAttribute);
        // 
        // Help method to remove the attribute
        // 
        this.removeAttribute((ResolverAttribute) target);
        // 
        // Which table?
        // 
        if (sender.equals(this.tableRequiredAttributes)) {
            // 
            // Now remove it from the table
            // 
            this.tableRequiredAttributes.removeItem(target);
        } else {
            // 
            // Now remove it from the table
            // 
            this.tableAttributes.removeItem(target);
        }
        // 
        // we have changed
        // 
        this.fireFormChangedEvent();
        return;
    }
}

19 View Complete Implementation : TableActionHandler.java
Copyright Apache License 2.0
Author : chelu
/**
 * Handle the action
 * @param action the action
 * @param sender component that send action
 * @param target target
 */
private void doHandleAction(Action action, Object sender, Object target) {
// Do nothing by default.
}

19 View Complete Implementation : TableActionHandler.java
Copyright Apache License 2.0
Author : chelu
@Override
public void handleAction(Action action, Object sender, Object target) {
    if (action instanceof Action.Handler) {
        ((Action.Handler) action).handleAction(action, sender, target);
    } else if (action instanceof ButtonListener) {
        ((ButtonListener) action).buttonClick(new ClickEvent((Component) sender));
    } else {
        doHandleAction(action, sender, target);
    }
}

19 View Complete Implementation : MainTabSheetActionHandler.java
Copyright Apache License 2.0
Author : cuba-platform
public clreplaced MainTabSheetActionHandler implements Action.Handler {

    protected com.vaadin.event.Action closeAllTabs;

    protected com.vaadin.event.Action closeOtherTabs;

    protected com.vaadin.event.Action closeCurrentTab;

    protected com.vaadin.event.Action showInfo;

    protected com.vaadin.event.Action replacedyzeLayout;

    protected com.vaadin.event.Action saveSettings;

    protected com.vaadin.event.Action restoreToDefaults;

    protected boolean initialized = false;

    protected HasTabSheetBehaviour tabSheet;

    public MainTabSheetActionHandler(HasTabSheetBehaviour tabSheet) {
        this.tabSheet = tabSheet;
    }

    @Override
    public Action[] getActions(Object target, Object sender) {
        if (!initialized) {
            Messages messages = AppBeans.get(Messages.NAME);
            closeAllTabs = new com.vaadin.event.Action(messages.getMainMessage("actions.closeAllTabs"));
            closeOtherTabs = new com.vaadin.event.Action(messages.getMainMessage("actions.closeOtherTabs"));
            closeCurrentTab = new com.vaadin.event.Action(messages.getMainMessage("actions.closeCurrentTab"));
            showInfo = new com.vaadin.event.Action(messages.getMainMessage("actions.showInfo"));
            replacedyzeLayout = new com.vaadin.event.Action(messages.getMainMessage("actions.replacedyzeLayout"));
            saveSettings = new com.vaadin.event.Action(messages.getMainMessage("actions.saveSettings"));
            restoreToDefaults = new com.vaadin.event.Action(messages.getMainMessage("actions.restoreToDefaults"));
            initialized = true;
        }
        List<Action> actions = new ArrayList<>(5);
        actions.add(closeCurrentTab);
        actions.add(closeOtherTabs);
        actions.add(closeAllTabs);
        if (target != null) {
            Configuration configuration = AppBeans.get(Configuration.NAME);
            ClientConfig clientConfig = configuration.getConfig(ClientConfig.clreplaced);
            if (clientConfig.getManualScreenSettingsSaving()) {
                actions.add(saveSettings);
                actions.add(restoreToDefaults);
            }
            UserSessionSource sessionSource = AppBeans.get(UserSessionSource.NAME);
            UserSession userSession = sessionSource.getUserSession();
            if (userSession.isSpecificPermitted(ShowInfoAction.ACTION_PERMISSION) && findEditor((Layout) target) != null) {
                actions.add(showInfo);
            }
            if (clientConfig.getLayoutreplacedyzerEnabled()) {
                actions.add(replacedyzeLayout);
            }
        }
        return actions.toArray(new Action[0]);
    }

    @Override
    public void handleAction(Action action, Object sender, Object target) {
        TabSheetBehaviour tabSheetBehaviour = tabSheet.getTabSheetBehaviour();
        if (initialized) {
            if (closeCurrentTab == action) {
                tabSheetBehaviour.closeTab((com.vaadin.ui.Component) target);
            } else if (closeOtherTabs == action) {
                tabSheetBehaviour.closeOtherTabs((com.vaadin.ui.Component) target);
            } else if (closeAllTabs == action) {
                tabSheetBehaviour.closeAllTabs();
            } else if (showInfo == action) {
                showInfo(target);
            } else if (replacedyzeLayout == action) {
                replacedyzeLayout(target);
            } else if (saveSettings == action) {
                saveSettings(target);
            } else if (restoreToDefaults == action) {
                restoreToDefaults(target);
            }
        }
    }

    protected void showInfo(Object target) {
        AbstractEditor editor = (AbstractEditor) findEditor((Layout) target);
        Enreplacedy enreplacedy = editor.gereplacedem();
        Metadata metadata = AppBeans.get(Metadata.NAME);
        MetaClreplaced metaClreplaced = metadata.getSession().getClreplaced(enreplacedy.getClreplaced());
        new ShowInfoAction().showInfo(enreplacedy, metaClreplaced, editor);
    }

    protected void replacedyzeLayout(Object target) {
        Window window = findWindow((Layout) target);
        if (window != null) {
            Layoutreplacedyzer replacedyzer = new Layoutreplacedyzer();
            List<LayoutTip> tipsList = replacedyzer.replacedyze(window);
            if (tipsList.isEmpty()) {
                Notifications notifications = ComponentsHelper.getScreenContext(window).getNotifications();
                notifications.create(NotificationType.HUMANIZED).withCaption("No layout problems found").show();
            } else {
                WindowManager wm = (WindowManager) ComponentsHelper.getScreenContext(window).getScreens();
                WindowInfo windowInfo = AppBeans.get(WindowConfig.clreplaced).getWindowInfo("layoutreplacedyzer");
                wm.openWindow(windowInfo, WindowManager.OpenType.DIALOG, ParamsMap.of("tipsList", tipsList));
            }
        }
    }

    @Nullable
    protected com.haulmont.cuba.gui.components.Window getWindow(Object target) {
        if (target instanceof Layout) {
            Layout layout = (Layout) target;
            for (Component component : layout) {
                if (component instanceof WindowBreadCrumbs) {
                    WindowBreadCrumbs breadCrumbs = (WindowBreadCrumbs) component;
                    return breadCrumbs.getCurrentWindow();
                }
            }
        }
        return null;
    }

    protected void restoreToDefaults(Object target) {
        com.haulmont.cuba.gui.components.Window window = getWindow(target);
        if (window != null) {
            window.deleteSettings();
        }
    }

    protected void saveSettings(Object target) {
        com.haulmont.cuba.gui.components.Window window = getWindow(target);
        if (window != null) {
            window.saveSettings();
        }
    }

    protected com.haulmont.cuba.gui.components.Window.Editor findEditor(Layout layout) {
        for (Object component : layout) {
            if (component instanceof WindowBreadCrumbs) {
                WindowBreadCrumbs breadCrumbs = (WindowBreadCrumbs) component;
                if (breadCrumbs.getCurrentWindow() instanceof Window.Editor)
                    return (Window.Editor) breadCrumbs.getCurrentWindow();
            }
        }
        return null;
    }

    protected com.haulmont.cuba.gui.components.Window findWindow(Layout layout) {
        for (Object component : layout) {
            if (component instanceof WindowBreadCrumbs) {
                WindowBreadCrumbs breadCrumbs = (WindowBreadCrumbs) component;
                if (breadCrumbs.getCurrentWindow() != null) {
                    return breadCrumbs.getCurrentWindow();
                }
            }
        }
        return null;
    }
}

19 View Complete Implementation : CubaMainTabSheet.java
Copyright Apache License 2.0
Author : cuba-platform
protected Set<Action> getActions(Component actionTarget) {
    Set<Action> actions = new LinkedHashSet<>();
    if (actionHandlers != null) {
        for (Action.Handler handler : actionHandlers) {
            Action[] as = handler.getActions(actionTarget, this);
            if (as != null) {
                Collections.addAll(actions, as);
            }
        }
    }
    return actions;
}

19 View Complete Implementation : CorpusListPanel.java
Copyright Apache License 2.0
Author : korpling
@Override
public void handleAction(Action action, Object sender, Object target) {
    if (action instanceof AddRemoveAction && this.userConfig != null) {
        AddRemoveAction a = (AddRemoveAction) action;
        int idx = this.userConfig.getCorpusSets().indexOf(a.getCorpusSet());
        if (idx > -1) {
            CorpusSet set = this.userConfig.getCorpusSets().get(idx);
            if (a.type == ActionType.Remove) {
                set.getCorpora().remove(a.getCorpusId());
                if (set.getCorpora().isEmpty()) {
                    // remove the set itself when it gets empty
                    this.userConfig.getCorpusSets().remove(set);
                    cbSelection.removeItem(a.getCorpusSet().getName());
                    cbSelection.select(ALL_CORPORA);
                }
            } else if (a.type == ActionType.Add) {
                set.getCorpora().add(a.getCorpusId());
            }
            storeChangesRemote();
            // update view
            updateCorpusTable();
        }
    }
}

19 View Complete Implementation : AdminUI.java
Copyright Mozilla Public License 2.0
Author : sensiasoft
// @Theme("reindeer")
// @Theme("runo")
// @Theme("valo")
@Theme("sensorhub")
public clreplaced AdminUI extends com.vaadin.ui.UI {

    private static final long serialVersionUID = 4069325051233125115L;

    private static final Action ADD_MODULE_ACTION = new Action("Add Module", new ThemeResource("icons/module_add.png"));

    private static final Action REMOVE_MODULE_ACTION = new Action("Remove Module", new ThemeResource("icons/module_delete.png"));

    private static final Action ENABLE_MODULE_ACTION = new Action("Enable", new ThemeResource("icons/enable.png"));

    private static final Action DISABLE_MODULE_ACTION = new Action("Disable", new ThemeResource("icons/disable.gif"));

    private static final Resource LOGO_ICON = new ClreplacedResource("/sensorhub_logo_128.png");

    private static final Resource ACC_TAB_ICON = new ThemeResource("icons/enable.png");

    private static final String STYLE_LOGO = "logo";

    protected static final Logger log = LoggerFactory.getLogger(AdminUI.clreplaced);

    private static AdminUI singleton;

    VerticalLayout configArea;

    AdminUIConfig uiConfig;

    protected Map<Clreplaced<?>, MyBeanItemContainer<ModuleConfig>> moduleConfigLists = new HashMap<Clreplaced<?>, MyBeanItemContainer<ModuleConfig>>();

    protected Map<String, Clreplaced<? extends IModuleAdminPanel<?>>> customPanels = new HashMap<String, Clreplaced<? extends IModuleAdminPanel<?>>>();

    protected Map<String, Clreplaced<? extends IModuleConfigForm>> customForms = new HashMap<String, Clreplaced<? extends IModuleConfigForm>>();

    public static AdminUI getInstance() {
        return singleton;
    }

    public AdminUI() {
        singleton = this;
    }

    @Override
    protected void init(VaadinRequest request) {
        String configClreplaced = null;
        moduleConfigLists.clear();
        // retrieve module config
        try {
            Properties initParams = request.getService().getDeploymentConfiguration().getInitParameters();
            String moduleID = initParams.getProperty(AdminUIModule.SERVLET_PARAM_MODULE_ID);
            uiConfig = (AdminUIConfig) SensorHub.getInstance().getModuleRegistry().getModuleById(moduleID).getConfiguration();
        } catch (Exception e) {
            throw new RuntimeException("Cannot get UI module configuration", e);
        }
        try {
            // load default form builders
            customForms.put(HttpServerConfig.clreplaced.getCanonicalName(), HttpServerConfigForm.clreplaced);
            customForms.put(StreamStorageConfig.clreplaced.getCanonicalName(), GenericStorageConfigForm.clreplaced);
            customForms.put(CommConfig.clreplaced.getCanonicalName(), CommConfigForm.clreplaced);
            customForms.put(SOSConfigForm.SOS_PACKAGE + "SOSServiceConfig", SOSConfigForm.clreplaced);
            customForms.put(SOSConfigForm.SOS_PACKAGE + "SOSProviderConfig", SOSConfigForm.clreplaced);
            // load custom form builders defined in config
            for (CustomUIConfig customForm : uiConfig.customForms) {
                configClreplaced = customForm.configClreplaced;
                Clreplaced<?> clazz = Clreplaced.forName(customForm.uiClreplaced);
                customForms.put(configClreplaced, (Clreplaced<IModuleConfigForm>) clazz);
                log.debug("Loaded custom form for " + configClreplaced);
            }
        } catch (Exception e) {
            log.error("Error while instantiating form builder for config clreplaced " + configClreplaced, e);
        }
        try {
            // load default panel builders
            customPanels.put(SensorConfig.clreplaced.getCanonicalName(), SensorAdminPanel.clreplaced);
            customPanels.put(StorageConfig.clreplaced.getCanonicalName(), StorageAdminPanel.clreplaced);
            // load custom panel builders defined in config
            for (CustomUIConfig customPanel : uiConfig.customPanels) {
                configClreplaced = customPanel.configClreplaced;
                Clreplaced<?> clazz = Clreplaced.forName(customPanel.uiClreplaced);
                customPanels.put(configClreplaced, (Clreplaced<IModuleAdminPanel<?>>) clazz);
                log.debug("Loaded custom panel for " + configClreplaced);
            }
        } catch (Exception e) {
            log.error("Error while instantiating panel builder for config clreplaced " + configClreplaced, e);
        }
        // register new field converter for interger numbers
        @SuppressWarnings("serial")
        ConverterFactory converterFactory = new DefaultConverterFactory() {

            @Override
            protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> findConverter(Clreplaced<PRESENTATION> presentationType, Clreplaced<MODEL> modelType) {
                // Handle String <-> Integer/Short/Long
                if (presentationType == String.clreplaced && (modelType == Long.clreplaced || modelType == Integer.clreplaced || modelType == Short.clreplaced)) {
                    return (Converter<PRESENTATION, MODEL>) new StringToIntegerConverter() {

                        @Override
                        protected NumberFormat getFormat(Locale locale) {
                            NumberFormat format = super.getFormat(Locale.US);
                            format.setGroupingUsed(false);
                            return format;
                        }
                    };
                }
                // Let default factory handle the rest
                return super.findConverter(presentationType, modelType);
            }
        };
        VaadinSession.getCurrent().setConverterFactory(converterFactory);
        // init main panels
        HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
        splitPanel.setMinSplitPosition(300.0f, Unit.PIXELS);
        splitPanel.setMaxSplitPosition(30.0f, Unit.PERCENTAGE);
        splitPanel.setSplitPosition(350.0f, Unit.PIXELS);
        setContent(splitPanel);
        // build left pane
        VerticalLayout leftPane = new VerticalLayout();
        leftPane.setSizeFull();
        // header image and replacedle
        Component header = buildHeader();
        leftPane.addComponent(header);
        leftPane.setExpandRatio(header, 0);
        // toolbar
        Component toolbar = buildToolbar();
        leftPane.addComponent(toolbar);
        leftPane.setExpandRatio(toolbar, 0);
        // accordion with several sections
        Accordion stack = new Accordion();
        stack.setSizeFull();
        VerticalLayout layout;
        Tab tab;
        layout = new VerticalLayout();
        tab = stack.addTab(layout, "Sensors");
        tab.setIcon(ACC_TAB_ICON);
        buildModuleList(layout, SensorConfig.clreplaced);
        layout = new VerticalLayout();
        tab = stack.addTab(layout, "Storage");
        tab.setIcon(ACC_TAB_ICON);
        buildModuleList(layout, StorageConfig.clreplaced);
        layout = new VerticalLayout();
        tab = stack.addTab(layout, "Processing");
        tab.setIcon(ACC_TAB_ICON);
        buildModuleList(layout, ProcessConfig.clreplaced);
        layout = new VerticalLayout();
        tab = stack.addTab(layout, "Services");
        tab.setIcon(ACC_TAB_ICON);
        buildModuleList(layout, ServiceConfig.clreplaced);
        layout = new VerticalLayout();
        tab = stack.addTab(layout, "Clients");
        tab.setIcon(ACC_TAB_ICON);
        buildModuleList(layout, ClientConfig.clreplaced);
        layout = new VerticalLayout();
        tab = stack.addTab(layout, "Network");
        tab.setIcon(ACC_TAB_ICON);
        buildNetworkConfig(layout);
        leftPane.addComponent(stack);
        leftPane.setExpandRatio(stack, 1);
        splitPanel.addComponent(leftPane);
        // init config area
        configArea = new VerticalLayout();
        configArea.setMargin(true);
        splitPanel.addComponent(configArea);
    }

    protected Component buildHeader() {
        HorizontalLayout header = new HorizontalLayout();
        header.setMargin(false);
        header.setHeight(100.0f, Unit.PIXELS);
        header.setWidth(100.0f, Unit.PERCENTAGE);
        Image img = new Image(null, LOGO_ICON);
        img.setHeight(90, Unit.PIXELS);
        img.setStyleName(STYLE_LOGO);
        header.addComponent(img);
        Label replacedle = new Label("SensorHub");
        replacedle.addStyleName(UIConstants.STYLE_H1);
        replacedle.addStyleName(STYLE_LOGO);
        replacedle.setWidth(null);
        header.addComponent(replacedle);
        header.setExpandRatio(img, 0);
        header.setExpandRatio(replacedle, 1);
        header.setComponentAlignment(img, Alignment.MIDDLE_LEFT);
        header.setComponentAlignment(replacedle, Alignment.MIDDLE_RIGHT);
        return header;
    }

    protected Component buildToolbar() {
        HorizontalLayout toolbar = new HorizontalLayout();
        toolbar.setWidth(100.0f, Unit.PERCENTAGE);
        // apply changes button
        Button saveButton = new Button("Save Config");
        saveButton.setDescription("Save Config");
        saveButton.setIcon(UIConstants.APPLY_ICON);
        saveButton.addStyleName(UIConstants.STYLE_SMALL);
        saveButton.setWidth(100.0f, Unit.PERCENTAGE);
        // apply button action
        saveButton.addClickListener(new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                try {
                    SensorHub.getInstance().getModuleRegistry().saveModulesConfiguration();
                } catch (Exception e) {
                    AdminUI.log.error("Error while saving SensorHub configuration", e);
                    Notification.show("Error", e.getMessage(), Notification.Type.ERROR_MESSAGE);
                }
            }
        });
        toolbar.addComponent(saveButton);
        return toolbar;
    }

    protected void buildNetworkConfig(VerticalLayout layout) {
        // add config objects to container
        MyBeanItemContainer<ModuleConfig> container = new MyBeanItemContainer<ModuleConfig>(ModuleConfig.clreplaced);
        container.addBean(HttpServer.getInstance().getConfiguration());
        // container.addBean(uiConfig);
        displayModuleList(layout, container, null);
    }

    protected void buildModuleList(VerticalLayout layout, final Clreplaced<?> configType) {
        ModuleRegistry reg = SensorHub.getInstance().getModuleRegistry();
        // build bean items and add them to container
        MyBeanItemContainer<ModuleConfig> container = new MyBeanItemContainer<ModuleConfig>(ModuleConfig.clreplaced);
        for (IModule<?> module : reg.getLoadedModules()) {
            ModuleConfig config = module.getConfiguration().clone();
            if (configType.isreplacedignableFrom(config.getClreplaced()))
                container.addBean(config);
        }
        moduleConfigLists.put(configType, container);
        displayModuleList(layout, container, configType);
    }

    @SuppressWarnings("serial")
    protected void displayModuleList(VerticalLayout layout, final MyBeanItemContainer<ModuleConfig> container, final Clreplaced<?> configType) {
        // create table to display module list
        final Table table = new Table();
        table.setSizeFull();
        table.setSelectable(true);
        table.setImmediate(true);
        table.setColumnReorderingAllowed(false);
        table.setContainerDataSource(container);
        table.setVisibleColumns(new Object[] { UIConstants.PROP_NAME, UIConstants.PROP_ENABLED });
        table.setColumnWidth(UIConstants.PROP_ENABLED, 100);
        table.setColumnHeaderMode(ColumnHeaderMode.HIDDEN);
        // value converter for enabled field
        table.setConverter(UIConstants.PROP_ENABLED, new Converter<String, Boolean>() {

            @Override
            public Boolean convertToModel(String value, Clreplaced<? extends Boolean> targetType, Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException {
                return (value != null && value.equals("enabled"));
            }

            @Override
            public String convertToPresentation(Boolean value, Clreplaced<? extends String> targetType, Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException {
                return value ? "enabled" : "disabled";
            }

            @Override
            public Clreplaced<Boolean> getModelType() {
                return boolean.clreplaced;
            }

            @Override
            public Clreplaced<String> getPresentationType() {
                return String.clreplaced;
            }
        });
        table.setCellStyleGenerator(new CellStyleGenerator() {

            @Override
            public String getStyle(Table source, Object itemId, Object propertyId) {
                if (propertyId != null && propertyId.equals(UIConstants.PROP_ENABLED)) {
                    boolean val = (boolean) table.gereplacedem(itemId).gereplacedemProperty(propertyId).getValue();
                    if (val == true)
                        return "green";
                    else
                        return "red";
                }
                return null;
            }
        });
        // item click listener to display selected module settings
        table.addItemClickListener(new ItemClickListener() {

            @Override
            public void itemClick(ItemClickEvent event) {
                openModuleInfo((MyBeanItem<ModuleConfig>) event.gereplacedem());
            }
        });
        layout.addComponent(table);
        // context menu
        table.addActionHandler(new Handler() {

            @Override
            public Action[] getActions(Object target, Object sender) {
                List<Action> actions = new ArrayList<Action>(10);
                if (target != null) {
                    boolean enabled = ((MyBeanItem<ModuleConfig>) table.gereplacedem(target)).getBean().enabled;
                    if (enabled)
                        actions.add(DISABLE_MODULE_ACTION);
                    else
                        actions.add(ENABLE_MODULE_ACTION);
                    actions.add(REMOVE_MODULE_ACTION);
                } else {
                    if (configType != null)
                        actions.add(ADD_MODULE_ACTION);
                }
                return actions.toArray(new Action[0]);
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                final Object selectedId = table.getValue();
                if (action == ADD_MODULE_ACTION) {
                    // show popup to select among available module types
                    ModuleTypeSelectionPopup popup = new ModuleTypeSelectionPopup(configType, new ModuleTypeSelectionCallback() {

                        public void configSelected(Clreplaced<?> moduleType, ModuleConfig config) {
                            try {
                                // add to main config
                                ModuleRegistry reg = SensorHub.getInstance().getModuleRegistry();
                                reg.loadModule(config);
                            } catch (Exception e) {
                                String msg = "The module could not be initialized";
                                Notification.show("Error", msg + '\n' + e.getMessage(), Notification.Type.ERROR_MESSAGE);
                            }
                            MyBeanItem<ModuleConfig> newBeanItem = container.addBean(config);
                            openModuleInfo(newBeanItem);
                        }
                    });
                    popup.setModal(true);
                    addWindow(popup);
                } else if (selectedId != null) {
                    // possible actions when a module is selected
                    final Item item = table.gereplacedem(selectedId);
                    final String moduleId = (String) item.gereplacedemProperty(UIConstants.PROP_ID).getValue();
                    final String moduleName = (String) item.gereplacedemProperty(UIConstants.PROP_NAME).getValue();
                    if (action == REMOVE_MODULE_ACTION) {
                        final ConfirmDialog popup = new ConfirmDialog("Are you sure you want to remove module " + moduleName + "?</br>All settings will be lost.");
                        popup.addCloseListener(new CloseListener() {

                            @Override
                            public void windowClose(CloseEvent e) {
                                if (popup.isConfirmed()) {
                                    try {
                                        SensorHub.getInstance().getModuleRegistry().destroyModule(moduleId);
                                        container.removeItem(selectedId);
                                    } catch (SensorHubException ex) {
                                        String msg = "The module could not be removed";
                                        Notification.show("Error", msg + '\n' + ex.getMessage(), Notification.Type.ERROR_MESSAGE);
                                        AdminUI.log.debug(msg, e);
                                    }
                                }
                            }
                        });
                        addWindow(popup);
                    } else if (action == ENABLE_MODULE_ACTION) {
                        final ConfirmDialog popup = new ConfirmDialog("Are you sure you want to enable module " + moduleName + "?");
                        popup.addCloseListener(new CloseListener() {

                            @Override
                            public void windowClose(CloseEvent e) {
                                if (popup.isConfirmed()) {
                                    try {
                                        SensorHub.getInstance().getModuleRegistry().enableModule(moduleId);
                                        item.gereplacedemProperty(UIConstants.PROP_ENABLED).setValue(true);
                                        openModuleInfo((MyBeanItem<ModuleConfig>) item);
                                    } catch (SensorHubException ex) {
                                        String msg = "The module could not be enabled";
                                        Notification.show("Error", msg + '\n' + ex.getMessage(), Notification.Type.ERROR_MESSAGE);
                                    }
                                }
                            }
                        });
                        addWindow(popup);
                    } else if (action == DISABLE_MODULE_ACTION) {
                        final ConfirmDialog popup = new ConfirmDialog("Are you sure you want to disable module " + moduleName + "?");
                        popup.addCloseListener(new CloseListener() {

                            @Override
                            public void windowClose(CloseEvent e) {
                                if (popup.isConfirmed()) {
                                    try {
                                        SensorHub.getInstance().getModuleRegistry().disableModule(moduleId);
                                        item.gereplacedemProperty(UIConstants.PROP_ENABLED).setValue(false);
                                    } catch (SensorHubException ex) {
                                        String msg = "The module could not be disabled";
                                        Notification.show("Error", msg + '\n' + ex.getMessage(), Notification.Type.ERROR_MESSAGE);
                                    }
                                }
                            }
                        });
                        addWindow(popup);
                    }
                }
            }
        });
        layout.setSizeFull();
    }

    protected void openModuleInfo(MyBeanItem<ModuleConfig> beanItem) {
        configArea.removeAllComponents();
        // this will load the module (i.e. call init) if not already loaded
        IModule<?> module = null;
        try {
            module = SensorHub.getInstance().getModuleRegistry().getModuleById(beanItem.getBean().id);
        } catch (Exception e) {
        }
        // get panel for this config object
        Clreplaced<?> configClreplaced = beanItem.getBean().getClreplaced();
        IModuleAdminPanel<IModule<?>> panel = generatePanel(configClreplaced);
        panel.build(beanItem, module);
        // generate module admin panel
        configArea.addComponent(panel);
    }

    protected IModuleAdminPanel<IModule<?>> generatePanel(Clreplaced<?> clazz) {
        try {
            // check if there is a custom panel registered, if not use default
            Clreplaced<IModuleAdminPanel<IModule<?>>> uiClreplaced = null;
            while (uiClreplaced == null && clazz != null) {
                uiClreplaced = (Clreplaced<IModuleAdminPanel<IModule<?>>>) customPanels.get(clazz.getCanonicalName());
                clazz = clazz.getSuperclreplaced();
            }
            if (uiClreplaced == null)
                return new DefaultModulePanel<IModule<?>>();
            return uiClreplaced.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Cannot instantiate UI clreplaced", e);
        }
    }

    protected IModuleConfigForm generateForm(Clreplaced<?> clazz) {
        try {
            // check if there is a custom form registered, if not use default
            Clreplaced<IModuleConfigForm> uiClreplaced = null;
            while (uiClreplaced == null && clazz != null) {
                uiClreplaced = (Clreplaced<IModuleConfigForm>) customForms.get(clazz.getCanonicalName());
                clazz = clazz.getSuperclreplaced();
            }
            if (uiClreplaced == null)
                return new GenericConfigForm();
            return uiClreplaced.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Cannot instantiate UI clreplaced", e);
        }
    }
}

18 View Complete Implementation : CmsMessageBundleEditor.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Controller for the VAADIN UI of the Message Bundle Editor.
 */
@Theme("opencms")
public clreplaced CmsMessageBundleEditor implements I_CmsEditor, I_CmsWindowCloseListener, ViewChangeListener, I_EntryChangeListener, I_ItemDeletionListener, I_OptionListener, I_CmsHreplacedhortcutActions {

    /**
     * Used to implement {@link java.io.Serializable}.
     */
    private static final long serialVersionUID = 5366955716462191580L;

    /**
     * The log object for this clreplaced.
     */
    private static final Log LOG = CmsLog.getLog(CmsMessageBundleEditor.clreplaced);

    /**
     * Exit shortcut.
     */
    private static final Action ACTION_EXIT = new ShortcutAction("Ctrl+Shift+X", ShortcutAction.KeyCode.X, new int[] { ShortcutAction.ModifierKey.CTRL, ShortcutAction.ModifierKey.SHIFT });

    /**
     * Exit shortcut, (using Apple CMD as modifier).
     */
    private static final Action ACTION_EXIT_CMD = new ShortcutAction("CMD+Shift+X", ShortcutAction.KeyCode.X, new int[] { ShortcutAction.ModifierKey.META, ShortcutAction.ModifierKey.SHIFT });

    /**
     * Save shortcut.
     */
    private static final Action ACTION_SAVE = new ShortcutAction("Ctrl+S", ShortcutAction.KeyCode.S, new int[] { ShortcutAction.ModifierKey.CTRL });

    /**
     * Save shortcut, (using Apple CMD as modifier).
     */
    private static final Action ACTION_SAVE_CMD = new ShortcutAction("CMD+S", ShortcutAction.KeyCode.S, new int[] { ShortcutAction.ModifierKey.META });

    /**
     * Save & Exit shortcut.
     */
    private static final Action ACTION_SAVE_AND_EXIT = new ShortcutAction("Ctrl+Shift+S", ShortcutAction.KeyCode.S, new int[] { ShortcutAction.ModifierKey.CTRL, ShortcutAction.ModifierKey.SHIFT });

    /**
     * Save & Exit shortcut, (using Apple CMD as modifier).
     */
    private static final Action ACTION_SAVE_AND_EXIT_CMD = new ShortcutAction("CMD+Shift+S", ShortcutAction.KeyCode.S, new int[] { ShortcutAction.ModifierKey.META, ShortcutAction.ModifierKey.SHIFT });

    /**
     * The bundle editor shortcuts.
     */
    Map<Action, Runnable> m_shortcutActions;

    /**
     * Messages used by the GUI.
     */
    CmsMessages m_messages;

    /**
     * Configurable Messages.
     */
    ConfigurableMessages m_configurableMessages;

    /**
     * The field factories for the different modes.
     */
    private final Map<CmsMessageBundleEditorTypes.EditMode, CmsMessageBundleEditorTypes.TranslateTableFieldFactory> m_fieldFactories = new HashMap<CmsMessageBundleEditorTypes.EditMode, CmsMessageBundleEditorTypes.TranslateTableFieldFactory>(2);

    /**
     * The cell style generators for the different modes.
     */
    private final Map<CmsMessageBundleEditorTypes.EditMode, CmsMessageBundleEditorTypes.TranslateTableCellStyleGenerator> m_styleGenerators = new HashMap<CmsMessageBundleEditorTypes.EditMode, CmsMessageBundleEditorTypes.TranslateTableCellStyleGenerator>(2);

    /**
     * Flag, indicating if leaving the editor is confirmed.
     */
    boolean m_leaving;

    /**
     * The context of the UI.
     */
    I_CmsAppUIContext m_context;

    /**
     * The model behind the UI.
     */
    CmsMessageBundleEditorModel m_model;

    /**
     * CmsObject for read / write actions.
     */
    CmsObject m_cms;

    /**
     * The resource that was opened with the editor.
     */
    CmsResource m_resource;

    /**
     * The table component that is shown.
     */
    FilterTable m_table;

    /**
     * The save button.
     */
    Button m_saveBtn;

    /**
     * The save and exit button.
     */
    Button m_saveExitBtn;

    /**
     * The options column, optionally shown in the table.
     */
    CmsMessageBundleEditorTypes.OptionColumnGenerator m_optionsColumn;

    /**
     * The place where to go when the editor is closed.
     */
    private String m_backLink;

    /**
     * The options view of the editor.
     */
    private CmsMessageBundleEditorOptions m_options;

    /**
     * Default constructor.
     */
    public CmsMessageBundleEditor() {
        m_shortcutActions = new HashMap<Action, Runnable>();
        m_shortcutActions = new HashMap<Action, Runnable>();
        Runnable save = new Runnable() {

            public void run() {
                saveAction();
            }
        };
        m_shortcutActions.put(ACTION_SAVE, save);
        m_shortcutActions.put(ACTION_SAVE_CMD, save);
        Runnable saveExit = new Runnable() {

            public void run() {
                saveAction();
                closeAction();
            }
        };
        m_shortcutActions.put(ACTION_SAVE_AND_EXIT, saveExit);
        m_shortcutActions.put(ACTION_SAVE_AND_EXIT_CMD, saveExit);
        Runnable exit = new Runnable() {

            public void run() {
                closeAction();
            }
        };
        m_shortcutActions.put(ACTION_EXIT, exit);
        m_shortcutActions.put(ACTION_EXIT_CMD, exit);
    }

    /**
     * @see com.vaadin.navigator.ViewChangeListener#afterViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent)
     */
    public void afterViewChange(ViewChangeEvent event) {
    // do nothing
    }

    /**
     * @see com.vaadin.navigator.ViewChangeListener#beforeViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent)
     */
    public boolean beforeViewChange(final ViewChangeEvent event) {
        if (!m_leaving && m_model.hasChanges()) {
            CmsConfirmationDialog.show(CmsVaadinUtils.getMessageText(org.opencms.ui.apps.Messages.GUI_EDITOR_CLOSE_CAPTION_0), CmsVaadinUtils.getMessageText(org.opencms.ui.apps.Messages.GUI_EDITOR_CLOSE_TEXT_0), new Runnable() {

                public void run() {
                    m_leaving = true;
                    event.getNavigator().navigateTo(event.getViewName());
                }
            });
            return false;
        }
        cleanUpAction();
        return true;
    }

    /**
     * @see org.opencms.ui.editors.I_CmsEditor#getPriority()
     */
    public int getPriority() {
        return 200;
    }

    /**
     * @see org.opencms.ui.apps.I_CmsHreplacedhortcutActions#getShortcutActions()
     */
    public Map<Action, Runnable> getShortcutActions() {
        return m_shortcutActions;
    }

    /**
     * @see org.opencms.ui.editors.messagebundle.CmsMessageBundleEditorTypes.I_OptionListener#handleAddKey(java.lang.String)
     */
    public boolean handleAddKey(final String newKey) {
        Map<Object, Object> filters = getFilters();
        m_table.clearFilters();
        boolean canAdd = !keyAlreadyExists(newKey);
        if (canAdd) {
            Object copyEntryId = m_table.addItem();
            Item copyEntry = m_table.gereplacedem(copyEntryId);
            copyEntry.gereplacedemProperty(TableProperty.KEY).setValue(newKey);
        }
        setFilters(filters);
        if (m_model.hasDescriptor() | m_model.getBundleType().equals(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR)) {
            handleChange(TableProperty.KEY);
            handleChange(TableProperty.DESCRIPTION);
        }
        return canAdd;
    }

    /**
     * @see org.opencms.ui.editors.messagebundle.CmsMessageBundleEditorTypes.I_EntryChangeListener#handleEntryChange(org.opencms.ui.editors.messagebundle.CmsMessageBundleEditorTypes.EntryChangeEvent)
     */
    public void handleEntryChange(EntryChangeEvent event) {
        if (event.getPropertyId().equals(TableProperty.KEY)) {
            KeyChangeResult result = m_model.handleKeyChange(event, true);
            String captionKey = null;
            String descriptionKey = null;
            switch(result) {
                case SUCCESS:
                    handleChange(event.getPropertyId());
                    return;
                case FAILED_DUPLICATED_KEY:
                    captionKey = Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADY_EXISTS_CAPTION_0;
                    descriptionKey = Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADY_EXISTS_DESCRIPTION_0;
                    break;
                case FAILED_FOR_OTHER_LANGUAGE:
                    captionKey = Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_RENAMING_FAILED_CAPTION_0;
                    descriptionKey = Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_RENAMING_FAILED_DESCRIPTION_0;
                    break;
                default:
                    throw new IllegalArgumentException();
            }
            CmsMessageBundleEditorTypes.showWarning(m_messages.key(captionKey), m_messages.key(descriptionKey));
            event.getSource().focus();
        }
        handleChange(event.getPropertyId());
    }

    /**
     * @see org.opencms.ui.editors.messagebundle.CmsMessageBundleEditorTypes.I_ItemDeletionListener#handleItemDeletion(org.opencms.ui.editors.messagebundle.CmsMessageBundleEditorTypes.ItemDeletionEvent)
     */
    public boolean handleItemDeletion(ItemDeletionEvent e) {
        Item it = m_table.gereplacedem(e.gereplacedemId());
        Property<?> keyProp = it.gereplacedemProperty(TableProperty.KEY);
        String key = (String) keyProp.getValue();
        if (m_model.handleKeyDeletion(key)) {
            if (m_model.hasDescriptor() | m_model.getBundleType().equals(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR)) {
                handleChange(TableProperty.DESCRIPTION);
            }
            handleChange(TableProperty.KEY);
            return true;
        }
        CmsMessageBundleEditorTypes.showWarning(m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_REMOVE_ENTRY_FAILED_CAPTION_0), m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_REMOVE_ENTRY_FAILED_DESCRIPTION_0));
        return false;
    }

    /**
     * @see org.opencms.ui.editors.messagebundle.CmsMessageBundleEditorTypes.I_OptionListener#handleLanguageChange(java.util.Locale)
     */
    public void handleLanguageChange(final Locale locale) {
        if (!locale.equals(m_model.getLocale())) {
            Object sortProperty = m_table.getSortContainerPropertyId();
            boolean isAcending = m_table.isSortAscending();
            Map<Object, Object> filters = getFilters();
            m_table.clearFilters();
            if (m_model.setLocale(locale)) {
                m_options.setEditedFilePath(m_model.getEditedFilePath());
                m_table.sort(new Object[] { sortProperty }, new boolean[] { isAcending });
            } else {
                String caption = m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_LOCALE_SWITCHING_FAILED_CAPTION_0);
                String description = m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_LOCALE_SWITCHING_FAILED_DESCRIPTION_0);
                Notification warning = new Notification(caption, description, Type.WARNING_MESSAGE, true);
                warning.setDelayMsec(-1);
                warning.show(UI.getCurrent().getPage());
                m_options.setLanguage(m_model.getLocale());
            }
            setFilters(filters);
            m_table.select(m_table.getCurrentPageFirsreplacedemId());
        }
    }

    /**
     * @see org.opencms.ui.editors.messagebundle.CmsMessageBundleEditorTypes.I_OptionListener#handleModeChange(org.opencms.ui.editors.messagebundle.CmsMessageBundleEditorTypes.EditMode)
     */
    public void handleModeChange(final EditMode mode) {
        setEditMode(mode);
    }

    /**
     * @see org.opencms.ui.editors.I_CmsEditor#initUI(org.opencms.ui.apps.I_CmsAppUIContext, org.opencms.file.CmsResource, java.lang.String, java.util.Map)
     */
    public void initUI(I_CmsAppUIContext context, CmsResource resource, String backLink, Map<String, String> params) {
        m_cms = ((CmsUIServlet) VaadinServlet.getCurrent()).getCmsObject();
        m_messages = Messages.get().getBundle(UI.getCurrent().getLocale());
        m_resource = resource;
        m_backLink = backLink;
        m_context = context;
        try {
            m_model = new CmsMessageBundleEditorModel(m_cms, m_resource);
            m_options = new CmsMessageBundleEditorOptions(m_model.getLocales(), m_model.getLocale(), m_model.getEditMode(), this);
            m_options.setEditedFilePath(m_model.getEditedFilePath());
            m_configurableMessages = m_model.getConfigurableMessages(m_messages, UI.getCurrent().getLocale());
            fillToolBar(context);
            context.showInfoArea(false);
            Component main = createMainComponent();
            initFieldFactories();
            initStyleGenerators();
            m_table.setTableFieldFactory(m_fieldFactories.get(m_model.getEditMode()));
            m_table.setCellStyleGenerator(m_styleGenerators.get(m_model.getEditMode()));
            m_optionsColumn.registerItemDeletionListener(this);
            adjustVisibleColumns();
            context.setAppContent(main);
            adjustFocus();
            if (m_model.getSwitchedLocaleOnOpening()) {
                CmsMessageBundleEditorTypes.showWarning(m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_SWITCHED_LOCALE_CAPTION_0), m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_SWITCHED_LOCALE_DESCRIPTION_0));
            }
        } catch (IOException | CmsException e) {
            LOG.error(m_messages.key(Messages.ERR_LOADING_RESOURCES_0), e);
            Notification.show(m_messages.key(Messages.ERR_LOADING_RESOURCES_0), Type.ERROR_MESSAGE);
            closeAction();
        }
    }

    /**
     * @see org.opencms.ui.editors.I_CmsEditor#matchesResource(org.opencms.file.CmsResource, boolean)
     */
    public boolean matchesResource(CmsResource resource, boolean plainText) {
        I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(resource);
        return matchesType(type, plainText);
    }

    /**
     * @see org.opencms.ui.editors.I_CmsEditor#matchesResource(org.opencms.file.CmsResource, boolean)
     */
    public boolean matchesType(I_CmsResourceType type, boolean plainText) {
        return !plainText && (CmsMessageBundleEditorTypes.BundleType.toBundleType(type.getTypeName()) != null);
    }

    /**
     * @see org.opencms.ui.editors.I_CmsEditor#newInstance()
     */
    public I_CmsEditor newInstance() {
        return new CmsMessageBundleEditor();
    }

    /**
     * @see org.opencms.ui.components.I_CmsWindowCloseListener#onWindowClose()
     */
    public void onWindowClose() {
        cleanUpAction();
    }

    /**
     * Unlocks all resources. Call when closing the editor.
     */
    void closeAction() {
        CmsEditor.openBackLink(m_backLink);
    }

    /**
     * Returns the currently set filters in a map column -> filter.
     *
     * @return the currently set filters in a map column -> filter.
     */
    Map<Object, Object> getFilters() {
        Map<Object, Object> result = new HashMap<Object, Object>(4);
        result.put(TableProperty.KEY, m_table.getFilterFieldValue(TableProperty.KEY));
        result.put(TableProperty.DEFAULT, m_table.getFilterFieldValue(TableProperty.DEFAULT));
        result.put(TableProperty.DESCRIPTION, m_table.getFilterFieldValue(TableProperty.DESCRIPTION));
        result.put(TableProperty.TRANSLATION, m_table.getFilterFieldValue(TableProperty.TRANSLATION));
        return result;
    }

    /**
     * Publish the changes.
     */
    void publishAction() {
        // save first
        saveAction();
        // publish
        m_model.publish();
    }

    /**
     * Save the changes.
     */
    void saveAction() {
        Map<Object, Object> filters = getFilters();
        m_table.clearFilters();
        try {
            m_model.save();
            disableSaveButtons();
        } catch (CmsException e) {
            LOG.error(m_messages.key(Messages.ERR_SAVING_CHANGES_0), e);
            CmsErrorDialog.showErrorDialog(m_messages.key(Messages.ERR_SAVING_CHANGES_0), e);
        }
        setFilters(filters);
    }

    /**
     * Set the edit mode.
     * @param newMode the edit mode to set.
     * @return Flag, indicating if mode switching was successful.
     */
    boolean setEditMode(CmsMessageBundleEditorTypes.EditMode newMode) {
        CmsMessageBundleEditorTypes.EditMode oldMode = m_model.getEditMode();
        boolean success = false;
        if (!newMode.equals(oldMode)) {
            Map<Object, Object> filters = getFilters();
            m_table.clearFilters();
            if (m_model.setEditMode(newMode)) {
                m_table.setTableFieldFactory(m_fieldFactories.get(newMode));
                m_table.setCellStyleGenerator(m_styleGenerators.get(newMode));
                adjustOptionsColumn(oldMode, newMode);
                m_options.updateShownOptions(m_model.hasMasterMode(), m_model.canAddKeys());
                m_options.setEditMode(newMode);
                success = true;
            } else {
                Notification.show(m_messages.key(Messages.ERR_MODE_CHANGE_NOT_POSSIBLE_0), Type.ERROR_MESSAGE);
            }
            setFilters(filters);
            adjustFocus();
        }
        return success;
    }

    /**
     * Sets the provided filters.
     * @param filters a map "column id -> filter".
     */
    void setFilters(Map<Object, Object> filters) {
        for (Object column : filters.keySet()) {
            Object filterValue = filters.get(column);
            if ((filterValue != null) && !filterValue.toString().isEmpty() && !m_table.isColumnCollapsed(column)) {
                m_table.setFilterFieldValue(column, filterValue);
            }
        }
    }

    /**
     * Sets the focus to the first editable field of the table.
     * If entries can be added, it is set to the first field of the "Add entries" row.
     */
    private void adjustFocus() {
        // Put the focus on the "Filter key" field first
        ((Focusable) m_table.getFilterField(TableProperty.KEY)).focus();
    }

    /**
     * Show or hide the options column dependent on the provided edit mode.
     * @param oldMode the old edit mode
     * @param newMode the edit mode for which the options column's visibility should be adjusted.
     */
    private void adjustOptionsColumn(CmsMessageBundleEditorTypes.EditMode oldMode, CmsMessageBundleEditorTypes.EditMode newMode) {
        if (m_model.isShowOptionsColumn(oldMode) != m_model.isShowOptionsColumn(newMode)) {
            m_table.removeGeneratedColumn(TableProperty.OPTIONS);
            if (m_model.isShowOptionsColumn(newMode)) {
                // Don't know why exactly setting the filter field invisible is necessary here,
                // it should be already set invisible - but apparently not setting it invisible again
                // will result in the field being visible.
                m_table.setFilterFieldVisible(TableProperty.OPTIONS, false);
                m_table.addGeneratedColumn(TableProperty.OPTIONS, m_optionsColumn);
            }
        }
    }

    /**
     * Adjust the visible columns.
     */
    private void adjustVisibleColumns() {
        if (m_table.isColumnCollapsingAllowed()) {
            if ((m_model.hasDefaultValues()) || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {
                m_table.setColumnCollapsed(TableProperty.DEFAULT, false);
            } else {
                m_table.setColumnCollapsed(TableProperty.DEFAULT, true);
            }
            if (((m_model.getEditMode().equals(EditMode.MASTER) || m_model.hasDescriptionValues())) || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {
                m_table.setColumnCollapsed(TableProperty.DESCRIPTION, false);
            } else {
                m_table.setColumnCollapsed(TableProperty.DESCRIPTION, true);
            }
        }
    }

    /**
     * Unlock all edited resources.
     */
    private void cleanUpAction() {
        try {
            m_model.deleteDescriptorIfNecessary();
        } catch (CmsException e) {
            LOG.error(m_messages.key(Messages.ERR_DELETING_DESCRIPTOR_0), e);
        }
        // unlock resource
        m_model.unlock();
    }

    /**
     * Returns a button component. On click, it triggers adding a bundle descriptor.
     * @return a button for adding a descriptor to a bundle.
     */
    @SuppressWarnings("serial")
    private Component createAddDescriptorButton() {
        Button addDescriptorButton = CmsToolBar.createButton(FontOpenCms.COPY_LOCALE, m_messages.key(Messages.GUI_ADD_DESCRIPTOR_0));
        addDescriptorButton.setDisableOnClick(true);
        addDescriptorButton.addClickListener(new ClickListener() {

            @SuppressWarnings("synthetic-access")
            public void buttonClick(ClickEvent event) {
                Map<Object, Object> filters = getFilters();
                m_table.clearFilters();
                if (!m_model.addDescriptor()) {
                    CmsVaadinUtils.showAlert(m_messages.key(Messages.ERR_BUNDLE_DESCRIPTOR_CREATION_FAILED_0), m_messages.key(Messages.ERR_BUNDLE_DESCRIPTOR_CREATION_FAILED_DESCRIPTION_0), null);
                } else {
                    IndexedContainer newContainer = null;
                    try {
                        newContainer = m_model.getContainerForCurrentLocale();
                        m_table.setContainerDataSource(newContainer);
                        initFieldFactories();
                        initStyleGenerators();
                        setEditMode(EditMode.MASTER);
                        m_table.setColumnCollapsingAllowed(true);
                        adjustVisibleColumns();
                        m_options.updateShownOptions(m_model.hasMasterMode(), m_model.canAddKeys());
                        m_options.setEditMode(m_model.getEditMode());
                    } catch (IOException | CmsException e) {
                        // Can never appear here, since container is created by addDescriptor already.
                        LOG.error(e.getLocalizedMessage(), e);
                    }
                }
                setFilters(filters);
            }
        });
        return addDescriptorButton;
    }

    /**
     * Create the close button UI Component.
     * @return the close button.
     */
    @SuppressWarnings("serial")
    private Component createCloseButton() {
        Button closeBtn = CmsToolBar.createButton(FontOpenCms.CIRCLE_INV_CANCEL, m_messages.key(Messages.GUI_BUTTON_CANCEL_0));
        closeBtn.addClickListener(new ClickListener() {

            public void buttonClick(ClickEvent event) {
                closeAction();
            }
        });
        return closeBtn;
    }

    /**
     * Creates the button for converting an XML bundle in a property bundle.
     * @return the created button.
     */
    private Component createConvertToPropertyBundleButton() {
        Button addDescriptorButton = CmsToolBar.createButton(FontOpenCms.SETTINGS, m_messages.key(Messages.GUI_CONVERT_TO_PROPERTY_BUNDLE_0));
        addDescriptorButton.setDisableOnClick(true);
        addDescriptorButton.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                try {
                    m_model.saveAsPropertyBundle();
                    Notification.show("Conversion successful.");
                } catch (CmsException | IOException e) {
                    CmsVaadinUtils.showAlert("Conversion failed", e.getLocalizedMessage(), null);
                }
            }
        });
        addDescriptorButton.setDisableOnClick(true);
        return addDescriptorButton;
    }

    /**
     * Creates the main component of the editor with all sub-components.
     * @return the completely filled main component of the editor.
     * @throws IOException thrown if setting the table's content data source fails.
     * @throws CmsException thrown if setting the table's content data source fails.
     */
    private Component createMainComponent() throws IOException, CmsException {
        VerticalLayout mainComponent = new VerticalLayout();
        mainComponent.setSizeFull();
        mainComponent.addStyleName("o-message-bundle-editor");
        m_table = createTable();
        Panel navigator = new Panel();
        navigator.setSizeFull();
        navigator.setContent(m_table);
        navigator.addActionHandler(new CmsMessageBundleEditorTypes.TableKeyboardHandler(m_table));
        navigator.addStyleName("v-panel-borderless");
        mainComponent.addComponent(m_options.getOptionsComponent());
        mainComponent.addComponent(navigator);
        mainComponent.setExpandRatio(navigator, 1f);
        m_options.updateShownOptions(m_model.hasMasterMode(), m_model.canAddKeys());
        return mainComponent;
    }

    /**
     * Creates the save button UI Component.
     * @return the save button.
     */
    @SuppressWarnings("serial")
    private Component createPublishButton() {
        Button publishBtn = CmsToolBar.createButton(FontOpenCms.PUBLISH, m_messages.key(Messages.GUI_BUTTON_PUBLISH_0));
        publishBtn.addClickListener(new ClickListener() {

            public void buttonClick(ClickEvent event) {
                publishAction();
            }
        });
        return publishBtn;
    }

    /**
     * Creates the save button UI Component.
     * @return the save button.
     */
    @SuppressWarnings("serial")
    private Button createSaveButton() {
        Button saveBtn = CmsToolBar.createButton(FontOpenCms.SAVE, m_messages.key(Messages.GUI_BUTTON_SAVE_0));
        saveBtn.addClickListener(new ClickListener() {

            public void buttonClick(ClickEvent event) {
                saveAction();
            }
        });
        saveBtn.setEnabled(false);
        return saveBtn;
    }

    /**
     * Creates the save and exit button UI Component.
     * @return the save and exit button.
     */
    @SuppressWarnings("serial")
    private Button createSaveExitButton() {
        Button saveExitBtn = CmsToolBar.createButton(FontOpenCms.SAVE_EXIT, m_messages.key(Messages.GUI_BUTTON_SAVE_AND_EXIT_0));
        saveExitBtn.addClickListener(new ClickListener() {

            public void buttonClick(ClickEvent event) {
                saveAction();
                closeAction();
            }
        });
        saveExitBtn.setEnabled(false);
        return saveExitBtn;
    }

    /**
     * Creates the (filled) table UI component.
     * @return the (filled) table
     * @throws IOException thrown if reading the properties file fails.
     * @throws CmsException thrown if some read action for getting the table contentFilter fails.
     */
    private FilterTable createTable() throws IOException, CmsException {
        final FilterTable table = new FilterTable();
        table.setSizeFull();
        table.setContainerDataSource(m_model.getContainerForCurrentLocale());
        table.setColumnHeader(TableProperty.KEY, m_configurableMessages.getColumnHeader(TableProperty.KEY));
        table.setColumnCollapsible(TableProperty.KEY, false);
        table.setColumnHeader(TableProperty.DEFAULT, m_configurableMessages.getColumnHeader(TableProperty.DEFAULT));
        table.setColumnCollapsible(TableProperty.DEFAULT, true);
        table.setColumnHeader(TableProperty.DESCRIPTION, m_configurableMessages.getColumnHeader(TableProperty.DESCRIPTION));
        table.setColumnCollapsible(TableProperty.DESCRIPTION, true);
        table.setColumnHeader(TableProperty.TRANSLATION, m_configurableMessages.getColumnHeader(TableProperty.TRANSLATION));
        table.setColumnCollapsible(TableProperty.TRANSLATION, false);
        table.setColumnHeader(TableProperty.OPTIONS, m_configurableMessages.getColumnHeader(TableProperty.OPTIONS));
        table.setFilterDecorator(new CmsMessageBundleEditorFilterDecorator());
        table.setFilterBarVisible(true);
        table.setColumnCollapsible(TableProperty.OPTIONS, false);
        table.setSortEnabled(true);
        table.setEditable(true);
        table.setSelectable(true);
        table.setImmediate(true);
        table.setMultiSelect(false);
        table.setColumnCollapsingAllowed(m_model.hasDescriptor());
        table.setColumnReorderingAllowed(false);
        m_optionsColumn = generateOptionsColumn(table);
        if (m_model.isShowOptionsColumn(m_model.getEditMode())) {
            table.setFilterFieldVisible(TableProperty.OPTIONS, false);
            table.addGeneratedColumn(TableProperty.OPTIONS, m_optionsColumn);
        }
        table.setColumnWidth(TableProperty.OPTIONS, CmsMessageBundleEditorTypes.OPTION_COLUMN_WIDTH);
        table.setColumnExpandRatio(TableProperty.KEY, 1f);
        table.setColumnExpandRatio(TableProperty.DESCRIPTION, 1f);
        table.setColumnExpandRatio(TableProperty.DEFAULT, 1f);
        table.setColumnExpandRatio(TableProperty.TRANSLATION, 1f);
        table.setPageLength(30);
        table.setCacheRate(1);
        table.sort(new Object[] { TableProperty.KEY }, new boolean[] { true });
        table.addContextClickListener(new ContextClickListener() {

            private static final long serialVersionUID = 1L;

            public void contextClick(ContextClickEvent event) {
                Object itemId = m_table.getValue();
                CmsContextMenu contextMenu = m_model.getContextMenuForItem(itemId);
                if (null != contextMenu) {
                    contextMenu.setAsContextMenuOf(m_table);
                    contextMenu.setOpenAutomatically(false);
                    contextMenu.open(event.getClientX(), event.getClientY());
                }
            }
        });
        table.setNullSelectionAllowed(false);
        table.select(table.getCurrentPageFirsreplacedemId());
        return table;
    }

    /**
     * Disable the save buttons, e.g., after saving.
     */
    private void disableSaveButtons() {
        if (m_saveBtn.isEnabled()) {
            m_saveBtn.setEnabled(false);
            m_saveExitBtn.setEnabled(false);
        }
    }

    /**
     * Adds Editor specific UI components to the toolbar.
     * @param context The context that provides access to the toolbar.
     */
    private void fillToolBar(final I_CmsAppUIContext context) {
        context.setAppreplacedle(m_messages.key(Messages.GUI_APP_replacedLE_0));
        // create components
        Component publishBtn = createPublishButton();
        m_saveBtn = createSaveButton();
        m_saveExitBtn = createSaveExitButton();
        Component closeBtn = createCloseButton();
        context.enableDefaultToolbarButtons(false);
        context.addToolbarButtonRight(closeBtn);
        context.addToolbarButton(publishBtn);
        context.addToolbarButton(m_saveExitBtn);
        context.addToolbarButton(m_saveBtn);
        Component addDescriptorBtn = createAddDescriptorButton();
        if (m_model.hasDescriptor() || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {
            addDescriptorBtn.setEnabled(false);
        }
        context.addToolbarButton(addDescriptorBtn);
        if (m_model.getBundleType().equals(BundleType.XML)) {
            Component convertToPropertyBundleBtn = createConvertToPropertyBundleButton();
            context.addToolbarButton(convertToPropertyBundleBtn);
        }
    }

    /**
     * Generates the options column for the table.
     * @param table table instance preplaceded to the option column generator
     * @return the options column
     */
    private CmsMessageBundleEditorTypes.OptionColumnGenerator generateOptionsColumn(FilterTable table) {
        return new CmsMessageBundleEditorTypes.OptionColumnGenerator(table);
    }

    /**
     * Handle a value change.
     * @param propertyId the column in which the value has changed.
     */
    private void handleChange(Object propertyId) {
        if (!m_saveBtn.isEnabled()) {
            m_saveBtn.setEnabled(true);
            m_saveExitBtn.setEnabled(true);
        }
        m_model.handleChange(propertyId);
    }

    /**
     * Initialize the field factories for the messages table.
     */
    private void initFieldFactories() {
        if (m_model.hasMasterMode()) {
            TranslateTableFieldFactory masterFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(m_table, m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.MASTER));
            masterFieldFactory.registerKeyChangeListener(this);
            m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.MASTER, masterFieldFactory);
        }
        TranslateTableFieldFactory defaultFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(m_table, m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.DEFAULT));
        defaultFieldFactory.registerKeyChangeListener(this);
        m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, defaultFieldFactory);
    }

    /**
     * Initialize the style generators for the messages table.
     */
    private void initStyleGenerators() {
        if (m_model.hasMasterMode()) {
            m_styleGenerators.put(CmsMessageBundleEditorTypes.EditMode.MASTER, new CmsMessageBundleEditorTypes.TranslateTableCellStyleGenerator(m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.MASTER)));
        }
        m_styleGenerators.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, new CmsMessageBundleEditorTypes.TranslateTableCellStyleGenerator(m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.DEFAULT)));
    }

    /**
     * Checks if a key already exists.
     * @param newKey the key to check for.
     * @return <code>true</code> if the key already exists, <code>false</code> otherwise.
     */
    private boolean keyAlreadyExists(String newKey) {
        Collection<?> itemIds = m_table.gereplacedemIds();
        for (Object itemId : itemIds) {
            if (m_table.gereplacedem(itemId).gereplacedemProperty(TableProperty.KEY).getValue().equals(newKey)) {
                return true;
            }
        }
        return false;
    }
}

18 View Complete Implementation : PIPResolverComponent.java
Copyright Apache License 2.0
Author : apache
public clreplaced PIPResolverComponent extends CustomComponent {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Table tableResolvers;

    private final Action ADD_RESOLVER = new Action("Add Resolver");

    private final Action EDIT_RESOLVER = new Action("Edit Resolver");

    private final Action CLONE_RESOLVER = new Action("Clone Resolver");

    private final Action REMOVE_RESOLVER = new Action("Remove Resolver");

    private static final long serialVersionUID = 1L;

    private static final Log logger = LogFactory.getLog(PIPResolverComponent.clreplaced);

    private final PIPResolverComponent self = this;

    private final PIPConfiguration config;

    private final JPAContainer<PIPResolver> resolverContainer = new JPAContainer<PIPResolver>(PIPResolver.clreplaced);

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     */
    public PIPResolverComponent(PIPConfiguration configuration) {
        buildMainLayout();
        setCompositionRoot(mainLayout);
        // 
        // Save
        // 
        this.config = configuration;
        this.resolverContainer.setEnreplacedyProvider(new CachingMutableLocalEnreplacedyProvider<PIPResolver>(PIPResolver.clreplaced, ((XacmlAdminUI) UI.getCurrent()).getEnreplacedyManager()));
        this.resolverContainer.addContainerFilter(new Compare.Equal("pipconfiguration", this.config));
        // 
        // Initialize GUI
        // 
        this.initializeTable();
    }

    protected void initializeTable() {
        // 
        // Setup the container datasource
        // 
        this.tableResolvers.setContainerDataSource(this.resolverContainer);
        // 
        // Set GUI properties
        // 
        this.tableResolvers.setImmediate(true);
        this.tableResolvers.setVisibleColumns(new Object[] { "name", "description", "issuer" });
        this.tableResolvers.setColumnHeaders(new String[] { "Name", "Description", "Issuer" });
        this.tableResolvers.setPageLength(this.config.getPipresolvers().size() + 1);
        this.tableResolvers.setSizeFull();
        this.tableResolvers.setSelectable(true);
        // 
        // Add the actions
        // 
        this.tableResolvers.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    return new Action[] { ADD_RESOLVER };
                }
                return new Action[] { EDIT_RESOLVER, CLONE_RESOLVER, REMOVE_RESOLVER };
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == ADD_RESOLVER) {
                    PIPResolverComponent.addResolver(self.config, null);
                    return;
                }
                if (action == EDIT_RESOLVER) {
                    PIPResolverComponent.editResolver(self.resolverContainer.gereplacedem(target));
                    return;
                }
                if (action == CLONE_RESOLVER) {
                    PIPResolverComponent.addResolver(self.config, self.resolverContainer.gereplacedem(target).getEnreplacedy());
                    return;
                }
                if (action == REMOVE_RESOLVER) {
                    self.removeResolver(self.config, self.resolverContainer.gereplacedem(target).getEnreplacedy());
                    return;
                }
            }
        });
        // 
        // Respond to events
        // 
        this.tableResolvers.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    Object id = event.gereplacedemId();
                    if (id == null) {
                        return;
                    }
                    PIPResolverComponent.editResolver(self.resolverContainer.gereplacedem(id));
                }
            }
        });
    }

    protected void removeResolver(PIPConfiguration config, PIPResolver resolver) {
        config.removePipresolver(resolver);
        this.tableResolvers.removeItem(resolver.getId());
    }

    public static void addResolver(PIPConfiguration config, PIPResolver pipResolver) {
        // 
        // Create the enreplacedy
        // 
        PIPResolver resolver = null;
        if (pipResolver != null) {
            resolver = new PIPResolver(pipResolver);
        } else {
            resolver = new PIPResolver();
        }
        resolver.setCreatedBy(((XacmlAdminUI) UI.getCurrent()).getUserid());
        resolver.setModifiedBy(((XacmlAdminUI) UI.getCurrent()).getUserid());
        resolver.setPipconfiguration(config);
        // 
        // Set its default clreplaced
        // 
        if (config.getPiptype().isSQL()) {
            resolver.setClreplacedname(ConfigurableJDBCResolver.clreplaced.getCanonicalName());
        } else if (config.getPiptype().isLDAP()) {
            resolver.setClreplacedname(ConfigurableLDAPResolver.clreplaced.getCanonicalName());
        } else if (config.getPiptype().isCSV()) {
            resolver.setClreplacedname(ConfigurableCSVResolver.clreplaced.getCanonicalName());
        } else if (config.getPiptype().isHyperCSV()) {
            resolver.setClreplacedname(ConfigurableJDBCResolver.clreplaced.getCanonicalName());
        }
        // 
        // Bring up the editor window
        // 
        PIPResolverComponent.editResolver(((XacmlAdminUI) UI.getCurrent()).getPIPResolvers().createEnreplacedyItem(resolver));
    }

    public static void editResolver(final EnreplacedyItem<PIPResolver> enreplacedy) {
        final PIPResolverEditorWindow window = new PIPResolverEditorWindow(enreplacedy);
        window.setModal(true);
        window.center();
        if (enreplacedy.isPersistent()) {
            window.setCaption("Edit Resolver");
        } else {
            window.setCaption("Create Resolver");
        }
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user click "save"?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Adding a new enreplacedy?
                // 
                if (enreplacedy.isPersistent() == false) {
                    // 
                    // Yes - let's official add it
                    // 
                    ((XacmlAdminUI) UI.getCurrent()).getPIPResolvers().addEnreplacedy(enreplacedy.getEnreplacedy());
                    ((XacmlAdminUI) UI.getCurrent()).refreshPIPConfiguration();
                }
            }
        });
        UI.getCurrent().addWindow(window);
    }

    public static void publishConfiguration(EnreplacedyItem<PIPConfiguration> config) {
        Properties properties = config.getEnreplacedy().generateProperties(Integer.toString(config.getEnreplacedy().getId()));
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            properties.store(os, "");
            if (logger.isDebugEnabled()) {
                logger.debug(os.toString());
            }
        } catch (IOException e) {
        // NOPMD
        // TODO - Handle, Log or NOPMD
        // TODO - Will vaadin display error?
        }
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("-1px");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(false);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // tableResolvers
        tableResolvers = new Table();
        tableResolvers.setCaption("Resolvers");
        tableResolvers.setImmediate(false);
        tableResolvers.setWidth("-1px");
        tableResolvers.setHeight("-1px");
        mainLayout.addComponent(tableResolvers);
        return mainLayout;
    }
}

18 View Complete Implementation : ExpressionBuilderComponent.java
Copyright Apache License 2.0
Author : apache
public clreplaced ExpressionBuilderComponent extends Window implements ApplyParametersChangedListener {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Button buttonSave;

    @AutoGenerated
    private TreeTable treeExpressions;

    @AutoGenerated
    private HorizontalLayout horizontalLayout_1;

    @AutoGenerated
    private CheckBox checkBoxShortName;

    @AutoGenerated
    private Button buttonClearAll;

    @AutoGenerated
    private Button buttonDeleteExpression;

    @AutoGenerated
    private Button buttonAddExpression;

    /*
	 * 
	 * 
	 * 
	 */
    private static final long serialVersionUID = 1L;

    private static Log logger = LogFactory.getLog(ExpressionBuilderComponent.clreplaced);

    private static final Action ADD_EXPRESSION = new Action("Add Expression");

    private static final Action EDIT_EXPRESSION = new Action("Edit Expression");

    private static final Action DELETE_EXPRESSION = new Action("Delete Expression");

    private static final Action ADD_ARGUMENT = new Action("Add Argument");

    private static final Action EDIT_ARGUMENT = new Action("Edit Argument");

    private static final Action DELETE_ARGUMENT = new Action("Delete Argument");

    private final Object[] visibleColumns = new Object[] { ExpressionContainer.PROPERTY_NAME, ExpressionContainer.PROPERTY_ID, ExpressionContainer.PROPERTY_ID_SHORT, ExpressionContainer.PROPERTY_DATATYPE, ExpressionContainer.PROPERTY_DATATYPE_SHORT };

    private final String[] columnHeaders = new String[] { "Name", "XCAML ID or Value", "XCAML ID or Value", "Data Type ID", "Data Type ID" };

    private final ExpressionBuilderComponent self = this;

    private final Object parent;

    private final Map<VariableDefinitionType, PolicyType> variables;

    private final ExpressionContainer container;

    private boolean isSaved = false;

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     */
    public ExpressionBuilderComponent(Object parent, Object root, FunctionArgument argument, Map<VariableDefinitionType, PolicyType> variables) {
        buildMainLayout();
        // setCompositionRoot(mainLayout);
        setContent(mainLayout);
        // 
        // Save our data
        // 
        this.parent = parent;
        this.variables = variables;
        this.container = new ExpressionContainer(parent, root, argument);
        // 
        // Make sure we support the parent object
        // 
        if (this.isSupported() == false) {
            throw new IllegalArgumentException("Unsupported object type");
        }
        // 
        // Set our shortcuts
        // 
        this.setCloseShortcut(KeyCode.ESCAPE);
        // 
        // Finish our GUI initialization
        // 
        this.initializeTree();
        this.initializeButtons();
        this.initializeCheckbox();
        // 
        // Setup the buttons
        // 
        this.setupButtons();
    }

    private boolean isSupported() {
        return this.isParentACondition() || this.isParentAVariable() || this.isParentAreplacedignment();
    }

    private boolean isParentACondition() {
        return this.parent instanceof ConditionType;
    }

    private boolean isParentAVariable() {
        return this.parent instanceof VariableDefinitionType;
    }

    private boolean isParentAreplacedignment() {
        return this.parent instanceof AttributereplacedignmentExpressionType;
    }

    private void initializeTree() {
        // 
        // Initialize GUI properties
        // 
        this.treeExpressions.setImmediate(true);
        this.treeExpressions.setSelectable(true);
        // 
        // Initialize the data source
        // 
        this.treeExpressions.setContainerDataSource(this.container);
        this.treeExpressions.sereplacedemCaptionMode(ItemCaptionMode.PROPERTY);
        this.treeExpressions.setVisibleColumns(this.visibleColumns);
        this.treeExpressions.setColumnHeaders(this.columnHeaders);
        this.treeExpressions.setColumnCollapsingAllowed(true);
        this.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_ID, true);
        this.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_DATATYPE, true);
        // 
        // Add our action handler
        // 
        this.treeExpressions.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    if (self.container.size() == 0) {
                        return new Action[] { ADD_EXPRESSION };
                    }
                    return null;
                }
                if (target instanceof ApplyType && XACMLFunctionValidator.canHaveMoreArguments((ApplyType) target)) {
                    return new Action[] { ADD_ARGUMENT, EDIT_EXPRESSION, DELETE_EXPRESSION };
                }
                return new Action[] { EDIT_ARGUMENT, DELETE_ARGUMENT };
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == ADD_EXPRESSION && target == null) {
                    self.addExpression(null, null);
                }
                if (action == EDIT_EXPRESSION && target != null) {
                    self.editExpression(target, (ApplyType) self.container.getParent(target), (FunctionArgument) self.container.getArgument(target));
                }
                if (action == DELETE_EXPRESSION && target != null) {
                    self.deleteExpression(target);
                }
                if (action == ADD_ARGUMENT && target != null && target instanceof ApplyType) {
                    self.addArgument((ApplyType) target);
                }
                if (action == EDIT_ARGUMENT && target != null) {
                    self.editExpression(target, (ApplyType) self.container.getParent(target), (FunctionArgument) self.container.getArgument(target));
                }
                if (action == DELETE_ARGUMENT && target != null) {
                    self.deleteExpression(target);
                }
            }
        });
        // 
        // Listen to double-click item selections
        // 
        this.treeExpressions.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    // self.treeExpressions.getValue();
                    Object target = event.gereplacedemId();
                    if (target == null) {
                        return;
                    }
                    self.editExpression(target, (ApplyType) self.container.getParent(target), (FunctionArgument) self.container.getArgument(target));
                }
            }
        });
        // 
        // Listen when the user selects a row
        // 
        this.treeExpressions.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                self.setupButtons();
            }
        });
        // 
        // Listen to when the table contents change
        // 
        this.treeExpressions.addItemSetChangeListener(new ItemSetChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void containerItemSetChange(ItemSetChangeEvent event) {
                self.validateExpression();
            }
        });
        // 
        // Expand columns automatically
        // 
        this.treeExpressions.setColumnExpandRatio(ExpressionContainer.PROPERTY_NAME, 1.0f);
        this.treeExpressions.setColumnExpandRatio(ExpressionContainer.PROPERTY_ID, 1.0f);
        this.treeExpressions.setColumnExpandRatio(ExpressionContainer.PROPERTY_DATATYPE, 1.0f);
        // 
        // Expand all the children
        // 
        for (Object id : this.treeExpressions.gereplacedemIds()) {
            this.treeExpressions.setCollapsed(id, false);
        }
        // 
        // Have a description generator
        // 
        this.treeExpressions.sereplacedemDescriptionGenerator(new ItemDescriptionGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public String generateDescription(Component source, Object itemId, Object propertyId) {
                if (propertyId != null && propertyId.equals(ExpressionContainer.PROPERTY_NAME) && itemId instanceof ApplyType) {
                    return ((ApplyType) itemId).getDescription();
                }
                return null;
            }
        });
    }

    private void initializeButtons() {
        this.buttonClearAll.setImmediate(true);
        this.buttonClearAll.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.clearAllExpressions();
            }
        });
        this.buttonAddExpression.setImmediate(true);
        this.buttonAddExpression.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                Object selected = self.treeExpressions.getValue();
                if (selected == null) {
                    // 
                    // Adding a root expression
                    // 
                    self.addExpression(null, null);
                } else {
                    // 
                    // Adding an argument
                    // 
                    if (selected instanceof ApplyType) {
                        // 
                        // Get the function
                        // 
                        self.addArgument((ApplyType) selected);
                    }
                }
            }
        });
        this.buttonDeleteExpression.setImmediate(true);
        this.buttonDeleteExpression.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                Object id = self.treeExpressions.getValue();
                if (id == null) {
                    logger.error("Delete button clicked on null selection");
                    return;
                }
                self.deleteExpression(id);
            }
        });
        this.buttonSave.setImmediate(true);
        this.buttonSave.setClickShortcut(KeyCode.ENTER);
        this.buttonSave.setEnabled(false);
        this.buttonSave.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                // 
                // TODO validate
                // 
                // 
                // Mark that we are saved
                // 
                self.isSaved = true;
                // 
                // Close the window
                // 
                self.close();
            }
        });
    }

    protected void initializeCheckbox() {
        this.checkBoxShortName.setValue(true);
        this.checkBoxShortName.setImmediate(true);
        this.checkBoxShortName.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                self.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_ID, self.checkBoxShortName.getValue());
                self.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_DATATYPE, self.checkBoxShortName.getValue());
                self.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_ID_SHORT, !self.checkBoxShortName.getValue());
                self.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_DATATYPE_SHORT, !self.checkBoxShortName.getValue());
            }
        });
    }

    protected void setupButtons() {
        if (this.treeExpressions.size() == 0) {
            this.buttonAddExpression.setEnabled(true);
            this.buttonClearAll.setEnabled(false);
            this.buttonSave.setEnabled(false);
        } else {
            this.validateExpression();
            this.buttonAddExpression.setEnabled(false);
            this.buttonClearAll.setEnabled(true);
        }
        Object value = this.treeExpressions.getValue();
        if (value == null) {
            this.buttonDeleteExpression.setEnabled(false);
        } else {
            this.buttonDeleteExpression.setEnabled(true);
        }
    }

    protected void validateExpression() {
        boolean valid = false;
        boolean canHaveMore = false;
        if (this.isParentACondition()) {
            valid = XACMLFunctionValidator.validateCondition((ConditionType) this.parent);
            canHaveMore = XACMLFunctionValidator.canHaveMoreArguments((ConditionType) this.parent);
        } else if (this.isParentAVariable()) {
            valid = XACMLFunctionValidator.validateVariable((VariableDefinitionType) this.parent);
            canHaveMore = XACMLFunctionValidator.canHaveMoreArguments((VariableDefinitionType) this.parent);
        } else if (this.isParentAreplacedignment()) {
            valid = XACMLFunctionValidator.validatereplacedignment((AttributereplacedignmentExpressionType) this.parent);
            canHaveMore = XACMLFunctionValidator.canHaveMoreArguments((AttributereplacedignmentExpressionType) this.parent);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("valid: " + valid + " canHaveMore: " + canHaveMore);
        }
        // this.buttonAddExpression.setEnabled(canHaveMore);
        this.buttonSave.setEnabled(valid);
    }

    protected void addArgument(final ApplyType parentApply) {
        // 
        // Get the function
        // 
        FunctionDefinition function = JPAUtils.findFunction(parentApply.getFunctionId());
        if (function != null) {
            FunctionArgument argument = XACMLFunctionValidator.getFunctionArgument(parentApply.getExpression().size() + 1, function);
            if (logger.isDebugEnabled()) {
                logger.debug("Add Argument: " + argument);
            }
            replacedert argument != null;
            // 
            // Is this a high order bag function? And it's data type not defined? (most likely)
            // 
            if (function.isHigherOrder() && argument.getDatatypeBean() == null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("isHighOrder and a null datatype bean");
                }
                // 
                // Get what the data type restriction should be
                // 
                try {
                    replacedert parentApply.getExpression().size() > 0;
                    JAXBElement<?> element = parentApply.getExpression().get(0);
                    replacedert element != null && element.getValue() != null;
                    Object declaredFunction = element.getValue();
                    replacedert declaredFunction instanceof FunctionType;
                    FunctionDefinition declaredFunctionDefinition = JPAUtils.findFunction(((FunctionType) declaredFunction).getFunctionId());
                    replacedert declaredFunctionDefinition != null;
                    if (logger.isDebugEnabled()) {
                        logger.debug("declaredFunction is: " + declaredFunctionDefinition);
                    }
                    FunctionArgument declaredFunctionArgument = XACMLFunctionValidator.getFunctionArgument(parentApply.getExpression().size(), declaredFunctionDefinition);
                    replacedert declaredFunctionArgument != null;
                    if (logger.isDebugEnabled()) {
                        logger.debug("declaredFunctionArgument is: " + declaredFunctionArgument);
                    }
                    // 
                    // Copy the argument
                    // 
                    argument = new FunctionArgument(argument);
                    argument.setDatatypeBean(declaredFunctionArgument.getDatatypeBean());
                } catch (Exception e) {
                    logger.error("Exception while determining parent apply's FunctionType argument datatype.");
                }
            }
            self.addExpression(parentApply, argument);
        } else {
            AdminNotification.error("ApplyType does not have a function defined. Please define that first.");
        }
    }

    protected void addExpression(final ApplyType parentApply, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("Adding Expression: " + parentApply + " arg: " + argument);
        }
        // 
        // First we need to select what Expression They want
        // 
        final ExpressionSelectionWindow selector = new ExpressionSelectionWindow(parentApply, this.isParentAreplacedignment(), (argument != null ? argument.isBag() : false), (argument != null ? !argument.isBag() : false));
        selector.setCaption("Select the Expression Type");
        selector.setModal(true);
        selector.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Was something selected?
                // 
                String selection = selector.getSelection();
                if (selection == null) {
                    return;
                }
                // 
                // What did the user select?
                // 
                if (selection.equals(ExpressionSelectionWindow.OPTION_APPLY)) {
                    // 
                    self.editApply(new ApplyType(), parentApply, argument);
                // 
                } else if (selection.equals(ExpressionSelectionWindow.OPTION_DESIGNATOR)) {
                    // 
                    self.editAttribute(new AttributeDesignatorType(), parentApply, argument);
                // 
                } else if (selection.equals(ExpressionSelectionWindow.OPTION_SELECTOR)) {
                    // 
                    self.editAttribute(new AttributeSelectorType(), parentApply, argument);
                // 
                } else if (selection.equals(ExpressionSelectionWindow.OPTION_VALUE)) {
                    // 
                    self.editValue(new AttributeValueType(), parentApply, argument);
                // 
                } else if (selection.equals(ExpressionSelectionWindow.OPTION_VARIABLE)) {
                    // 
                    self.editVariable(new VariableReferenceType(), parentApply, argument);
                // 
                }
            }
        });
        selector.center();
        UI.getCurrent().addWindow(selector);
    }

    protected void editApply(final ApplyType apply, final ApplyType parent, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("editApply: " + apply + " parent: " + parent + " :" + argument);
        }
        // 
        // Copy the apply and create its window
        // 
        final ApplyType copyApply = XACMLObjectCopy.copy(apply);
        final ApplyEditorWindow window = new ApplyEditorWindow(copyApply, parent, argument, self.parent);
        window.setCaption("Edit The Apply Expression");
        window.setModal(true);
        // 
        // Set ourselves as an ApplyParametersChanged listener
        // 
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Copy back the apply
                // 
                apply.setDescription(copyApply.getDescription());
                apply.setFunctionId(copyApply.getFunctionId());
                // 
                // Get the function information
                // 
                FunctionDefinition function = JPAUtils.findFunction(apply.getFunctionId());
                replacedert function != null;
                // 
                // Is this a new Apply?
                // 
                if (self.container.containsId(apply)) {
                    // 
                    // No - we are updating
                    // 
                    self.container.updateItem(apply);
                } else {
                    // 
                    // Is this a higher-order bag function?
                    // 
                    if (function.isHigherOrder()) {
                        // 
                        // Have the user select a function for it
                        // 
                        final FunctionSelectionWindow functionSelection = new FunctionSelectionWindow(null);
                        functionSelection.setCaption("Select Function");
                        functionSelection.setModal(true);
                        functionSelection.addCloseListener(new CloseListener() {

                            private static final long serialVersionUID = 1L;

                            @Override
                            public void windowClose(CloseEvent e) {
                                // 
                                // Did the user save?
                                // 
                                if (functionSelection.isSaved() == false) {
                                    return;
                                }
                                // 
                                // Get the function
                                // 
                                String function = functionSelection.getSelectedFunction();
                                if (function == null || function.isEmpty()) {
                                    logger.error("Function window said it was saved, but there was no function.");
                                    return;
                                }
                                // 
                                // Create the function object
                                // 
                                FunctionType hoFunction = new FunctionType();
                                hoFunction.setFunctionId(function);
                                // 
                                // Add it into the apply
                                // 
                                apply.getExpression().add(new ObjectFactory().createFunction(hoFunction));
                                // 
                                // New Item
                                // 
                                Item item = self.container.addItem(apply, parent, argument);
                                replacedert item != null;
                                self.treeExpressions.setCollapsed(apply, false);
                                self.treeExpressions.select(apply);
                            }
                        });
                        functionSelection.center();
                        UI.getCurrent().addWindow(functionSelection);
                    } else {
                        // 
                        // New Item
                        // 
                        Item item = self.container.addItem(apply, parent, argument);
                        replacedert item != null;
                        self.treeExpressions.setCollapsed(apply, false);
                        self.treeExpressions.select(apply);
                    }
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editAttribute(final Object target, final ApplyType parent, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("editAttribute: " + target + " parent: " + parent + " :" + argument);
        }
        // 
        // Determine what the data type needs to be
        // 
        Datatype datatype = null;
        if (parent == null && this.isParentACondition()) {
            datatype = JPAUtils.getBooleanDatatype();
        } else {
            if (argument != null) {
                datatype = argument.getDatatypeBean();
            }
        }
        // 
        // Copy the attribute
        // 
        final Object copyAttribute = XACMLObjectCopy.deepCopy(target);
        // 
        // Create the window
        // 
        final AttributeSelectionWindow window = new AttributeSelectionWindow(datatype, copyAttribute);
        if (target instanceof AttributeDesignatorType) {
            window.setCaption("Edit Designator " + (((AttributeDesignatorType) target).getAttributeId() != null ? ((AttributeDesignatorType) target).getAttributeId() : ""));
        } else {
            window.setCaption("Edit Selector " + (((AttributeSelectorType) target).getContextSelectorId() != null ? ((AttributeSelectorType) target).getContextSelectorId() : ""));
        }
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user hit save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Grab the attribute
                // 
                Attribute attribute = window.getAttribute();
                if (attribute == null) {
                    return;
                }
                // 
                // Save it back into the original
                // 
                if (target instanceof AttributeDesignatorType) {
                    ((AttributeDesignatorType) target).setAttributeId(attribute.getXacmlId());
                    ((AttributeDesignatorType) target).setCategory(attribute.getCategoryBean().getXacmlId());
                    ((AttributeDesignatorType) target).setDataType(attribute.getDatatypeBean().getXacmlId());
                    ((AttributeDesignatorType) target).setIssuer(attribute.getIssuer());
                    ((AttributeDesignatorType) target).setMustBePresent(attribute.isMustBePresent());
                } else {
                    ((AttributeSelectorType) target).setContextSelectorId(attribute.getXacmlId());
                    ((AttributeSelectorType) target).setCategory(attribute.getCategoryBean().getXacmlId());
                    ((AttributeSelectorType) target).setDataType(attribute.getDatatypeBean().getXacmlId());
                    ((AttributeSelectorType) target).setPath(attribute.getSelectorPath());
                    ((AttributeSelectorType) target).setMustBePresent(attribute.isMustBePresent());
                }
                // 
                // Is this a new item?
                // 
                if (self.container.containsId(target)) {
                    // 
                    // No, just update the container
                    // 
                    self.container.updateItem(target);
                } else {
                    // 
                    // Yes a new item, add it in
                    // 
                    // replacedert(self.container.addItem(JPAUtils.createDesignator(attribute), parent, argument) != null);
                    Item item = self.container.addItem(target, parent, argument);
                    replacedert item != null;
                    self.treeExpressions.select(target);
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editValue(final AttributeValueType value, final ApplyType parent, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("editvalue: " + value + " parent: " + parent + " :" + argument);
        }
        // 
        // Copy the attribute value
        // 
        final AttributeValueType copyValue = XACMLObjectCopy.copy(value);
        // 
        // Get what the datatype should be
        // 
        Datatype datatypeRestriction = null;
        // 
        // Is this a root?
        // 
        if (parent == null) {
            // 
            // Check if our parent container is a condition
            // 
            if (self.isParentACondition()) {
                // 
                // We are only allowed to return boolean's
                // 
                datatypeRestriction = JPAUtils.getBooleanDatatype();
            }
        } else {
            // 
            // Are we an argument?
            // 
            if (argument != null) {
                // 
                // Yes - we are restricted to that argument's datatype
                // 
                datatypeRestriction = argument.getDatatypeBean();
            }
        }
        // 
        // Create the window
        // 
        final AttributeValueEditorWindow window = new AttributeValueEditorWindow(copyValue, datatypeRestriction);
        window.setCaption("Edit Attribute Value");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user click save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Yes - get the value
                // 
                value.getContent().clear();
                for (Object o : copyValue.getContent()) {
                    value.getContent().add(o);
                }
                value.setDataType(copyValue.getDataType());
                // 
                // Was this a new value?
                // 
                if (self.container.containsId(value)) {
                    // 
                    // No - update it
                    // 
                    self.container.updateItem(value);
                } else {
                    // 
                    // Yes - add it in
                    // 
                    Item item = self.container.addItem(value, parent, argument);
                    replacedert item != null;
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editVariable(final VariableReferenceType variable, final ApplyType parent, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("editVariable: " + variable + " parent: " + parent + " :" + argument);
        }
        // 
        // Copy the variable
        // 
        final VariableReferenceType copyVariable = XACMLObjectCopy.copy(variable);
        // 
        // Create the window
        // 
        final VariableReferenceEditorWindow window = new VariableReferenceEditorWindow(copyVariable, this.variables);
        window.setCaption("Edit Variable Reference");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user click save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Copy the variable changes back
                // 
                variable.setVariableId(copyVariable.getVariableId());
                // 
                // Is this a new one?
                // 
                if (self.container.containsId(variable)) {
                    // 
                    // No - update it
                    // 
                    self.container.updateItem(variable);
                } else {
                    // 
                    // Yes - add it
                    // 
                    Item item = self.container.addItem(variable, parent, argument);
                    replacedert item != null;
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editFunction(final FunctionType func, final ApplyType parent, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("editFunction: " + func + " parent: " + parent + " :" + argument);
        }
        final FunctionSelectionWindow functionSelection = new FunctionSelectionWindow((func != null ? func.getFunctionId() : null));
        functionSelection.setCaption("Edit Function");
        functionSelection.setModal(true);
        functionSelection.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user save?
                // 
                if (functionSelection.isSaved() == false) {
                    return;
                }
                // 
                // Get the function
                // 
                String function = functionSelection.getSelectedFunction();
                if (function == null || function.isEmpty()) {
                    logger.error("Function window said it was saved, but there was no function.");
                    return;
                }
                // 
                // New one?
                // 
                if (func == null) {
                    // 
                    // Create the function object
                    // 
                    FunctionType hoFunction = new FunctionType();
                    hoFunction.setFunctionId(function);
                    // 
                    // Add it into the apply
                    // 
                    replacedert parent.getExpression().size() == 0;
                    parent.getExpression().add(new ObjectFactory().createFunction(hoFunction));
                    // 
                    // New Item
                    // 
                    Item item = self.container.addItem(func, parent, argument);
                    replacedert item != null;
                    self.treeExpressions.setCollapsed(parent, false);
                    self.treeExpressions.select(func);
                } else {
                    // 
                    // Editing an existing
                    // 
                    func.setFunctionId(function);
                    self.container.updateItem(func);
                    // 
                    // Warn user
                    // 
                    if (parent.getExpression().size() > 1) {
                        AdminNotification.warn("You have updated the function ID. The rest of the arguments may be invalid for the function. Please verify the other arguments.");
                    }
                }
            }
        });
        functionSelection.center();
        UI.getCurrent().addWindow(functionSelection);
    }

    protected void editExpression(final Object target, final ApplyType parent, final FunctionArgument argument) {
        if (target instanceof ApplyType) {
            // 
            this.editApply((ApplyType) target, parent, argument);
        // 
        } else if (target instanceof AttributeValueType) {
            // 
            this.editValue((AttributeValueType) target, parent, argument);
        // 
        } else if (target instanceof AttributeDesignatorType || target instanceof AttributeSelectorType) {
            // 
            this.editAttribute(target, parent, argument);
        // 
        } else if (target instanceof VariableReferenceType) {
            // 
            this.editVariable((VariableReferenceType) target, parent, argument);
        // 
        } else if (target instanceof FunctionType) {
            // 
            this.editFunction((FunctionType) target, parent, argument);
        // 
        }
    }

    protected void deleteExpression(Object target) {
        if (this.container.isRoot(target)) {
            if (this.treeExpressions.removeAllItems() == false) {
                logger.error("Failed to remove everything.");
            }
        } else {
            if (this.treeExpressions.removeItem(target) == false) {
                logger.error("Failed to remove " + target);
            }
        }
        this.setupButtons();
    }

    protected void clearAllExpressions() {
        if (this.treeExpressions.removeAllItems() == false) {
            logger.error("Failed to remove everything.");
        }
        this.setupButtons();
    }

    @Override
    public void applyParameterChanged(ApplyType apply, ApplyType parent, FunctionArgument argument, Object container) {
        logger.info("applyParameterChanged: " + apply + " " + parent + " " + argument + " " + container);
    // 
    // TODO - figure out if this something being edited, or a new one
    // 
    }

    public boolean isSaved() {
        return this.isSaved;
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("100%");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // horizontalLayout_1
        horizontalLayout_1 = buildHorizontalLayout_1();
        mainLayout.addComponent(horizontalLayout_1);
        mainLayout.setExpandRatio(horizontalLayout_1, 1.0f);
        // treeExpressions
        treeExpressions = new TreeTable();
        treeExpressions.setImmediate(false);
        treeExpressions.setWidth("100.0%");
        treeExpressions.setHeight("-1px");
        mainLayout.addComponent(treeExpressions);
        mainLayout.setExpandRatio(treeExpressions, 1.0f);
        // buttonSave
        buttonSave = new Button();
        buttonSave.setCaption("Save");
        buttonSave.setImmediate(true);
        buttonSave.setWidth("-1px");
        buttonSave.setHeight("-1px");
        mainLayout.addComponent(buttonSave);
        mainLayout.setComponentAlignment(buttonSave, new Alignment(48));
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayout_1() {
        // common part: create layout
        horizontalLayout_1 = new HorizontalLayout();
        horizontalLayout_1.setImmediate(false);
        horizontalLayout_1.setWidth("-1px");
        horizontalLayout_1.setHeight("-1px");
        horizontalLayout_1.setMargin(false);
        horizontalLayout_1.setSpacing(true);
        // buttonAddExpression
        buttonAddExpression = new Button();
        buttonAddExpression.setCaption("Add Expression");
        buttonAddExpression.setImmediate(true);
        buttonAddExpression.setWidth("-1px");
        buttonAddExpression.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonAddExpression);
        // buttonDeleteExpression
        buttonDeleteExpression = new Button();
        buttonDeleteExpression.setCaption("Delete Expression");
        buttonDeleteExpression.setImmediate(true);
        buttonDeleteExpression.setWidth("-1px");
        buttonDeleteExpression.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonDeleteExpression);
        // buttonClearAll
        buttonClearAll = new Button();
        buttonClearAll.setCaption("Clear All");
        buttonClearAll.setImmediate(true);
        buttonClearAll.setDescription("Clears all the expressions.");
        buttonClearAll.setWidth("-1px");
        buttonClearAll.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonClearAll);
        // checkBoxShortName
        checkBoxShortName = new CheckBox();
        checkBoxShortName.setCaption("Display Short XACML ID's");
        checkBoxShortName.setImmediate(false);
        checkBoxShortName.setDescription("If checked, the right-most string of the function and datatype URI's will only be displayed.");
        checkBoxShortName.setWidth("-1px");
        checkBoxShortName.setHeight("-1px");
        horizontalLayout_1.addComponent(checkBoxShortName);
        return horizontalLayout_1;
    }
}

18 View Complete Implementation : ObligationAdviceEditorWindow.java
Copyright Apache License 2.0
Author : apache
public clreplaced ObligationAdviceEditorWindow extends Window {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Button buttonSave;

    @AutoGenerated
    private TreeTable tableExpressions;

    @AutoGenerated
    private HorizontalLayout horizontalLayout_1;

    @AutoGenerated
    private Button buttonClear;

    @AutoGenerated
    private Button buttonRemove;

    @AutoGenerated
    private Button buttonAdd;

    /**
     */
    private static final long serialVersionUID = 1L;

    private static Log logger = LogFactory.getLog(ObligationAdviceEditorWindow.clreplaced);

    private final ObligationAdviceEditorWindow self = this;

    private final Object root;

    private final Map<VariableDefinitionType, PolicyType> variables;

    private ObligationAdviceContainer container;

    private boolean isSaved = false;

    private static final Action ADD_OBLIGATION = new Action("Add Obligation");

    private static final Action ADD_ADVICE = new Action("Add Advice");

    private static final Action ADD_EXPRESSION = new Action("Add Expression");

    private static final Action ADD_ATTRIBUTE = new Action("Add Attribute");

    private static final Action EDIT_OBLIGATION = new Action("Edit Obligation");

    private static final Action EDIT_ADVICE = new Action("Edit Advice");

    private static final Action EDIT_EXPRESSION = new Action("Edit Expression");

    private static final Action EDIT_ATTRIBUTE = new Action("Edit Attribute");

    private static final Action REMOVE_OBLIGATION = new Action("Remove Obligation");

    private static final Action REMOVE_ADVICE = new Action("Remove Advice");

    private static final Action REMOVE_EXPRESSION = new Action("Remove Expression");

    private static final Action REMOVE_ATTRIBUTE = new Action("Remove Attribute");

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     */
    public ObligationAdviceEditorWindow(Object root, Map<VariableDefinitionType, PolicyType> variables) {
        buildMainLayout();
        // setCompositionRoot(mainLayout);
        setContent(mainLayout);
        // 
        // Save
        // 
        if (!(root instanceof ObligationExpressionsType) && !(root instanceof AdviceExpressionsType)) {
            throw new IllegalArgumentException("This window supports Obligation or Advice Expressions only.");
        }
        this.root = root;
        this.variables = variables;
        this.container = new ObligationAdviceContainer(this.root);
        // 
        // Set our shortcuts
        // 
        this.setCloseShortcut(KeyCode.ESCAPE);
        // 
        // Initialize GUI
        // 
        this.initializeTable();
        this.initializeButtons();
        this.setupButtons();
        // 
        // Focus
        // 
        this.tableExpressions.focus();
    }

    protected void initializeTable() {
        // 
        // GUI properties
        // 
        this.tableExpressions.setImmediate(true);
        // 
        // Set the container
        // 
        this.tableExpressions.setContainerDataSource(this.container);
        this.tableExpressions.setVisibleColumns(new Object[] { ObligationAdviceContainer.PROPERTY_NAME, ObligationAdviceContainer.PROPERTY_ID_SHORT, ObligationAdviceContainer.PROPERTY_EFFECT, ObligationAdviceContainer.PROPERTY_CATEGORY_SHORT, ObligationAdviceContainer.PROPERTY_DATATYPE_SHORT });
        this.tableExpressions.setColumnHeaders(new String[] { "Name", "ID or Value", (this.root instanceof ObligationExpressionsType ? "Effect" : "Applies"), "Category", "Data Type" });
        // this.tableExpressions.setColumnExpandRatio(ObligationAdviceContainer.PROPERTY_NAME, 1.0f);
        // this.tableExpressions.setColumnExpandRatio(ObligationAdviceContainer.PROPERTY_ID_SHORT, 1.0f);
        // this.tableExpressions.setColumnWi
        this.tableExpressions.setSelectable(true);
        // 
        // Expand it out
        // 
        for (Object item : this.tableExpressions.gereplacedemIds()) {
            this.tableExpressions.setCollapsed(item, false);
            for (Object child : this.tableExpressions.getChildren(item)) {
                this.tableExpressions.setCollapsed(child, false);
            }
        }
        this.tableExpressions.setPageLength(this.container.size() + 3);
        // 
        // Respond to events
        // 
        this.tableExpressions.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    if (self.root instanceof ObligationExpressionsType) {
                        return new Action[] { ADD_OBLIGATION };
                    }
                    if (self.root instanceof AdviceExpressionsType) {
                        return new Action[] { ADD_ADVICE };
                    }
                }
                if (target instanceof ObligationExpressionType) {
                    return new Action[] { EDIT_OBLIGATION, REMOVE_OBLIGATION, ADD_EXPRESSION };
                }
                if (target instanceof AdviceExpressionType) {
                    return new Action[] { EDIT_ADVICE, REMOVE_ADVICE, ADD_EXPRESSION };
                }
                if (target instanceof AttributereplacedignmentExpressionType) {
                    return new Action[] { EDIT_EXPRESSION, REMOVE_EXPRESSION, ADD_ATTRIBUTE };
                }
                if (target instanceof AttributeValueType || target instanceof AttributeDesignatorType || target instanceof AttributeSelectorType || target instanceof ApplyType) {
                    return new Action[] { EDIT_ATTRIBUTE, REMOVE_ATTRIBUTE };
                }
                return null;
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == ADD_OBLIGATION) {
                    self.editObligation(null);
                    return;
                }
                if (action == EDIT_OBLIGATION) {
                    replacedert target instanceof ObligationExpressionType;
                    self.editObligation((ObligationExpressionType) target);
                    return;
                }
                if (action == REMOVE_OBLIGATION) {
                    replacedert target instanceof ObligationExpressionType;
                    if (self.container.removeItem(target) == false) {
                        logger.error("Failed to remove obligation");
                        replacedert false;
                    }
                    return;
                }
                if (action == ADD_ADVICE) {
                    self.editAdvice(null);
                    return;
                }
                if (action == EDIT_ADVICE) {
                    replacedert target instanceof AdviceExpressionType;
                    self.editAdvice((AdviceExpressionType) target);
                    return;
                }
                if (action == REMOVE_ADVICE) {
                    replacedert target instanceof AdviceExpressionType;
                    if (self.container.removeItem(target) == false) {
                        logger.error("Failed to remove advice");
                        replacedert false;
                    }
                    return;
                }
                if (action == ADD_EXPRESSION) {
                    replacedert target instanceof ObligationExpressionType || target instanceof AdviceExpressionType;
                    self.editExpression(null, target);
                    return;
                }
                if (action == EDIT_EXPRESSION) {
                    replacedert target instanceof AttributereplacedignmentExpressionType;
                    self.editExpression((AttributereplacedignmentExpressionType) target, self.container.getParent(target));
                    return;
                }
                if (action == REMOVE_EXPRESSION) {
                    replacedert target instanceof AttributereplacedignmentExpressionType;
                    if (self.container.removeItem(target) == false) {
                        logger.error("Failed to remove expression");
                        replacedert false;
                    }
                    return;
                }
                if (action == ADD_ATTRIBUTE) {
                    replacedert target instanceof AttributereplacedignmentExpressionType;
                    self.editAttribute(null, (AttributereplacedignmentExpressionType) target);
                    return;
                }
                if (action == EDIT_ATTRIBUTE) {
                    replacedert target instanceof AttributeValueType || target instanceof AttributeDesignatorType || target instanceof AttributeSelectorType || target instanceof ApplyType;
                    self.editAttribute(target, (AttributereplacedignmentExpressionType) self.container.getParent(target));
                    return;
                }
                if (action == REMOVE_ATTRIBUTE) {
                    replacedert target instanceof AttributeValueType || target instanceof AttributeDesignatorType || target instanceof AttributeSelectorType || target instanceof ApplyType;
                    if (self.container.removeItem(target) == false) {
                        logger.error("Failed to remove attribute");
                        replacedert false;
                    }
                    return;
                }
            }
        });
        // 
        // Respond to selections
        // 
        this.tableExpressions.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                self.setupButtons();
            }
        });
        this.tableExpressions.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    if (event.getSource() instanceof AdviceExpressionType) {
                        self.editAdvice((AdviceExpressionType) event.getSource());
                    } else if (event.getSource() instanceof ObligationExpressionType) {
                        self.editObligation((ObligationExpressionType) event.getSource());
                    } else if (event.getSource() instanceof AttributereplacedignmentExpressionType) {
                        self.editExpression((AttributereplacedignmentExpressionType) event.getSource(), self.container.getParent(event.getSource()));
                    } else {
                        self.editAttribute(event.getSource(), (AttributereplacedignmentExpressionType) self.container.getParent(event.getSource()));
                    }
                }
            }
        });
        // 
        // Implement a description generator, to display the full XACML ID.
        // 
        this.tableExpressions.sereplacedemDescriptionGenerator(new ItemDescriptionGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public String generateDescription(Component source, Object itemId, Object propertyId) {
                if (propertyId == ObligationAdviceContainer.PROPERTY_ID_SHORT) {
                    if (itemId instanceof AdviceExpressionType) {
                        return ((AdviceExpressionType) itemId).getAdviceId();
                    }
                    if (itemId instanceof ObligationExpressionType) {
                        return ((ObligationExpressionType) itemId).getObligationId();
                    }
                    if (itemId instanceof AttributereplacedignmentExpressionType) {
                        return ((AttributereplacedignmentExpressionType) itemId).getAttributeId();
                    }
                    if (itemId instanceof AttributeDesignatorType) {
                        return ((AttributeDesignatorType) itemId).getAttributeId();
                    }
                    if (itemId instanceof AttributeSelectorType) {
                        return ((AttributeSelectorType) itemId).getContextSelectorId();
                    }
                    if (itemId instanceof ApplyType) {
                        return ((ApplyType) itemId).getDescription();
                    }
                }
                if (propertyId == ObligationAdviceContainer.PROPERTY_CATEGORY_SHORT) {
                    if (itemId instanceof AttributereplacedignmentExpressionType) {
                        return ((AttributereplacedignmentExpressionType) itemId).getCategory();
                    }
                    if (itemId instanceof AttributeDesignatorType) {
                        return ((AttributeDesignatorType) itemId).getCategory();
                    }
                    if (itemId instanceof AttributeSelectorType) {
                        return ((AttributeSelectorType) itemId).getCategory();
                    }
                    if (itemId instanceof ApplyType) {
                        return null;
                    }
                }
                if (propertyId == ObligationAdviceContainer.PROPERTY_DATATYPE_SHORT) {
                    if (itemId instanceof AttributeValueType) {
                        return ((AttributeValueType) itemId).getDataType();
                    }
                    if (itemId instanceof AttributeDesignatorType) {
                        return ((AttributeDesignatorType) itemId).getDataType();
                    }
                    if (itemId instanceof AttributeSelectorType) {
                        return ((AttributeSelectorType) itemId).getDataType();
                    }
                /*
					if (itemId instanceof ApplyType) {
						//
						// TODO - get the datatype for the function
						//
					}
					*/
                }
                return null;
            }
        });
    }

    protected void initializeButtons() {
        this.buttonAdd.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                if (self.tableExpressions.getValue() == null) {
                    // 
                    // Add new root advice or obligation
                    // 
                    if (self.root instanceof AdviceExpressionsType) {
                        self.editAdvice(null);
                    } else {
                        self.editObligation(null);
                    }
                } else {
                    // 
                    // Add new replacedignment expression
                    // 
                    self.editExpression(null, self.tableExpressions.getValue());
                }
            }
        });
        this.buttonRemove.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                Object object = self.tableExpressions.getValue();
                if (object != null) {
                    if (object instanceof AttributeValueType || object instanceof AttributeDesignatorType || object instanceof AttributeSelectorType || object instanceof ApplyType) {
                        if (self.container.removeItem(self.container.getParent(object)) == false) {
                            logger.error("Failed to remove attribute value/des/sel/apply");
                            replacedert false;
                        }
                    } else {
                        if (self.container.removeItem(object) == false) {
                            logger.error("Failed to remove object");
                            replacedert false;
                        }
                    }
                } else {
                    logger.error("This code should never get executed if the button was properly disabled.");
                }
            }
        });
        this.buttonClear.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                Object object = self.tableExpressions.getValue();
                if (object == null) {
                    if (self.container.removeAllItems() == false) {
                        logger.error("Failed to remove all items");
                        replacedert false;
                    }
                } else {
                    if (self.container.removeAllreplacedignments() == false) {
                        logger.error("Failed to remove all replacedignments");
                        replacedert false;
                    }
                }
            }
        });
        this.buttonSave.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                // 
                // Mark ourselves as saved
                // 
                self.isSaved = true;
                // 
                // Close the window
                // 
                self.close();
            }
        });
    }

    protected void setupButtons() {
        Object target = this.tableExpressions.getValue();
        if (target == null) {
            if (this.root instanceof AdviceExpressionsType) {
                this.buttonAdd.setVisible(true);
                this.buttonAdd.setCaption("Add Advice");
                this.buttonRemove.setCaption("Remove Advice");
                this.buttonClear.setCaption("Clear All Advice");
                this.buttonClear.setVisible(true);
            } else {
                this.buttonAdd.setVisible(true);
                this.buttonAdd.setCaption("Add Obligation");
                this.buttonRemove.setCaption("Remove Obligation");
                this.buttonClear.setCaption("Clear All Obligations");
                this.buttonClear.setVisible(true);
            }
            this.buttonRemove.setEnabled(false);
        } else {
            if (target instanceof AdviceExpressionType || target instanceof ObligationExpressionType) {
                this.buttonAdd.setVisible(true);
                this.buttonAdd.setCaption("Add replacedignment");
                if (target instanceof AdviceExpressionType) {
                    this.buttonRemove.setCaption("Remove Advice");
                } else {
                    this.buttonRemove.setCaption("Remove Obligation");
                }
                this.buttonClear.setCaption("Clear All replacedignments");
                this.buttonClear.setVisible(true);
            } else {
                this.buttonAdd.setVisible(false);
                this.buttonRemove.setCaption("Remove replacedignment");
                this.buttonClear.setVisible(false);
            }
            this.buttonRemove.setEnabled(true);
        }
        if (this.tableExpressions.size() == 0) {
            this.buttonClear.setEnabled(false);
        } else {
            this.buttonClear.setEnabled(true);
        }
    }

    protected void editAttribute(Object target, final AttributereplacedignmentExpressionType parent) {
        // 
        // Make a copy
        // 
        final AttributereplacedignmentExpressionType copyreplacedignment = (parent == null ? new AttributereplacedignmentExpressionType() : XACMLObjectCopy.copy(parent));
        // 
        // Prompt user for attribute right away
        // 
        final ExpressionBuilderComponent builder = new ExpressionBuilderComponent(copyreplacedignment, copyreplacedignment.getExpression() != null ? copyreplacedignment.getExpression().getValue() : null, null, self.variables);
        builder.setCaption("Define replacedignment Attribute");
        builder.setModal(true);
        builder.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user save?
                // 
                if (builder.isSaved() == false) {
                    return;
                }
                // 
                // Yes - update it
                // 
                parent.setExpression(copyreplacedignment.getExpression());
                if (parent.getExpression() != null) {
                    self.container.removeItem(parent.getExpression().getValue());
                }
                self.container.addItem(copyreplacedignment.getExpression().getValue(), parent);
                // 
                // Set the table size
                // 
                self.tableExpressions.setPageLength(self.container.size() + 1);
            }
        });
        builder.center();
        UI.getCurrent().addWindow(builder);
    }

    protected void editExpression(final AttributereplacedignmentExpressionType replacedignment, final Object parent) {
        // 
        // Copy
        // 
        final AttributereplacedignmentExpressionType copyreplacedignment = (replacedignment == null ? new AttributereplacedignmentExpressionType() : XACMLObjectCopy.copy(replacedignment));
        // 
        // Create the window
        // 
        final AttributereplacedignmentExpressionEditorWindow window = new AttributereplacedignmentExpressionEditorWindow(copyreplacedignment);
        window.setCaption(replacedignment == null ? "Create Attribute replacedignment" : "Edit Attribute replacedignment");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user click save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Was this a new replacedignment?
                // 
                if (replacedignment == null) {
                    // 
                    // Prompt user for attribute right away
                    // 
                    final ExpressionBuilderComponent builder = new ExpressionBuilderComponent(copyreplacedignment, null, null, self.variables);
                    builder.setCaption("Define replacedignment Attribute");
                    builder.setModal(true);
                    builder.addCloseListener(new CloseListener() {

                        private static final long serialVersionUID = 1L;

                        @Override
                        public void windowClose(CloseEvent e) {
                            // 
                            // Did the user save?
                            // 
                            if (builder.isSaved() == false) {
                                return;
                            }
                            // 
                            // Yes - add it to the container
                            // 
                            if (self.container.addItem(copyreplacedignment, parent) == null) {
                                logger.error("Failed to add copy replacedignment");
                                replacedert false;
                            }
                            // 
                            // Set the table size
                            // 
                            self.tableExpressions.setPageLength(self.container.size() + 1);
                        }
                    });
                    builder.center();
                    UI.getCurrent().addWindow(builder);
                } else {
                    // 
                    // No - copy back the data
                    // 
                    replacedignment.setAttributeId(copyreplacedignment.getAttributeId());
                    replacedignment.setIssuer(replacedignment.getIssuer());
                    replacedignment.setCategory(copyreplacedignment.getCategory());
                    // 
                    // Update the container
                    // 
                    self.container.updateItem(replacedignment);
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editAdvice(final AdviceExpressionType advice) {
        // 
        // Copy the advice
        // 
        final AdviceExpressionType copyAdvice = (advice == null ? new AdviceExpressionType() : XACMLObjectCopy.copy(advice));
        // 
        // Setup the window
        // 
        final AdviceEditorWindow window = new AdviceEditorWindow(copyAdvice);
        window.setCaption("Edit Advice");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Is it saved?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Was this a new object?
                // 
                if (advice == null) {
                    // 
                    // New - add it to the container
                    // 
                    if (self.container.addItem(copyAdvice) == null) {
                        logger.error("failed to add advice");
                        replacedert false;
                    }
                    // 
                    // Set the table size
                    // 
                    self.tableExpressions.setPageLength(self.container.size() + 1);
                } else {
                    // 
                    // No - copy it back
                    // 
                    advice.setAdviceId(copyAdvice.getAdviceId());
                    advice.setAppliesTo(copyAdvice.getAppliesTo());
                    // 
                    // Update
                    // 
                    self.container.updateItem(advice);
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editObligation(final ObligationExpressionType obligation) {
        // 
        // Copy the advice
        // 
        final ObligationExpressionType copyObligation = (obligation == null ? new ObligationExpressionType() : XACMLObjectCopy.copy(obligation));
        // 
        // Setup the window
        // 
        final ObligationEditorWindow window = new ObligationEditorWindow(copyObligation);
        window.setCaption("Edit Obligation");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Is it saved?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Was this a new object?
                // 
                if (obligation == null) {
                    // 
                    // New - add it to the container
                    // 
                    if (self.container.addItem(copyObligation) == null) {
                        logger.error("Failed to add obligation");
                        replacedert false;
                    }
                    // 
                    // Set the table size
                    // 
                    self.tableExpressions.setPageLength(self.container.size() + 1);
                } else {
                    // 
                    // No - copy it back
                    // 
                    obligation.setObligationId(copyObligation.getObligationId());
                    obligation.setFulfillOn(copyObligation.getFulfillOn());
                    // 
                    // Update
                    // 
                    self.container.updateItem(obligation);
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    public boolean isSaved() {
        return this.isSaved;
    }

    public Object getRootObject() {
        return this.root;
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("100%");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // horizontalLayout_1
        horizontalLayout_1 = buildHorizontalLayout_1();
        mainLayout.addComponent(horizontalLayout_1);
        // tableExpressions
        tableExpressions = new TreeTable();
        tableExpressions.setCaption("Expressions");
        tableExpressions.setImmediate(false);
        tableExpressions.setWidth("100%");
        tableExpressions.setHeight("-1px");
        mainLayout.addComponent(tableExpressions);
        mainLayout.setExpandRatio(tableExpressions, 1.0f);
        // buttonSave
        buttonSave = new Button();
        buttonSave.setCaption("Save");
        buttonSave.setImmediate(false);
        buttonSave.setWidth("-1px");
        buttonSave.setHeight("-1px");
        mainLayout.addComponent(buttonSave);
        mainLayout.setComponentAlignment(buttonSave, new Alignment(48));
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayout_1() {
        // common part: create layout
        horizontalLayout_1 = new HorizontalLayout();
        horizontalLayout_1.setImmediate(false);
        horizontalLayout_1.setWidth("-1px");
        horizontalLayout_1.setHeight("-1px");
        horizontalLayout_1.setMargin(false);
        horizontalLayout_1.setSpacing(true);
        // buttonAdd
        buttonAdd = new Button();
        buttonAdd.setCaption("Add Expression");
        buttonAdd.setImmediate(false);
        buttonAdd.setWidth("-1px");
        buttonAdd.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonAdd);
        // buttonRemove
        buttonRemove = new Button();
        buttonRemove.setCaption("Remove Expression");
        buttonRemove.setImmediate(false);
        buttonRemove.setWidth("-1px");
        buttonRemove.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonRemove);
        // buttonClear
        buttonClear = new Button();
        buttonClear.setCaption("Clear Expressions");
        buttonClear.setImmediate(false);
        buttonClear.setWidth("-1px");
        buttonClear.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonClear);
        return horizontalLayout_1;
    }
}

18 View Complete Implementation : ObligationAdviceEditorWindow.java
Copyright MIT License
Author : att
public clreplaced ObligationAdviceEditorWindow extends Window {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Button buttonSave;

    @AutoGenerated
    private TreeTable tableExpressions;

    @AutoGenerated
    private HorizontalLayout horizontalLayout_1;

    @AutoGenerated
    private Button buttonClear;

    @AutoGenerated
    private Button buttonRemove;

    @AutoGenerated
    private Button buttonAdd;

    /**
     */
    private static final long serialVersionUID = 1L;

    private static Log logger = LogFactory.getLog(ObligationAdviceEditorWindow.clreplaced);

    private final ObligationAdviceEditorWindow self = this;

    private final Object root;

    private final Map<VariableDefinitionType, PolicyType> variables;

    private ObligationAdviceContainer container;

    private boolean isSaved = false;

    private static final Action ADD_OBLIGATION = new Action("Add Obligation");

    private static final Action ADD_ADVICE = new Action("Add Advice");

    private static final Action ADD_EXPRESSION = new Action("Add Expression");

    private static final Action ADD_ATTRIBUTE = new Action("Add Attribute");

    private static final Action EDIT_OBLIGATION = new Action("Edit Obligation");

    private static final Action EDIT_ADVICE = new Action("Edit Advice");

    private static final Action EDIT_EXPRESSION = new Action("Edit Expression");

    private static final Action EDIT_ATTRIBUTE = new Action("Edit Attribute");

    private static final Action REMOVE_OBLIGATION = new Action("Remove Obligation");

    private static final Action REMOVE_ADVICE = new Action("Remove Advice");

    private static final Action REMOVE_EXPRESSION = new Action("Remove Expression");

    private static final Action REMOVE_ATTRIBUTE = new Action("Remove Attribute");

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     * @param root
     * @param variables
     */
    public ObligationAdviceEditorWindow(Object root, Map<VariableDefinitionType, PolicyType> variables) {
        buildMainLayout();
        // setCompositionRoot(mainLayout);
        setContent(mainLayout);
        // 
        // Save
        // 
        if (!(root instanceof ObligationExpressionsType) && !(root instanceof AdviceExpressionsType)) {
            throw new IllegalArgumentException("This window supports Obligation or Advice Expressions only.");
        }
        this.root = root;
        this.variables = variables;
        this.container = new ObligationAdviceContainer(this.root);
        // 
        // Set our shortcuts
        // 
        this.setCloseShortcut(KeyCode.ESCAPE);
        // 
        // Initialize GUI
        // 
        this.initializeTable();
        this.initializeButtons();
        this.setupButtons();
        // 
        // Focus
        // 
        this.tableExpressions.focus();
    }

    protected void initializeTable() {
        // 
        // GUI properties
        // 
        this.tableExpressions.setImmediate(true);
        // 
        // Set the container
        // 
        this.tableExpressions.setContainerDataSource(this.container);
        this.tableExpressions.setVisibleColumns(new Object[] { ObligationAdviceContainer.PROPERTY_NAME, ObligationAdviceContainer.PROPERTY_ID_SHORT, ObligationAdviceContainer.PROPERTY_EFFECT, ObligationAdviceContainer.PROPERTY_CATEGORY_SHORT, ObligationAdviceContainer.PROPERTY_DATATYPE_SHORT });
        this.tableExpressions.setColumnHeaders(new String[] { "Name", "ID or Value", (this.root instanceof ObligationExpressionsType ? "Effect" : "Applies"), "Category", "Data Type" });
        // this.tableExpressions.setColumnExpandRatio(ObligationAdviceContainer.PROPERTY_NAME, 1.0f);
        // this.tableExpressions.setColumnExpandRatio(ObligationAdviceContainer.PROPERTY_ID_SHORT, 1.0f);
        // this.tableExpressions.setColumnWi
        this.tableExpressions.setSelectable(true);
        // 
        // Expand it out
        // 
        for (Object item : this.tableExpressions.gereplacedemIds()) {
            this.tableExpressions.setCollapsed(item, false);
            for (Object child : this.tableExpressions.getChildren(item)) {
                this.tableExpressions.setCollapsed(child, false);
            }
        }
        this.tableExpressions.setPageLength(this.container.size() + 3);
        // 
        // Respond to events
        // 
        this.tableExpressions.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    if (self.root instanceof ObligationExpressionsType) {
                        return new Action[] { ADD_OBLIGATION };
                    }
                    if (self.root instanceof AdviceExpressionsType) {
                        return new Action[] { ADD_ADVICE };
                    }
                }
                if (target instanceof ObligationExpressionType) {
                    return new Action[] { EDIT_OBLIGATION, REMOVE_OBLIGATION, ADD_EXPRESSION };
                }
                if (target instanceof AdviceExpressionType) {
                    return new Action[] { EDIT_ADVICE, REMOVE_ADVICE, ADD_EXPRESSION };
                }
                if (target instanceof AttributereplacedignmentExpressionType) {
                    return new Action[] { EDIT_EXPRESSION, REMOVE_EXPRESSION, ADD_ATTRIBUTE };
                }
                if (target instanceof AttributeValueType || target instanceof AttributeDesignatorType || target instanceof AttributeSelectorType || target instanceof ApplyType) {
                    return new Action[] { EDIT_ATTRIBUTE, REMOVE_ATTRIBUTE };
                }
                return null;
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == ADD_OBLIGATION) {
                    self.editObligation(null);
                    return;
                }
                if (action == EDIT_OBLIGATION) {
                    replacedert (target instanceof ObligationExpressionType);
                    self.editObligation((ObligationExpressionType) target);
                    return;
                }
                if (action == REMOVE_OBLIGATION) {
                    replacedert (target instanceof ObligationExpressionType);
                    if (self.container.removeItem(target) == false) {
                        logger.error("Failed to remove obligation");
                        replacedert (false);
                    }
                    return;
                }
                if (action == ADD_ADVICE) {
                    self.editAdvice(null);
                    return;
                }
                if (action == EDIT_ADVICE) {
                    replacedert (target instanceof AdviceExpressionType);
                    self.editAdvice((AdviceExpressionType) target);
                    return;
                }
                if (action == REMOVE_ADVICE) {
                    replacedert (target instanceof AdviceExpressionType);
                    if (self.container.removeItem(target) == false) {
                        logger.error("Failed to remove advice");
                        replacedert (false);
                    }
                    return;
                }
                if (action == ADD_EXPRESSION) {
                    replacedert (target instanceof ObligationExpressionType || target instanceof AdviceExpressionType);
                    self.editExpression(null, target);
                    return;
                }
                if (action == EDIT_EXPRESSION) {
                    replacedert (target instanceof AttributereplacedignmentExpressionType);
                    self.editExpression((AttributereplacedignmentExpressionType) target, self.container.getParent(target));
                    return;
                }
                if (action == REMOVE_EXPRESSION) {
                    replacedert (target instanceof AttributereplacedignmentExpressionType);
                    if (self.container.removeItem(target) == false) {
                        logger.error("Failed to remove expression");
                        replacedert (false);
                    }
                    return;
                }
                if (action == ADD_ATTRIBUTE) {
                    replacedert (target instanceof AttributereplacedignmentExpressionType);
                    self.editAttribute(null, (AttributereplacedignmentExpressionType) target);
                    return;
                }
                if (action == EDIT_ATTRIBUTE) {
                    replacedert (target instanceof AttributeValueType || target instanceof AttributeDesignatorType || target instanceof AttributeSelectorType || target instanceof ApplyType);
                    self.editAttribute(target, (AttributereplacedignmentExpressionType) self.container.getParent(target));
                    return;
                }
                if (action == REMOVE_ATTRIBUTE) {
                    replacedert (target instanceof AttributeValueType || target instanceof AttributeDesignatorType || target instanceof AttributeSelectorType || target instanceof ApplyType);
                    if (self.container.removeItem(target) == false) {
                        logger.error("Failed to remove attribute");
                        replacedert (false);
                    }
                    return;
                }
            }
        });
        // 
        // Respond to selections
        // 
        this.tableExpressions.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                self.setupButtons();
            }
        });
        this.tableExpressions.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    if (event.getSource() instanceof AdviceExpressionType) {
                        self.editAdvice((AdviceExpressionType) event.getSource());
                    } else if (event.getSource() instanceof ObligationExpressionType) {
                        self.editObligation((ObligationExpressionType) event.getSource());
                    } else if (event.getSource() instanceof AttributereplacedignmentExpressionType) {
                        self.editExpression((AttributereplacedignmentExpressionType) event.getSource(), self.container.getParent(event.getSource()));
                    } else {
                        self.editAttribute(event.getSource(), (AttributereplacedignmentExpressionType) self.container.getParent(event.getSource()));
                    }
                }
            }
        });
        // 
        // Implement a description generator, to display the full XACML ID.
        // 
        this.tableExpressions.sereplacedemDescriptionGenerator(new ItemDescriptionGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public String generateDescription(Component source, Object itemId, Object propertyId) {
                if (propertyId == ObligationAdviceContainer.PROPERTY_ID_SHORT) {
                    if (itemId instanceof AdviceExpressionType) {
                        return ((AdviceExpressionType) itemId).getAdviceId();
                    }
                    if (itemId instanceof ObligationExpressionType) {
                        return ((ObligationExpressionType) itemId).getObligationId();
                    }
                    if (itemId instanceof AttributereplacedignmentExpressionType) {
                        return ((AttributereplacedignmentExpressionType) itemId).getAttributeId();
                    }
                    if (itemId instanceof AttributeDesignatorType) {
                        return ((AttributeDesignatorType) itemId).getAttributeId();
                    }
                    if (itemId instanceof AttributeSelectorType) {
                        return ((AttributeSelectorType) itemId).getContextSelectorId();
                    }
                    if (itemId instanceof ApplyType) {
                        return ((ApplyType) itemId).getDescription();
                    }
                }
                if (propertyId == ObligationAdviceContainer.PROPERTY_CATEGORY_SHORT) {
                    if (itemId instanceof AttributereplacedignmentExpressionType) {
                        return ((AttributereplacedignmentExpressionType) itemId).getCategory();
                    }
                    if (itemId instanceof AttributeDesignatorType) {
                        return ((AttributeDesignatorType) itemId).getCategory();
                    }
                    if (itemId instanceof AttributeSelectorType) {
                        return ((AttributeSelectorType) itemId).getCategory();
                    }
                    if (itemId instanceof ApplyType) {
                        return null;
                    }
                }
                if (propertyId == ObligationAdviceContainer.PROPERTY_DATATYPE_SHORT) {
                    if (itemId instanceof AttributeValueType) {
                        return ((AttributeValueType) itemId).getDataType();
                    }
                    if (itemId instanceof AttributeDesignatorType) {
                        return ((AttributeDesignatorType) itemId).getDataType();
                    }
                    if (itemId instanceof AttributeSelectorType) {
                        return ((AttributeSelectorType) itemId).getDataType();
                    }
                    if (itemId instanceof ApplyType) {
                    // 
                    // TODO - get the datatype for the function
                    // 
                    }
                }
                return null;
            }
        });
    }

    protected void initializeButtons() {
        this.buttonAdd.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                if (self.tableExpressions.getValue() == null) {
                    // 
                    // Add new root advice or obligation
                    // 
                    if (self.root instanceof AdviceExpressionsType) {
                        self.editAdvice(null);
                    } else {
                        self.editObligation(null);
                    }
                } else {
                    // 
                    // Add new replacedignment expression
                    // 
                    self.editExpression(null, self.tableExpressions.getValue());
                }
            }
        });
        this.buttonRemove.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                Object object = self.tableExpressions.getValue();
                if (object != null) {
                    if (object instanceof AttributeValueType || object instanceof AttributeDesignatorType || object instanceof AttributeSelectorType || object instanceof ApplyType) {
                        if (self.container.removeItem(self.container.getParent(object)) == false) {
                            logger.error("Failed to remove attribute value/des/sel/apply");
                            replacedert (false);
                        }
                    } else {
                        if (self.container.removeItem(object) == false) {
                            logger.error("Failed to remove object");
                            replacedert (false);
                        }
                    }
                } else {
                    logger.error("This code should never get executed if the button was properly disabled.");
                }
            }
        });
        this.buttonClear.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                Object object = self.tableExpressions.getValue();
                if (object == null) {
                    if (self.container.removeAllItems() == false) {
                        logger.error("Failed to remove all items");
                        replacedert (false);
                    }
                } else {
                    if (self.container.removeAllreplacedignments() == false) {
                        logger.error("Failed to remove all replacedignments");
                        replacedert (false);
                    }
                }
            }
        });
        this.buttonSave.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                // 
                // Mark ourselves as saved
                // 
                self.isSaved = true;
                // 
                // Close the window
                // 
                self.close();
            }
        });
    }

    protected void setupButtons() {
        Object target = this.tableExpressions.getValue();
        if (target == null) {
            if (this.root instanceof AdviceExpressionsType) {
                this.buttonAdd.setVisible(true);
                this.buttonAdd.setCaption("Add Advice");
                this.buttonRemove.setCaption("Remove Advice");
                this.buttonClear.setCaption("Clear All Advice");
                this.buttonClear.setVisible(true);
            } else {
                this.buttonAdd.setVisible(true);
                this.buttonAdd.setCaption("Add Obligation");
                this.buttonRemove.setCaption("Remove Obligation");
                this.buttonClear.setCaption("Clear All Obligations");
                this.buttonClear.setVisible(true);
            }
            this.buttonRemove.setEnabled(false);
        } else {
            if (target instanceof AdviceExpressionType || target instanceof ObligationExpressionType) {
                this.buttonAdd.setVisible(true);
                this.buttonAdd.setCaption("Add replacedignment");
                if (target instanceof AdviceExpressionType) {
                    this.buttonRemove.setCaption("Remove Advice");
                } else {
                    this.buttonRemove.setCaption("Remove Obligation");
                }
                this.buttonClear.setCaption("Clear All replacedignments");
                this.buttonClear.setVisible(true);
            } else {
                this.buttonAdd.setVisible(false);
                this.buttonRemove.setCaption("Remove replacedignment");
                this.buttonClear.setVisible(false);
            }
            this.buttonRemove.setEnabled(true);
        }
        if (this.tableExpressions.size() == 0) {
            this.buttonClear.setEnabled(false);
        } else {
            this.buttonClear.setEnabled(true);
        }
    }

    protected void editAttribute(Object target, final AttributereplacedignmentExpressionType parent) {
        // 
        // Make a copy
        // 
        final AttributereplacedignmentExpressionType copyreplacedignment = (parent == null ? new AttributereplacedignmentExpressionType() : XACMLObjectCopy.copy(parent));
        // 
        // Prompt user for attribute right away
        // 
        final ExpressionBuilderComponent builder = new ExpressionBuilderComponent(copyreplacedignment, copyreplacedignment.getExpression() != null ? copyreplacedignment.getExpression().getValue() : null, null, self.variables);
        builder.setCaption("Define replacedignment Attribute");
        builder.setModal(true);
        builder.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user save?
                // 
                if (builder.isSaved() == false) {
                    return;
                }
                // 
                // Yes - update it
                // 
                parent.setExpression(copyreplacedignment.getExpression());
                if (parent.getExpression() != null) {
                    self.container.removeItem(parent.getExpression().getValue());
                }
                self.container.addItem(copyreplacedignment.getExpression().getValue(), parent);
                // 
                // Set the table size
                // 
                self.tableExpressions.setPageLength(self.container.size() + 1);
            }
        });
        builder.center();
        UI.getCurrent().addWindow(builder);
    }

    protected void editExpression(final AttributereplacedignmentExpressionType replacedignment, final Object parent) {
        // 
        // Copy
        // 
        final AttributereplacedignmentExpressionType copyreplacedignment = (replacedignment == null ? new AttributereplacedignmentExpressionType() : XACMLObjectCopy.copy(replacedignment));
        // 
        // Create the window
        // 
        final AttributereplacedignmentExpressionEditorWindow window = new AttributereplacedignmentExpressionEditorWindow(copyreplacedignment);
        window.setCaption(replacedignment == null ? "Create Attribute replacedignment" : "Edit Attribute replacedignment");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user click save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Was this a new replacedignment?
                // 
                if (replacedignment == null) {
                    // 
                    // Prompt user for attribute right away
                    // 
                    final ExpressionBuilderComponent builder = new ExpressionBuilderComponent(copyreplacedignment, null, null, self.variables);
                    builder.setCaption("Define replacedignment Attribute");
                    builder.setModal(true);
                    builder.addCloseListener(new CloseListener() {

                        private static final long serialVersionUID = 1L;

                        @Override
                        public void windowClose(CloseEvent e) {
                            // 
                            // Did the user save?
                            // 
                            if (builder.isSaved() == false) {
                                return;
                            }
                            // 
                            // Yes - add it to the container
                            // 
                            if (self.container.addItem(copyreplacedignment, parent) == null) {
                                logger.error("Failed to add copy replacedignment");
                                replacedert (false);
                            }
                            // 
                            // Set the table size
                            // 
                            self.tableExpressions.setPageLength(self.container.size() + 1);
                        }
                    });
                    builder.center();
                    UI.getCurrent().addWindow(builder);
                } else {
                    // 
                    // No - copy back the data
                    // 
                    replacedignment.setAttributeId(copyreplacedignment.getAttributeId());
                    replacedignment.setIssuer(replacedignment.getIssuer());
                    replacedignment.setCategory(copyreplacedignment.getCategory());
                    // 
                    // Update the container
                    // 
                    self.container.updateItem(replacedignment);
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editAdvice(final AdviceExpressionType advice) {
        // 
        // Copy the advice
        // 
        final AdviceExpressionType copyAdvice = (advice == null ? new AdviceExpressionType() : XACMLObjectCopy.copy(advice));
        // 
        // Setup the window
        // 
        final AdviceEditorWindow window = new AdviceEditorWindow(copyAdvice);
        window.setCaption("Edit Advice");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Is it saved?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Was this a new object?
                // 
                if (advice == null) {
                    // 
                    // New - add it to the container
                    // 
                    if (self.container.addItem(copyAdvice) == null) {
                        logger.error("failed to add advice");
                        replacedert (false);
                    }
                    // 
                    // Set the table size
                    // 
                    self.tableExpressions.setPageLength(self.container.size() + 1);
                } else {
                    // 
                    // No - copy it back
                    // 
                    advice.setAdviceId(copyAdvice.getAdviceId());
                    advice.setAppliesTo(copyAdvice.getAppliesTo());
                    // 
                    // Update
                    // 
                    self.container.updateItem(advice);
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editObligation(final ObligationExpressionType obligation) {
        // 
        // Copy the advice
        // 
        final ObligationExpressionType copyObligation = (obligation == null ? new ObligationExpressionType() : XACMLObjectCopy.copy(obligation));
        // 
        // Setup the window
        // 
        final ObligationEditorWindow window = new ObligationEditorWindow(copyObligation);
        window.setCaption("Edit Obligation");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Is it saved?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Was this a new object?
                // 
                if (obligation == null) {
                    // 
                    // New - add it to the container
                    // 
                    if (self.container.addItem(copyObligation) == null) {
                        logger.error("Failed to add obligation");
                        replacedert (false);
                    }
                    // 
                    // Set the table size
                    // 
                    self.tableExpressions.setPageLength(self.container.size() + 1);
                } else {
                    // 
                    // No - copy it back
                    // 
                    obligation.setObligationId(copyObligation.getObligationId());
                    obligation.setFulfillOn(copyObligation.getFulfillOn());
                    // 
                    // Update
                    // 
                    self.container.updateItem(obligation);
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    public boolean isSaved() {
        return this.isSaved;
    }

    public Object getRootObject() {
        return this.root;
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("100%");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // horizontalLayout_1
        horizontalLayout_1 = buildHorizontalLayout_1();
        mainLayout.addComponent(horizontalLayout_1);
        // tableExpressions
        tableExpressions = new TreeTable();
        tableExpressions.setCaption("Expressions");
        tableExpressions.setImmediate(false);
        tableExpressions.setWidth("100%");
        tableExpressions.setHeight("-1px");
        mainLayout.addComponent(tableExpressions);
        mainLayout.setExpandRatio(tableExpressions, 1.0f);
        // buttonSave
        buttonSave = new Button();
        buttonSave.setCaption("Save");
        buttonSave.setImmediate(false);
        buttonSave.setWidth("-1px");
        buttonSave.setHeight("-1px");
        mainLayout.addComponent(buttonSave);
        mainLayout.setComponentAlignment(buttonSave, new Alignment(48));
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayout_1() {
        // common part: create layout
        horizontalLayout_1 = new HorizontalLayout();
        horizontalLayout_1.setImmediate(false);
        horizontalLayout_1.setWidth("-1px");
        horizontalLayout_1.setHeight("-1px");
        horizontalLayout_1.setMargin(false);
        horizontalLayout_1.setSpacing(true);
        // buttonAdd
        buttonAdd = new Button();
        buttonAdd.setCaption("Add Expression");
        buttonAdd.setImmediate(false);
        buttonAdd.setWidth("-1px");
        buttonAdd.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonAdd);
        // buttonRemove
        buttonRemove = new Button();
        buttonRemove.setCaption("Remove Expression");
        buttonRemove.setImmediate(false);
        buttonRemove.setWidth("-1px");
        buttonRemove.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonRemove);
        // buttonClear
        buttonClear = new Button();
        buttonClear.setCaption("Clear Expressions");
        buttonClear.setImmediate(false);
        buttonClear.setWidth("-1px");
        buttonClear.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonClear);
        return horizontalLayout_1;
    }
}

18 View Complete Implementation : CubaWindow.java
Copyright Apache License 2.0
Author : cuba-platform
protected Collection<Action> getContextActions(Component actionTarget) {
    List<Action> actions = new ArrayList<>();
    if (contextActionHandlers != null) {
        for (Action.Handler handler : contextActionHandlers) {
            Action[] as = handler.getActions(actionTarget, this);
            if (as != null) {
                Collections.addAll(actions, as);
            }
        }
    }
    return actions;
}

17 View Complete Implementation : PDPManagement.java
Copyright Apache License 2.0
Author : apache
public clreplaced PDPManagement extends CustomComponent {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Table table;

    @AutoGenerated
    private HorizontalLayout horizontalLayoutToolbar;

    @AutoGenerated
    private Button buttonRemove;

    @AutoGenerated
    private Button buttonCreate;

    private static final long serialVersionUID = 1L;

    private final PDPManagement self = this;

    private static final Log logger = LogFactory.getLog(PDPManagement.clreplaced);

    private PDPGroupContainer container;

    private static final Action CREATE_GROUP = new Action("Create Group");

    private static final Action REPAIR_GROUP = new Action("Repair Group");

    private static final Action EDIT_GROUP = new Action("Edit Group");

    private static final Action DELETE_GROUP = new Action("Delete Group");

    private static final Action SYNCHRONIZE = new Action("Synchronize");

    private static final Action MAKE_DEFAULT = new Action("Make Default");

    private static final Action CREATE_PDP = new Action("Create PDP");

    private static final Action EDIT_PDP = new Action("Edit PDP");

    private static final Action DELETE_PDP = new Action("Delete PDP");

    private static final Action MOVE_PDP = new Action("Move PDP");

    private static final Action GET_PDP_STATUS = new Action("View Status");

    private PAPEngine papEngine;

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     */
    public PDPManagement(PAPEngine engine) {
        buildMainLayout();
        setCompositionRoot(mainLayout);
        // 
        // Initialize
        // 
        this.papEngine = engine;
        // 
        // Initialize
        // 
        this.initialize();
        // 
        // setup the buttons
        // 
        this.setupButtons();
    }

    protected void initialize() {
        // 
        // Don't create a container if the engine doesn't exist
        // 
        if (this.papEngine == null) {
            // 
            // remove all the components
            // 
            this.mainLayout.removeAllComponents();
            // 
            // Add a label
            // 
            this.mainLayout.addComponent(new Label("PDP Management unavailable - PAP servlet unavailable."));
            // 
            // done
            // 
            return;
        }
        // 
        // Create our container
        // 
        this.container = new PDPGroupContainer(this.papEngine);
        // 
        // Determine authorization level
        // 
        boolean isAdmin = ((XacmlAdminUI) UI.getCurrent()).isAuthorized(XacmlAdminAuthorization.AdminAction.ACTION_ADMIN, XacmlAdminAuthorization.AdminResource.RESOURCE_PDP_ADMIN);
        try {
            this.initializeTree(isAdmin);
            this.initializeButtons(isAdmin);
        } catch (Exception e) {
            logger.error("UNABLE TO START PDPManagement: " + e, e);
            // check if PAP servlet is up
            try {
                Set<PDPGroup> groups = this.papEngine.getPDPGroups();
                if (groups == null) {
                    throw new PAPException("PAP not running");
                }
            } catch (PAPException | NullPointerException e1) {
                setCompositionRoot(new Label("Cannot use PDP Management because the PAP servlet was not running when Admin Console Servlet first initialized."));
                return;
            }
            setCompositionRoot(new Label("Cannot use PDP Management because of error during initialization: " + e.getMessage()));
        }
    }

    protected void initializeTree(final boolean isAdmin) {
        // 
        // Set the data source
        // 
        this.table.setContainerDataSource(this.container);
        // 
        // Setup the GUI properties
        // 
        this.table.setVisibleColumns("Name", "Description", "Status", "Default", "PDPs", "Policies", "PIP Configurations");
        this.table.setColumnHeaders("Name", "Description", "Status", "Default", "PDP's", "Policies", "PIP Configurations");
        // 
        // The description should be a text area
        // 
        this.table.addGeneratedColumn("Description", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                TextArea area = new TextArea();
                area.setValue(((PDPGroup) itemId).getDescription());
                area.setReadOnly(true);
                return area;
            }
        });
        // 
        // Generate a GUI element for the PDP's
        // 
        this.table.addGeneratedColumn("PDPs", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                final Table table = new Table();
                final PDPContainer container = new PDPContainer((PDPGroup) itemId);
                // 
                // Setup the container data
                // 
                table.setContainerDataSource(container);
                // 
                // Save the group for easy access
                // 
                table.setData(itemId);
                // 
                // GUI properties
                // 
                table.setPageLength(table.getContainerDataSource().size() + 2);
                table.setVisibleColumns("Name", "Status", "Description");
                table.setColumnCollapsingAllowed(true);
                table.setColumnCollapsed("Description", true);
                table.setWidth("100%");
                // 
                // If an admin, then it is editable
                // 
                if (isAdmin) {
                    // 
                    // Set it as selectable
                    // 
                    table.setSelectable(true);
                    // 
                    // Add actions
                    // 
                    table.addActionHandler(new Handler() {

                        private static final long serialVersionUID = 1L;

                        @Override
                        public Action[] getActions(Object target, Object sender) {
                            if (target == null) {
                                return new Action[] { CREATE_PDP };
                            }
                            if (target instanceof PDP) {
                                if (self.container.size() > 1) {
                                    return new Action[] { EDIT_PDP, GET_PDP_STATUS, MOVE_PDP, DELETE_PDP };
                                } else {
                                    return new Action[] { EDIT_PDP, GET_PDP_STATUS, DELETE_PDP };
                                }
                            }
                            return null;
                        }

                        @Override
                        public void handleAction(Action action, Object sender, Object target) {
                            if (action == CREATE_PDP) {
                                self.editPDP(null, (PDPGroup) table.getData());
                                return;
                            }
                            if (action == EDIT_PDP) {
                                replacedert target instanceof PDP;
                                self.editPDP((PDP) target, (PDPGroup) table.getData());
                                return;
                            }
                            if (action == MOVE_PDP) {
                                replacedert target instanceof PDP;
                                self.movePDP((PDP) target, (PDPGroup) table.getData());
                                return;
                            }
                            if (action == DELETE_PDP) {
                                replacedert target instanceof PDP;
                                self.deletePDP((PDP) target, (PDPGroup) table.getData());
                                return;
                            }
                            if (action == GET_PDP_STATUS) {
                                replacedert target instanceof PDP;
                                self.getPDPStatus((PDP) target, (PDPGroup) table.getData());
                            }
                        }
                    });
                    // 
                    // Respond to events
                    // 
                    table.addItemClickListener(new ItemClickListener() {

                        private static final long serialVersionUID = 1L;

                        @Override
                        public void itemClick(ItemClickEvent event) {
                            if (event.isDoubleClick()) {
                                self.editPDP((PDP) event.gereplacedemId(), (PDPGroup) table.getData());
                            }
                        }
                    });
                }
                return table;
            }
        });
        // 
        // Generate a GUI element for the policies
        // 
        this.table.addGeneratedColumn("Policies", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                Table table = new Table();
                table.setContainerDataSource(new PDPPolicyContainer((PDPGroup) itemId));
                table.setPageLength(table.getContainerDataSource().size() + 2);
                table.setVisibleColumns("Root", "Name", "Version", "Description");
                table.setColumnCollapsingAllowed(true);
                table.setColumnCollapsed("Description", true);
                table.setWidth("100%");
                return table;
            }
        });
        // 
        // Generate a GUI element for the PIP configurations
        // 
        this.table.addGeneratedColumn("PIP Configurations", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                Table table = new Table();
                if (itemId instanceof PDPGroup) {
                    table.setContainerDataSource(new PDPPIPContainer((PDPGroup) itemId));
                    table.setPageLength(table.getContainerDataSource().size() + 2);
                }
                if (itemId instanceof PDP) {
                    table.setContainerDataSource(new PDPPIPContainer((PDP) itemId));
                    table.setVisible(false);
                    table.setPageLength(0);
                }
                table.setVisibleColumns("Name", "Description");
                table.setColumnCollapsingAllowed(true);
                table.setColumnCollapsed("Description", true);
                table.setWidth("100%");
                return table;
            }
        });
        // 
        // Check the user's authorization level
        // 
        if (((XacmlAdminUI) UI.getCurrent()).isAuthorized(XacmlAdminAuthorization.AdminAction.ACTION_ADMIN, XacmlAdminAuthorization.AdminResource.RESOURCE_PDP_ADMIN)) {
            this.table.setSelectable(true);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("No admin access to pdp management");
            }
            return;
        }
        // 
        // Setup Action Handlers
        // 
        this.table.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    // 
                    // Nothing is selected, they right-clicked empty space.
                    // Only one action.
                    // 
                    return new Action[] { CREATE_GROUP };
                }
                if (target instanceof PDPGroup) {
                    List<Action> actions = new ArrayList<Action>();
                    PDPGroupStatus.Status status = ((PDPGroup) target).getStatus().getStatus();
                    if (status == PDPGroupStatus.Status.LOAD_ERRORS) {
                        actions.add(REPAIR_GROUP);
                    }
                    if (((PDPGroup) target).isDefaultGroup() == false) {
                        actions.add(MAKE_DEFAULT);
                    }
                    actions.add(EDIT_GROUP);
                    if (status == PDPGroupStatus.Status.OUT_OF_SYNCH) {
                        actions.add(SYNCHRONIZE);
                    }
                    if (((PDPGroup) target).isDefaultGroup() == false) {
                        actions.add(DELETE_GROUP);
                    }
                    actions.add(CREATE_PDP);
                    // Throws a clreplaced cast exception
                    // return (Action[]) actions.toArray();
                    Action[] actions2 = new Action[actions.size()];
                    int index = 0;
                    for (Action a : actions) {
                        actions2[index++] = a;
                    }
                    return actions2;
                }
                return null;
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == CREATE_GROUP) {
                    self.editPDPGroup(null);
                    return;
                }
                if (action == EDIT_GROUP) {
                    replacedert target instanceof PDPGroup;
                    self.editPDPGroup((PDPGroup) target);
                    return;
                }
                if (action == DELETE_GROUP) {
                    self.deleteGroup((PDPGroup) target);
                    return;
                }
                if (action == REPAIR_GROUP) {
                    if (target instanceof PDPGroup) {
                        ((PDPGroup) target).repair();
                    } else {
                        String message = "Action '" + REPAIR_GROUP.getCaption() + "' called on non-group target '" + target + "'";
                        logger.error(message);
                        AdminNotification.error(message);
                    }
                    return;
                }
                if (action == MAKE_DEFAULT) {
                    if (target instanceof PDPGroup) {
                        try {
                            self.container.makeDefault((PDPGroup) target);
                        } catch (Exception e) {
                            AdminNotification.error("Make Default failed. Reason:\n" + e.getMessage());
                        }
                    } else {
                        String message = "Action '" + MAKE_DEFAULT.getCaption() + "' called on non-group target '" + target + "'";
                        logger.error(message);
                        AdminNotification.error(message);
                    }
                    return;
                }
                if (action == SYNCHRONIZE) {
                    if (target instanceof PDPGroup) {
                        logger.error("SYNCHRONIZE NOT YET IMPLMENTED");
                        AdminNotification.error("Synchronize not yet implemented");
                    } else {
                        String message = "Action '" + SYNCHRONIZE.getCaption() + "' called on non-group target '" + target + "'";
                        logger.error(message);
                        AdminNotification.error(message);
                    }
                    return;
                }
                if (action == CREATE_PDP) {
                    if (target instanceof PDPGroup) {
                        self.editPDP(null, ((PDPGroup) target));
                    } else {
                        String message = "Action '" + CREATE_PDP.getCaption() + "' called on non-group target '" + target + "'";
                        logger.error(message);
                        AdminNotification.error(message);
                    }
                    return;
                }
            }
        });
        // 
        // Listen for item change notifications
        // 
        this.table.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    replacedert event.gereplacedemId() instanceof PDPGroup;
                    self.editPDPGroup((PDPGroup) event.gereplacedemId());
                }
            }
        });
        // 
        // Respond to selection events
        // 
        this.table.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                Object id = self.table.getValue();
                if (id == null) {
                    self.buttonRemove.setEnabled(false);
                } else {
                    // 
                    // Make sure its not the default group
                    // 
                    if (((PDPGroup) id).isDefaultGroup()) {
                        self.buttonRemove.setEnabled(false);
                    } else {
                        self.buttonRemove.setEnabled(true);
                    }
                }
            }
        });
        // 
        // Maximize the table
        // 
        this.table.setSizeFull();
    }

    protected void initializeButtons(final boolean isAdmin) {
        if (isAdmin == false) {
            return;
        }
        this.buttonCreate.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.editPDPGroup(null);
            }
        });
        this.buttonRemove.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                Object id = self.table.getValue();
                replacedert id != null;
                replacedert id instanceof PDPGroup;
                self.deleteGroup((PDPGroup) id);
                self.table.select(self.table.getNullSelectionItemId());
            }
        });
    }

    protected void setupButtons() {
        if (this.table.getValue() == null) {
            this.buttonRemove.setEnabled(false);
        } else {
            this.buttonRemove.setEnabled(true);
        }
    }

    protected void editPDP(final PDP pdp, final PDPGroup group) {
        final EditPDPWindow editor = new EditPDPWindow(pdp, this.container.getGroups());
        if (pdp == null) {
            editor.setCaption("Create New PDP");
        } else {
            editor.setCaption("Edit PDP " + pdp.getId());
        }
        editor.setModal(true);
        editor.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent event) {
                if (editor.isSaved() == false) {
                    return;
                }
                try {
                    // 
                    // Adding a new PDP?
                    // 
                    if (pdp == null) {
                        // 
                        // Yes tell the container to add it
                        // 
                        self.container.addNewPDP(editor.getPDPId(), group, editor.getPDPName(), editor.getPDPDescription());
                    } else {
                        // 
                        // No tell the container to update it
                        // 
                        pdp.setName(editor.getPDPName());
                        pdp.setDescription(editor.getPDPDescription());
                        self.container.updatePDP(pdp);
                    }
                } catch (Exception e) {
                    String message = "Unable to create PDP.  Reason:\n" + e.getMessage();
                    logger.error(message);
                    AdminNotification.error(message);
                }
            }
        });
        editor.center();
        UI.getCurrent().addWindow(editor);
    }

    protected void editPDPGroup(final PDPGroup group) {
        // 
        // copy the group
        // 
        final StdPDPGroup copyGroup = (group == null ? null : new StdPDPGroup(group));
        // 
        // 
        // 
        final EditPDPGroupWindow editor = new EditPDPGroupWindow(copyGroup, this.container.getGroups(), papEngine);
        if (group == null) {
            editor.setCaption("Create PDP Group");
        } else {
            editor.setCaption("Edit PDP Group " + ((PDPGroup) group).getName());
        }
        editor.setModal(true);
        editor.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent event) {
                if (editor.isSaved() == false) {
                    return;
                }
                if (group == null) {
                    // 
                    // Creating a new group
                    // 
                    try {
                        self.container.addNewGroup(editor.getGroupName(), editor.getGroupDescription());
                    } catch (Exception e) {
                        String message = "Unable to create Group.  Reason:\n" + e.getMessage();
                        logger.error(message);
                        AdminNotification.error(message);
                    }
                } else {
                    // 
                    // Update group
                    // 
                    self.container.updateGroup(editor.getUpdatedObject());
                }
            }
        });
        editor.center();
        UI.getCurrent().addWindow(editor);
    }

    protected void deletePDP(final PDP pdp, final PDPGroup pdpGroup) {
        String message = "Are you sure you want to delete <B>" + (pdp.getName() == null ? "" : pdp.getName()) + "</B> group?";
        ConfirmDialog dialog = ConfirmDialog.getFactory().create("Confirm PDP Deletion", message, "Delete", "Cancel");
        dialog.setContentMode(ContentMode.HTML);
        dialog.show(getUI(), new ConfirmDialog.Listener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void onClose(ConfirmDialog dialog) {
                if (dialog.isConfirmed()) {
                    try {
                        self.container.removePDP(pdp, pdpGroup);
                    } catch (PAPException e) {
                        logger.warn("Failed to remove pdp");
                        AdminNotification.warn("Failed to remove PDP");
                    }
                }
            }
        }, true);
    }

    protected void movePDP(final PDP pdp, final PDPGroup currentGroup) {
        List<PDPGroup> currentGroups = this.container.getGroups();
        Set<PDPGroup> otherGroups = new HashSet<PDPGroup>(currentGroups);
        if (otherGroups.remove(currentGroup) == false) {
            logger.warn("Group list inconsistency - failed to move pdp to selected group");
            return;
        }
        final SelectPDPGroupWindow editor = new SelectPDPGroupWindow(otherGroups, "What was this?");
        editor.setCaption("Move PDP to group");
        editor.setModal(true);
        editor.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent event) {
                if (editor.isSaved()) {
                    self.container.movePDP((PDP) pdp, editor.selectedGroup());
                }
            }
        });
        editor.center();
        UI.getCurrent().addWindow(editor);
    }

    protected void getPDPStatus(final PDP pdp, final PDPGroup group) {
        PDPStatus status;
        try {
            status = papEngine.getStatus(pdp);
        } catch (Exception e) {
            AdminNotification.error("Unable to get details for pdp '" + pdp.getId() + "' with summary status: " + pdp.getStatus().getStatus());
            return;
        }
        logger.info(status);
        PDPStatusWindow window = new PDPStatusWindow(status);
        window.setCaption("Status for PDP " + pdp.getName());
        window.setModal(true);
        window.center();
        UI.getCurrent().addWindow(window);
    }

    private void deleteGroup(final PDPGroup group) {
        // 
        // Cannot be the default group
        // 
        if (group.isDefaultGroup()) {
            logger.error("Cannot delete the Default group");
            return;
        }
        // 
        // Any PDPs in the group?
        // 
        Set<PDP> pdps = group.getPdps();
        if (pdps.isEmpty()) {
            // 
            // There are no PDP's, so just prompt to remove it
            // 
            String message = "Are you sure you want to delete <B>" + (group.getName() == null ? "" : group.getName()) + "</B> group?";
            ConfirmDialog dialog = ConfirmDialog.getFactory().create("Confirm Group Deletion", message, "Delete", "Cancel");
            dialog.setContentMode(ContentMode.HTML);
            dialog.show(getUI(), new ConfirmDialog.Listener() {

                private static final long serialVersionUID = 1L;

                @Override
                public void onClose(ConfirmDialog dialog) {
                    if (dialog.isConfirmed()) {
                        try {
                            self.container.removeGroup(group, null);
                        } catch (Exception e1) {
                            logger.warn("Container failed to remove group");
                            AdminNotification.error("Unable to delete group '" + group.getId() + "'.  Reason:\n" + e1.getMessage());
                        }
                        return;
                    }
                }
            }, true);
            return;
        }
        // 
        // Get our set of groups
        // 
        List<PDPGroup> currentGroups = this.container.getGroups();
        Set<PDPGroup> otherGroups = new HashSet<PDPGroup>(currentGroups);
        if (otherGroups.remove(group) == false) {
            logger.warn("Group list inconsistency - failed to remove group we are attempting to delete");
            return;
        }
        // 
        // We should have at least one group
        // 
        if (otherGroups.isEmpty()) {
            logger.error("Group list inconsistency - no other groups to choose from.");
            return;
        }
        // 
        // If there is only one group, it SHOULD be the default group
        // 
        if (otherGroups.size() == 1) {
            PDPGroup loneGroup = otherGroups.iterator().next();
            if (loneGroup.isDefaultGroup() == false) {
                logger.error("Group list inconsistency - lone group is NOT default.");
                return;
            }
        }
        // 
        // Create our confirmation window
        // 
        final SelectPDPGroupWindow window = new SelectPDPGroupWindow(otherGroups, "Select New Group for PDPs");
        window.setCaption("Confirm Group " + group.getName() + " Deletion");
        window.setCloseShortcut(KeyCode.ESCAPE);
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                if (window.isSaved()) {
                    PDPGroup newGroup = window.selectedGroup();
                    if (newGroup == null) {
                        logger.warn("No group selected for moving PDPs into");
                        AdminNotification.warn("No group selected for moving PDPs into.  Group '" + group.getId() + "' not deleted");
                        return;
                    }
                    try {
                        self.container.removeGroup(group, newGroup);
                    } catch (Exception e1) {
                        logger.warn("Container failed to remove group: " + e1, e1);
                        AdminNotification.error("Unable to delete group '" + group.getId() + "'.  Reason:\n" + e1.getMessage());
                    }
                }
            }
        });
        getUI().addWindow(window);
    }

    public void refreshContainer() {
        if (this.container != null) {
            this.container.refreshGroups();
        }
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("100%");
        mainLayout.setHeight("100%");
        mainLayout.setMargin(false);
        // top-level component properties
        setWidth("100.0%");
        setHeight("100.0%");
        // horizontalLayoutToolbar
        horizontalLayoutToolbar = buildHorizontalLayoutToolbar();
        mainLayout.addComponent(horizontalLayoutToolbar);
        // tree
        table = new Table();
        table.setImmediate(false);
        table.setWidth("-1px");
        table.setHeight("-1px");
        mainLayout.addComponent(table);
        mainLayout.setExpandRatio(table, 1.0f);
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayoutToolbar() {
        // common part: create layout
        horizontalLayoutToolbar = new HorizontalLayout();
        horizontalLayoutToolbar.setImmediate(false);
        horizontalLayoutToolbar.setWidth("-1px");
        horizontalLayoutToolbar.setHeight("-1px");
        horizontalLayoutToolbar.setMargin(true);
        horizontalLayoutToolbar.setSpacing(true);
        // buttonCreate
        buttonCreate = new Button();
        buttonCreate.setCaption("Create Group");
        buttonCreate.setImmediate(false);
        buttonCreate.setWidth("-1px");
        buttonCreate.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonCreate);
        // buttonRemove
        buttonRemove = new Button();
        buttonRemove.setCaption("Remove Group");
        buttonRemove.setImmediate(false);
        buttonRemove.setWidth("-1px");
        buttonRemove.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonRemove);
        return horizontalLayoutToolbar;
    }
}

17 View Complete Implementation : PIPManagement.java
Copyright Apache License 2.0
Author : apache
public clreplaced PIPManagement extends CustomComponent {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Table tablePIP;

    @AutoGenerated
    private HorizontalLayout horizontalLayoutToolbar;

    @AutoGenerated
    private Button buttonImport;

    @AutoGenerated
    private Button buttonRemove;

    @AutoGenerated
    private Button buttonClone;

    @AutoGenerated
    private Button buttonAdd;

    /**
     */
    private static final long serialVersionUID = 1L;

    private static final Log logger = LogFactory.getLog(PIPManagement.clreplaced);

    private static final Object[] visibleColumns = new Object[] { "name", "description", "piptype", "issuer" };

    private static final String[] columnHeaders = new String[] { "Name", "Description", "Type", "Issuer" };

    private final Action ADD_CONFIGURATION = new Action("Add Configuration");

    private final Action EDIT_CONFIGURATION = new Action("Edit Configuration");

    private final Action CLONE_CONFIGURATION = new Action("Clone Configuration");

    private final Action REMOVE_CONFIGURATION = new Action("Remove Configuration");

    private final Action ADD_RESOLVER = new Action("Add Resolver");

    private final Action PUBLISH_CONFIGURATION = new Action("Publish Configuration");

    private final PIPManagement self = this;

    private final JPAContainer<PIPConfiguration> container = new JPAContainer<PIPConfiguration>(PIPConfiguration.clreplaced);

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     */
    public PIPManagement() {
        buildMainLayout();
        setCompositionRoot(mainLayout);
        // 
        // Setup containers
        // 
        boolean isReadOnly;
        if (((XacmlAdminUI) UI.getCurrent()).isAuthorized(XacmlAdminAuthorization.AdminAction.ACTION_WRITE, XacmlAdminAuthorization.AdminResource.RESOURCE_PIP_ADMIN)) {
            // 
            // Writable container
            // 
            container.setEnreplacedyProvider(new CachingMutableLocalEnreplacedyProvider<PIPConfiguration>(PIPConfiguration.clreplaced, ((XacmlAdminUI) UI.getCurrent()).getEnreplacedyManager()));
            isReadOnly = false;
        } else {
            // 
            // Read only container
            // 
            container.setEnreplacedyProvider(new CachingLocalEnreplacedyProvider<PIPConfiguration>(PIPConfiguration.clreplaced, ((XacmlAdminUI) UI.getCurrent()).getEnreplacedyManager()));
            isReadOnly = true;
        }
        // 
        // Finish initialization
        // 
        this.initializeTree(isReadOnly);
        this.initializeButtons(isReadOnly);
        // 
        // Setup
        // 
        this.setupButtons();
    }

    protected void initializeTree(boolean isReadOnly) {
        // 
        // Initialize GUI properties
        // 
        this.tablePIP.setImmediate(true);
        this.tablePIP.setContainerDataSource(this.container);
        this.tablePIP.sereplacedemCaptionMode(ItemCaptionMode.PROPERTY);
        this.tablePIP.sereplacedemCaptionPropertyId("name");
        this.tablePIP.setVisibleColumns(visibleColumns);
        this.tablePIP.setColumnHeaders(columnHeaders);
        this.tablePIP.setSizeFull();
        // 
        // Access?
        // 
        if (isReadOnly) {
            if (logger.isDebugEnabled()) {
                logger.debug("read only pip access");
            }
            return;
        }
        this.tablePIP.setSelectable(true);
        // 
        // Setup click handler
        // 
        this.tablePIP.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    PIPManagement.editConfiguration(self.container.gereplacedem(event.gereplacedemId()));
                }
            }
        });
        // 
        // Setup action handler
        // 
        this.tablePIP.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    return new Action[] { ADD_CONFIGURATION };
                }
                // 
                // Target is an Object ID
                // 
                EnreplacedyItem<PIPConfiguration> config = self.container.gereplacedem(target);
                if (config != null && config.getEnreplacedy().isReadOnly() == false) {
                    if (config.getEnreplacedy().requiresResolvers()) {
                        return new Action[] { EDIT_CONFIGURATION, CLONE_CONFIGURATION, REMOVE_CONFIGURATION, PUBLISH_CONFIGURATION, ADD_RESOLVER };
                    } else {
                        return new Action[] { EDIT_CONFIGURATION, CLONE_CONFIGURATION, REMOVE_CONFIGURATION, PUBLISH_CONFIGURATION };
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not find item: " + target);
                }
                return null;
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                EnreplacedyItem<PIPConfiguration> config = self.container.gereplacedem(target);
                if (config == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Could not find item: " + target);
                    }
                    return;
                }
                if (action == ADD_CONFIGURATION) {
                    PIPManagement.editConfiguration(self.container.createEnreplacedyItem(new PIPConfiguration()));
                    return;
                }
                if (action == EDIT_CONFIGURATION) {
                    PIPManagement.editConfiguration(config);
                    return;
                }
                if (action == CLONE_CONFIGURATION) {
                    self.cloneConfiguration(config);
                    return;
                }
                if (action == REMOVE_CONFIGURATION) {
                    self.removeConfiguration(config);
                    return;
                }
                if (action == ADD_RESOLVER) {
                    PIPResolverComponent.addResolver(config.getEnreplacedy(), null);
                    return;
                }
                if (action == PUBLISH_CONFIGURATION) {
                    PIPResolverComponent.publishConfiguration(config);
                    return;
                }
            }
        });
        // 
        // When a selection changes listener
        // 
        this.tablePIP.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                self.setupButtons();
            }
        });
        this.tablePIP.addGeneratedColumn("description", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                EnreplacedyItem<PIPConfiguration> enreplacedy = self.container.gereplacedem(itemId);
                if (enreplacedy != null && enreplacedy.getEnreplacedy() != null) {
                    TextArea area = new TextArea();
                    area.setValue(enreplacedy.getEnreplacedy().getDescription());
                    area.setNullRepresentation("");
                    area.setSizeFull();
                    area.setReadOnly(true);
                    return area;
                }
                return null;
            }
        });
        this.tablePIP.addGeneratedColumn("piptype", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                EnreplacedyItem<PIPConfiguration> enreplacedy = self.container.gereplacedem(itemId);
                if (enreplacedy != null && enreplacedy.getEnreplacedy() != null) {
                    return enreplacedy.getEnreplacedy().getPiptype().getType();
                }
                return null;
            }
        });
        // 
        // Customize the resolver column
        // 
        this.tablePIP.addGeneratedColumn("Resolvers", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                EnreplacedyItem<PIPConfiguration> enreplacedy = self.container.gereplacedem(itemId);
                if (enreplacedy != null && enreplacedy.getEnreplacedy() != null && enreplacedy.getEnreplacedy().requiresResolvers()) {
                    PIPResolverComponent component = new PIPResolverComponent(enreplacedy.getEnreplacedy());
                    return component;
                }
                return null;
            }
        });
    }

    protected void initializeButtons(boolean isReadOnly) {
        if (isReadOnly) {
            this.buttonAdd.setVisible(false);
            this.buttonRemove.setVisible(false);
            this.buttonClone.setVisible(false);
            return;
        }
        this.buttonAdd.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                PIPManagement.editConfiguration(self.container.createEnreplacedyItem(new PIPConfiguration()));
            }
        });
        this.buttonRemove.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.removeConfiguration(self.container.gereplacedem(self.tablePIP.getValue()));
            }
        });
        this.buttonClone.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.cloneConfiguration(self.container.gereplacedem(self.tablePIP.getValue()));
            }
        });
        this.buttonImport.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                final PIPImportWindow window = new PIPImportWindow();
                window.setCaption("Import PIP Configuration");
                window.setModal(true);
                window.center();
                window.addCloseListener(new CloseListener() {

                    private static final long serialVersionUID = 1L;

                    @Override
                    public void windowClose(CloseEvent e) {
                        String file = window.getUploadedFile();
                        if (file == null) {
                            return;
                        }
                        self.importConfiguration(file);
                    }
                });
                UI.getCurrent().addWindow(window);
            }
        });
    }

    protected void importConfiguration(String file) {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(file));
            Collection<PIPConfiguration> configs = PIPConfiguration.importPIPConfigurations(properties);
            if (configs == null || configs.isEmpty()) {
                AdminNotification.warn("There were no PIP Engine configurations found.");
            } else {
                for (PIPConfiguration config : configs) {
                    this.container.addEnreplacedy(config);
                }
            }
        } catch (IOException e) {
            String message = "Failed to load properties: " + e.getLocalizedMessage();
            logger.error(message);
            AdminNotification.error(message);
        }
    }

    public static void editConfiguration(final EnreplacedyItem<PIPConfiguration> enreplacedy) {
        final PIPConfigurationEditorWindow editor = new PIPConfigurationEditorWindow(enreplacedy);
        if (enreplacedy.isPersistent()) {
            editor.setCaption("Edit PIP Configuration " + enreplacedy.getEnreplacedy().getName());
        } else {
            editor.setCaption("Create New PIP Configuration");
        }
        editor.setModal(true);
        editor.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent event) {
                if (editor.isSaved()) {
                    if (enreplacedy.isPersistent() == false) {
                        ((XacmlAdminUI) UI.getCurrent()).getPIPConfigurations().addEnreplacedy(enreplacedy.getEnreplacedy());
                    }
                    ((XacmlAdminUI) UI.getCurrent()).refreshPIPConfiguration();
                }
            }
        });
        editor.center();
        UI.getCurrent().addWindow(editor);
    }

    protected void removeConfiguration(final EnreplacedyItem<PIPConfiguration> enreplacedy) {
        // 
        // Sanity checks
        // 
        if (enreplacedy == null || enreplacedy.getEnreplacedy() == null) {
            logger.error("Removing a null enreplacedy");
            return;
        }
        String message = "Are you sure you want to remove the " + enreplacedy.getEnreplacedy().getName() + " configuration?";
        ConfirmDialog dialog = ConfirmDialog.getFactory().create("Confirm PIP Configuration Deletion", message, "Remove", "Cancel");
        dialog.setContentMode(ContentMode.HTML);
        dialog.show(getUI(), new ConfirmDialog.Listener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void onClose(ConfirmDialog dialog) {
                if (dialog.isConfirmed()) {
                    if (self.container.removeItem(enreplacedy.gereplacedemId()) == false) {
                        logger.warn("Failed to remove PIP configuration");
                        AdminNotification.warn("Failed to remove PIP configuration.");
                    } else {
                        self.setupButtons();
                    }
                }
            }
        }, true);
    }

    protected void cloneConfiguration(final EnreplacedyItem<PIPConfiguration> enreplacedy) {
        // 
        // Sanity checks
        // 
        if (enreplacedy == null || enreplacedy.getEnreplacedy() == null) {
            logger.warn("Cloning a null enreplacedy, the buttons were not reset. Resetting them.");
            this.setupButtons();
            return;
        }
        // 
        // Clone it
        // 
        PIPManagement.editConfiguration(this.container.createEnreplacedyItem(new PIPConfiguration(enreplacedy.getEnreplacedy(), ((XacmlAdminUI) UI.getCurrent()).getUserid())));
    }

    protected void setupButtons() {
        if (this.tablePIP.getValue() != null) {
            Object id = this.tablePIP.getValue();
            EnreplacedyItem<PIPConfiguration> enreplacedy = this.container.gereplacedem(id);
            if (enreplacedy == null || enreplacedy.getEnreplacedy().isReadOnly()) {
                this.buttonRemove.setEnabled(false);
                this.buttonClone.setEnabled(false);
            } else {
                this.buttonRemove.setEnabled(true);
                this.buttonClone.setEnabled(true);
            }
        } else {
            this.buttonRemove.setEnabled(false);
            this.buttonClone.setEnabled(false);
        }
    }

    public void refreshContainer() {
        this.container.refresh();
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("100%");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("100.0%");
        setHeight("-1px");
        // horizontalLayoutToolbar
        horizontalLayoutToolbar = buildHorizontalLayoutToolbar();
        mainLayout.addComponent(horizontalLayoutToolbar);
        // tablePIP
        tablePIP = new Table();
        tablePIP.setCaption("PIP Configurations");
        tablePIP.setImmediate(false);
        tablePIP.setWidth("100.0%");
        tablePIP.setHeight("-1px");
        mainLayout.addComponent(tablePIP);
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayoutToolbar() {
        // common part: create layout
        horizontalLayoutToolbar = new HorizontalLayout();
        horizontalLayoutToolbar.setImmediate(false);
        horizontalLayoutToolbar.setWidth("-1px");
        horizontalLayoutToolbar.setHeight("-1px");
        horizontalLayoutToolbar.setMargin(false);
        horizontalLayoutToolbar.setSpacing(true);
        // buttonAdd
        buttonAdd = new Button();
        buttonAdd.setCaption("Add Configuration");
        buttonAdd.setImmediate(true);
        buttonAdd.setWidth("-1px");
        buttonAdd.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonAdd);
        // buttonClone
        buttonClone = new Button();
        buttonClone.setCaption("Clone Configuration");
        buttonClone.setImmediate(true);
        buttonClone.setWidth("-1px");
        buttonClone.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonClone);
        // buttonRemove
        buttonRemove = new Button();
        buttonRemove.setCaption("Remove Configuration");
        buttonRemove.setImmediate(true);
        buttonRemove.setWidth("-1px");
        buttonRemove.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonRemove);
        // buttonImport
        buttonImport = new Button();
        buttonImport.setCaption("Import Configuration");
        buttonImport.setImmediate(false);
        buttonImport.setDescription("Imports a configuration from a properties file.");
        buttonImport.setWidth("-1px");
        buttonImport.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonImport);
        return horizontalLayoutToolbar;
    }
}

17 View Complete Implementation : PIPParameterComponent.java
Copyright Apache License 2.0
Author : apache
public clreplaced PIPParameterComponent extends CustomComponent implements FormChangedEventNotifier {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Table tableParameters;

    @AutoGenerated
    private HorizontalLayout horizontalLayout_1;

    @AutoGenerated
    private Button buttonClear;

    @AutoGenerated
    private Button buttonClone;

    @AutoGenerated
    private Button buttonRemove;

    @AutoGenerated
    private Button buttonAdd;

    /**
     */
    private static final long serialVersionUID = 1L;

    private static final Log logger = LogFactory.getLog(PIPParameterComponent.clreplaced);

    private final PIPParameterComponent self = this;

    private final Object config;

    private final BasicNotifier notifier = new BasicNotifier();

    private static final Action ADD_PARAM = new Action("Add Parameter");

    private static final Action EDIT_PARAM = new Action("Edit Parameter");

    private static final Action REMOVE_PARAM = new Action("Remove Parameter");

    private static final Action CLONE_PARAM = new Action("Clone Parameter");

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     */
    public PIPParameterComponent(Object config) {
        buildMainLayout();
        setCompositionRoot(mainLayout);
        // 
        // Save
        // 
        this.config = config;
        // 
        // Initialize
        // 
        this.initializeTable();
        this.initializeButtons();
        // 
        // Initial button setup
        // 
        this.setupButtons();
    }

    protected void initializeTable() {
        // 
        // Initialize GUI properties
        // 
        this.tableParameters.setImmediate(true);
        this.tableParameters.setSelectable(true);
        // 
        // Add in the data
        // 
        if (this.config instanceof PIPConfiguration) {
            BeanItemContainer<PIPConfigParam> container = new BeanItemContainer<PIPConfigParam>(PIPConfigParam.clreplaced);
            PIPConfiguration config = (PIPConfiguration) this.config;
            for (PIPConfigParam param : config.getPipconfigParams()) {
                container.addBean(param);
            }
            this.tableParameters.setContainerDataSource(container);
        } else if (this.config instanceof PIPResolver) {
            BeanItemContainer<PIPResolverParam> container = new BeanItemContainer<PIPResolverParam>(PIPResolverParam.clreplaced);
            PIPResolver resolver = (PIPResolver) this.config;
            for (PIPResolverParam param : resolver.getPipresolverParams()) {
                container.addBean(param);
            }
            this.tableParameters.setContainerDataSource(container);
        } else {
            throw new IllegalArgumentException("Unsupported object");
        }
        // 
        // Finish more gui initialization
        // 
        // this.tableParameters.getContainerDataSource().size() + 1);
        this.tableParameters.setPageLength(5);
        this.tableParameters.setVisibleColumns(new Object[] { "paramName", "paramValue" });
        this.tableParameters.setColumnHeaders(new String[] { "Name", "Value" });
        this.tableParameters.setSizeFull();
        // 
        // Action Handler
        // 
        this.tableParameters.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    return new Action[] { ADD_PARAM };
                }
                return new Action[] { EDIT_PARAM, REMOVE_PARAM, CLONE_PARAM };
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == ADD_PARAM) {
                    self.editParameter(null);
                    return;
                }
                if (action == EDIT_PARAM) {
                    self.editParameter(target);
                    return;
                }
                if (action == REMOVE_PARAM) {
                    self.removeParameter(target);
                    return;
                }
                if (action == CLONE_PARAM) {
                    self.cloneParameter(target);
                    return;
                }
            }
        });
        // 
        // Respond to events
        // 
        this.tableParameters.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                self.setupButtons();
            }
        });
        // 
        // Double click
        // 
        this.tableParameters.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    self.editParameter(event.gereplacedemId());
                }
            }
        });
    }

    protected void initializeButtons() {
        this.buttonAdd.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.editParameter(null);
            }
        });
        this.buttonClone.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.cloneParameter(self.tableParameters.getValue());
            }
        });
        this.buttonRemove.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.removeParameter(self.tableParameters.getValue());
            }
        });
        this.buttonClear.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.clearParameters();
            }
        });
    }

    protected void setupButtons() {
        if (this.tableParameters.getValue() != null) {
            this.buttonClone.setEnabled(true);
            this.buttonRemove.setEnabled(true);
        } else {
            this.buttonClone.setEnabled(false);
            this.buttonRemove.setEnabled(false);
        }
    }

    protected void editParameter(final Object source) {
        // 
        // Make a copy
        // 
        final Object target = source != null ? source : this.config instanceof PIPConfiguration ? new PIPConfigParam() : new PIPResolverParam();
        final PIPParamEditorWindow window = new PIPParamEditorWindow(target);
        window.setModal(true);
        window.setCaption((source == null ? "Create New Parameter" : "Edit Parameter"));
        window.center();
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did user save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Yes - was it a brand new object?
                // 
                if (source == null) {
                    // 
                    // yes add it to the parent object
                    // 
                    if (self.config instanceof PIPConfiguration) {
                        ((PIPConfiguration) self.config).addPipconfigParam((PIPConfigParam) target);
                    } else {
                        ((PIPResolver) self.config).addPipresolverParam((PIPResolverParam) target);
                    }
                    // 
                    // add it to the table
                    // 
                    Item item = self.tableParameters.addItem(target);
                    if (item == null) {
                        logger.error("Failed to add parameter: " + target);
                    } else {
                        self.tableParameters.select(target);
                    }
                } else {
                    // 
                    // Copy the parameters over
                    // 
                    if (source instanceof PIPConfigParam) {
                        ((PIPConfigParam) source).setParamName(((PIPConfigParam) target).getParamName());
                        ((PIPConfigParam) source).setParamValue(((PIPConfigParam) target).getParamValue());
                    } else {
                        ((PIPResolverParam) source).setParamName(((PIPResolverParam) target).getParamName());
                        ((PIPResolverParam) source).setParamValue(((PIPResolverParam) target).getParamValue());
                    }
                    // 
                    // Update the table
                    // 
                    self.tableParameters.refreshRowCache();
                }
            }
        });
        UI.getCurrent().addWindow(window);
    }

    protected void cloneParameter(Object target) {
        if (target == null) {
            logger.error("null target sent to clone method");
            return;
        }
        Item item;
        if (target instanceof PIPConfigParam && this.config instanceof PIPConfiguration) {
            PIPConfigParam param = new PIPConfigParam((PIPConfigParam) target);
            ((PIPConfiguration) this.config).addPipconfigParam(param);
            item = this.tableParameters.addItem(new BeanItem<PIPConfigParam>(param));
        } else if (target instanceof PIPResolverParam && this.config instanceof PIPResolver) {
            PIPResolverParam param = new PIPResolverParam((PIPResolverParam) target);
            ((PIPResolver) this.config).addPipresolverParam(param);
            item = this.tableParameters.addItem(new BeanItem<PIPResolverParam>(param));
        } else {
            throw new IllegalArgumentException("Unsupported param and config combination.");
        }
        if (item == null) {
            logger.error("Failed to add parameter to table: " + target);
        } else {
            this.tableParameters.select(target);
        }
    }

    protected void removeParameter(Object target) {
        if (target == null) {
            logger.error("null target sent to remove method");
            return;
        }
        if (this.config instanceof PIPConfiguration) {
            if (((PIPConfiguration) this.config).removePipconfigParam((PIPConfigParam) target) == null) {
                logger.error("Failed to remove parameter from pip configuration");
                return;
            }
        } else {
            if (((PIPResolver) this.config).removePipresolverParam((PIPResolverParam) target) == null) {
                logger.error("Failed to remove parameter from pip resolver");
                return;
            }
        }
        if (this.tableParameters.removeItem(target) == false) {
            logger.error("Failed to remove parameter from table");
        }
    }

    protected void clearParameters() {
        this.tableParameters.removeAllItems();
        if (this.config instanceof PIPConfiguration) {
            ((PIPConfiguration) this.config).clearConfigParams();
        } else {
            ((PIPResolver) this.config).clearParams();
        }
    }

    @Override
    public boolean addListener(FormChangedEventListener listener) {
        return this.notifier.addListener(listener);
    }

    @Override
    public boolean removeListener(FormChangedEventListener listener) {
        return this.notifier.removeListener(listener);
    }

    @Override
    public void fireFormChangedEvent() {
        this.notifier.fireFormChangedEvent();
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("-1px");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(false);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // horizontalLayout_1
        horizontalLayout_1 = buildHorizontalLayout_1();
        mainLayout.addComponent(horizontalLayout_1);
        // tableParameters
        tableParameters = new Table();
        tableParameters.setCaption("Configuration Parameters");
        tableParameters.setImmediate(false);
        tableParameters.setWidth("-1px");
        tableParameters.setHeight("-1px");
        mainLayout.addComponent(tableParameters);
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayout_1() {
        // common part: create layout
        horizontalLayout_1 = new HorizontalLayout();
        horizontalLayout_1.setImmediate(false);
        horizontalLayout_1.setWidth("-1px");
        horizontalLayout_1.setHeight("-1px");
        horizontalLayout_1.setMargin(false);
        horizontalLayout_1.setSpacing(true);
        // buttonAdd
        buttonAdd = new Button();
        buttonAdd.setCaption("Add");
        buttonAdd.setImmediate(false);
        buttonAdd.setWidth("-1px");
        buttonAdd.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonAdd);
        // buttonRemove
        buttonRemove = new Button();
        buttonRemove.setCaption("Remove");
        buttonRemove.setImmediate(false);
        buttonRemove.setWidth("-1px");
        buttonRemove.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonRemove);
        // buttonClone
        buttonClone = new Button();
        buttonClone.setCaption("Clone");
        buttonClone.setImmediate(false);
        buttonClone.setWidth("-1px");
        buttonClone.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonClone);
        // buttonClear
        buttonClear = new Button();
        buttonClear.setCaption("Clear All");
        buttonClear.setImmediate(false);
        buttonClear.setWidth("-1px");
        buttonClear.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonClear);
        return horizontalLayout_1;
    }
}

17 View Complete Implementation : PIPSQLResolverEditorWindow.java
Copyright Apache License 2.0
Author : apache
public clreplaced PIPSQLResolverEditorWindow extends CustomComponent implements FormChangedEventNotifier, Handler {

    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Table tableAttributes;

    @AutoGenerated
    private Table tableRequiredAttributes;

    @AutoGenerated
    private CheckBox checkBoxShortIds;

    @AutoGenerated
    private TextField textFieldFilter;

    @AutoGenerated
    private TextField textFieldBase;

    @AutoGenerated
    private TextArea textAreaSelect;

    private final Action ADD_ATTRIBUTE = new Action("Add Attribute");

    private final Action EDIT_ATTRIBUTE = new Action("Edit Attribute");

    private final Action CLONE_ATTRIBUTE = new Action("Clone Attribute");

    private final Action REMOVE_ATTRIBUTE = new Action("Remove Attribute");

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    /**
     */
    protected clreplaced ResolverAttribute implements Serializable {

        private static final long serialVersionUID = 1L;

        String identifier = null;

        String prefix = null;

        PIPResolverParam id = null;

        PIPResolverParam category = null;

        PIPResolverParam datatype = null;

        PIPResolverParam issuer = null;

        PIPResolverParam column = null;

        public ResolverAttribute(String prefix, String identifier) {
            this.prefix = prefix;
            this.identifier = identifier;
        }

        public ResolverAttribute(String prefix, String identifier, ResolverAttribute target) {
            this(prefix, identifier);
            this.setId(target.getId());
            this.setCategory(target.getCategory());
            this.setDatatype(target.getDatatype());
            this.setIssuer(target.getIssuer());
            this.setColumn(target.getColumn());
            this.setResolver(target.id.getPipresolver());
        }

        public String getIdentifier() {
            return this.identifier;
        }

        public String getId() {
            if (this.id == null) {
                return null;
            }
            return this.id.getParamValue();
        }

        public String getShortId() {
            String id = this.getId();
            if (id == null) {
                return null;
            }
            return XACMLConstants.extractShortName(id);
        }

        public PIPResolverParam getIdParam() {
            return this.id;
        }

        public void setId(String id) {
            if (this.id == null) {
                this.id = new PIPResolverParam();
                this.id.setParamName(this.prefix + this.identifier + ".id");
            }
            this.id.setParamValue(id);
        }

        public void setId(PIPResolverParam param) {
            this.id = param;
        }

        public String getCategory() {
            if (this.category == null) {
                return null;
            }
            return this.category.getParamValue();
        }

        public String getShortCategory() {
            String category = this.getCategory();
            if (category == null) {
                return null;
            }
            return XACMLConstants.extractShortName(category);
        }

        public PIPResolverParam getCategoryParam() {
            return this.category;
        }

        public void setCategory(String category) {
            if (this.category == null) {
                this.category = new PIPResolverParam();
                this.category.setParamName(this.prefix + this.identifier + ".category");
            }
            this.category.setParamValue(category);
        }

        public void setCategory(PIPResolverParam param) {
            this.category = param;
        }

        public String getDatatype() {
            if (this.datatype == null) {
                return null;
            }
            return this.datatype.getParamValue();
        }

        public String getShortDatatype() {
            String dt = this.getDatatype();
            if (dt == null) {
                return null;
            }
            return XACMLConstants.extractShortName(dt);
        }

        public PIPResolverParam getDatatypeParam() {
            return this.datatype;
        }

        public void setDatatype(String datatype) {
            if (this.datatype == null) {
                this.datatype = new PIPResolverParam();
                this.datatype.setParamName(this.prefix + this.identifier + ".datatype");
            }
            this.datatype.setParamValue(datatype);
        }

        public void setDatatype(PIPResolverParam param) {
            this.datatype = param;
        }

        public String getIssuer() {
            if (this.issuer == null) {
                return null;
            }
            return this.issuer.getParamValue();
        }

        public String getShortIssuer() {
            String issuer = this.getIssuer();
            if (issuer == null) {
                return null;
            }
            return XACMLConstants.extractShortName(issuer);
        }

        public PIPResolverParam getIssuerParam() {
            return this.issuer;
        }

        public void setIssuer(String issuer) {
            if (this.issuer == null) {
                this.issuer = new PIPResolverParam();
                this.issuer.setParamName(this.prefix + this.identifier + ".issuer");
            }
            this.issuer.setParamValue(issuer);
        }

        public void setIssuer(PIPResolverParam param) {
            this.issuer = param;
        }

        public Integer getColumn() {
            if (this.column == null) {
                return null;
            }
            try {
                return Integer.parseInt(this.column.getParamValue());
            } catch (NumberFormatException e) {
                logger.error("Failed to set column: " + e);
                return null;
            }
        }

        public PIPResolverParam getColumnParam() {
            return this.column;
        }

        public void setColumn(Integer col) {
            if (this.column == null) {
                this.column = new PIPResolverParam();
                this.column.setParamName(this.prefix + this.identifier + "column");
            }
            this.column.setParamValue(col.toString());
        }

        public void setColumn(PIPResolverParam param) {
            this.column = param;
        }

        public void setResolver(PIPResolver resolver) {
            if (this.id != null) {
                this.id.setPipresolver(resolver);
            }
            if (this.category != null) {
                this.category.setPipresolver(resolver);
            }
            if (this.datatype != null) {
                this.datatype.setPipresolver(resolver);
            }
            if (this.issuer != null) {
                this.issuer.setPipresolver(resolver);
            }
            if (this.column != null) {
                this.column.setPipresolver(resolver);
            }
        }
    }

    private static final long serialVersionUID = 1L;

    private static final Log logger = LogFactory.getLog(PIPSQLResolverEditorWindow.clreplaced);

    private final PIPSQLResolverEditorWindow self = this;

    private final EnreplacedyItem<PIPResolver> enreplacedy;

    private final BeanItemContainer<ResolverAttribute> fieldsContainer = new BeanItemContainer<ResolverAttribute>(ResolverAttribute.clreplaced);

    private final BeanItemContainer<ResolverAttribute> parametersContainer = new BeanItemContainer<ResolverAttribute>(ResolverAttribute.clreplaced);

    private final BasicNotifier notifier = new BasicNotifier();

    boolean isSaved = false;

    String fieldPrefix;

    String parameterPrefix;

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     */
    public PIPSQLResolverEditorWindow(EnreplacedyItem<PIPResolver> enreplacedy) {
        buildMainLayout();
        setCompositionRoot(mainLayout);
        // 
        // Save
        // 
        this.enreplacedy = enreplacedy;
        // 
        // Initialize
        // 
        this.initialize();
    }

    protected boolean isSQL() {
        if (this.enreplacedy.getEnreplacedy().getPipconfiguration().getPiptype().isSQL() || this.enreplacedy.getEnreplacedy().getPipconfiguration().getPiptype().isHyperCSV()) {
            return true;
        }
        return false;
    }

    protected boolean isLDAP() {
        return this.enreplacedy.getEnreplacedy().getPipconfiguration().getPiptype().isLDAP();
    }

    protected boolean isCSV() {
        return this.enreplacedy.getEnreplacedy().getPipconfiguration().getPiptype().isCSV();
    }

    protected void initialize() {
        // 
        // Initialize enreplacedy
        // 
        this.initializeEnreplacedy();
        // 
        // Go through the parameters, save them into a
        // properties object.
        // 
        boolean sourceInitialized = false;
        boolean attributeInitialized = false;
        for (PIPResolverParam param : this.enreplacedy.getEnreplacedy().getPipresolverParams()) {
            // 
            // Look for ones we know about
            // 
            if (param.getParamName().equalsIgnoreCase("select")) {
                this.textAreaSelect.setValue(param.getParamValue());
                this.textAreaSelect.setData(param);
            } else if (param.getParamName().equals("fields") || param.getParamName().equals("filter.view")) {
                this.initializeSourceTable(param.getParamValue());
                this.tableRequiredAttributes.setData(param);
                sourceInitialized = true;
            } else if (param.getParamName().equals("parameters") || param.getParamName().equals("filter.parameters")) {
                this.initializeAttributeTable(param.getParamValue());
                this.tableAttributes.setData(param);
                attributeInitialized = true;
            } else if (param.getParamName().equalsIgnoreCase("base")) {
                this.textFieldBase.setValue(param.getParamValue());
                this.textFieldBase.setData(param);
            } else if (param.getParamName().equalsIgnoreCase("filter")) {
                this.textFieldFilter.setValue(param.getParamValue());
                this.textFieldFilter.setData(param);
            }
        }
        // 
        // Initialize GUI
        // 
        this.initializeText();
        this.initializeCheckBox();
        // 
        // Verify the tables get setup, if this is a new object
        // then they haven't been.
        // 
        if (sourceInitialized == false) {
            this.initializeSourceTable("");
        }
        if (attributeInitialized == false) {
            this.initializeAttributeTable("");
        }
    }

    protected void initializeEnreplacedy() {
        // 
        // Make sure the clreplacedname is set correctly
        // 
        if (this.isSQL()) {
            // 
            // 
            // 
            this.fieldPrefix = "field.";
            this.parameterPrefix = "parameter.";
            this.enreplacedy.getEnreplacedy().setClreplacedname(ConfigurableJDBCResolver.clreplaced.getCanonicalName());
        } else if (this.isLDAP()) {
            // 
            // 
            // 
            this.fieldPrefix = "filter.view.";
            this.parameterPrefix = "filter.parameters.";
            this.enreplacedy.getEnreplacedy().setClreplacedname(ConfigurableLDAPResolver.clreplaced.getCanonicalName());
        } else if (this.isCSV()) {
            // 
            // 
            // 
            this.fieldPrefix = "field.";
            this.parameterPrefix = "parameter.";
            this.enreplacedy.getEnreplacedy().setClreplacedname(ConfigurableCSVResolver.clreplaced.getCanonicalName());
        }
    }

    protected void initializeText() {
        // 
        // Are we SQL or LDAP?
        // 
        if (this.isSQL()) {
            // 
            // Turn these off
            // 
            this.textFieldBase.setRequired(false);
            this.textFieldBase.setVisible(false);
            this.textFieldFilter.setRequired(false);
            this.textFieldFilter.setVisible(false);
            // 
            // GUI properties
            // 
            this.textAreaSelect.setImmediate(true);
            // 
            // Respond to changes
            // 
            this.textAreaSelect.addValueChangeListener(new ValueChangeListener() {

                private static final long serialVersionUID = 1L;

                @Override
                public void valueChange(ValueChangeEvent event) {
                    PIPResolverParam param = (PIPResolverParam) self.textAreaSelect.getData();
                    if (param == null) {
                        param = new PIPResolverParam();
                        param.setPipresolver(self.enreplacedy.getEnreplacedy());
                        param.setParamName("select");
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(param);
                        self.textAreaSelect.setData(param);
                    }
                    param.setParamValue(self.textAreaSelect.getValue());
                    self.fireFormChangedEvent();
                }
            });
        } else if (this.isLDAP()) {
            // 
            // Turn these off
            // 
            this.textAreaSelect.setRequired(false);
            this.textAreaSelect.setVisible(false);
            // 
            // 
            // 
            this.textFieldBase.setImmediate(true);
            this.textFieldBase.addValueChangeListener(new ValueChangeListener() {

                private static final long serialVersionUID = 1L;

                @Override
                public void valueChange(ValueChangeEvent event) {
                    PIPResolverParam param = (PIPResolverParam) self.textFieldBase.getData();
                    if (param == null) {
                        param = new PIPResolverParam();
                        param.setPipresolver(self.enreplacedy.getEnreplacedy());
                        param.setParamName("base");
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(param);
                        self.textFieldBase.setData(param);
                    }
                    param.setParamValue(self.textFieldBase.getValue());
                    self.fireFormChangedEvent();
                }
            });
            // 
            // 
            // 
            this.textFieldFilter.setImmediate(true);
            this.textFieldFilter.addValueChangeListener(new ValueChangeListener() {

                private static final long serialVersionUID = 1L;

                @Override
                public void valueChange(ValueChangeEvent event) {
                    PIPResolverParam param = (PIPResolverParam) self.textFieldFilter.getData();
                    if (param == null) {
                        param = new PIPResolverParam();
                        param.setPipresolver(self.enreplacedy.getEnreplacedy());
                        param.setParamName("filter");
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(param);
                        self.textFieldFilter.setData(param);
                    }
                    param.setParamValue(self.textFieldFilter.getValue());
                    self.fireFormChangedEvent();
                }
            });
        } else if (this.isCSV()) {
            // 
            // Turn these off
            // 
            this.textAreaSelect.setRequired(false);
            this.textAreaSelect.setVisible(false);
            this.textFieldBase.setRequired(false);
            this.textFieldBase.setVisible(false);
            this.textFieldFilter.setRequired(false);
            this.textFieldFilter.setVisible(false);
        }
    }

    protected void initializeCheckBox() {
        this.checkBoxShortIds.setValue(true);
        this.checkBoxShortIds.setImmediate(true);
        this.checkBoxShortIds.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                if (self.checkBoxShortIds.getValue()) {
                    self.tableRequiredAttributes.setColumnCollapsed("id", true);
                    self.tableRequiredAttributes.setColumnCollapsed("category", true);
                    self.tableRequiredAttributes.setColumnCollapsed("datatype", true);
                    self.tableRequiredAttributes.setColumnCollapsed("shortId", false);
                    self.tableRequiredAttributes.setColumnCollapsed("shortCategory", false);
                    self.tableRequiredAttributes.setColumnCollapsed("shortDatatype", false);
                } else {
                    self.tableRequiredAttributes.setColumnCollapsed("id", false);
                    self.tableRequiredAttributes.setColumnCollapsed("category", false);
                    self.tableRequiredAttributes.setColumnCollapsed("datatype", false);
                    self.tableRequiredAttributes.setColumnCollapsed("shortId", true);
                    self.tableRequiredAttributes.setColumnCollapsed("shortCategory", true);
                    self.tableRequiredAttributes.setColumnCollapsed("shortDatatype", true);
                }
            }
        });
    }

    protected void initializeSourceTable(String fields) {
        // 
        // Add data into the container
        // 
        this.populateData(this.fieldPrefix, fields, this.fieldsContainer);
        // 
        // Set GUI properties
        // 
        this.tableRequiredAttributes.setContainerDataSource(this.fieldsContainer);
        this.tableRequiredAttributes.setPageLength((this.fieldsContainer.size() == 0 ? 3 : this.fieldsContainer.size() + 1));
        this.tableRequiredAttributes.setSizeFull();
        this.tableRequiredAttributes.setColumnCollapsingAllowed(true);
        this.tableRequiredAttributes.setVisibleColumns(new Object[] { "identifier", "id", "category", "datatype", "shortId", "shortCategory", "shortDatatype" });
        this.tableRequiredAttributes.setColumnHeaders(new String[] { "Field", "Attribute Id", "Category", "Data Type", "Attribute Id", "Category", "Data Type" });
        this.tableRequiredAttributes.setColumnCollapsed("id", true);
        this.tableRequiredAttributes.setColumnCollapsed("category", true);
        this.tableRequiredAttributes.setColumnCollapsed("datatype", true);
        this.tableRequiredAttributes.setSelectable(true);
        // 
        // Setup its handler
        // 
        this.tableRequiredAttributes.addActionHandler(this);
        // 
        // Respond to events
        // 
        this.tableRequiredAttributes.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    Object id = event.gereplacedemId();
                    if (id == null) {
                        // 
                        // Really shouldn't get here
                        // 
                        return;
                    }
                    BeanItem<ResolverAttribute> beanItem = self.fieldsContainer.gereplacedem(id);
                    if (beanItem == null) {
                        // 
                        // Again, shouldn't get here
                        // 
                        return;
                    }
                    self.editAttribute(self.tableRequiredAttributes, beanItem.getBean());
                }
            }
        });
    }

    protected void initializeAttributeTable(String parameters) {
        // 
        // Add data into the container
        // 
        this.populateData(this.parameterPrefix, parameters, this.parametersContainer);
        // 
        // setup gui properties
        // 
        this.tableAttributes.setContainerDataSource(this.parametersContainer);
        this.tableAttributes.setPageLength(this.parametersContainer.size() + 1);
        this.tableAttributes.setSizeFull();
        this.tableAttributes.setColumnCollapsingAllowed(true);
        this.tableAttributes.setVisibleColumns(new Object[] { "identifier", "id", "category", "datatype", "shortId", "shortCategory", "shortDatatype" });
        this.tableAttributes.setColumnHeaders(new String[] { "Position", "Attribute Id", "Category", "Data Type", "Attribute Id", "Category", "Data Type" });
        this.tableAttributes.setColumnCollapsed("id", true);
        this.tableAttributes.setColumnCollapsed("category", true);
        this.tableAttributes.setColumnCollapsed("datatype", true);
        this.tableAttributes.setSelectable(true);
        // 
        // Setup its handler
        // 
        this.tableAttributes.addActionHandler(this);
        // 
        // Respond to events
        // 
        this.tableAttributes.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    Object id = event.gereplacedemId();
                    if (id == null) {
                        // 
                        // Really shouldn't get here
                        // 
                        return;
                    }
                    BeanItem<ResolverAttribute> beanItem = self.parametersContainer.gereplacedem(id);
                    if (beanItem == null) {
                        // 
                        // Again, shouldn't get here
                        // 
                        return;
                    }
                    self.editAttribute(self.tableAttributes, beanItem.getBean());
                }
            }
        });
    }

    protected void populateData(String prefix, String list, BeanItemContainer<ResolverAttribute> container) {
        for (String field : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
            // 
            // Create a bean for this field
            // 
            ResolverAttribute bean = new ResolverAttribute(prefix, field);
            // 
            // Now try to find the attribute information
            // 
            for (PIPResolverParam param : this.enreplacedy.getEnreplacedy().getPipresolverParams()) {
                if (param.getParamName().equals(prefix + field + ".id")) {
                    bean.setId(param);
                } else if (param.getParamName().equals(prefix + field + ".category")) {
                    bean.setCategory(param);
                } else if (param.getParamName().equals(prefix + field + ".datatype")) {
                    bean.setDatatype(param);
                } else if (param.getParamName().equals(prefix + field + ".issuer")) {
                    bean.setIssuer(param);
                } else if (param.getParamName().equals(prefix + field + ".column")) {
                    bean.setColumn(param);
                }
            }
            container.addBean(bean);
        }
    }

    @Override
    public Action[] getActions(Object target, Object sender) {
        if (target == null) {
            return new Action[] { ADD_ATTRIBUTE };
        }
        return new Action[] { EDIT_ATTRIBUTE, CLONE_ATTRIBUTE, REMOVE_ATTRIBUTE };
    }

    @Override
    public void handleAction(Action action, Object sender, Object target) {
        if (action == ADD_ATTRIBUTE) {
            if (sender.equals(this.tableRequiredAttributes)) {
                this.editAttribute(self.tableRequiredAttributes, null);
            } else {
                this.editAttribute(self.tableAttributes, null);
            }
            return;
        }
        if (action == EDIT_ATTRIBUTE) {
            replacedert target instanceof ResolverAttribute;
            if (sender.equals(this.tableRequiredAttributes)) {
                this.editAttribute(self.tableRequiredAttributes, (ResolverAttribute) target);
            } else {
                this.editAttribute(self.tableAttributes, (ResolverAttribute) target);
            }
            return;
        }
        if (action == CLONE_ATTRIBUTE) {
            replacedert target instanceof ResolverAttribute;
            try {
                // 
                // Which table?
                // 
                if (sender.equals(this.tableRequiredAttributes)) {
                    // 
                    // Clone the attribute giving it a new
                    // field name.
                    // 
                    ResolverAttribute clone = new ResolverAttribute(this.fieldPrefix, this.getNextField(), (ResolverAttribute) target);
                    // 
                    // Add it to the container
                    // 
                    this.fieldsContainer.addBean(clone);
                    // 
                    // Reset the page length so we can see it and have room
                    // to add another.
                    // 
                    this.tableRequiredAttributes.setPageLength(this.fieldsContainer.size() + 1);
                    // 
                    // Select it
                    // 
                    this.tableRequiredAttributes.select(clone);
                } else {
                    // 
                    // Clone the attribute giving it a new
                    // field name.
                    // 
                    ResolverAttribute clone = new ResolverAttribute(this.parameterPrefix, this.getNextParameter(), (ResolverAttribute) target);
                    // 
                    // Add it to the container
                    // 
                    this.parametersContainer.addBean(clone);
                    // 
                    // Reset the page length so we can see it and have room
                    // to add another.
                    // 
                    this.tableAttributes.setPageLength(this.parametersContainer.size() + 1);
                    // 
                    // Select it
                    // 
                    this.tableAttributes.select(clone);
                }
                // 
                // We have changed
                // 
                this.fireFormChangedEvent();
            } catch (Exception e) {
                logger.error("Failed to clone: " + e);
            }
            return;
        }
        if (action == REMOVE_ATTRIBUTE) {
            replacedert target instanceof ResolverAttribute;
            // 
            // Help method to remove the attribute
            // 
            this.removeAttribute((ResolverAttribute) target);
            // 
            // Which table?
            // 
            if (sender.equals(this.tableRequiredAttributes)) {
                // 
                // Now remove it from the table
                // 
                this.tableRequiredAttributes.removeItem(target);
            } else {
                // 
                // Now remove it from the table
                // 
                this.tableAttributes.removeItem(target);
            }
            // 
            // we have changed
            // 
            this.fireFormChangedEvent();
            return;
        }
    }

    protected void removeAttribute(ResolverAttribute target) {
        this.enreplacedy.getEnreplacedy().removePipresolverParam(target.getIdParam());
        this.enreplacedy.getEnreplacedy().removePipresolverParam(target.getCategoryParam());
        this.enreplacedy.getEnreplacedy().removePipresolverParam(target.getDatatypeParam());
        this.enreplacedy.getEnreplacedy().removePipresolverParam(target.getIssuerParam());
    }

    protected void editAttribute(final Table table, final ResolverAttribute request) {
        if (this.isCSV()) {
            this.editCSVAttribute(table, request);
        } else {
            this.editResolverAttribute(table, request, null);
        }
    }

    protected void editCSVAttribute(final Table table, final ResolverAttribute request) {
        replacedert this.isCSV();
        // 
        // Prompt for the column
        // 
        final ColumnSelectionWindow window = new ColumnSelectionWindow((request != null ? request.getColumn() : 0));
        if (request == null) {
            window.setCaption("Input the CSV Column for the new attribute");
        } else {
            window.setCaption("Edit the CSV Column for the attribute");
        }
        window.setModal(true);
        window.center();
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Save it if its not a new
                // 
                if (request != null) {
                    request.setColumn(window.getColumn());
                }
                // 
                // Now we select the attribute, preplaced the column
                // in case this is a brand new attribute. Yeah its messy.
                // 
                self.editResolverAttribute(table, request, window.getColumn());
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editResolverAttribute(final Table table, final ResolverAttribute request, final Integer column) {
        // 
        // Provide objects to the attribute selection window
        // 
        AttributeDesignatorType designator = new AttributeDesignatorType();
        if (request == null) {
            designator.setAttributeId(XACML3.ID_SUBJECT_SUBJECT_ID.stringValue());
            designator.setCategory(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue());
            designator.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
            designator.setIssuer(this.enreplacedy.getEnreplacedy().getIssuer());
        } else {
            designator.setAttributeId(request.getId());
            designator.setCategory(request.getCategory());
            designator.setDataType(request.getDatatype());
            designator.setIssuer(request.getIssuer());
        }
        // 
        // Have user select an attribute
        // 
        final AttributeSelectionWindow selection = new AttributeSelectionWindow(null, designator);
        selection.setModal(true);
        selection.setCaption("Select Attribute");
        selection.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent event) {
                // 
                // User click Save button?
                // 
                if (selection.isSaved() == false) {
                    return;
                }
                // 
                // Yes - get the final attribute
                // 
                Attribute attribute = selection.getAttribute();
                // 
                // Is it a new one?
                // 
                if (request == null) {
                    try {
                        // 
                        // Create a new bean
                        // 
                        ResolverAttribute bean = null;
                        if (table.equals(self.tableRequiredAttributes)) {
                            bean = new ResolverAttribute(self.fieldPrefix, self.getNextField());
                        } else {
                            bean = new ResolverAttribute(self.parameterPrefix, self.getNextParameter());
                        }
                        bean.setId(attribute.getXacmlId());
                        bean.setCategory(attribute.getCategoryBean().getXacmlId());
                        bean.setDatatype(attribute.getDatatypeBean().getXacmlId());
                        if (attribute.getIssuer() != null) {
                            bean.setIssuer(attribute.getIssuer());
                        }
                        if (column != null) {
                            bean.setColumn(column);
                        }
                        // 
                        // Add it to the resolver
                        // 
                        bean.setResolver(self.enreplacedy.getEnreplacedy());
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(bean.getIdParam());
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(bean.getCategoryParam());
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(bean.getDatatypeParam());
                        if (bean.getIssuer() != null) {
                            self.enreplacedy.getEnreplacedy().addPipresolverParam(bean.getIssuerParam());
                        }
                        // 
                        // Which table?
                        // 
                        if (table.equals(self.tableRequiredAttributes)) {
                            // 
                            // Add to table
                            // 
                            self.fieldsContainer.addBean(bean);
                            // 
                            // Reset the page length
                            // 
                            self.tableRequiredAttributes.setPageLength(self.fieldsContainer.size() + 1);
                        } else if (table.equals(self.tableAttributes)) {
                            // 
                            // Add to table
                            // 
                            self.parametersContainer.addBean(bean);
                            // 
                            // Reset the page length
                            // 
                            self.tableAttributes.setPageLength(self.parametersContainer.size() + 1);
                        }
                        if (logger.isDebugEnabled()) {
                            logger.debug("Added new attribute: " + bean);
                        }
                    } catch (Exception e) {
                        logger.error(e);
                        AdminNotification.error("Unable to add another required attribute field");
                    }
                } else {
                    // 
                    // Update the table entry
                    // 
                    request.setId(attribute.getXacmlId());
                    request.setCategory(attribute.getCategoryBean().getXacmlId());
                    request.setDatatype(attribute.getDatatypeBean().getXacmlId());
                    request.setIssuer(attribute.getIssuer());
                    // 
                    // Let the table know
                    // 
                    table.refreshRowCache();
                }
                // 
                // we have changed
                // 
                self.fireFormChangedEvent();
            }
        });
        selection.center();
        UI.getCurrent().addWindow(selection);
    }

    protected String getNextField() throws Exception {
        // 
        // Start at the next index number. NOTE: The GUI needs
        // to use numbers to index the fields.
        // 
        int index = this.tableRequiredAttributes.size() + 1;
        // 
        // Really if we get to 100, that's an insane number of fields
        // needed for a SQL query.
        // 
        while (index < 100) {
            String field = String.format("%02d", index);
            boolean exists = false;
            for (Object id : this.tableRequiredAttributes.gereplacedemIds()) {
                @SuppressWarnings("unchecked")
                BeanItem<ResolverAttribute> required = (BeanItem<ResolverAttribute>) this.tableRequiredAttributes.gereplacedem(id);
                if (required.getBean().getIdentifier().equals(field)) {
                    exists = true;
                    index++;
                    break;
                }
            }
            if (exists == false) {
                return field;
            }
        }
        // 
        // Sanity check
        // 
        throw new Exception("Unable to find a next field name. Are there too many fields?");
    }

    protected String getNextParameter() throws Exception {
        // 
        // Start at the next index number. NOTE: The GUI needs
        // to use numbers to index the fields.
        // 
        int index = this.tableAttributes.size() + 1;
        // 
        // Really if we get to 100, that's an insane number of fields
        // needed for a SQL query.
        // 
        while (index < 100) {
            String field = String.format("%02d", index);
            boolean exists = false;
            for (Object id : this.tableAttributes.gereplacedemIds()) {
                @SuppressWarnings("unchecked")
                BeanItem<ResolverAttribute> required = (BeanItem<ResolverAttribute>) this.tableAttributes.gereplacedem(id);
                if (required.getBean().getIdentifier().equals(field)) {
                    exists = true;
                    index++;
                    break;
                }
            }
            if (exists == false) {
                return field;
            }
        }
        // 
        // Sanity check
        // 
        throw new Exception("Unable to find a next parameter name. Are there too many parameters?");
    }

    public void discard() throws SourceException {
        if (this.isSQL()) {
            this.textAreaSelect.discard();
        } else if (this.isLDAP()) {
            this.textFieldBase.discard();
            this.textFieldFilter.discard();
        // } else if (this.isCSV()) {
        }
    }

    public void validate() throws InvalidValueException {
        if (this.isSQL()) {
            this.textAreaSelect.validate();
        } else if (this.isLDAP()) {
            this.textFieldBase.validate();
            this.textFieldFilter.validate();
        // } else if (this.isCSV()) {
        }
    }

    public void commit() throws SourceException, InvalidValueException {
        // 
        // Commit required fields
        // 
        if (this.isSQL()) {
            this.textAreaSelect.commit();
        } else if (this.isLDAP()) {
            this.textFieldBase.commit();
            this.textFieldFilter.commit();
        // } else if (this.isCSV()) {
        }
        // 
        // Setup the fields
        // 
        {
            List<String> fields = new ArrayList<String>(this.fieldsContainer.size());
            for (ResolverAttribute attribute : this.fieldsContainer.gereplacedemIds()) {
                fields.add(attribute.getIdentifier());
            }
            PIPResolverParam param = (PIPResolverParam) this.tableRequiredAttributes.getData();
            if (param == null) {
                param = new PIPResolverParam();
                if (this.isSQL()) {
                    param.setParamName("fields");
                } else if (this.isLDAP()) {
                    param.setParamName("filter.view");
                } else if (this.isCSV()) {
                    param.setParamName("fields");
                }
                this.enreplacedy.getEnreplacedy().addPipresolverParam(param);
                this.tableRequiredAttributes.setData(param);
            }
            param.setParamValue(Joiner.on(',').join(fields));
        }
        // 
        // Setup the parameters
        // 
        {
            List<String> parameters = new ArrayList<String>(this.parametersContainer.size());
            for (ResolverAttribute attribute : this.parametersContainer.gereplacedemIds()) {
                parameters.add(attribute.getIdentifier());
            }
            PIPResolverParam param = (PIPResolverParam) this.tableAttributes.getData();
            if (param == null) {
                param = new PIPResolverParam();
                if (this.isSQL()) {
                    param.setParamName("parameters");
                } else if (this.isLDAP()) {
                    param.setParamName("filter.parameters");
                } else if (this.isCSV()) {
                    param.setParamName("parameters");
                }
                this.enreplacedy.getEnreplacedy().addPipresolverParam(param);
                this.tableAttributes.setData(param);
            }
            param.setParamValue(Joiner.on(',').join(parameters));
        }
    }

    public boolean isSaved() {
        return this.isSaved;
    }

    @Override
    public boolean addListener(FormChangedEventListener listener) {
        return this.notifier.addListener(listener);
    }

    @Override
    public boolean removeListener(FormChangedEventListener listener) {
        return this.notifier.removeListener(listener);
    }

    @Override
    public void fireFormChangedEvent() {
        this.notifier.fireFormChangedEvent();
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("-1px");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // textAreaSelect
        textAreaSelect = new TextArea();
        textAreaSelect.setCaption("SQL Select Statement");
        textAreaSelect.setImmediate(false);
        textAreaSelect.setWidth("100.0%");
        textAreaSelect.setHeight("-1px");
        textAreaSelect.setInvalidAllowed(false);
        textAreaSelect.setRequired(true);
        mainLayout.addComponent(textAreaSelect);
        mainLayout.setExpandRatio(textAreaSelect, 1.0f);
        // textFieldBase
        textFieldBase = new TextField();
        textFieldBase.setCaption("Base DN");
        textFieldBase.setImmediate(false);
        textFieldBase.setWidth("-1px");
        textFieldBase.setHeight("-1px");
        mainLayout.addComponent(textFieldBase);
        // textFieldFilter
        textFieldFilter = new TextField();
        textFieldFilter.setCaption("Filter");
        textFieldFilter.setImmediate(false);
        textFieldFilter.setWidth("-1px");
        textFieldFilter.setHeight("-1px");
        mainLayout.addComponent(textFieldFilter);
        // checkBoxShortIds
        checkBoxShortIds = new CheckBox();
        checkBoxShortIds.setCaption("Display short id’s.");
        checkBoxShortIds.setImmediate(false);
        checkBoxShortIds.setWidth("-1px");
        checkBoxShortIds.setHeight("-1px");
        mainLayout.addComponent(checkBoxShortIds);
        // tableRequiredAttributes
        tableRequiredAttributes = new Table();
        tableRequiredAttributes.setCaption("Attributes Returned");
        tableRequiredAttributes.setImmediate(false);
        tableRequiredAttributes.setWidth("-1px");
        tableRequiredAttributes.setHeight("-1px");
        mainLayout.addComponent(tableRequiredAttributes);
        // tableAttributes
        tableAttributes = new Table();
        tableAttributes.setCaption("Parameters - Attributes Needed (i.e. ?)");
        tableAttributes.setImmediate(false);
        tableAttributes.setWidth("-1px");
        tableAttributes.setHeight("-1px");
        tableAttributes.setInvalidAllowed(false);
        tableAttributes.setRequired(true);
        mainLayout.addComponent(tableAttributes);
        return mainLayout;
    }
}

17 View Complete Implementation : PDPManagement.java
Copyright MIT License
Author : att
public clreplaced PDPManagement extends CustomComponent {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Table table;

    @AutoGenerated
    private HorizontalLayout horizontalLayoutToolbar;

    @AutoGenerated
    private Button buttonRemove;

    @AutoGenerated
    private Button buttonCreate;

    private static final long serialVersionUID = 1L;

    private final PDPManagement self = this;

    private static final Log logger = LogFactory.getLog(PDPManagement.clreplaced);

    private PDPGroupContainer container;

    private static final Action CREATE_GROUP = new Action("Create Group");

    private static final Action REPAIR_GROUP = new Action("Repair Group");

    private static final Action EDIT_GROUP = new Action("Edit Group");

    private static final Action DELETE_GROUP = new Action("Delete Group");

    private static final Action SYNCHRONIZE = new Action("Synchronize");

    private static final Action MAKE_DEFAULT = new Action("Make Default");

    private static final Action CREATE_PDP = new Action("Create PDP");

    private static final Action EDIT_PDP = new Action("Edit PDP");

    private static final Action DELETE_PDP = new Action("Delete PDP");

    private static final Action MOVE_PDP = new Action("Move PDP");

    private static final Action GET_PDP_STATUS = new Action("View Status");

    private PAPEngine papEngine;

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     * @param engine
     */
    public PDPManagement(PAPEngine engine) {
        buildMainLayout();
        setCompositionRoot(mainLayout);
        // 
        // Initialize
        // 
        this.papEngine = engine;
        // 
        // Initialize
        // 
        this.initialize();
        // 
        // setup the buttons
        // 
        this.setupButtons();
    }

    protected void initialize() {
        // 
        // Don't create a container if the engine doesn't exist
        // 
        if (this.papEngine == null) {
            // 
            // remove all the components
            // 
            this.mainLayout.removeAllComponents();
            // 
            // Add a label
            // 
            this.mainLayout.addComponent(new Label("PDP Management unavailable - PAP servlet unavailable."));
            // 
            // done
            // 
            return;
        }
        // 
        // Create our container
        // 
        this.container = new PDPGroupContainer(this.papEngine);
        // 
        // Determine authorization level
        // 
        boolean isAdmin = ((XacmlAdminUI) UI.getCurrent()).isAuthorized(XacmlAdminAuthorization.AdminAction.ACTION_ADMIN, XacmlAdminAuthorization.AdminResource.RESOURCE_PDP_ADMIN);
        try {
            this.initializeTree(isAdmin);
            this.initializeButtons(isAdmin);
        } catch (Exception e) {
            logger.error("UNABLE TO START PDPManagement: " + e, e);
            // check if PAP servlet is up
            try {
                Set<PDPGroup> groups = this.papEngine.getPDPGroups();
                if (groups == null) {
                    throw new PAPException("PAP not running");
                }
            } catch (PAPException | NullPointerException e1) {
                setCompositionRoot(new Label("Cannot use PDP Management because the PAP servlet was not running when Admin Console Servlet first initialized."));
                return;
            }
            setCompositionRoot(new Label("Cannot use PDP Management because of error during initialization: " + e.getMessage()));
        }
    }

    protected void initializeTree(final boolean isAdmin) {
        // 
        // Set the data source
        // 
        this.table.setContainerDataSource(this.container);
        // 
        // Setup the GUI properties
        // 
        this.table.setVisibleColumns("Name", "Description", "Status", "Default", "PDPs", "Policies", "PIP Configurations");
        this.table.setColumnHeaders("Name", "Description", "Status", "Default", "PDP's", "Policies", "PIP Configurations");
        // 
        // The description should be a text area
        // 
        this.table.addGeneratedColumn("Description", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                TextArea area = new TextArea();
                area.setValue(((PDPGroup) itemId).getDescription());
                area.setReadOnly(true);
                return area;
            }
        });
        // 
        // Generate a GUI element for the PDP's
        // 
        this.table.addGeneratedColumn("PDPs", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                final Table table = new Table();
                final PDPContainer container = new PDPContainer((PDPGroup) itemId);
                // 
                // Setup the container data
                // 
                table.setContainerDataSource(container);
                // 
                // Save the group for easy access
                // 
                table.setData(itemId);
                // 
                // GUI properties
                // 
                table.setPageLength(table.getContainerDataSource().size() + 2);
                table.setVisibleColumns("Name", "Status", "Description");
                table.setColumnCollapsingAllowed(true);
                table.setColumnCollapsed("Description", true);
                table.setWidth("100%");
                // 
                // If an admin, then it is editable
                // 
                if (isAdmin) {
                    // 
                    // Set it as selectable
                    // 
                    table.setSelectable(true);
                    // 
                    // Add actions
                    // 
                    table.addActionHandler(new Handler() {

                        private static final long serialVersionUID = 1L;

                        @Override
                        public Action[] getActions(Object target, Object sender) {
                            if (target == null) {
                                return new Action[] { CREATE_PDP };
                            }
                            if (target instanceof PDP) {
                                if (self.container.size() > 1) {
                                    return new Action[] { EDIT_PDP, GET_PDP_STATUS, MOVE_PDP, DELETE_PDP };
                                } else {
                                    return new Action[] { EDIT_PDP, GET_PDP_STATUS, DELETE_PDP };
                                }
                            }
                            return null;
                        }

                        @Override
                        public void handleAction(Action action, Object sender, Object target) {
                            if (action == CREATE_PDP) {
                                self.editPDP(null, (PDPGroup) table.getData());
                                return;
                            }
                            if (action == EDIT_PDP) {
                                replacedert (target instanceof PDP);
                                self.editPDP((PDP) target, (PDPGroup) table.getData());
                                return;
                            }
                            if (action == MOVE_PDP) {
                                replacedert (target instanceof PDP);
                                self.movePDP((PDP) target, (PDPGroup) table.getData());
                                return;
                            }
                            if (action == DELETE_PDP) {
                                replacedert (target instanceof PDP);
                                self.deletePDP((PDP) target, (PDPGroup) table.getData());
                                return;
                            }
                            if (action == GET_PDP_STATUS) {
                                replacedert (target instanceof PDP);
                                self.getPDPStatus((PDP) target, (PDPGroup) table.getData());
                            }
                        }
                    });
                    // 
                    // Respond to events
                    // 
                    table.addItemClickListener(new ItemClickListener() {

                        private static final long serialVersionUID = 1L;

                        @Override
                        public void itemClick(ItemClickEvent event) {
                            if (event.isDoubleClick()) {
                                self.editPDP((PDP) event.gereplacedemId(), (PDPGroup) table.getData());
                            }
                        }
                    });
                }
                return table;
            }
        });
        // 
        // Generate a GUI element for the policies
        // 
        this.table.addGeneratedColumn("Policies", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                Table table = new Table();
                table.setContainerDataSource(new PDPPolicyContainer((PDPGroup) itemId));
                table.setPageLength(table.getContainerDataSource().size() + 2);
                table.setVisibleColumns("Root", "Name", "Version", "Description");
                table.setColumnCollapsingAllowed(true);
                table.setColumnCollapsed("Description", true);
                table.setWidth("100%");
                return table;
            }
        });
        // 
        // Generate a GUI element for the PIP configurations
        // 
        this.table.addGeneratedColumn("PIP Configurations", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                Table table = new Table();
                if (itemId instanceof PDPGroup) {
                    table.setContainerDataSource(new PDPPIPContainer((PDPGroup) itemId));
                    table.setPageLength(table.getContainerDataSource().size() + 2);
                }
                if (itemId instanceof PDP) {
                    table.setContainerDataSource(new PDPPIPContainer((PDP) itemId));
                    table.setVisible(false);
                    table.setPageLength(0);
                }
                table.setVisibleColumns("Name", "Description");
                table.setColumnCollapsingAllowed(true);
                table.setColumnCollapsed("Description", true);
                table.setWidth("100%");
                return table;
            }
        });
        // 
        // Check the user's authorization level
        // 
        if (((XacmlAdminUI) UI.getCurrent()).isAuthorized(XacmlAdminAuthorization.AdminAction.ACTION_ADMIN, XacmlAdminAuthorization.AdminResource.RESOURCE_PDP_ADMIN)) {
            this.table.setSelectable(true);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("No admin access to pdp management");
            }
            return;
        }
        // 
        // Setup Action Handlers
        // 
        this.table.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    // 
                    // Nothing is selected, they right-clicked empty space.
                    // Only one action.
                    // 
                    return new Action[] { CREATE_GROUP };
                }
                if (target instanceof PDPGroup) {
                    List<Action> actions = new ArrayList<Action>();
                    PDPGroupStatus.Status status = ((PDPGroup) target).getStatus().getStatus();
                    if (status == PDPGroupStatus.Status.LOAD_ERRORS) {
                        actions.add(REPAIR_GROUP);
                    }
                    if (((PDPGroup) target).isDefaultGroup() == false) {
                        actions.add(MAKE_DEFAULT);
                    }
                    actions.add(EDIT_GROUP);
                    if (status == PDPGroupStatus.Status.OUT_OF_SYNCH) {
                        actions.add(SYNCHRONIZE);
                    }
                    if (((PDPGroup) target).isDefaultGroup() == false) {
                        actions.add(DELETE_GROUP);
                    }
                    actions.add(CREATE_PDP);
                    // Throws a clreplaced cast exception
                    // return (Action[]) actions.toArray();
                    Action[] actions2 = new Action[actions.size()];
                    int index = 0;
                    for (Action a : actions) {
                        actions2[index++] = a;
                    }
                    return actions2;
                }
                return null;
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == CREATE_GROUP) {
                    self.editPDPGroup(null);
                    return;
                }
                if (action == EDIT_GROUP) {
                    replacedert (target instanceof PDPGroup);
                    self.editPDPGroup((PDPGroup) target);
                    return;
                }
                if (action == DELETE_GROUP) {
                    self.deleteGroup((PDPGroup) target);
                    return;
                }
                if (action == REPAIR_GROUP) {
                    if (target instanceof PDPGroup) {
                        ((PDPGroup) target).repair();
                    } else {
                        String message = "Action '" + REPAIR_GROUP.getCaption() + "' called on non-group target '" + target + "'";
                        logger.error(message);
                        AdminNotification.error(message);
                    }
                    return;
                }
                if (action == MAKE_DEFAULT) {
                    if (target instanceof PDPGroup) {
                        try {
                            self.container.makeDefault((PDPGroup) target);
                        } catch (Exception e) {
                            AdminNotification.error("Make Default failed. Reason:\n" + e.getMessage());
                        }
                    } else {
                        String message = "Action '" + MAKE_DEFAULT.getCaption() + "' called on non-group target '" + target + "'";
                        logger.error(message);
                        AdminNotification.error(message);
                    }
                    return;
                }
                if (action == SYNCHRONIZE) {
                    if (target instanceof PDPGroup) {
                        logger.error("SYNCHRONIZE NOT YET IMPLMENTED");
                        AdminNotification.error("Synchronize not yet implemented");
                    } else {
                        String message = "Action '" + SYNCHRONIZE.getCaption() + "' called on non-group target '" + target + "'";
                        logger.error(message);
                        AdminNotification.error(message);
                    }
                    return;
                }
                if (action == CREATE_PDP) {
                    if (target instanceof PDPGroup) {
                        self.editPDP(null, ((PDPGroup) target));
                    } else {
                        String message = "Action '" + CREATE_PDP.getCaption() + "' called on non-group target '" + target + "'";
                        logger.error(message);
                        AdminNotification.error(message);
                    }
                    return;
                }
            }
        });
        // 
        // Listen for item change notifications
        // 
        this.table.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    replacedert (event.gereplacedemId() instanceof PDPGroup);
                    self.editPDPGroup((PDPGroup) event.gereplacedemId());
                }
            }
        });
        // 
        // Respond to selection events
        // 
        this.table.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                Object id = self.table.getValue();
                if (id == null) {
                    self.buttonRemove.setEnabled(false);
                } else {
                    // 
                    // Make sure its not the default group
                    // 
                    if (((PDPGroup) id).isDefaultGroup()) {
                        self.buttonRemove.setEnabled(false);
                    } else {
                        self.buttonRemove.setEnabled(true);
                    }
                }
            }
        });
        // 
        // Maximize the table
        // 
        this.table.setSizeFull();
    }

    protected void initializeButtons(final boolean isAdmin) {
        if (isAdmin == false) {
            return;
        }
        this.buttonCreate.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.editPDPGroup(null);
            }
        });
        this.buttonRemove.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                Object id = self.table.getValue();
                replacedert (id != null);
                replacedert (id instanceof PDPGroup);
                self.deleteGroup((PDPGroup) id);
                self.table.select(self.table.getNullSelectionItemId());
            }
        });
    }

    protected void setupButtons() {
        if (this.table.getValue() == null) {
            this.buttonRemove.setEnabled(false);
        } else {
            this.buttonRemove.setEnabled(true);
        }
    }

    protected void editPDP(final PDP pdp, final PDPGroup group) {
        final EditPDPWindow editor = new EditPDPWindow(pdp, this.container.getGroups());
        if (pdp == null) {
            editor.setCaption("Create New PDP");
        } else {
            editor.setCaption("Edit PDP " + pdp.getId());
        }
        editor.setModal(true);
        editor.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent event) {
                if (editor.isSaved() == false) {
                    return;
                }
                try {
                    // 
                    // Adding a new PDP?
                    // 
                    if (pdp == null) {
                        // 
                        // Yes tell the container to add it
                        // 
                        self.container.addNewPDP(editor.getPDPId(), group, editor.getPDPName(), editor.getPDPDescription());
                    } else {
                        // 
                        // No tell the container to update it
                        // 
                        pdp.setName(editor.getPDPName());
                        pdp.setDescription(editor.getPDPDescription());
                        self.container.updatePDP(pdp);
                    }
                } catch (Exception e) {
                    String message = "Unable to create PDP.  Reason:\n" + e.getMessage();
                    logger.error(message);
                    AdminNotification.error(message);
                }
            }
        });
        editor.center();
        UI.getCurrent().addWindow(editor);
    }

    protected void editPDPGroup(final PDPGroup group) {
        // 
        // copy the group
        // 
        final StdPDPGroup copyGroup = (group == null ? null : new StdPDPGroup(group));
        // 
        // 
        // 
        final EditPDPGroupWindow editor = new EditPDPGroupWindow(copyGroup, this.container.getGroups(), papEngine);
        if (group == null) {
            editor.setCaption("Create PDP Group");
        } else {
            editor.setCaption("Edit PDP Group " + ((PDPGroup) group).getName());
        }
        editor.setModal(true);
        editor.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent event) {
                if (editor.isSaved() == false) {
                    return;
                }
                if (group == null) {
                    // 
                    // Creating a new group
                    // 
                    try {
                        self.container.addNewGroup(editor.getGroupName(), editor.getGroupDescription());
                    } catch (Exception e) {
                        String message = "Unable to create Group.  Reason:\n" + e.getMessage();
                        logger.error(message);
                        AdminNotification.error(message);
                    }
                } else {
                    // 
                    // Update group
                    // 
                    self.container.updateGroup(editor.getUpdatedObject());
                }
            }
        });
        editor.center();
        UI.getCurrent().addWindow(editor);
    }

    protected void deletePDP(final PDP pdp, final PDPGroup pdpGroup) {
        String message = "Are you sure you want to delete <B>" + (pdp.getName() == null ? "" : pdp.getName()) + "</B> group?";
        ConfirmDialog dialog = ConfirmDialog.getFactory().create("Confirm PDP Deletion", message, "Delete", "Cancel");
        dialog.setContentMode(ContentMode.HTML);
        dialog.show(getUI(), new ConfirmDialog.Listener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void onClose(ConfirmDialog dialog) {
                if (dialog.isConfirmed()) {
                    try {
                        self.container.removePDP(pdp, pdpGroup);
                    } catch (PAPException e) {
                        logger.warn("Failed to remove pdp");
                        AdminNotification.warn("Failed to remove PDP");
                    }
                }
            }
        }, true);
    }

    protected void movePDP(final PDP pdp, final PDPGroup currentGroup) {
        List<PDPGroup> currentGroups = this.container.getGroups();
        Set<PDPGroup> otherGroups = new HashSet<PDPGroup>(currentGroups);
        if (otherGroups.remove(currentGroup) == false) {
            logger.warn("Group list inconsistency - failed to move pdp to selected group");
            return;
        }
        final SelectPDPGroupWindow editor = new SelectPDPGroupWindow(otherGroups, "What was this?");
        editor.setCaption("Move PDP to group");
        editor.setModal(true);
        editor.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent event) {
                if (editor.isSaved()) {
                    self.container.movePDP((PDP) pdp, editor.selectedGroup());
                }
            }
        });
        editor.center();
        UI.getCurrent().addWindow(editor);
    }

    protected void getPDPStatus(final PDP pdp, final PDPGroup group) {
        PDPStatus status;
        try {
            status = papEngine.getStatus(pdp);
        } catch (Exception e) {
            AdminNotification.error("Unable to get details for pdp '" + pdp.getId() + "' with summary status: " + pdp.getStatus().getStatus());
            return;
        }
        logger.info(status);
        PDPStatusWindow window = new PDPStatusWindow(status);
        window.setCaption("Status for PDP " + pdp.getName());
        window.setModal(true);
        window.center();
        UI.getCurrent().addWindow(window);
    }

    private void deleteGroup(final PDPGroup group) {
        // 
        // Cannot be the default group
        // 
        if (group.isDefaultGroup()) {
            logger.error("Cannot delete the Default group");
            return;
        }
        // 
        // Any PDPs in the group?
        // 
        Set<PDP> pdps = group.getPdps();
        if (pdps.isEmpty()) {
            // 
            // There are no PDP's, so just prompt to remove it
            // 
            String message = "Are you sure you want to delete <B>" + (group.getName() == null ? "" : group.getName()) + "</B> group?";
            ConfirmDialog dialog = ConfirmDialog.getFactory().create("Confirm Group Deletion", message, "Delete", "Cancel");
            dialog.setContentMode(ContentMode.HTML);
            dialog.show(getUI(), new ConfirmDialog.Listener() {

                private static final long serialVersionUID = 1L;

                @Override
                public void onClose(ConfirmDialog dialog) {
                    if (dialog.isConfirmed()) {
                        try {
                            self.container.removeGroup(group, null);
                        } catch (Exception e1) {
                            logger.warn("Container failed to remove group");
                            AdminNotification.error("Unable to delete group '" + group.getId() + "'.  Reason:\n" + e1.getMessage());
                        }
                        return;
                    }
                }
            }, true);
            return;
        }
        // 
        // Get our set of groups
        // 
        List<PDPGroup> currentGroups = this.container.getGroups();
        Set<PDPGroup> otherGroups = new HashSet<PDPGroup>(currentGroups);
        if (otherGroups.remove(group) == false) {
            logger.warn("Group list inconsistency - failed to remove group we are attempting to delete");
            return;
        }
        // 
        // We should have at least one group
        // 
        if (otherGroups.isEmpty()) {
            logger.error("Group list inconsistency - no other groups to choose from.");
            return;
        }
        // 
        // If there is only one group, it SHOULD be the default group
        // 
        if (otherGroups.size() == 1) {
            PDPGroup loneGroup = otherGroups.iterator().next();
            if (loneGroup.isDefaultGroup() == false) {
                logger.error("Group list inconsistency - lone group is NOT default.");
                return;
            }
        }
        // 
        // Create our confirmation window
        // 
        final SelectPDPGroupWindow window = new SelectPDPGroupWindow(otherGroups, "Select New Group for PDPs");
        window.setCaption("Confirm Group " + group.getName() + " Deletion");
        window.setCloseShortcut(KeyCode.ESCAPE);
        window.setModal(true);
        ;
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                if (window.isSaved()) {
                    PDPGroup newGroup = window.selectedGroup();
                    if (newGroup == null) {
                        logger.warn("No group selected for moving PDPs into");
                        AdminNotification.warn("No group selected for moving PDPs into.  Group '" + group.getId() + "' not deleted");
                        return;
                    }
                    try {
                        self.container.removeGroup(group, newGroup);
                    } catch (Exception e1) {
                        logger.warn("Container failed to remove group: " + e1, e1);
                        AdminNotification.error("Unable to delete group '" + group.getId() + "'.  Reason:\n" + e1.getMessage());
                    }
                }
            }
        });
        getUI().addWindow(window);
    }

    public void refreshContainer() {
        if (this.container != null) {
            this.container.refreshGroups();
        }
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("100%");
        mainLayout.setHeight("100%");
        mainLayout.setMargin(false);
        // top-level component properties
        setWidth("100.0%");
        setHeight("100.0%");
        // horizontalLayoutToolbar
        horizontalLayoutToolbar = buildHorizontalLayoutToolbar();
        mainLayout.addComponent(horizontalLayoutToolbar);
        // tree
        table = new Table();
        table.setImmediate(false);
        table.setWidth("-1px");
        table.setHeight("-1px");
        mainLayout.addComponent(table);
        mainLayout.setExpandRatio(table, 1.0f);
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayoutToolbar() {
        // common part: create layout
        horizontalLayoutToolbar = new HorizontalLayout();
        horizontalLayoutToolbar.setImmediate(false);
        horizontalLayoutToolbar.setWidth("-1px");
        horizontalLayoutToolbar.setHeight("-1px");
        horizontalLayoutToolbar.setMargin(true);
        horizontalLayoutToolbar.setSpacing(true);
        // buttonCreate
        buttonCreate = new Button();
        buttonCreate.setCaption("Create Group");
        buttonCreate.setImmediate(false);
        buttonCreate.setWidth("-1px");
        buttonCreate.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonCreate);
        // buttonRemove
        buttonRemove = new Button();
        buttonRemove.setCaption("Remove Group");
        buttonRemove.setImmediate(false);
        buttonRemove.setWidth("-1px");
        buttonRemove.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonRemove);
        return horizontalLayoutToolbar;
    }
}

17 View Complete Implementation : PIPManagement.java
Copyright MIT License
Author : att
public clreplaced PIPManagement extends CustomComponent {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Table tablePIP;

    @AutoGenerated
    private HorizontalLayout horizontalLayoutToolbar;

    @AutoGenerated
    private Button buttonImport;

    @AutoGenerated
    private Button buttonRemove;

    @AutoGenerated
    private Button buttonClone;

    @AutoGenerated
    private Button buttonAdd;

    /**
     */
    private static final long serialVersionUID = 1L;

    private static final Log logger = LogFactory.getLog(PIPManagement.clreplaced);

    private static final Object[] visibleColumns = new Object[] { "name", "description", "piptype", "issuer" };

    private static final String[] columnHeaders = new String[] { "Name", "Description", "Type", "Issuer" };

    private final Action ADD_CONFIGURATION = new Action("Add Configuration");

    private final Action EDIT_CONFIGURATION = new Action("Edit Configuration");

    private final Action CLONE_CONFIGURATION = new Action("Clone Configuration");

    private final Action REMOVE_CONFIGURATION = new Action("Remove Configuration");

    private final Action ADD_RESOLVER = new Action("Add Resolver");

    private final Action PUBLISH_CONFIGURATION = new Action("Publish Configuration");

    private final PIPManagement self = this;

    private final JPAContainer<PIPConfiguration> container = new JPAContainer<PIPConfiguration>(PIPConfiguration.clreplaced);

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     */
    public PIPManagement() {
        buildMainLayout();
        setCompositionRoot(mainLayout);
        // 
        // Setup containers
        // 
        boolean isReadOnly;
        if (((XacmlAdminUI) UI.getCurrent()).isAuthorized(XacmlAdminAuthorization.AdminAction.ACTION_WRITE, XacmlAdminAuthorization.AdminResource.RESOURCE_PIP_ADMIN)) {
            // 
            // Writable container
            // 
            container.setEnreplacedyProvider(new CachingMutableLocalEnreplacedyProvider<PIPConfiguration>(PIPConfiguration.clreplaced, ((XacmlAdminUI) UI.getCurrent()).getEnreplacedyManager()));
            isReadOnly = false;
        } else {
            // 
            // Read only container
            // 
            container.setEnreplacedyProvider(new CachingLocalEnreplacedyProvider<PIPConfiguration>(PIPConfiguration.clreplaced, ((XacmlAdminUI) UI.getCurrent()).getEnreplacedyManager()));
            isReadOnly = true;
        }
        // 
        // Finish initialization
        // 
        this.initializeTree(isReadOnly);
        this.initializeButtons(isReadOnly);
        // 
        // Setup
        // 
        this.setupButtons();
    }

    protected void initializeTree(boolean isReadOnly) {
        // 
        // Initialize GUI properties
        // 
        this.tablePIP.setImmediate(true);
        this.tablePIP.setContainerDataSource(this.container);
        this.tablePIP.sereplacedemCaptionMode(ItemCaptionMode.PROPERTY);
        this.tablePIP.sereplacedemCaptionPropertyId("name");
        this.tablePIP.setVisibleColumns(visibleColumns);
        this.tablePIP.setColumnHeaders(columnHeaders);
        this.tablePIP.setSizeFull();
        // 
        // Access?
        // 
        if (isReadOnly) {
            if (logger.isDebugEnabled()) {
                logger.debug("read only pip access");
            }
            return;
        }
        this.tablePIP.setSelectable(true);
        // 
        // Setup click handler
        // 
        this.tablePIP.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    PIPManagement.editConfiguration(self.container.gereplacedem(event.gereplacedemId()));
                }
            }
        });
        // 
        // Setup action handler
        // 
        this.tablePIP.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    return new Action[] { ADD_CONFIGURATION };
                }
                // 
                // Target is an Object ID
                // 
                EnreplacedyItem<PIPConfiguration> config = self.container.gereplacedem(target);
                if (config != null) {
                    if (config.getEnreplacedy().isReadOnly() == false) {
                        if (config.getEnreplacedy().requiresResolvers()) {
                            return new Action[] { EDIT_CONFIGURATION, CLONE_CONFIGURATION, REMOVE_CONFIGURATION, PUBLISH_CONFIGURATION, ADD_RESOLVER };
                        } else {
                            return new Action[] { EDIT_CONFIGURATION, CLONE_CONFIGURATION, REMOVE_CONFIGURATION, PUBLISH_CONFIGURATION };
                        }
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not find item: " + target);
                }
                return null;
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                EnreplacedyItem<PIPConfiguration> config = self.container.gereplacedem(target);
                if (config == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Could not find item: " + target);
                    }
                    return;
                }
                if (action == ADD_CONFIGURATION) {
                    PIPManagement.editConfiguration(self.container.createEnreplacedyItem(new PIPConfiguration()));
                    return;
                }
                if (action == EDIT_CONFIGURATION) {
                    PIPManagement.editConfiguration(config);
                    return;
                }
                if (action == CLONE_CONFIGURATION) {
                    self.cloneConfiguration(config);
                    return;
                }
                if (action == REMOVE_CONFIGURATION) {
                    self.removeConfiguration(config);
                    return;
                }
                if (action == ADD_RESOLVER) {
                    PIPResolverComponent.addResolver(config.getEnreplacedy(), null);
                    return;
                }
                if (action == PUBLISH_CONFIGURATION) {
                    PIPResolverComponent.publishConfiguration(config);
                    return;
                }
            }
        });
        // 
        // When a selection changes listener
        // 
        this.tablePIP.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                self.setupButtons();
            }
        });
        this.tablePIP.addGeneratedColumn("description", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                EnreplacedyItem<PIPConfiguration> enreplacedy = self.container.gereplacedem(itemId);
                if (enreplacedy != null && enreplacedy.getEnreplacedy() != null) {
                    TextArea area = new TextArea();
                    area.setValue(enreplacedy.getEnreplacedy().getDescription());
                    area.setNullRepresentation("");
                    area.setSizeFull();
                    area.setReadOnly(true);
                    return area;
                }
                return null;
            }
        });
        this.tablePIP.addGeneratedColumn("piptype", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                EnreplacedyItem<PIPConfiguration> enreplacedy = self.container.gereplacedem(itemId);
                if (enreplacedy != null && enreplacedy.getEnreplacedy() != null) {
                    return enreplacedy.getEnreplacedy().getPiptype().getType();
                }
                return null;
            }
        });
        // 
        // Customize the resolver column
        // 
        this.tablePIP.addGeneratedColumn("Resolvers", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                EnreplacedyItem<PIPConfiguration> enreplacedy = self.container.gereplacedem(itemId);
                if (enreplacedy != null && enreplacedy.getEnreplacedy() != null && enreplacedy.getEnreplacedy().requiresResolvers()) {
                    PIPResolverComponent component = new PIPResolverComponent(enreplacedy.getEnreplacedy());
                    return component;
                }
                return null;
            }
        });
    }

    protected void initializeButtons(boolean isReadOnly) {
        if (isReadOnly) {
            this.buttonAdd.setVisible(false);
            this.buttonRemove.setVisible(false);
            this.buttonClone.setVisible(false);
            return;
        }
        this.buttonAdd.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                PIPManagement.editConfiguration(self.container.createEnreplacedyItem(new PIPConfiguration()));
            }
        });
        this.buttonRemove.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.removeConfiguration(self.container.gereplacedem(self.tablePIP.getValue()));
            }
        });
        this.buttonClone.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.cloneConfiguration(self.container.gereplacedem(self.tablePIP.getValue()));
            }
        });
        this.buttonImport.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                final PIPImportWindow window = new PIPImportWindow();
                window.setCaption("Import PIP Configuration");
                window.setModal(true);
                window.center();
                window.addCloseListener(new CloseListener() {

                    private static final long serialVersionUID = 1L;

                    @Override
                    public void windowClose(CloseEvent e) {
                        String file = window.getUploadedFile();
                        if (file == null) {
                            return;
                        }
                        self.importConfiguration(file);
                    }
                });
                UI.getCurrent().addWindow(window);
            }
        });
    }

    protected void importConfiguration(String file) {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(file));
            Collection<PIPConfiguration> configs = PIPConfiguration.importPIPConfigurations(properties);
            if (configs == null || configs.isEmpty()) {
                AdminNotification.warn("There were no PIP Engine configurations found.");
            } else {
                for (PIPConfiguration config : configs) {
                    this.container.addEnreplacedy(config);
                }
            }
        } catch (IOException e) {
            String message = "Failed to load properties: " + e.getLocalizedMessage();
            logger.error(message);
            AdminNotification.error(message);
        }
    }

    public static void editConfiguration(final EnreplacedyItem<PIPConfiguration> enreplacedy) {
        final PIPConfigurationEditorWindow editor = new PIPConfigurationEditorWindow(enreplacedy);
        if (enreplacedy.isPersistent()) {
            editor.setCaption("Edit PIP Configuration " + enreplacedy.getEnreplacedy().getName());
        } else {
            editor.setCaption("Create New PIP Configuration");
        }
        editor.setModal(true);
        editor.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent event) {
                if (editor.isSaved()) {
                    if (enreplacedy.isPersistent() == false) {
                        ((XacmlAdminUI) UI.getCurrent()).getPIPConfigurations().addEnreplacedy(enreplacedy.getEnreplacedy());
                    }
                    ((XacmlAdminUI) UI.getCurrent()).refreshPIPConfiguration();
                }
            }
        });
        editor.center();
        UI.getCurrent().addWindow(editor);
    }

    protected void removeConfiguration(final EnreplacedyItem<PIPConfiguration> enreplacedy) {
        // 
        // Sanity checks
        // 
        if (enreplacedy == null || enreplacedy.getEnreplacedy() == null) {
            logger.error("Removing a null enreplacedy");
            return;
        }
        String message = "Are you sure you want to remove the " + enreplacedy.getEnreplacedy().getName() + " configuration?";
        ConfirmDialog dialog = ConfirmDialog.getFactory().create("Confirm PIP Configuration Deletion", message, "Remove", "Cancel");
        dialog.setContentMode(ContentMode.HTML);
        dialog.show(getUI(), new ConfirmDialog.Listener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void onClose(ConfirmDialog dialog) {
                if (dialog.isConfirmed()) {
                    if (self.container.removeItem(enreplacedy.gereplacedemId()) == false) {
                        logger.warn("Failed to remove PIP configuration");
                        AdminNotification.warn("Failed to remove PIP configuration.");
                    } else {
                        self.setupButtons();
                    }
                }
            }
        }, true);
    }

    protected void cloneConfiguration(final EnreplacedyItem<PIPConfiguration> enreplacedy) {
        // 
        // Sanity checks
        // 
        if (enreplacedy == null || enreplacedy.getEnreplacedy() == null) {
            logger.warn("Cloning a null enreplacedy, the buttons were not reset. Resetting them.");
            this.setupButtons();
            return;
        }
        // 
        // Clone it
        // 
        PIPManagement.editConfiguration(this.container.createEnreplacedyItem(new PIPConfiguration(enreplacedy.getEnreplacedy(), ((XacmlAdminUI) UI.getCurrent()).getUserid())));
    }

    protected void setupButtons() {
        if (this.tablePIP.getValue() != null) {
            Object id = this.tablePIP.getValue();
            EnreplacedyItem<PIPConfiguration> enreplacedy = this.container.gereplacedem(id);
            if (enreplacedy == null || enreplacedy.getEnreplacedy().isReadOnly()) {
                this.buttonRemove.setEnabled(false);
                this.buttonClone.setEnabled(false);
            } else {
                this.buttonRemove.setEnabled(true);
                this.buttonClone.setEnabled(true);
            }
        } else {
            this.buttonRemove.setEnabled(false);
            this.buttonClone.setEnabled(false);
        }
    }

    public void refreshContainer() {
        this.container.refresh();
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("100%");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("100.0%");
        setHeight("-1px");
        // horizontalLayoutToolbar
        horizontalLayoutToolbar = buildHorizontalLayoutToolbar();
        mainLayout.addComponent(horizontalLayoutToolbar);
        // tablePIP
        tablePIP = new Table();
        tablePIP.setCaption("PIP Configurations");
        tablePIP.setImmediate(false);
        tablePIP.setWidth("100.0%");
        tablePIP.setHeight("-1px");
        mainLayout.addComponent(tablePIP);
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayoutToolbar() {
        // common part: create layout
        horizontalLayoutToolbar = new HorizontalLayout();
        horizontalLayoutToolbar.setImmediate(false);
        horizontalLayoutToolbar.setWidth("-1px");
        horizontalLayoutToolbar.setHeight("-1px");
        horizontalLayoutToolbar.setMargin(false);
        horizontalLayoutToolbar.setSpacing(true);
        // buttonAdd
        buttonAdd = new Button();
        buttonAdd.setCaption("Add Configuration");
        buttonAdd.setImmediate(true);
        buttonAdd.setWidth("-1px");
        buttonAdd.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonAdd);
        // buttonClone
        buttonClone = new Button();
        buttonClone.setCaption("Clone Configuration");
        buttonClone.setImmediate(true);
        buttonClone.setWidth("-1px");
        buttonClone.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonClone);
        // buttonRemove
        buttonRemove = new Button();
        buttonRemove.setCaption("Remove Configuration");
        buttonRemove.setImmediate(true);
        buttonRemove.setWidth("-1px");
        buttonRemove.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonRemove);
        // buttonImport
        buttonImport = new Button();
        buttonImport.setCaption("Import Configuration");
        buttonImport.setImmediate(false);
        buttonImport.setDescription("Imports a configuration from a properties file.");
        buttonImport.setWidth("-1px");
        buttonImport.setHeight("-1px");
        horizontalLayoutToolbar.addComponent(buttonImport);
        return horizontalLayoutToolbar;
    }
}

17 View Complete Implementation : PIPParameterComponent.java
Copyright MIT License
Author : att
public clreplaced PIPParameterComponent extends CustomComponent implements FormChangedEventNotifier {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Table tableParameters;

    @AutoGenerated
    private HorizontalLayout horizontalLayout_1;

    @AutoGenerated
    private Button buttonClear;

    @AutoGenerated
    private Button buttonClone;

    @AutoGenerated
    private Button buttonRemove;

    @AutoGenerated
    private Button buttonAdd;

    /**
     */
    private static final long serialVersionUID = 1L;

    private static final Log logger = LogFactory.getLog(PIPParameterComponent.clreplaced);

    private final PIPParameterComponent self = this;

    private final Object config;

    private final BasicNotifier notifier = new BasicNotifier();

    private static final Action ADD_PARAM = new Action("Add Parameter");

    private static final Action EDIT_PARAM = new Action("Edit Parameter");

    private static final Action REMOVE_PARAM = new Action("Remove Parameter");

    private static final Action CLONE_PARAM = new Action("Clone Parameter");

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     * @param config
     */
    public PIPParameterComponent(Object config) {
        buildMainLayout();
        setCompositionRoot(mainLayout);
        // 
        // Save
        // 
        this.config = config;
        // 
        // Initialize
        // 
        this.initializeTable();
        this.initializeButtons();
        // 
        // Initial button setup
        // 
        this.setupButtons();
    }

    protected void initializeTable() {
        // 
        // Initialize GUI properties
        // 
        this.tableParameters.setImmediate(true);
        this.tableParameters.setSelectable(true);
        // 
        // Add in the data
        // 
        if (this.config instanceof PIPConfiguration) {
            BeanItemContainer<PIPConfigParam> container = new BeanItemContainer<PIPConfigParam>(PIPConfigParam.clreplaced);
            PIPConfiguration config = (PIPConfiguration) this.config;
            for (PIPConfigParam param : config.getPipconfigParams()) {
                container.addBean(param);
            }
            this.tableParameters.setContainerDataSource(container);
        } else if (this.config instanceof PIPResolver) {
            BeanItemContainer<PIPResolverParam> container = new BeanItemContainer<PIPResolverParam>(PIPResolverParam.clreplaced);
            PIPResolver resolver = (PIPResolver) this.config;
            for (PIPResolverParam param : resolver.getPipresolverParams()) {
                container.addBean(param);
            }
            this.tableParameters.setContainerDataSource(container);
        } else {
            throw new IllegalArgumentException("Unsupported object");
        }
        // 
        // Finish more gui initialization
        // 
        // this.tableParameters.getContainerDataSource().size() + 1);
        this.tableParameters.setPageLength(5);
        this.tableParameters.setVisibleColumns(new Object[] { "paramName", "paramValue" });
        this.tableParameters.setColumnHeaders(new String[] { "Name", "Value" });
        this.tableParameters.setSizeFull();
        // 
        // Action Handler
        // 
        this.tableParameters.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    return new Action[] { ADD_PARAM };
                }
                return new Action[] { EDIT_PARAM, REMOVE_PARAM, CLONE_PARAM };
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == ADD_PARAM) {
                    self.editParameter(null);
                    return;
                }
                if (action == EDIT_PARAM) {
                    self.editParameter(target);
                    return;
                }
                if (action == REMOVE_PARAM) {
                    self.removeParameter(target);
                    return;
                }
                if (action == CLONE_PARAM) {
                    self.cloneParameter(target);
                    return;
                }
            }
        });
        // 
        // Respond to events
        // 
        this.tableParameters.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                self.setupButtons();
            }
        });
        // 
        // Double click
        // 
        this.tableParameters.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    self.editParameter(event.gereplacedemId());
                }
            }
        });
    }

    protected void initializeButtons() {
        this.buttonAdd.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.editParameter(null);
            }
        });
        this.buttonClone.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.cloneParameter(self.tableParameters.getValue());
            }
        });
        this.buttonRemove.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.removeParameter(self.tableParameters.getValue());
            }
        });
        this.buttonClear.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.clearParameters();
            }
        });
    }

    protected void setupButtons() {
        if (this.tableParameters.getValue() != null) {
            this.buttonClone.setEnabled(true);
            this.buttonRemove.setEnabled(true);
        } else {
            this.buttonClone.setEnabled(false);
            this.buttonRemove.setEnabled(false);
        }
    }

    protected void editParameter(final Object source) {
        // 
        // Make a copy
        // 
        final Object target = (source != null ? source : (this.config instanceof PIPConfiguration ? new PIPConfigParam() : new PIPResolverParam()));
        final PIPParamEditorWindow window = new PIPParamEditorWindow(target);
        window.setModal(true);
        window.setCaption((source == null ? "Create New Parameter" : "Edit Parameter"));
        window.center();
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did user save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Yes - was it a brand new object?
                // 
                if (source == null) {
                    // 
                    // yes add it to the parent object
                    // 
                    if (self.config instanceof PIPConfiguration) {
                        ((PIPConfiguration) self.config).addPipconfigParam((PIPConfigParam) target);
                    } else {
                        ((PIPResolver) self.config).addPipresolverParam((PIPResolverParam) target);
                    }
                    // 
                    // add it to the table
                    // 
                    Item item = self.tableParameters.addItem(target);
                    if (item == null) {
                        logger.error("Failed to add parameter: " + target);
                    } else {
                        self.tableParameters.select(target);
                    }
                } else {
                    // 
                    // Copy the parameters over
                    // 
                    if (source instanceof PIPConfigParam) {
                        ((PIPConfigParam) source).setParamName(((PIPConfigParam) target).getParamName());
                        ((PIPConfigParam) source).setParamValue(((PIPConfigParam) target).getParamValue());
                    } else {
                        ((PIPResolverParam) source).setParamName(((PIPResolverParam) target).getParamName());
                        ((PIPResolverParam) source).setParamValue(((PIPResolverParam) target).getParamValue());
                    }
                    // 
                    // Update the table
                    // 
                    self.tableParameters.refreshRowCache();
                }
            }
        });
        UI.getCurrent().addWindow(window);
    }

    protected void cloneParameter(Object target) {
        if (target == null) {
            logger.error("null target sent to clone method");
            return;
        }
        Item item;
        if (target instanceof PIPConfigParam && this.config instanceof PIPConfiguration) {
            PIPConfigParam param = new PIPConfigParam((PIPConfigParam) target);
            ((PIPConfiguration) this.config).addPipconfigParam(param);
            item = this.tableParameters.addItem(new BeanItem<PIPConfigParam>(param));
        } else if (target instanceof PIPResolverParam && this.config instanceof PIPResolver) {
            PIPResolverParam param = new PIPResolverParam((PIPResolverParam) target);
            ((PIPResolver) this.config).addPipresolverParam(param);
            item = this.tableParameters.addItem(new BeanItem<PIPResolverParam>(param));
        } else {
            throw new IllegalArgumentException("Unsupported param and config combination.");
        }
        if (item == null) {
            logger.error("Failed to add parameter to table: " + target);
        } else {
            this.tableParameters.select(target);
        }
    }

    protected void removeParameter(Object target) {
        if (target == null) {
            logger.error("null target sent to remove method");
            return;
        }
        if (this.config instanceof PIPConfiguration) {
            if (((PIPConfiguration) this.config).removePipconfigParam((PIPConfigParam) target) == null) {
                logger.error("Failed to remove parameter from pip configuration");
                return;
            }
        } else {
            if (((PIPResolver) this.config).removePipresolverParam((PIPResolverParam) target) == null) {
                logger.error("Failed to remove parameter from pip resolver");
                return;
            }
        }
        if (this.tableParameters.removeItem(target) == false) {
            logger.error("Failed to remove parameter from table");
        }
    }

    protected void clearParameters() {
        this.tableParameters.removeAllItems();
        if (this.config instanceof PIPConfiguration) {
            ((PIPConfiguration) this.config).clearConfigParams();
        } else {
            ((PIPResolver) this.config).clearParams();
        }
    }

    @Override
    public boolean addListener(FormChangedEventListener listener) {
        return this.notifier.addListener(listener);
    }

    @Override
    public boolean removeListener(FormChangedEventListener listener) {
        return this.notifier.removeListener(listener);
    }

    @Override
    public void fireFormChangedEvent() {
        this.notifier.fireFormChangedEvent();
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("-1px");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(false);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // horizontalLayout_1
        horizontalLayout_1 = buildHorizontalLayout_1();
        mainLayout.addComponent(horizontalLayout_1);
        // tableParameters
        tableParameters = new Table();
        tableParameters.setCaption("Configuration Parameters");
        tableParameters.setImmediate(false);
        tableParameters.setWidth("-1px");
        tableParameters.setHeight("-1px");
        mainLayout.addComponent(tableParameters);
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayout_1() {
        // common part: create layout
        horizontalLayout_1 = new HorizontalLayout();
        horizontalLayout_1.setImmediate(false);
        horizontalLayout_1.setWidth("-1px");
        horizontalLayout_1.setHeight("-1px");
        horizontalLayout_1.setMargin(false);
        horizontalLayout_1.setSpacing(true);
        // buttonAdd
        buttonAdd = new Button();
        buttonAdd.setCaption("Add");
        buttonAdd.setImmediate(false);
        buttonAdd.setWidth("-1px");
        buttonAdd.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonAdd);
        // buttonRemove
        buttonRemove = new Button();
        buttonRemove.setCaption("Remove");
        buttonRemove.setImmediate(false);
        buttonRemove.setWidth("-1px");
        buttonRemove.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonRemove);
        // buttonClone
        buttonClone = new Button();
        buttonClone.setCaption("Clone");
        buttonClone.setImmediate(false);
        buttonClone.setWidth("-1px");
        buttonClone.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonClone);
        // buttonClear
        buttonClear = new Button();
        buttonClear.setCaption("Clear All");
        buttonClear.setImmediate(false);
        buttonClear.setWidth("-1px");
        buttonClear.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonClear);
        return horizontalLayout_1;
    }
}

17 View Complete Implementation : PIPResolverComponent.java
Copyright MIT License
Author : att
public clreplaced PIPResolverComponent extends CustomComponent {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Table tableResolvers;

    private final Action ADD_RESOLVER = new Action("Add Resolver");

    private final Action EDIT_RESOLVER = new Action("Edit Resolver");

    private final Action CLONE_RESOLVER = new Action("Clone Resolver");

    private final Action REMOVE_RESOLVER = new Action("Remove Resolver");

    private static final long serialVersionUID = 1L;

    private static final Log logger = LogFactory.getLog(PIPResolverComponent.clreplaced);

    private final PIPResolverComponent self = this;

    private final PIPConfiguration config;

    private final JPAContainer<PIPResolver> resolverContainer = new JPAContainer<PIPResolver>(PIPResolver.clreplaced);

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     * @param configuration
     */
    public PIPResolverComponent(PIPConfiguration configuration) {
        buildMainLayout();
        setCompositionRoot(mainLayout);
        // 
        // Save
        // 
        this.config = configuration;
        this.resolverContainer.setEnreplacedyProvider(new CachingMutableLocalEnreplacedyProvider<PIPResolver>(PIPResolver.clreplaced, ((XacmlAdminUI) UI.getCurrent()).getEnreplacedyManager()));
        this.resolverContainer.addContainerFilter(new Compare.Equal("pipconfiguration", this.config));
        // 
        // Initialize GUI
        // 
        this.initializeTable();
    }

    protected void initializeTable() {
        // 
        // Setup the container datasource
        // 
        this.tableResolvers.setContainerDataSource(this.resolverContainer);
        // 
        // Set GUI properties
        // 
        this.tableResolvers.setImmediate(true);
        this.tableResolvers.setVisibleColumns(new Object[] { "name", "description", "issuer" });
        this.tableResolvers.setColumnHeaders(new String[] { "Name", "Description", "Issuer" });
        this.tableResolvers.setPageLength(this.config.getPipresolvers().size() + 1);
        this.tableResolvers.setSizeFull();
        this.tableResolvers.setSelectable(true);
        // 
        // Add the actions
        // 
        this.tableResolvers.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    return new Action[] { ADD_RESOLVER };
                }
                return new Action[] { EDIT_RESOLVER, CLONE_RESOLVER, REMOVE_RESOLVER };
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == ADD_RESOLVER) {
                    PIPResolverComponent.addResolver(self.config, null);
                    return;
                }
                if (action == EDIT_RESOLVER) {
                    PIPResolverComponent.editResolver(self.resolverContainer.gereplacedem(target));
                    return;
                }
                if (action == CLONE_RESOLVER) {
                    PIPResolverComponent.addResolver(self.config, self.resolverContainer.gereplacedem(target).getEnreplacedy());
                    return;
                }
                if (action == REMOVE_RESOLVER) {
                    self.removeResolver(self.config, self.resolverContainer.gereplacedem(target).getEnreplacedy());
                    return;
                }
            }
        });
        // 
        // Respond to events
        // 
        this.tableResolvers.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    Object id = event.gereplacedemId();
                    if (id == null) {
                        return;
                    }
                    PIPResolverComponent.editResolver(self.resolverContainer.gereplacedem(id));
                }
            }
        });
    }

    protected void removeResolver(PIPConfiguration config, PIPResolver resolver) {
        config.removePipresolver(resolver);
        this.tableResolvers.removeItem(resolver.getId());
    }

    public static void addResolver(PIPConfiguration config, PIPResolver pipResolver) {
        // 
        // Create the enreplacedy
        // 
        PIPResolver resolver = null;
        if (pipResolver != null) {
            resolver = new PIPResolver(pipResolver);
        } else {
            resolver = new PIPResolver();
        }
        resolver.setCreatedBy(((XacmlAdminUI) UI.getCurrent()).getUserid());
        resolver.setModifiedBy(((XacmlAdminUI) UI.getCurrent()).getUserid());
        resolver.setPipconfiguration(config);
        // 
        // Set its default clreplaced
        // 
        if (config.getPiptype().isSQL()) {
            resolver.setClreplacedname(ConfigurableJDBCResolver.clreplaced.getCanonicalName());
        } else if (config.getPiptype().isLDAP()) {
            resolver.setClreplacedname(ConfigurableLDAPResolver.clreplaced.getCanonicalName());
        } else if (config.getPiptype().isCSV()) {
            resolver.setClreplacedname(ConfigurableCSVResolver.clreplaced.getCanonicalName());
        } else if (config.getPiptype().isHyperCSV()) {
            resolver.setClreplacedname(ConfigurableJDBCResolver.clreplaced.getCanonicalName());
        }
        // 
        // Bring up the editor window
        // 
        PIPResolverComponent.editResolver(((XacmlAdminUI) UI.getCurrent()).getPIPResolvers().createEnreplacedyItem(resolver));
    }

    public static void editResolver(final EnreplacedyItem<PIPResolver> enreplacedy) {
        final PIPResolverEditorWindow window = new PIPResolverEditorWindow(enreplacedy);
        window.setModal(true);
        window.center();
        if (enreplacedy.isPersistent()) {
            window.setCaption("Edit Resolver");
        } else {
            window.setCaption("Create Resolver");
        }
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user click "save"?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Adding a new enreplacedy?
                // 
                if (enreplacedy.isPersistent() == false) {
                    // 
                    // Yes - let's official add it
                    // 
                    ((XacmlAdminUI) UI.getCurrent()).getPIPResolvers().addEnreplacedy(enreplacedy.getEnreplacedy());
                    ((XacmlAdminUI) UI.getCurrent()).refreshPIPConfiguration();
                }
            }
        });
        UI.getCurrent().addWindow(window);
    }

    public static void publishConfiguration(EnreplacedyItem<PIPConfiguration> config) {
        Properties properties = config.getEnreplacedy().generateProperties(Integer.toString(config.getEnreplacedy().getId()));
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            properties.store(os, "");
            if (logger.isDebugEnabled()) {
                logger.debug(os.toString());
            }
        } catch (IOException e) {
        }
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("-1px");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(false);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // tableResolvers
        tableResolvers = new Table();
        tableResolvers.setCaption("Resolvers");
        tableResolvers.setImmediate(false);
        tableResolvers.setWidth("-1px");
        tableResolvers.setHeight("-1px");
        mainLayout.addComponent(tableResolvers);
        return mainLayout;
    }
}

17 View Complete Implementation : ExpressionBuilderComponent.java
Copyright MIT License
Author : att
public clreplaced ExpressionBuilderComponent extends Window implements ApplyParametersChangedListener {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Button buttonSave;

    @AutoGenerated
    private TreeTable treeExpressions;

    @AutoGenerated
    private HorizontalLayout horizontalLayout_1;

    @AutoGenerated
    private CheckBox checkBoxShortName;

    @AutoGenerated
    private Button buttonClearAll;

    @AutoGenerated
    private Button buttonDeleteExpression;

    @AutoGenerated
    private Button buttonAddExpression;

    /*
	 * 
	 * 
	 * 
	 */
    private static final long serialVersionUID = 1L;

    private static Log logger = LogFactory.getLog(ExpressionBuilderComponent.clreplaced);

    private static final Action ADD_EXPRESSION = new Action("Add Expression");

    private static final Action EDIT_EXPRESSION = new Action("Edit Expression");

    private static final Action DELETE_EXPRESSION = new Action("Delete Expression");

    private static final Action ADD_ARGUMENT = new Action("Add Argument");

    private static final Action EDIT_ARGUMENT = new Action("Edit Argument");

    private static final Action DELETE_ARGUMENT = new Action("Delete Argument");

    private final Object[] visibleColumns = new Object[] { ExpressionContainer.PROPERTY_NAME, ExpressionContainer.PROPERTY_ID, ExpressionContainer.PROPERTY_ID_SHORT, ExpressionContainer.PROPERTY_DATATYPE, ExpressionContainer.PROPERTY_DATATYPE_SHORT };

    private final String[] columnHeaders = new String[] { "Name", "XCAML ID or Value", "XCAML ID or Value", "Data Type ID", "Data Type ID" };

    private final ExpressionBuilderComponent self = this;

    private final Object parent;

    private final Map<VariableDefinitionType, PolicyType> variables;

    private final ExpressionContainer container;

    private boolean isSaved = false;

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     * @param parent
     * @param root
     * @param argument
     * @param variables
     */
    public ExpressionBuilderComponent(Object parent, Object root, FunctionArgument argument, Map<VariableDefinitionType, PolicyType> variables) {
        buildMainLayout();
        // setCompositionRoot(mainLayout);
        setContent(mainLayout);
        // 
        // Save our data
        // 
        this.parent = parent;
        this.variables = variables;
        this.container = new ExpressionContainer(parent, root, argument);
        // 
        // Make sure we support the parent object
        // 
        if (this.isSupported(parent) == false) {
            throw new IllegalArgumentException("Unsupported object type");
        }
        // 
        // Set our shortcuts
        // 
        this.setCloseShortcut(KeyCode.ESCAPE);
        // 
        // Finish our GUI initialization
        // 
        this.initializeTree();
        this.initializeButtons();
        this.initializeCheckbox();
        // 
        // Setup the buttons
        // 
        this.setupButtons();
    }

    private boolean isSupported(Object object) {
        if (this.isParentACondition() || this.isParentAVariable() || this.isParentAreplacedignment()) {
            return true;
        }
        return false;
    }

    private boolean isParentACondition() {
        return (this.parent instanceof ConditionType);
    }

    private boolean isParentAVariable() {
        return (this.parent instanceof VariableDefinitionType);
    }

    private boolean isParentAreplacedignment() {
        return (this.parent instanceof AttributereplacedignmentExpressionType);
    }

    private void initializeTree() {
        // 
        // Initialize GUI properties
        // 
        this.treeExpressions.setImmediate(true);
        this.treeExpressions.setSelectable(true);
        // 
        // Initialize the data source
        // 
        this.treeExpressions.setContainerDataSource(this.container);
        this.treeExpressions.sereplacedemCaptionMode(ItemCaptionMode.PROPERTY);
        this.treeExpressions.setVisibleColumns(this.visibleColumns);
        this.treeExpressions.setColumnHeaders(this.columnHeaders);
        this.treeExpressions.setColumnCollapsingAllowed(true);
        this.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_ID, true);
        this.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_DATATYPE, true);
        // 
        // Add our action handler
        // 
        this.treeExpressions.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    if (self.container.size() == 0) {
                        return new Action[] { ADD_EXPRESSION };
                    }
                    return null;
                }
                if (target instanceof ApplyType) {
                    if (XACMLFunctionValidator.canHaveMoreArguments((ApplyType) target)) {
                        return new Action[] { ADD_ARGUMENT, EDIT_EXPRESSION, DELETE_EXPRESSION };
                    }
                }
                return new Action[] { EDIT_ARGUMENT, DELETE_ARGUMENT };
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == ADD_EXPRESSION && target == null) {
                    self.addExpression(null, null);
                }
                if (action == EDIT_EXPRESSION && target != null) {
                    self.editExpression(target, (ApplyType) self.container.getParent(target), (FunctionArgument) self.container.getArgument(target));
                }
                if (action == DELETE_EXPRESSION && target != null) {
                    self.deleteExpression(target);
                }
                if (action == ADD_ARGUMENT && target != null && target instanceof ApplyType) {
                    self.addArgument((ApplyType) target);
                }
                if (action == EDIT_ARGUMENT && target != null) {
                    self.editExpression(target, (ApplyType) self.container.getParent(target), (FunctionArgument) self.container.getArgument(target));
                }
                if (action == DELETE_ARGUMENT && target != null) {
                    self.deleteExpression(target);
                }
            }
        });
        // 
        // Listen to double-click item selections
        // 
        this.treeExpressions.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    // self.treeExpressions.getValue();
                    Object target = event.gereplacedemId();
                    if (target == null) {
                        return;
                    }
                    self.editExpression(target, (ApplyType) self.container.getParent(target), (FunctionArgument) self.container.getArgument(target));
                }
            }
        });
        // 
        // Listen when the user selects a row
        // 
        this.treeExpressions.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                self.setupButtons();
            }
        });
        // 
        // Listen to when the table contents change
        // 
        this.treeExpressions.addItemSetChangeListener(new ItemSetChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void containerItemSetChange(ItemSetChangeEvent event) {
                self.validateExpression();
            }
        });
        // 
        // Expand columns automatically
        // 
        this.treeExpressions.setColumnExpandRatio(ExpressionContainer.PROPERTY_NAME, 1.0f);
        this.treeExpressions.setColumnExpandRatio(ExpressionContainer.PROPERTY_ID, 1.0f);
        this.treeExpressions.setColumnExpandRatio(ExpressionContainer.PROPERTY_DATATYPE, 1.0f);
        // 
        // Expand all the children
        // 
        for (Object id : this.treeExpressions.gereplacedemIds()) {
            this.treeExpressions.setCollapsed(id, false);
        }
        // 
        // Have a description generator
        // 
        this.treeExpressions.sereplacedemDescriptionGenerator(new ItemDescriptionGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public String generateDescription(Component source, Object itemId, Object propertyId) {
                if (propertyId != null && propertyId.equals(ExpressionContainer.PROPERTY_NAME) && itemId instanceof ApplyType) {
                    return ((ApplyType) itemId).getDescription();
                }
                return null;
            }
        });
    }

    private void initializeButtons() {
        this.buttonClearAll.setImmediate(true);
        this.buttonClearAll.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                self.clearAllExpressions();
            }
        });
        this.buttonAddExpression.setImmediate(true);
        this.buttonAddExpression.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                Object selected = self.treeExpressions.getValue();
                if (selected == null) {
                    // 
                    // Adding a root expression
                    // 
                    self.addExpression(null, null);
                } else {
                    // 
                    // Adding an argument
                    // 
                    if (selected instanceof ApplyType) {
                        // 
                        // Get the function
                        // 
                        self.addArgument((ApplyType) selected);
                    }
                }
            }
        });
        this.buttonDeleteExpression.setImmediate(true);
        this.buttonDeleteExpression.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                Object id = self.treeExpressions.getValue();
                if (id == null) {
                    logger.error("Delete button clicked on null selection");
                    return;
                }
                self.deleteExpression(id);
            }
        });
        this.buttonSave.setImmediate(true);
        this.buttonSave.setClickShortcut(KeyCode.ENTER);
        this.buttonSave.setEnabled(false);
        this.buttonSave.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                // 
                // TODO validate
                // 
                // 
                // Mark that we are saved
                // 
                self.isSaved = true;
                // 
                // Close the window
                // 
                self.close();
            }
        });
    }

    protected void initializeCheckbox() {
        this.checkBoxShortName.setValue(true);
        this.checkBoxShortName.setImmediate(true);
        this.checkBoxShortName.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                self.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_ID, self.checkBoxShortName.getValue());
                self.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_DATATYPE, self.checkBoxShortName.getValue());
                self.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_ID_SHORT, !self.checkBoxShortName.getValue());
                self.treeExpressions.setColumnCollapsed(ExpressionContainer.PROPERTY_DATATYPE_SHORT, !self.checkBoxShortName.getValue());
            }
        });
    }

    protected void setupButtons() {
        if (this.treeExpressions.size() == 0) {
            this.buttonAddExpression.setEnabled(true);
            this.buttonClearAll.setEnabled(false);
            this.buttonSave.setEnabled(false);
        } else {
            this.validateExpression();
            this.buttonAddExpression.setEnabled(false);
            this.buttonClearAll.setEnabled(true);
        }
        Object value = this.treeExpressions.getValue();
        if (value == null) {
            this.buttonDeleteExpression.setEnabled(false);
        } else {
            this.buttonDeleteExpression.setEnabled(true);
        }
    }

    protected void validateExpression() {
        boolean valid = false;
        boolean canHaveMore = false;
        if (this.isParentACondition()) {
            valid = XACMLFunctionValidator.validateCondition((ConditionType) this.parent);
            canHaveMore = XACMLFunctionValidator.canHaveMoreArguments((ConditionType) this.parent);
        } else if (this.isParentAVariable()) {
            valid = XACMLFunctionValidator.validateVariable((VariableDefinitionType) this.parent);
            canHaveMore = XACMLFunctionValidator.canHaveMoreArguments((VariableDefinitionType) this.parent);
        } else if (this.isParentAreplacedignment()) {
            valid = XACMLFunctionValidator.validatereplacedignment((AttributereplacedignmentExpressionType) this.parent);
            canHaveMore = XACMLFunctionValidator.canHaveMoreArguments((AttributereplacedignmentExpressionType) this.parent);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("valid: " + valid + " canHaveMore: " + canHaveMore);
        }
        // this.buttonAddExpression.setEnabled(canHaveMore);
        this.buttonSave.setEnabled(valid);
    }

    protected void addArgument(final ApplyType parentApply) {
        // 
        // Get the function
        // 
        FunctionDefinition function = JPAUtils.findFunction(parentApply.getFunctionId());
        if (function != null) {
            FunctionArgument argument = XACMLFunctionValidator.getFunctionArgument(parentApply.getExpression().size() + 1, function);
            if (logger.isDebugEnabled()) {
                logger.debug("Add Argument: " + argument);
            }
            replacedert (argument != null);
            // 
            // Is this a high order bag function? And it's data type not defined? (most likely)
            // 
            if (function.isHigherOrder() && argument.getDatatypeBean() == null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("isHighOrder and a null datatype bean");
                }
                // 
                // Get what the data type restriction should be
                // 
                try {
                    replacedert (parentApply.getExpression().size() > 0);
                    JAXBElement<?> element = parentApply.getExpression().get(0);
                    replacedert (element != null && element.getValue() != null);
                    Object declaredFunction = element.getValue();
                    replacedert (declaredFunction instanceof FunctionType);
                    FunctionDefinition declaredFunctionDefinition = JPAUtils.findFunction(((FunctionType) declaredFunction).getFunctionId());
                    replacedert (declaredFunctionDefinition != null);
                    if (logger.isDebugEnabled()) {
                        logger.debug("declaredFunction is: " + declaredFunctionDefinition);
                    }
                    FunctionArgument declaredFunctionArgument = XACMLFunctionValidator.getFunctionArgument(parentApply.getExpression().size(), declaredFunctionDefinition);
                    replacedert (declaredFunctionArgument != null);
                    if (logger.isDebugEnabled()) {
                        logger.debug("declaredFunctionArgument is: " + declaredFunctionArgument);
                    }
                    // 
                    // Copy the argument
                    // 
                    argument = new FunctionArgument(argument);
                    argument.setDatatypeBean(declaredFunctionArgument.getDatatypeBean());
                } catch (Exception e) {
                    logger.error("Exception while determining parent apply's FunctionType argument datatype.");
                }
            }
            self.addExpression(parentApply, argument);
        } else {
            AdminNotification.error("ApplyType does not have a function defined. Please define that first.");
        }
    }

    protected void addExpression(final ApplyType parentApply, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("Adding Expression: " + parentApply + " arg: " + argument);
        }
        // 
        // First we need to select what Expression They want
        // 
        final ExpressionSelectionWindow selector = new ExpressionSelectionWindow(parentApply, this.isParentAreplacedignment(), (argument != null ? argument.isBag() : false), (argument != null ? !argument.isBag() : false));
        selector.setCaption("Select the Expression Type");
        selector.setModal(true);
        selector.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Was something selected?
                // 
                String selection = selector.getSelection();
                if (selection == null) {
                    return;
                }
                // 
                // What did the user select?
                // 
                if (selection.equals(ExpressionSelectionWindow.OPTION_APPLY)) {
                    // 
                    self.editApply(new ApplyType(), parentApply, argument);
                // 
                } else if (selection.equals(ExpressionSelectionWindow.OPTION_DESIGNATOR)) {
                    // 
                    self.editAttribute(new AttributeDesignatorType(), parentApply, argument);
                // 
                } else if (selection.equals(ExpressionSelectionWindow.OPTION_SELECTOR)) {
                    // 
                    self.editAttribute(new AttributeSelectorType(), parentApply, argument);
                // 
                } else if (selection.equals(ExpressionSelectionWindow.OPTION_VALUE)) {
                    // 
                    self.editValue(new AttributeValueType(), parentApply, argument);
                // 
                } else if (selection.equals(ExpressionSelectionWindow.OPTION_VARIABLE)) {
                    // 
                    self.editVariable(new VariableReferenceType(), parentApply, argument);
                // 
                }
            }
        });
        selector.center();
        UI.getCurrent().addWindow(selector);
    }

    protected void editApply(final ApplyType apply, final ApplyType parent, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("editApply: " + apply + " parent: " + parent + " :" + argument);
        }
        // 
        // Copy the apply and create its window
        // 
        final ApplyType copyApply = XACMLObjectCopy.copy(apply);
        final ApplyEditorWindow window = new ApplyEditorWindow(copyApply, parent, argument, self.parent);
        window.setCaption("Edit The Apply Expression");
        window.setModal(true);
        // 
        // Set ourselves as an ApplyParametersChanged listener
        // 
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Copy back the apply
                // 
                apply.setDescription(copyApply.getDescription());
                apply.setFunctionId(copyApply.getFunctionId());
                // 
                // Get the function information
                // 
                FunctionDefinition function = JPAUtils.findFunction(apply.getFunctionId());
                replacedert (function != null);
                // 
                // Is this a new Apply?
                // 
                if (self.container.containsId(apply)) {
                    // 
                    // No - we are updating
                    // 
                    self.container.updateItem(apply);
                } else {
                    // 
                    // Is this a higher-order bag function?
                    // 
                    if (function.isHigherOrder()) {
                        // 
                        // Have the user select a function for it
                        // 
                        final FunctionSelectionWindow functionSelection = new FunctionSelectionWindow(null);
                        functionSelection.setCaption("Select Function");
                        functionSelection.setModal(true);
                        functionSelection.addCloseListener(new CloseListener() {

                            private static final long serialVersionUID = 1L;

                            @Override
                            public void windowClose(CloseEvent e) {
                                // 
                                // Did the user save?
                                // 
                                if (functionSelection.isSaved() == false) {
                                    return;
                                }
                                // 
                                // Get the function
                                // 
                                String function = functionSelection.getSelectedFunction();
                                if (function == null || function.isEmpty()) {
                                    logger.error("Function window said it was saved, but there was no function.");
                                    return;
                                }
                                // 
                                // Create the function object
                                // 
                                FunctionType hoFunction = new FunctionType();
                                hoFunction.setFunctionId(function);
                                // 
                                // Add it into the apply
                                // 
                                apply.getExpression().add(new ObjectFactory().createFunction(hoFunction));
                                // 
                                // New Item
                                // 
                                Item item = self.container.addItem(apply, parent, argument);
                                replacedert (item != null);
                                self.treeExpressions.setCollapsed(apply, false);
                                self.treeExpressions.select(apply);
                            }
                        });
                        functionSelection.center();
                        UI.getCurrent().addWindow(functionSelection);
                    } else {
                        // 
                        // New Item
                        // 
                        Item item = self.container.addItem(apply, parent, argument);
                        replacedert (item != null);
                        self.treeExpressions.setCollapsed(apply, false);
                        self.treeExpressions.select(apply);
                    }
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editAttribute(final Object target, final ApplyType parent, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("editAttribute: " + target + " parent: " + parent + " :" + argument);
        }
        // 
        // Determine what the data type needs to be
        // 
        Datatype datatype = null;
        if (parent == null && this.isParentACondition()) {
            datatype = JPAUtils.getBooleanDatatype();
        } else {
            if (argument != null) {
                datatype = argument.getDatatypeBean();
            }
        }
        // 
        // Copy the attribute
        // 
        final Object copyAttribute = XACMLObjectCopy.deepCopy(target);
        // 
        // Create the window
        // 
        final AttributeSelectionWindow window = new AttributeSelectionWindow(datatype, copyAttribute);
        if (target instanceof AttributeDesignatorType) {
            window.setCaption("Edit Designator " + (((AttributeDesignatorType) target).getAttributeId() != null ? ((AttributeDesignatorType) target).getAttributeId() : ""));
        } else {
            window.setCaption("Edit Selector " + (((AttributeSelectorType) target).getContextSelectorId() != null ? ((AttributeSelectorType) target).getContextSelectorId() : ""));
        }
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user hit save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Grab the attribute
                // 
                Attribute attribute = window.getAttribute();
                if (attribute == null) {
                    return;
                }
                // 
                // Save it back into the original
                // 
                if (target instanceof AttributeDesignatorType) {
                    ((AttributeDesignatorType) target).setAttributeId(attribute.getXacmlId());
                    ((AttributeDesignatorType) target).setCategory(attribute.getCategoryBean().getXacmlId());
                    ((AttributeDesignatorType) target).setDataType(attribute.getDatatypeBean().getXacmlId());
                    ((AttributeDesignatorType) target).setIssuer(attribute.getIssuer());
                    ((AttributeDesignatorType) target).setMustBePresent(attribute.isMustBePresent());
                } else {
                    ((AttributeSelectorType) target).setContextSelectorId(attribute.getXacmlId());
                    ((AttributeSelectorType) target).setCategory(attribute.getCategoryBean().getXacmlId());
                    ((AttributeSelectorType) target).setDataType(attribute.getDatatypeBean().getXacmlId());
                    ((AttributeSelectorType) target).setPath(attribute.getSelectorPath());
                    ((AttributeSelectorType) target).setMustBePresent(attribute.isMustBePresent());
                }
                // 
                // Is this a new item?
                // 
                if (self.container.containsId(target)) {
                    // 
                    // No, just update the container
                    // 
                    self.container.updateItem(target);
                } else {
                    // 
                    // Yes a new item, add it in
                    // 
                    // replacedert(self.container.addItem(JPAUtils.createDesignator(attribute), parent, argument) != null);
                    Item item = self.container.addItem(target, parent, argument);
                    replacedert (item != null);
                    self.treeExpressions.select(target);
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editValue(final AttributeValueType value, final ApplyType parent, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("editvalue: " + value + " parent: " + parent + " :" + argument);
        }
        // 
        // Copy the attribute value
        // 
        final AttributeValueType copyValue = XACMLObjectCopy.copy(value);
        // 
        // Get what the datatype should be
        // 
        Datatype datatypeRestriction = null;
        // 
        // Is this a root?
        // 
        if (parent == null) {
            // 
            // Check if our parent container is a condition
            // 
            if (self.isParentACondition()) {
                // 
                // We are only allowed to return boolean's
                // 
                datatypeRestriction = JPAUtils.getBooleanDatatype();
            }
        } else {
            // 
            // Are we an argument?
            // 
            if (argument != null) {
                // 
                // Yes - we are restricted to that argument's datatype
                // 
                datatypeRestriction = argument.getDatatypeBean();
            }
        }
        // 
        // Create the window
        // 
        final AttributeValueEditorWindow window = new AttributeValueEditorWindow(copyValue, datatypeRestriction);
        window.setCaption("Edit Attribute Value");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user click save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Yes - get the value
                // 
                value.getContent().clear();
                for (Object o : copyValue.getContent()) {
                    value.getContent().add(o);
                }
                value.setDataType(copyValue.getDataType());
                // 
                // Was this a new value?
                // 
                if (self.container.containsId(value)) {
                    // 
                    // No - update it
                    // 
                    self.container.updateItem(value);
                } else {
                    // 
                    // Yes - add it in
                    // 
                    Item item = self.container.addItem(value, parent, argument);
                    replacedert (item != null);
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editVariable(final VariableReferenceType variable, final ApplyType parent, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("editVariable: " + variable + " parent: " + parent + " :" + argument);
        }
        // 
        // Copy the variable
        // 
        final VariableReferenceType copyVariable = XACMLObjectCopy.copy(variable);
        // 
        // Create the window
        // 
        final VariableReferenceEditorWindow window = new VariableReferenceEditorWindow(copyVariable, this.variables);
        window.setCaption("Edit Variable Reference");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user click save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Copy the variable changes back
                // 
                variable.setVariableId(copyVariable.getVariableId());
                // 
                // Is this a new one?
                // 
                if (self.container.containsId(variable)) {
                    // 
                    // No - update it
                    // 
                    self.container.updateItem(variable);
                } else {
                    // 
                    // Yes - add it
                    // 
                    Item item = self.container.addItem(variable, parent, argument);
                    replacedert (item != null);
                }
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editFunction(final FunctionType func, final ApplyType parent, final FunctionArgument argument) {
        if (logger.isDebugEnabled()) {
            logger.debug("editFunction: " + func + " parent: " + parent + " :" + argument);
        }
        final FunctionSelectionWindow functionSelection = new FunctionSelectionWindow((func != null ? func.getFunctionId() : null));
        functionSelection.setCaption("Edit Function");
        functionSelection.setModal(true);
        functionSelection.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user save?
                // 
                if (functionSelection.isSaved() == false) {
                    return;
                }
                // 
                // Get the function
                // 
                String function = functionSelection.getSelectedFunction();
                if (function == null || function.isEmpty()) {
                    logger.error("Function window said it was saved, but there was no function.");
                    return;
                }
                // 
                // New one?
                // 
                if (func == null) {
                    // 
                    // Create the function object
                    // 
                    FunctionType hoFunction = new FunctionType();
                    hoFunction.setFunctionId(function);
                    // 
                    // Add it into the apply
                    // 
                    replacedert (parent.getExpression().size() == 0);
                    parent.getExpression().add(new ObjectFactory().createFunction(hoFunction));
                    // 
                    // New Item
                    // 
                    Item item = self.container.addItem(func, parent, argument);
                    replacedert (item != null);
                    self.treeExpressions.setCollapsed(parent, false);
                    self.treeExpressions.select(func);
                } else {
                    // 
                    // Editing an existing
                    // 
                    func.setFunctionId(function);
                    self.container.updateItem(func);
                    // 
                    // Warn user
                    // 
                    if (parent.getExpression().size() > 1) {
                        AdminNotification.warn("You have updated the function ID. The rest of the arguments may be invalid for the function. Please verify the other arguments.");
                    }
                }
            }
        });
        functionSelection.center();
        UI.getCurrent().addWindow(functionSelection);
    }

    protected void editExpression(final Object target, final ApplyType parent, final FunctionArgument argument) {
        if (target instanceof ApplyType) {
            // 
            this.editApply((ApplyType) target, parent, argument);
        // 
        } else if (target instanceof AttributeValueType) {
            // 
            this.editValue((AttributeValueType) target, parent, argument);
        // 
        } else if (target instanceof AttributeDesignatorType || target instanceof AttributeSelectorType) {
            // 
            this.editAttribute(target, parent, argument);
        // 
        } else if (target instanceof VariableReferenceType) {
            // 
            this.editVariable((VariableReferenceType) target, parent, argument);
        // 
        } else if (target instanceof FunctionType) {
            // 
            this.editFunction((FunctionType) target, parent, argument);
        // 
        }
    }

    protected void deleteExpression(Object target) {
        if (this.container.isRoot(target)) {
            if (this.treeExpressions.removeAllItems() == false) {
                logger.error("Failed to remove everything.");
            }
        } else {
            if (this.treeExpressions.removeItem(target) == false) {
                logger.error("Failed to remove " + target);
            }
        }
        this.setupButtons();
    }

    protected void clearAllExpressions() {
        if (this.treeExpressions.removeAllItems() == false) {
            logger.error("Failed to remove everything.");
        }
        this.setupButtons();
    }

    @Override
    public void applyParameterChanged(ApplyType apply, ApplyType parent, FunctionArgument argument, Object container) {
        logger.info("applyParameterChanged: " + apply + " " + parent + " " + argument + " " + container);
    // 
    // TODO - figure out if this something being edited, or a new one
    // 
    }

    public boolean isSaved() {
        return this.isSaved;
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("100%");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // horizontalLayout_1
        horizontalLayout_1 = buildHorizontalLayout_1();
        mainLayout.addComponent(horizontalLayout_1);
        mainLayout.setExpandRatio(horizontalLayout_1, 1.0f);
        // treeExpressions
        treeExpressions = new TreeTable();
        treeExpressions.setImmediate(false);
        treeExpressions.setWidth("100.0%");
        treeExpressions.setHeight("-1px");
        mainLayout.addComponent(treeExpressions);
        mainLayout.setExpandRatio(treeExpressions, 1.0f);
        // buttonSave
        buttonSave = new Button();
        buttonSave.setCaption("Save");
        buttonSave.setImmediate(true);
        buttonSave.setWidth("-1px");
        buttonSave.setHeight("-1px");
        mainLayout.addComponent(buttonSave);
        mainLayout.setComponentAlignment(buttonSave, new Alignment(48));
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayout_1() {
        // common part: create layout
        horizontalLayout_1 = new HorizontalLayout();
        horizontalLayout_1.setImmediate(false);
        horizontalLayout_1.setWidth("-1px");
        horizontalLayout_1.setHeight("-1px");
        horizontalLayout_1.setMargin(false);
        horizontalLayout_1.setSpacing(true);
        // buttonAddExpression
        buttonAddExpression = new Button();
        buttonAddExpression.setCaption("Add Expression");
        buttonAddExpression.setImmediate(true);
        buttonAddExpression.setWidth("-1px");
        buttonAddExpression.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonAddExpression);
        // buttonDeleteExpression
        buttonDeleteExpression = new Button();
        buttonDeleteExpression.setCaption("Delete Expression");
        buttonDeleteExpression.setImmediate(true);
        buttonDeleteExpression.setWidth("-1px");
        buttonDeleteExpression.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonDeleteExpression);
        // buttonClearAll
        buttonClearAll = new Button();
        buttonClearAll.setCaption("Clear All");
        buttonClearAll.setImmediate(true);
        buttonClearAll.setDescription("Clears all the expressions.");
        buttonClearAll.setWidth("-1px");
        buttonClearAll.setHeight("-1px");
        horizontalLayout_1.addComponent(buttonClearAll);
        // checkBoxShortName
        checkBoxShortName = new CheckBox();
        checkBoxShortName.setCaption("Display Short XACML ID's");
        checkBoxShortName.setImmediate(false);
        checkBoxShortName.setDescription("If checked, the right-most string of the function and datatype URI's will only be displayed.");
        checkBoxShortName.setWidth("-1px");
        checkBoxShortName.setHeight("-1px");
        horizontalLayout_1.addComponent(checkBoxShortName);
        return horizontalLayout_1;
    }
}

17 View Complete Implementation : PIPSQLResolverEditorWindow.java
Copyright MIT License
Author : att
public clreplaced PIPSQLResolverEditorWindow extends CustomComponent implements FormChangedEventNotifier, Handler {

    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Table tableAttributes;

    @AutoGenerated
    private Table tableRequiredAttributes;

    @AutoGenerated
    private CheckBox checkBoxShortIds;

    @AutoGenerated
    private TextField textFieldFilter;

    @AutoGenerated
    private TextField textFieldBase;

    @AutoGenerated
    private TextArea textAreaSelect;

    private final Action ADD_ATTRIBUTE = new Action("Add Attribute");

    private final Action EDIT_ATTRIBUTE = new Action("Edit Attribute");

    private final Action CLONE_ATTRIBUTE = new Action("Clone Attribute");

    private final Action REMOVE_ATTRIBUTE = new Action("Remove Attribute");

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    /**
     */
    protected clreplaced ResolverAttribute implements Serializable {

        private static final long serialVersionUID = 1L;

        String identifier = null;

        String prefix = null;

        PIPResolverParam id = null;

        PIPResolverParam category = null;

        PIPResolverParam datatype = null;

        PIPResolverParam issuer = null;

        PIPResolverParam column = null;

        public ResolverAttribute(String prefix, String identifier) {
            this.prefix = prefix;
            this.identifier = identifier;
        }

        public ResolverAttribute(String prefix, String identifier, ResolverAttribute target) {
            this(prefix, identifier);
            this.setId(target.getId());
            this.setCategory(target.getCategory());
            this.setDatatype(target.getDatatype());
            this.setIssuer(target.getIssuer());
            this.setColumn(target.getColumn());
            this.setResolver(target.id.getPipresolver());
        }

        public String getIdentifier() {
            return this.identifier;
        }

        public String getId() {
            if (this.id == null) {
                return null;
            }
            return this.id.getParamValue();
        }

        public String getShortId() {
            String id = this.getId();
            if (id == null) {
                return null;
            }
            return XACMLConstants.extractShortName(id);
        }

        public PIPResolverParam getIdParam() {
            return this.id;
        }

        public void setId(String id) {
            if (this.id == null) {
                this.id = new PIPResolverParam();
                this.id.setParamName(this.prefix + this.identifier + ".id");
            }
            this.id.setParamValue(id);
        }

        public void setId(PIPResolverParam param) {
            this.id = param;
        }

        public String getCategory() {
            if (this.category == null) {
                return null;
            }
            return this.category.getParamValue();
        }

        public String getShortCategory() {
            String category = this.getCategory();
            if (category == null) {
                return null;
            }
            return XACMLConstants.extractShortName(category);
        }

        public PIPResolverParam getCategoryParam() {
            return this.category;
        }

        public void setCategory(String category) {
            if (this.category == null) {
                this.category = new PIPResolverParam();
                this.category.setParamName(this.prefix + this.identifier + ".category");
            }
            this.category.setParamValue(category);
        }

        public void setCategory(PIPResolverParam param) {
            this.category = param;
        }

        public String getDatatype() {
            if (this.datatype == null) {
                return null;
            }
            return this.datatype.getParamValue();
        }

        public String getShortDatatype() {
            String dt = this.getDatatype();
            if (dt == null) {
                return null;
            }
            return XACMLConstants.extractShortName(dt);
        }

        public PIPResolverParam getDatatypeParam() {
            return this.datatype;
        }

        public void setDatatype(String datatype) {
            if (this.datatype == null) {
                this.datatype = new PIPResolverParam();
                this.datatype.setParamName(this.prefix + this.identifier + ".datatype");
            }
            this.datatype.setParamValue(datatype);
        }

        public void setDatatype(PIPResolverParam param) {
            this.datatype = param;
        }

        public String getIssuer() {
            if (this.issuer == null) {
                return null;
            }
            return this.issuer.getParamValue();
        }

        public String getShortIssuer() {
            String issuer = this.getIssuer();
            if (issuer == null) {
                return null;
            }
            return XACMLConstants.extractShortName(issuer);
        }

        public PIPResolverParam getIssuerParam() {
            return this.issuer;
        }

        public void setIssuer(String issuer) {
            if (this.issuer == null) {
                this.issuer = new PIPResolverParam();
                this.issuer.setParamName(this.prefix + this.identifier + ".issuer");
            }
            this.issuer.setParamValue(issuer);
        }

        public void setIssuer(PIPResolverParam param) {
            this.issuer = param;
        }

        public Integer getColumn() {
            if (this.column == null) {
                return null;
            }
            try {
                return Integer.parseInt(this.column.getParamValue());
            } catch (NumberFormatException e) {
                logger.error("Failed to set column: " + e);
                return null;
            }
        }

        public PIPResolverParam getColumnParam() {
            return this.column;
        }

        public void setColumn(Integer col) {
            if (this.column == null) {
                this.column = new PIPResolverParam();
                this.column.setParamName(this.prefix + this.identifier + "column");
            }
            this.column.setParamValue(col.toString());
        }

        public void setColumn(PIPResolverParam param) {
            this.column = param;
        }

        public void setResolver(PIPResolver resolver) {
            if (this.id != null) {
                this.id.setPipresolver(resolver);
            }
            if (this.category != null) {
                this.category.setPipresolver(resolver);
            }
            if (this.datatype != null) {
                this.datatype.setPipresolver(resolver);
            }
            if (this.issuer != null) {
                this.issuer.setPipresolver(resolver);
            }
            if (this.column != null) {
                this.column.setPipresolver(resolver);
            }
        }
    }

    private static final long serialVersionUID = 1L;

    private static final Log logger = LogFactory.getLog(PIPSQLResolverEditorWindow.clreplaced);

    private final PIPSQLResolverEditorWindow self = this;

    private final EnreplacedyItem<PIPResolver> enreplacedy;

    private final BeanItemContainer<ResolverAttribute> fieldsContainer = new BeanItemContainer<ResolverAttribute>(ResolverAttribute.clreplaced);

    private final BeanItemContainer<ResolverAttribute> parametersContainer = new BeanItemContainer<ResolverAttribute>(ResolverAttribute.clreplaced);

    private final BasicNotifier notifier = new BasicNotifier();

    boolean isSaved = false;

    String fieldPrefix;

    String parameterPrefix;

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     * @param enreplacedy
     */
    public PIPSQLResolverEditorWindow(EnreplacedyItem<PIPResolver> enreplacedy) {
        buildMainLayout();
        setCompositionRoot(mainLayout);
        // 
        // Save
        // 
        this.enreplacedy = enreplacedy;
        // 
        // Initialize
        // 
        this.initialize();
    }

    protected boolean isSQL() {
        if (this.enreplacedy.getEnreplacedy().getPipconfiguration().getPiptype().isSQL() || this.enreplacedy.getEnreplacedy().getPipconfiguration().getPiptype().isHyperCSV()) {
            return true;
        }
        return false;
    }

    protected boolean isLDAP() {
        return this.enreplacedy.getEnreplacedy().getPipconfiguration().getPiptype().isLDAP();
    }

    protected boolean isCSV() {
        return this.enreplacedy.getEnreplacedy().getPipconfiguration().getPiptype().isCSV();
    }

    protected void initialize() {
        // 
        // Initialize enreplacedy
        // 
        this.initializeEnreplacedy();
        // 
        // Go through the parameters, save them into a
        // properties object.
        // 
        boolean sourceInitialized = false;
        boolean attributeInitialized = false;
        for (PIPResolverParam param : this.enreplacedy.getEnreplacedy().getPipresolverParams()) {
            // 
            // Look for ones we know about
            // 
            if (param.getParamName().equalsIgnoreCase("select")) {
                this.textAreaSelect.setValue(param.getParamValue());
                this.textAreaSelect.setData(param);
            } else if (param.getParamName().equals("fields") || param.getParamName().equals("filter.view")) {
                this.initializeSourceTable(param.getParamValue());
                this.tableRequiredAttributes.setData(param);
                sourceInitialized = true;
            } else if (param.getParamName().equals("parameters") || param.getParamName().equals("filter.parameters")) {
                this.initializeAttributeTable(param.getParamValue());
                this.tableAttributes.setData(param);
                attributeInitialized = true;
            } else if (param.getParamName().equalsIgnoreCase("base")) {
                this.textFieldBase.setValue(param.getParamValue());
                this.textFieldBase.setData(param);
            } else if (param.getParamName().equalsIgnoreCase("filter")) {
                this.textFieldFilter.setValue(param.getParamValue());
                this.textFieldFilter.setData(param);
            }
        }
        // 
        // Initialize GUI
        // 
        this.initializeText();
        this.initializeCheckBox();
        // 
        // Verify the tables get setup, if this is a new object
        // then they haven't been.
        // 
        if (sourceInitialized == false) {
            this.initializeSourceTable("");
        }
        if (attributeInitialized == false) {
            this.initializeAttributeTable("");
        }
    }

    protected void initializeEnreplacedy() {
        // 
        // Make sure the clreplacedname is set correctly
        // 
        if (this.isSQL()) {
            // 
            // 
            // 
            this.fieldPrefix = "field.";
            this.parameterPrefix = "parameter.";
            this.enreplacedy.getEnreplacedy().setClreplacedname(ConfigurableJDBCResolver.clreplaced.getCanonicalName());
        } else if (this.isLDAP()) {
            // 
            // 
            // 
            this.fieldPrefix = "filter.view.";
            this.parameterPrefix = "filter.parameters.";
            this.enreplacedy.getEnreplacedy().setClreplacedname(ConfigurableLDAPResolver.clreplaced.getCanonicalName());
        } else if (this.isCSV()) {
            // 
            // 
            // 
            this.fieldPrefix = "field.";
            this.parameterPrefix = "parameter.";
            this.enreplacedy.getEnreplacedy().setClreplacedname(ConfigurableCSVResolver.clreplaced.getCanonicalName());
        }
    }

    protected void initializeText() {
        // 
        // Are we SQL or LDAP?
        // 
        if (this.isSQL()) {
            // 
            // Turn these off
            // 
            this.textFieldBase.setRequired(false);
            this.textFieldBase.setVisible(false);
            this.textFieldFilter.setRequired(false);
            this.textFieldFilter.setVisible(false);
            // 
            // GUI properties
            // 
            this.textAreaSelect.setImmediate(true);
            // 
            // Respond to changes
            // 
            this.textAreaSelect.addValueChangeListener(new ValueChangeListener() {

                private static final long serialVersionUID = 1L;

                @Override
                public void valueChange(ValueChangeEvent event) {
                    PIPResolverParam param = (PIPResolverParam) self.textAreaSelect.getData();
                    if (param == null) {
                        param = new PIPResolverParam();
                        param.setPipresolver(self.enreplacedy.getEnreplacedy());
                        param.setParamName("select");
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(param);
                        self.textAreaSelect.setData(param);
                    }
                    param.setParamValue(self.textAreaSelect.getValue());
                    self.fireFormChangedEvent();
                }
            });
        } else if (this.isLDAP()) {
            // 
            // Turn these off
            // 
            this.textAreaSelect.setRequired(false);
            this.textAreaSelect.setVisible(false);
            // 
            // 
            // 
            this.textFieldBase.setImmediate(true);
            this.textFieldBase.addValueChangeListener(new ValueChangeListener() {

                private static final long serialVersionUID = 1L;

                @Override
                public void valueChange(ValueChangeEvent event) {
                    PIPResolverParam param = (PIPResolverParam) self.textFieldBase.getData();
                    if (param == null) {
                        param = new PIPResolverParam();
                        param.setPipresolver(self.enreplacedy.getEnreplacedy());
                        param.setParamName("base");
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(param);
                        self.textFieldBase.setData(param);
                    }
                    param.setParamValue(self.textFieldBase.getValue());
                    self.fireFormChangedEvent();
                }
            });
            // 
            // 
            // 
            this.textFieldFilter.setImmediate(true);
            this.textFieldFilter.addValueChangeListener(new ValueChangeListener() {

                private static final long serialVersionUID = 1L;

                @Override
                public void valueChange(ValueChangeEvent event) {
                    PIPResolverParam param = (PIPResolverParam) self.textFieldFilter.getData();
                    if (param == null) {
                        param = new PIPResolverParam();
                        param.setPipresolver(self.enreplacedy.getEnreplacedy());
                        param.setParamName("filter");
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(param);
                        self.textFieldFilter.setData(param);
                    }
                    param.setParamValue(self.textFieldFilter.getValue());
                    self.fireFormChangedEvent();
                }
            });
        } else if (this.isCSV()) {
            // 
            // Turn these off
            // 
            this.textAreaSelect.setRequired(false);
            this.textAreaSelect.setVisible(false);
            this.textFieldBase.setRequired(false);
            this.textFieldBase.setVisible(false);
            this.textFieldFilter.setRequired(false);
            this.textFieldFilter.setVisible(false);
        }
    }

    protected void initializeCheckBox() {
        this.checkBoxShortIds.setValue(true);
        this.checkBoxShortIds.setImmediate(true);
        this.checkBoxShortIds.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                if (self.checkBoxShortIds.getValue()) {
                    self.tableRequiredAttributes.setColumnCollapsed("id", true);
                    self.tableRequiredAttributes.setColumnCollapsed("category", true);
                    self.tableRequiredAttributes.setColumnCollapsed("datatype", true);
                    self.tableRequiredAttributes.setColumnCollapsed("shortId", false);
                    self.tableRequiredAttributes.setColumnCollapsed("shortCategory", false);
                    self.tableRequiredAttributes.setColumnCollapsed("shortDatatype", false);
                } else {
                    self.tableRequiredAttributes.setColumnCollapsed("id", false);
                    self.tableRequiredAttributes.setColumnCollapsed("category", false);
                    self.tableRequiredAttributes.setColumnCollapsed("datatype", false);
                    self.tableRequiredAttributes.setColumnCollapsed("shortId", true);
                    self.tableRequiredAttributes.setColumnCollapsed("shortCategory", true);
                    self.tableRequiredAttributes.setColumnCollapsed("shortDatatype", true);
                }
            }
        });
    }

    protected void initializeSourceTable(String fields) {
        // 
        // Add data into the container
        // 
        this.populateData(this.fieldPrefix, fields, this.fieldsContainer);
        // 
        // Set GUI properties
        // 
        this.tableRequiredAttributes.setContainerDataSource(this.fieldsContainer);
        this.tableRequiredAttributes.setPageLength((this.fieldsContainer.size() == 0 ? 3 : this.fieldsContainer.size() + 1));
        this.tableRequiredAttributes.setSizeFull();
        this.tableRequiredAttributes.setColumnCollapsingAllowed(true);
        this.tableRequiredAttributes.setVisibleColumns(new Object[] { "identifier", "id", "category", "datatype", "shortId", "shortCategory", "shortDatatype" });
        this.tableRequiredAttributes.setColumnHeaders(new String[] { "Field", "Attribute Id", "Category", "Data Type", "Attribute Id", "Category", "Data Type" });
        this.tableRequiredAttributes.setColumnCollapsed("id", true);
        this.tableRequiredAttributes.setColumnCollapsed("category", true);
        this.tableRequiredAttributes.setColumnCollapsed("datatype", true);
        this.tableRequiredAttributes.setSelectable(true);
        // 
        // Setup its handler
        // 
        this.tableRequiredAttributes.addActionHandler(this);
        // 
        // Respond to events
        // 
        this.tableRequiredAttributes.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    Object id = event.gereplacedemId();
                    if (id == null) {
                        // 
                        // Really shouldn't get here
                        // 
                        return;
                    }
                    BeanItem<ResolverAttribute> beanItem = self.fieldsContainer.gereplacedem(id);
                    if (beanItem == null) {
                        // 
                        // Again, shouldn't get here
                        // 
                        return;
                    }
                    self.editAttribute(self.tableRequiredAttributes, beanItem.getBean());
                }
            }
        });
    }

    protected void initializeAttributeTable(String parameters) {
        // 
        // Add data into the container
        // 
        this.populateData(this.parameterPrefix, parameters, this.parametersContainer);
        // 
        // setup gui properties
        // 
        this.tableAttributes.setContainerDataSource(this.parametersContainer);
        this.tableAttributes.setPageLength(this.parametersContainer.size() + 1);
        this.tableAttributes.setSizeFull();
        this.tableAttributes.setColumnCollapsingAllowed(true);
        this.tableAttributes.setVisibleColumns(new Object[] { "identifier", "id", "category", "datatype", "shortId", "shortCategory", "shortDatatype" });
        this.tableAttributes.setColumnHeaders(new String[] { "Position", "Attribute Id", "Category", "Data Type", "Attribute Id", "Category", "Data Type" });
        this.tableAttributes.setColumnCollapsed("id", true);
        this.tableAttributes.setColumnCollapsed("category", true);
        this.tableAttributes.setColumnCollapsed("datatype", true);
        this.tableAttributes.setSelectable(true);
        // 
        // Setup its handler
        // 
        this.tableAttributes.addActionHandler(this);
        // 
        // Respond to events
        // 
        this.tableAttributes.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    Object id = event.gereplacedemId();
                    if (id == null) {
                        // 
                        // Really shouldn't get here
                        // 
                        return;
                    }
                    BeanItem<ResolverAttribute> beanItem = self.parametersContainer.gereplacedem(id);
                    if (beanItem == null) {
                        // 
                        // Again, shouldn't get here
                        // 
                        return;
                    }
                    self.editAttribute(self.tableAttributes, beanItem.getBean());
                }
            }
        });
    }

    protected void populateData(String prefix, String list, BeanItemContainer<ResolverAttribute> container) {
        for (String field : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
            // 
            // Create a bean for this field
            // 
            ResolverAttribute bean = new ResolverAttribute(prefix, field);
            // 
            // Now try to find the attribute information
            // 
            for (PIPResolverParam param : this.enreplacedy.getEnreplacedy().getPipresolverParams()) {
                if (param.getParamName().equals(prefix + field + ".id")) {
                    bean.setId(param);
                } else if (param.getParamName().equals(prefix + field + ".category")) {
                    bean.setCategory(param);
                } else if (param.getParamName().equals(prefix + field + ".datatype")) {
                    bean.setDatatype(param);
                } else if (param.getParamName().equals(prefix + field + ".issuer")) {
                    bean.setIssuer(param);
                } else if (param.getParamName().equals(prefix + field + ".column")) {
                    bean.setColumn(param);
                }
            }
            container.addBean(bean);
        }
    }

    @Override
    public Action[] getActions(Object target, Object sender) {
        if (target == null) {
            return new Action[] { ADD_ATTRIBUTE };
        }
        return new Action[] { EDIT_ATTRIBUTE, CLONE_ATTRIBUTE, REMOVE_ATTRIBUTE };
    }

    @Override
    public void handleAction(Action action, Object sender, Object target) {
        if (action == ADD_ATTRIBUTE) {
            if (sender.equals(this.tableRequiredAttributes)) {
                this.editAttribute(self.tableRequiredAttributes, null);
            } else {
                this.editAttribute(self.tableAttributes, null);
            }
            return;
        }
        if (action == EDIT_ATTRIBUTE) {
            replacedert (target instanceof ResolverAttribute);
            if (sender.equals(this.tableRequiredAttributes)) {
                this.editAttribute(self.tableRequiredAttributes, (ResolverAttribute) target);
            } else {
                this.editAttribute(self.tableAttributes, (ResolverAttribute) target);
            }
            return;
        }
        if (action == CLONE_ATTRIBUTE) {
            replacedert (target instanceof ResolverAttribute);
            try {
                // 
                // Which table?
                // 
                if (sender.equals(this.tableRequiredAttributes)) {
                    // 
                    // Clone the attribute giving it a new
                    // field name.
                    // 
                    ResolverAttribute clone = new ResolverAttribute(this.fieldPrefix, this.getNextField(), (ResolverAttribute) target);
                    // 
                    // Add it to the container
                    // 
                    this.fieldsContainer.addBean(clone);
                    // 
                    // Reset the page length so we can see it and have room
                    // to add another.
                    // 
                    this.tableRequiredAttributes.setPageLength(this.fieldsContainer.size() + 1);
                    // 
                    // Select it
                    // 
                    this.tableRequiredAttributes.select(clone);
                } else {
                    // 
                    // Clone the attribute giving it a new
                    // field name.
                    // 
                    ResolverAttribute clone = new ResolverAttribute(this.parameterPrefix, this.getNextParameter(), (ResolverAttribute) target);
                    // 
                    // Add it to the container
                    // 
                    this.parametersContainer.addBean(clone);
                    // 
                    // Reset the page length so we can see it and have room
                    // to add another.
                    // 
                    this.tableAttributes.setPageLength(this.parametersContainer.size() + 1);
                    // 
                    // Select it
                    // 
                    this.tableAttributes.select(clone);
                }
                // 
                // We have changed
                // 
                this.fireFormChangedEvent();
            } catch (Exception e) {
                logger.error("Failed to clone: " + e);
            }
            return;
        }
        if (action == REMOVE_ATTRIBUTE) {
            replacedert (target instanceof ResolverAttribute);
            // 
            // Help method to remove the attribute
            // 
            this.removeAttribute((ResolverAttribute) target);
            // 
            // Which table?
            // 
            if (sender.equals(this.tableRequiredAttributes)) {
                // 
                // Now remove it from the table
                // 
                this.tableRequiredAttributes.removeItem(target);
            } else {
                // 
                // Now remove it from the table
                // 
                this.tableAttributes.removeItem(target);
            }
            // 
            // we have changed
            // 
            this.fireFormChangedEvent();
            return;
        }
    }

    protected void removeAttribute(ResolverAttribute target) {
        this.enreplacedy.getEnreplacedy().removePipresolverParam(target.getIdParam());
        this.enreplacedy.getEnreplacedy().removePipresolverParam(target.getCategoryParam());
        this.enreplacedy.getEnreplacedy().removePipresolverParam(target.getDatatypeParam());
        this.enreplacedy.getEnreplacedy().removePipresolverParam(target.getIssuerParam());
    }

    protected void editAttribute(final Table table, final ResolverAttribute request) {
        if (this.isCSV()) {
            this.editCSVAttribute(table, request);
        } else {
            this.editResolverAttribute(table, request, null);
        }
    }

    protected void editCSVAttribute(final Table table, final ResolverAttribute request) {
        replacedert (this.isCSV());
        // 
        // Prompt for the column
        // 
        final ColumnSelectionWindow window = new ColumnSelectionWindow((request != null ? request.getColumn() : 0));
        if (request == null) {
            window.setCaption("Input the CSV Column for the new attribute");
        } else {
            window.setCaption("Edit the CSV Column for the attribute");
        }
        window.setModal(true);
        window.center();
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user save?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Save it if its not a new
                // 
                if (request != null) {
                    request.setColumn(window.getColumn());
                }
                // 
                // Now we select the attribute, preplaced the column
                // in case this is a brand new attribute. Yeah its messy.
                // 
                self.editResolverAttribute(table, request, window.getColumn());
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void editResolverAttribute(final Table table, final ResolverAttribute request, final Integer column) {
        // 
        // Provide objects to the attribute selection window
        // 
        AttributeDesignatorType designator = new AttributeDesignatorType();
        if (request == null) {
            designator.setAttributeId(XACML3.ID_SUBJECT_SUBJECT_ID.stringValue());
            designator.setCategory(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue());
            designator.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
            designator.setIssuer(this.enreplacedy.getEnreplacedy().getIssuer());
        } else {
            designator.setAttributeId(request.getId());
            designator.setCategory(request.getCategory());
            designator.setDataType(request.getDatatype());
            designator.setIssuer(request.getIssuer());
        }
        // 
        // Have user select an attribute
        // 
        final AttributeSelectionWindow selection = new AttributeSelectionWindow(null, designator);
        selection.setModal(true);
        selection.setCaption("Select Attribute");
        selection.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent event) {
                // 
                // User click Save button?
                // 
                if (selection.isSaved() == false) {
                    return;
                }
                // 
                // Yes - get the final attribute
                // 
                Attribute attribute = selection.getAttribute();
                // 
                // Is it a new one?
                // 
                if (request == null) {
                    try {
                        // 
                        // Create a new bean
                        // 
                        ResolverAttribute bean = null;
                        if (table.equals(self.tableRequiredAttributes)) {
                            bean = new ResolverAttribute(self.fieldPrefix, self.getNextField());
                        } else {
                            bean = new ResolverAttribute(self.parameterPrefix, self.getNextParameter());
                        }
                        bean.setId(attribute.getXacmlId());
                        bean.setCategory(attribute.getCategoryBean().getXacmlId());
                        bean.setDatatype(attribute.getDatatypeBean().getXacmlId());
                        if (attribute.getIssuer() != null) {
                            bean.setIssuer(attribute.getIssuer());
                        }
                        if (column != null) {
                            bean.setColumn(column);
                        }
                        // 
                        // Add it to the resolver
                        // 
                        bean.setResolver(self.enreplacedy.getEnreplacedy());
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(bean.getIdParam());
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(bean.getCategoryParam());
                        self.enreplacedy.getEnreplacedy().addPipresolverParam(bean.getDatatypeParam());
                        if (bean.getIssuer() != null) {
                            self.enreplacedy.getEnreplacedy().addPipresolverParam(bean.getIssuerParam());
                        }
                        // 
                        // Which table?
                        // 
                        if (table.equals(self.tableRequiredAttributes)) {
                            // 
                            // Add to table
                            // 
                            self.fieldsContainer.addBean(bean);
                            // 
                            // Reset the page length
                            // 
                            self.tableRequiredAttributes.setPageLength(self.fieldsContainer.size() + 1);
                        } else if (table.equals(self.tableAttributes)) {
                            // 
                            // Add to table
                            // 
                            self.parametersContainer.addBean(bean);
                            // 
                            // Reset the page length
                            // 
                            self.tableAttributes.setPageLength(self.parametersContainer.size() + 1);
                        }
                        if (logger.isDebugEnabled()) {
                            logger.debug("Added new attribute: " + bean);
                        }
                    } catch (Exception e) {
                        logger.error(e);
                        AdminNotification.error("Unable to add another required attribute field");
                    }
                } else {
                    // 
                    // Update the table entry
                    // 
                    request.setId(attribute.getXacmlId());
                    request.setCategory(attribute.getCategoryBean().getXacmlId());
                    request.setDatatype(attribute.getDatatypeBean().getXacmlId());
                    request.setIssuer(attribute.getIssuer());
                    // 
                    // Let the table know
                    // 
                    table.refreshRowCache();
                }
                // 
                // we have changed
                // 
                self.fireFormChangedEvent();
            }
        });
        selection.center();
        UI.getCurrent().addWindow(selection);
    }

    protected String getNextField() throws Exception {
        // 
        // Start at the next index number. NOTE: The GUI needs
        // to use numbers to index the fields.
        // 
        int index = this.tableRequiredAttributes.size() + 1;
        // 
        // Really if we get to 100, that's an insane number of fields
        // needed for a SQL query.
        // 
        while (index < 100) {
            String field = String.format("%02d", index);
            boolean exists = false;
            for (Object id : this.tableRequiredAttributes.gereplacedemIds()) {
                @SuppressWarnings("unchecked")
                BeanItem<ResolverAttribute> required = (BeanItem<ResolverAttribute>) this.tableRequiredAttributes.gereplacedem(id);
                if (required.getBean().getIdentifier().equals(field)) {
                    exists = true;
                    index++;
                    break;
                }
            }
            if (exists == false) {
                return field;
            }
        }
        // 
        // Sanity check
        // 
        throw new Exception("Unable to find a next field name. Are there too many fields?");
    }

    protected String getNextParameter() throws Exception {
        // 
        // Start at the next index number. NOTE: The GUI needs
        // to use numbers to index the fields.
        // 
        int index = this.tableAttributes.size() + 1;
        // 
        // Really if we get to 100, that's an insane number of fields
        // needed for a SQL query.
        // 
        while (index < 100) {
            String field = String.format("%02d", index);
            boolean exists = false;
            for (Object id : this.tableAttributes.gereplacedemIds()) {
                @SuppressWarnings("unchecked")
                BeanItem<ResolverAttribute> required = (BeanItem<ResolverAttribute>) this.tableAttributes.gereplacedem(id);
                if (required.getBean().getIdentifier().equals(field)) {
                    exists = true;
                    index++;
                    break;
                }
            }
            if (exists == false) {
                return field;
            }
        }
        // 
        // Sanity check
        // 
        throw new Exception("Unable to find a next parameter name. Are there too many parameters?");
    }

    public void discard() throws SourceException {
        if (this.isSQL()) {
            this.textAreaSelect.discard();
        } else if (this.isLDAP()) {
            this.textFieldBase.discard();
            this.textFieldFilter.discard();
        } else if (this.isCSV()) {
        }
    }

    public void validate() throws InvalidValueException {
        if (this.isSQL()) {
            this.textAreaSelect.validate();
        } else if (this.isLDAP()) {
            this.textFieldBase.validate();
            this.textFieldFilter.validate();
        } else if (this.isCSV()) {
        }
    }

    public void commit() throws SourceException, InvalidValueException {
        // 
        // Commit required fields
        // 
        if (this.isSQL()) {
            this.textAreaSelect.commit();
        } else if (this.isLDAP()) {
            this.textFieldBase.commit();
            this.textFieldFilter.commit();
        } else if (this.isCSV()) {
        }
        // 
        // Setup the fields
        // 
        {
            List<String> fields = new ArrayList<String>(this.fieldsContainer.size());
            for (ResolverAttribute attribute : this.fieldsContainer.gereplacedemIds()) {
                fields.add(attribute.getIdentifier());
            }
            PIPResolverParam param = (PIPResolverParam) this.tableRequiredAttributes.getData();
            if (param == null) {
                param = new PIPResolverParam();
                if (this.isSQL()) {
                    param.setParamName("fields");
                } else if (this.isLDAP()) {
                    param.setParamName("filter.view");
                } else if (this.isCSV()) {
                    param.setParamName("fields");
                }
                this.enreplacedy.getEnreplacedy().addPipresolverParam(param);
                this.tableRequiredAttributes.setData(param);
            }
            param.setParamValue(Joiner.on(',').join(fields));
        }
        // 
        // Setup the parameters
        // 
        {
            List<String> parameters = new ArrayList<String>(this.parametersContainer.size());
            for (ResolverAttribute attribute : this.parametersContainer.gereplacedemIds()) {
                parameters.add(attribute.getIdentifier());
            }
            PIPResolverParam param = (PIPResolverParam) this.tableAttributes.getData();
            if (param == null) {
                param = new PIPResolverParam();
                if (this.isSQL()) {
                    param.setParamName("parameters");
                } else if (this.isLDAP()) {
                    param.setParamName("filter.parameters");
                } else if (this.isCSV()) {
                    param.setParamName("parameters");
                }
                this.enreplacedy.getEnreplacedy().addPipresolverParam(param);
                this.tableAttributes.setData(param);
            }
            param.setParamValue(Joiner.on(',').join(parameters));
        }
    }

    public boolean isSaved() {
        return this.isSaved;
    }

    @Override
    public boolean addListener(FormChangedEventListener listener) {
        return this.notifier.addListener(listener);
    }

    @Override
    public boolean removeListener(FormChangedEventListener listener) {
        return this.notifier.removeListener(listener);
    }

    @Override
    public void fireFormChangedEvent() {
        this.notifier.fireFormChangedEvent();
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("-1px");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // textAreaSelect
        textAreaSelect = new TextArea();
        textAreaSelect.setCaption("SQL Select Statement");
        textAreaSelect.setImmediate(false);
        textAreaSelect.setWidth("100.0%");
        textAreaSelect.setHeight("-1px");
        textAreaSelect.setInvalidAllowed(false);
        textAreaSelect.setRequired(true);
        mainLayout.addComponent(textAreaSelect);
        mainLayout.setExpandRatio(textAreaSelect, 1.0f);
        // textFieldBase
        textFieldBase = new TextField();
        textFieldBase.setCaption("Base DN");
        textFieldBase.setImmediate(false);
        textFieldBase.setWidth("-1px");
        textFieldBase.setHeight("-1px");
        mainLayout.addComponent(textFieldBase);
        // textFieldFilter
        textFieldFilter = new TextField();
        textFieldFilter.setCaption("Filter");
        textFieldFilter.setImmediate(false);
        textFieldFilter.setWidth("-1px");
        textFieldFilter.setHeight("-1px");
        mainLayout.addComponent(textFieldFilter);
        // checkBoxShortIds
        checkBoxShortIds = new CheckBox();
        checkBoxShortIds.setCaption("Display short id’s.");
        checkBoxShortIds.setImmediate(false);
        checkBoxShortIds.setWidth("-1px");
        checkBoxShortIds.setHeight("-1px");
        mainLayout.addComponent(checkBoxShortIds);
        // tableRequiredAttributes
        tableRequiredAttributes = new Table();
        tableRequiredAttributes.setCaption("Attributes Returned");
        tableRequiredAttributes.setImmediate(false);
        tableRequiredAttributes.setWidth("-1px");
        tableRequiredAttributes.setHeight("-1px");
        mainLayout.addComponent(tableRequiredAttributes);
        // tableAttributes
        tableAttributes = new Table();
        tableAttributes.setCaption("Parameters - Attributes Needed (i.e. ?)");
        tableAttributes.setImmediate(false);
        tableAttributes.setWidth("-1px");
        tableAttributes.setHeight("-1px");
        tableAttributes.setInvalidAllowed(false);
        tableAttributes.setRequired(true);
        mainLayout.addComponent(tableAttributes);
        return mainLayout;
    }
}

16 View Complete Implementation : EditPDPGroupWindow.java
Copyright Apache License 2.0
Author : apache
public clreplaced EditPDPGroupWindow extends Window {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Button buttonSave;

    @AutoGenerated
    private Table tablePIP;

    @AutoGenerated
    private Table tablePolicies;

    @AutoGenerated
    private TextArea textDescription;

    @AutoGenerated
    private TextField textName;

    private static final Action ADD_POLICY = new Action("Add New Policy");

    private static final Action REMOVE_POLICY = new Action("Remove Policy");

    private static final Action MAKE_ROOT = new Action("Make Root");

    private static final Action MAKE_REFERENCED = new Action("Make Referenced");

    private static final Action EDIT_CONFIG = new Action("Edit Configurations");

    // 
    // ?? Why is this static?
    // 
    private static PDPPolicyContainer policyContainer;

    private PDPPIPContainer pipContainer;

    /**
     */
    private static final long serialVersionUID = 1L;

    private final EditPDPGroupWindow self = this;

    private final StdPDPGroup group;

    private boolean isSaved = false;

    // this is the version that contains all of the edits made by the user.
    // it may be a copy of the original object (edited) or a new one.
    private StdPDPGroup updatedObject;

    private PAPEngine papEngine;

    private List<PDPGroup> groups;

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     */
    public EditPDPGroupWindow(StdPDPGroup group, List<PDPGroup> list, PAPEngine engine) {
        buildMainLayout();
        // setCompositionRoot(mainLayout);
        setContent(mainLayout);
        // 
        // Save pointers
        // 
        this.group = group;
        this.groups = list;
        this.papEngine = engine;
        // 
        // Initialize
        // 
        this.initialize();
        // 
        // Shortcuts
        // 
        this.setCloseShortcut(KeyCode.ESCAPE);
        this.buttonSave.setClickShortcut(KeyCode.ENTER);
        // 
        // Focus
        // 
        this.textName.focus();
    }

    protected void initialize() {
        this.initializeText();
        this.initializeButton();
        this.initializeTables();
    }

    protected void initializeText() {
        this.textName.setNullRepresentation("");
        this.textDescription.setNullRepresentation("");
        if (this.group != null) {
            this.textName.setValue(this.group.getName());
            this.textDescription.setValue(this.group.getDescription());
        }
        // 
        // Validation
        // 
        this.textName.addValidator(new Validator() {

            private static final long serialVersionUID = 1L;

            @Override
            public void validate(Object value) throws InvalidValueException {
                replacedert value instanceof String;
                if (value == null) {
                    throw new InvalidValueException("The name cannot be blank.");
                }
                // Group names must be unique so that user can distinguish between them (and we can create unique IDs from them)
                for (PDPGroup g : self.groups) {
                    if (group != null && g.getId().equals(group.getId())) {
                        // ignore this group - we may or may not be changing the name
                        continue;
                    }
                    if (g.getName().equals(value.toString())) {
                        throw new InvalidValueException("Name must be unique");
                    }
                }
            }
        });
        this.textName.addTextChangeListener(new TextChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void textChange(TextChangeEvent event) {
                if (event.getText() == null || event.getText().isEmpty()) {
                    self.buttonSave.setEnabled(false);
                } else {
                    self.buttonSave.setEnabled(true);
                }
            }
        });
    }

    protected void initializeTables() {
        this.initializePolicyTable();
        this.initializePIPTable();
    }

    protected void initializePolicyTable() {
        if (this.group == null) {
            this.tablePolicies.setVisible(false);
            return;
        }
        // 
        // GUI properties
        // 
        EditPDPGroupWindow.policyContainer = new PDPPolicyContainer(group);
        this.tablePolicies.setContainerDataSource(EditPDPGroupWindow.policyContainer);
        // , "Description");
        this.tablePolicies.setVisibleColumns("Root", "Name", "Version", "Id");
        this.tablePolicies.setPageLength(EditPDPGroupWindow.policyContainer.size() + 1);
        this.tablePolicies.setSelectable(true);
        this.tablePolicies.setSizeFull();
        /*
		 * Not in this release.
		 * 
		this.tablePolicies.setColumnCollapsingAllowed(true);
		this.tablePolicies.setColumnCollapsed("Description", true);
		//
		// Generated columns
		//
		this.tablePolicies.addGeneratedColumn("Description", new ColumnGenerator() {
			private static final long serialVersionUID = 1L;

			@Override
			public Object generateCell(Table source, Object itemId, Object columnId) {
				TextArea area = new TextArea();
				if (itemId != null && itemId instanceof PDPPolicy) {
					area.setValue(((PDPPolicy)itemId).getDescription());
				}
				area.setNullRepresentation("");
				area.setWidth("100.0%");
				return area;
			}
		});
		*/
        // 
        // Actions
        // 
        this.tablePolicies.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    return new Action[] { ADD_POLICY };
                }
                return new Action[] { ADD_POLICY, REMOVE_POLICY, MAKE_ROOT, MAKE_REFERENCED };
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == ADD_POLICY) {
                    final SelectWorkspacePoliciesWindow policiesWindow = new SelectWorkspacePoliciesWindow();
                    policiesWindow.setCaption("Select Policy to Add");
                    policiesWindow.setModal(true);
                    policiesWindow.addCloseListener(new CloseListener() {

                        private static final long serialVersionUID = 1L;

                        @Override
                        public void windowClose(CloseEvent event) {
                            // 
                            // Did the user hit save?
                            // 
                            if (policiesWindow.isSaved() == false) {
                                return;
                            }
                            // 
                            // Get the selected policy
                            // 
                            StdPDPPolicy selectedPolicy = policiesWindow.getSelectedPolicy();
                            if (selectedPolicy != null) {
                                // do not allow multiple copies of same policy
                                for (Object existingPolicy : EditPDPGroupWindow.policyContainer.gereplacedemIds()) {
                                    if (selectedPolicy.getId().equals(((PDPPolicy) existingPolicy).getId())) {
                                        AdminNotification.warn("Cannot re-add Policy with the same ID (i.e. same Name, source Sub-Domain and Version)");
                                        return;
                                    }
                                }
                                // copy policy to PAP
                                try {
                                    papEngine.copyPolicy(selectedPolicy, self.group);
                                } catch (PAPException e) {
                                    AdminNotification.warn("Unable to copy Policy '" + selectedPolicy.getPolicyId() + "' to PAP: " + e.getMessage());
                                    return;
                                }
                                // add Policy to group
                                EditPDPGroupWindow.policyContainer.addItem(selectedPolicy);
                                self.markAsDirtyRecursive();
                            }
                        }
                    });
                    policiesWindow.center();
                    UI.getCurrent().addWindow(policiesWindow);
                    return;
                }
                if (action == REMOVE_POLICY) {
                    replacedert target != null;
                    PDPPolicy policy = (PDPPolicy) target;
                    EditPDPGroupWindow.policyContainer.removeItem(policy);
                    self.markAsDirtyRecursive();
                    return;
                }
                if (action == MAKE_ROOT) {
                    replacedert target != null;
                    replacedert target instanceof StdPDPPolicy;
                    StdPDPPolicy policy = (StdPDPPolicy) target;
                    EditPDPGroupWindow.policyContainer.gereplacedem(policy).gereplacedemProperty("Root").setValue(true);
                    self.markAsDirtyRecursive();
                    return;
                }
                if (action == MAKE_REFERENCED) {
                    replacedert target != null;
                    replacedert target instanceof StdPDPPolicy;
                    StdPDPPolicy policy = (StdPDPPolicy) target;
                    EditPDPGroupWindow.policyContainer.gereplacedem(policy).gereplacedemProperty("Root").setValue(false);
                    self.markAsDirtyRecursive();
                    return;
                }
                AdminNotification.error("Unrecognized action '" + action + "' on target '" + target + "'");
            }
        });
    }

    protected void initializePIPTable() {
        if (this.group == null) {
            this.tablePIP.setVisible(false);
            return;
        }
        // 
        // Setup data source and GUI properties
        // 
        this.pipContainer = new PDPPIPContainer(group);
        this.tablePIP.setContainerDataSource(this.pipContainer);
        this.tablePIP.setPageLength(this.pipContainer.size() + 2);
        this.tablePIP.setSelectable(true);
        this.tablePIP.setSizeFull();
        // 
        // Add the action handler
        // 
        this.tablePIP.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                return new Action[] { EDIT_CONFIG };
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == EDIT_CONFIG) {
                    self.editPIPConfiguration();
                    return;
                }
            }
        });
    }

    protected void editPIPConfiguration() {
        final SelectPIPConfigurationWindow window = new SelectPIPConfigurationWindow(this.group);
        window.setCaption("Select PIP Configurations");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user click save button?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Yes - save the PIP configuration
                // 
                Set<PDPPIPConfig> configs = window.getSelectedConfigs();
                replacedert configs != null;
                self.group.setPipConfigs(configs);
                // 
                // Update the container
                // 
                self.pipContainer.refresh();
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void initializeButton() {
        this.buttonSave.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                try {
                    // 
                    // Validate
                    // 
                    self.textName.commit();
                    // 
                    // All good save everything
                    // 
                    self.doSave();
                    // 
                    // mark ourselves as saved
                    // 
                    self.isSaved = true;
                    // 
                    // Close the window
                    // 
                    self.close();
                } catch (InvalidValueException e) {
                // NOPMD
                // 
                // Ignore, Vaadin will display our message
                // 
                }
            }
        });
    }

    protected void doSave() {
        if (this.group == null) {
            return;
        }
        StdPDPGroup updatedGroupObject = new StdPDPGroup(this.group.getId(), this.group.isDefaultGroup(), this.textName.getValue(), this.textDescription.getValue(), null);
        // replace the original set of Policies with the set from the container (possibly modified by the user)
        Set<PDPPolicy> changedPolicies = new HashSet<PDPPolicy>();
        changedPolicies.addAll((Collection<PDPPolicy>) EditPDPGroupWindow.policyContainer.gereplacedemIds());
        updatedGroupObject.setPolicies(changedPolicies);
        updatedGroupObject.setPdps(this.group.getPdps());
        // replace the original set of PIP Configs with the set from the container
        // TODO - get PIP Configs from a container used to support editing
        // selfPDPObject.getPipConfigs().clear();
        // selfPDPObject.getPipConfigs().addAll(containerGroup.getPipConfigs());
        updatedGroupObject.setPipConfigs(this.group.getPipConfigs());
        // copy those things that the user cannot change from the original to the new object
        updatedGroupObject.setStatus(this.group.getStatus());
        this.updatedObject = updatedGroupObject;
    }

    public boolean isSaved() {
        return this.isSaved;
    }

    public String getGroupName() {
        return this.textName.getValue();
    }

    public String getGroupDescription() {
        return this.textDescription.getValue();
    }

    public PDPGroup getUpdatedObject() {
        return this.updatedObject;
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("100.0%");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // textName
        textName = new TextField();
        textName.setCaption("Group Name");
        textName.setImmediate(false);
        textName.setWidth("-1px");
        textName.setHeight("-1px");
        textName.setRequired(true);
        mainLayout.addComponent(textName);
        // textDescription
        textDescription = new TextArea();
        textDescription.setCaption("Group Description");
        textDescription.setImmediate(false);
        textDescription.setWidth("100.0%");
        textDescription.setHeight("-1px");
        textDescription.setNullSettingAllowed(true);
        mainLayout.addComponent(textDescription);
        mainLayout.setExpandRatio(textDescription, 1.0f);
        // tablePolicies
        tablePolicies = new Table();
        tablePolicies.setCaption("Policies");
        tablePolicies.setImmediate(false);
        tablePolicies.setWidth("-1px");
        tablePolicies.setHeight("-1px");
        mainLayout.addComponent(tablePolicies);
        mainLayout.setExpandRatio(tablePolicies, 1.0f);
        // tablePIP
        tablePIP = new Table();
        tablePIP.setCaption("PIP Configurations");
        tablePIP.setImmediate(false);
        tablePIP.setWidth("-1px");
        tablePIP.setHeight("-1px");
        mainLayout.addComponent(tablePIP);
        mainLayout.setExpandRatio(tablePIP, 1.0f);
        // buttonSave
        buttonSave = new Button();
        buttonSave.setCaption("Save");
        buttonSave.setImmediate(true);
        buttonSave.setWidth("-1px");
        buttonSave.setHeight("-1px");
        mainLayout.addComponent(buttonSave);
        mainLayout.setComponentAlignment(buttonSave, new Alignment(48));
        return mainLayout;
    }
}

16 View Complete Implementation : EditPDPGroupWindow.java
Copyright MIT License
Author : att
public clreplaced EditPDPGroupWindow extends Window {

    /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
    @AutoGenerated
    private VerticalLayout mainLayout;

    @AutoGenerated
    private Button buttonSave;

    @AutoGenerated
    private Table tablePIP;

    @AutoGenerated
    private Table tablePolicies;

    @AutoGenerated
    private TextArea textDescription;

    @AutoGenerated
    private TextField textName;

    private static final Action ADD_POLICY = new Action("Add New Policy");

    private static final Action REMOVE_POLICY = new Action("Remove Policy");

    private static final Action MAKE_ROOT = new Action("Make Root");

    private static final Action MAKE_REFERENCED = new Action("Make Referenced");

    private static final Action EDIT_CONFIG = new Action("Edit Configurations");

    // 
    // ?? Why is this static?
    // 
    private static PDPPolicyContainer policyContainer;

    private PDPPIPContainer pipContainer;

    /**
     */
    private static final long serialVersionUID = 1L;

    private final EditPDPGroupWindow self = this;

    private final StdPDPGroup group;

    private boolean isSaved = false;

    // this is the version that contains all of the edits made by the user.
    // it may be a copy of the original object (edited) or a new one.
    private StdPDPGroup updatedObject;

    private PAPEngine papEngine;

    private List<PDPGroup> groups;

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     * @param group
     * @param list
     * @param engine
     */
    public EditPDPGroupWindow(StdPDPGroup group, List<PDPGroup> list, PAPEngine engine) {
        buildMainLayout();
        // setCompositionRoot(mainLayout);
        setContent(mainLayout);
        // 
        // Save pointers
        // 
        this.group = group;
        this.groups = list;
        this.papEngine = engine;
        // 
        // Initialize
        // 
        this.initialize();
        // 
        // Shortcuts
        // 
        this.setCloseShortcut(KeyCode.ESCAPE);
        this.buttonSave.setClickShortcut(KeyCode.ENTER);
        // 
        // Focus
        // 
        this.textName.focus();
    }

    protected void initialize() {
        this.initializeText();
        this.initializeButton();
        this.initializeTables();
    }

    protected void initializeText() {
        this.textName.setNullRepresentation("");
        this.textDescription.setNullRepresentation("");
        if (this.group != null) {
            this.textName.setValue(this.group.getName());
            this.textDescription.setValue(this.group.getDescription());
        }
        // 
        // Validation
        // 
        this.textName.addValidator(new Validator() {

            private static final long serialVersionUID = 1L;

            @Override
            public void validate(Object value) throws InvalidValueException {
                replacedert (value instanceof String);
                if (value == null) {
                    throw new InvalidValueException("The name cannot be blank.");
                }
                // Group names must be unique so that user can distinguish between them (and we can create unique IDs from them)
                for (PDPGroup g : self.groups) {
                    if (group != null && g.getId().equals(group.getId())) {
                        // ignore this group - we may or may not be changing the name
                        continue;
                    }
                    if (g.getName().equals(value.toString())) {
                        throw new InvalidValueException("Name must be unique");
                    }
                }
            }
        });
        this.textName.addTextChangeListener(new TextChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void textChange(TextChangeEvent event) {
                if (event.getText() == null || event.getText().isEmpty()) {
                    self.buttonSave.setEnabled(false);
                } else {
                    self.buttonSave.setEnabled(true);
                }
            }
        });
    }

    protected void initializeTables() {
        this.initializePolicyTable();
        this.initializePIPTable();
    }

    protected void initializePolicyTable() {
        if (this.group == null) {
            this.tablePolicies.setVisible(false);
            return;
        }
        // 
        // GUI properties
        // 
        EditPDPGroupWindow.policyContainer = new PDPPolicyContainer(group);
        this.tablePolicies.setContainerDataSource(EditPDPGroupWindow.policyContainer);
        // , "Description");
        this.tablePolicies.setVisibleColumns("Root", "Name", "Version", "Id");
        this.tablePolicies.setPageLength(EditPDPGroupWindow.policyContainer.size() + 1);
        this.tablePolicies.setSelectable(true);
        this.tablePolicies.setSizeFull();
        /*
		 * Not in this release.
		 * 
		this.tablePolicies.setColumnCollapsingAllowed(true);
		this.tablePolicies.setColumnCollapsed("Description", true);
		//
		// Generated columns
		//
		this.tablePolicies.addGeneratedColumn("Description", new ColumnGenerator() {
			private static final long serialVersionUID = 1L;

			@Override
			public Object generateCell(Table source, Object itemId, Object columnId) {
				TextArea area = new TextArea();
				if (itemId != null && itemId instanceof PDPPolicy) {
					area.setValue(((PDPPolicy)itemId).getDescription());
				}
				area.setNullRepresentation("");
				area.setWidth("100.0%");
				return area;
			}
		});
		*/
        // 
        // Actions
        // 
        this.tablePolicies.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                if (target == null) {
                    return new Action[] { ADD_POLICY };
                }
                return new Action[] { ADD_POLICY, REMOVE_POLICY, MAKE_ROOT, MAKE_REFERENCED };
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == ADD_POLICY) {
                    final SelectWorkspacePoliciesWindow policiesWindow = new SelectWorkspacePoliciesWindow();
                    policiesWindow.setCaption("Select Policy to Add");
                    policiesWindow.setModal(true);
                    policiesWindow.addCloseListener(new CloseListener() {

                        private static final long serialVersionUID = 1L;

                        @Override
                        public void windowClose(CloseEvent event) {
                            // 
                            // Did the user hit save?
                            // 
                            if (policiesWindow.isSaved() == false) {
                                return;
                            }
                            // 
                            // Get the selected policy
                            // 
                            StdPDPPolicy selectedPolicy = policiesWindow.getSelectedPolicy();
                            if (selectedPolicy != null) {
                                // do not allow multiple copies of same policy
                                for (Object existingPolicy : EditPDPGroupWindow.policyContainer.gereplacedemIds()) {
                                    if (selectedPolicy.getId().equals(((PDPPolicy) existingPolicy).getId())) {
                                        AdminNotification.warn("Cannot re-add Policy with the same ID (i.e. same Name, source Sub-Domain and Version)");
                                        return;
                                    }
                                }
                                // copy policy to PAP
                                try {
                                    papEngine.copyPolicy(selectedPolicy, self.group);
                                } catch (PAPException e) {
                                    AdminNotification.warn("Unable to copy Policy '" + selectedPolicy.getPolicyId() + "' to PAP: " + e.getMessage());
                                    return;
                                }
                                // add Policy to group
                                EditPDPGroupWindow.policyContainer.addItem(selectedPolicy);
                                self.markAsDirtyRecursive();
                            }
                        }
                    });
                    policiesWindow.center();
                    UI.getCurrent().addWindow(policiesWindow);
                    return;
                }
                if (action == REMOVE_POLICY) {
                    replacedert (target != null);
                    PDPPolicy policy = (PDPPolicy) target;
                    EditPDPGroupWindow.policyContainer.removeItem(policy);
                    self.markAsDirtyRecursive();
                    return;
                }
                if (action == MAKE_ROOT) {
                    replacedert (target != null);
                    replacedert (target instanceof StdPDPPolicy);
                    StdPDPPolicy policy = (StdPDPPolicy) target;
                    EditPDPGroupWindow.policyContainer.gereplacedem(policy).gereplacedemProperty("Root").setValue(true);
                    self.markAsDirtyRecursive();
                    return;
                }
                if (action == MAKE_REFERENCED) {
                    replacedert (target != null);
                    replacedert (target instanceof StdPDPPolicy);
                    StdPDPPolicy policy = (StdPDPPolicy) target;
                    EditPDPGroupWindow.policyContainer.gereplacedem(policy).gereplacedemProperty("Root").setValue(false);
                    self.markAsDirtyRecursive();
                    return;
                }
                AdminNotification.error("Unrecognized action '" + action + "' on target '" + target + "'");
            }
        });
    }

    protected void initializePIPTable() {
        if (this.group == null) {
            this.tablePIP.setVisible(false);
            return;
        }
        // 
        // Setup data source and GUI properties
        // 
        this.pipContainer = new PDPPIPContainer(group);
        this.tablePIP.setContainerDataSource(this.pipContainer);
        this.tablePIP.setPageLength(this.pipContainer.size() + 2);
        this.tablePIP.setSelectable(true);
        this.tablePIP.setSizeFull();
        // 
        // Add the action handler
        // 
        this.tablePIP.addActionHandler(new Handler() {

            private static final long serialVersionUID = 1L;

            @Override
            public Action[] getActions(Object target, Object sender) {
                return new Action[] { EDIT_CONFIG };
            }

            @Override
            public void handleAction(Action action, Object sender, Object target) {
                if (action == EDIT_CONFIG) {
                    self.editPIPConfiguration();
                    return;
                }
            }
        });
    }

    protected void editPIPConfiguration() {
        final SelectPIPConfigurationWindow window = new SelectPIPConfigurationWindow(this.group);
        window.setCaption("Select PIP Configurations");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                // 
                // Did the user click save button?
                // 
                if (window.isSaved() == false) {
                    return;
                }
                // 
                // Yes - save the PIP configuration
                // 
                Set<PDPPIPConfig> configs = window.getSelectedConfigs();
                replacedert (configs != null);
                self.group.setPipConfigs(configs);
                // 
                // Update the container
                // 
                self.pipContainer.refresh();
            }
        });
        window.center();
        UI.getCurrent().addWindow(window);
    }

    protected void initializeButton() {
        this.buttonSave.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                try {
                    // 
                    // Validate
                    // 
                    self.textName.commit();
                    // 
                    // All good save everything
                    // 
                    self.doSave();
                    // 
                    // mark ourselves as saved
                    // 
                    self.isSaved = true;
                    // 
                    // Close the window
                    // 
                    self.close();
                } catch (InvalidValueException e) {
                // 
                // Ignore, Vaadin will display our message
                // 
                }
            }
        });
    }

    protected void doSave() {
        if (this.group == null) {
            return;
        }
        StdPDPGroup updatedGroupObject = new StdPDPGroup(this.group.getId(), this.group.isDefaultGroup(), this.textName.getValue(), this.textDescription.getValue(), null);
        // replace the original set of Policies with the set from the container (possibly modified by the user)
        Set<PDPPolicy> changedPolicies = new HashSet<PDPPolicy>();
        changedPolicies.addAll((Collection<PDPPolicy>) EditPDPGroupWindow.policyContainer.gereplacedemIds());
        updatedGroupObject.setPolicies(changedPolicies);
        updatedGroupObject.setPdps(this.group.getPdps());
        // replace the original set of PIP Configs with the set from the container
        // TODO - get PIP Configs from a container used to support editing
        // selfPDPObject.getPipConfigs().clear();
        // selfPDPObject.getPipConfigs().addAll(containerGroup.getPipConfigs());
        updatedGroupObject.setPipConfigs(this.group.getPipConfigs());
        // copy those things that the user cannot change from the original to the new object
        updatedGroupObject.setStatus(this.group.getStatus());
        this.updatedObject = updatedGroupObject;
    }

    public boolean isSaved() {
        return this.isSaved;
    }

    public String getGroupName() {
        return this.textName.getValue();
    }

    public String getGroupDescription() {
        return this.textDescription.getValue();
    }

    public PDPGroup getUpdatedObject() {
        return this.updatedObject;
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("100.0%");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // textName
        textName = new TextField();
        textName.setCaption("Group Name");
        textName.setImmediate(false);
        textName.setWidth("-1px");
        textName.setHeight("-1px");
        textName.setRequired(true);
        mainLayout.addComponent(textName);
        // textDescription
        textDescription = new TextArea();
        textDescription.setCaption("Group Description");
        textDescription.setImmediate(false);
        textDescription.setWidth("100.0%");
        textDescription.setHeight("-1px");
        textDescription.setNullSettingAllowed(true);
        mainLayout.addComponent(textDescription);
        mainLayout.setExpandRatio(textDescription, 1.0f);
        // tablePolicies
        tablePolicies = new Table();
        tablePolicies.setCaption("Policies");
        tablePolicies.setImmediate(false);
        tablePolicies.setWidth("-1px");
        tablePolicies.setHeight("-1px");
        mainLayout.addComponent(tablePolicies);
        mainLayout.setExpandRatio(tablePolicies, 1.0f);
        // tablePIP
        tablePIP = new Table();
        tablePIP.setCaption("PIP Configurations");
        tablePIP.setImmediate(false);
        tablePIP.setWidth("-1px");
        tablePIP.setHeight("-1px");
        mainLayout.addComponent(tablePIP);
        mainLayout.setExpandRatio(tablePIP, 1.0f);
        // buttonSave
        buttonSave = new Button();
        buttonSave.setCaption("Save");
        buttonSave.setImmediate(true);
        buttonSave.setWidth("-1px");
        buttonSave.setHeight("-1px");
        mainLayout.addComponent(buttonSave);
        mainLayout.setComponentAlignment(buttonSave, new Alignment(48));
        return mainLayout;
    }
}

16 View Complete Implementation : MainTabSheetActionHandler.java
Copyright Apache License 2.0
Author : cuba-platform
@Override
public void handleAction(Action action, Object sender, Object target) {
    TabSheetBehaviour tabSheetBehaviour = tabSheet.getTabSheetBehaviour();
    if (initialized) {
        if (closeCurrentTab == action) {
            tabSheetBehaviour.closeTab((com.vaadin.ui.Component) target);
        } else if (closeOtherTabs == action) {
            tabSheetBehaviour.closeOtherTabs((com.vaadin.ui.Component) target);
        } else if (closeAllTabs == action) {
            tabSheetBehaviour.closeAllTabs();
        } else if (showInfo == action) {
            showInfo(target);
        } else if (replacedyzeLayout == action) {
            replacedyzeLayout(target);
        } else if (saveSettings == action) {
            saveSettings(target);
        } else if (restoreToDefaults == action) {
            restoreToDefaults(target);
        }
    }
}