com.vaadin.v7.data.util.BeanItemContainer - java examples

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

48 Examples 7

19 View Complete Implementation : CmsQueuedTable.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Clreplaced for Vaadin Table showing history queue elements.<p>
 */
public clreplaced CmsQueuedTable extends Table {

    /**
     * Row bean for the bean item container.
     */
    public clreplaced Row {

        /**
         * The underlying job.
         */
        private CmsPublishJobBase m_job;

        /**
         * Cached list of resources.
         */
        private List<?> m_resourceList;

        /**
         * The icon.
         */
        private Resource m_icon;

        /**
         * Cached state.
         */
        private String m_state;

        /**
         * Used for initial sorting.
         */
        private int m_sortType;

        /**
         * Creates a new instance.
         *
         * @param job the underlying publish job
         */
        public Row(CmsPublishJobBase job, int sortType) {
            m_job = job;
            m_sortType = sortType;
            if (job == null) {
                throw new IllegalArgumentException("Job must not be null.");
            }
        }

        /**
         * Gets the file count.
         *
         * @return the file count
         */
        public int getFilesCount() {
            return m_job.getSize();
        }

        /**
         * Gets the icon.
         *
         * @return the icon
         */
        public Resource getIcon() {
            if (m_icon == null) {
                m_icon = new CmsCssIcon(OpenCmsTheme.ICON_PUBLISH);
            }
            return m_icon;
        }

        /**
         * Gets the publish job.
         *
         * @return the publish job
         */
        public CmsPublishJobBase getJob() {
            return m_job;
        }

        /**
         * Gets the project name.
         *
         * @return the project name
         */
        public String getProject() {
            return m_job.getProjectName().replace("/", "/");
        }

        /**
         * Gets the resource list.
         *
         * @return the resource list
         */
        public List<?> getResourceList() {
            if (m_resourceList == null) {
                if (m_job instanceof CmsPublishJobFinished) {
                    try {
                        m_resourceList = A_CmsUI.getCmsObject().readPublishedResources(m_job.getPublishHistoryId());
                    } catch (Exception e) {
                        LOG.error(e.getLocalizedMessage(), e);
                    }
                } else if (m_job instanceof CmsPublishJobEnqueued) {
                    m_resourceList = ((CmsPublishJobEnqueued) m_job).getOriginalPublishList().getAllResources();
                } else if (m_job instanceof CmsPublishJobRunning) {
                    CmsPublishList publishList = ((CmsPublishJobRunning) m_job).getOriginalPublishList();
                    if (publishList == null) {
                        // publish job has already finished, can't get the publish list
                        m_resourceList = Collections.emptyList();
                    } else {
                        m_resourceList = publishList.getAllResources();
                    }
                }
            }
            return m_resourceList;
        }

        /**
         * Gets the resource list as a string.
         *
         * @return the resource list string representation
         */
        public String getResources() {
            List<?> resources = getResourceList();
            if (resources == null) {
                return "";
            }
            return CmsResourcesCellGenerator.formatResourcesForTable(resources, 50);
        }

        /**
         * Used for initial sorting.
         *
         * @return the sort type
         */
        public int getSortType() {
            return m_sortType;
        }

        /**
         * Gets the start date of the job.
         *
         * @return the start date
         */
        public Date getStart() {
            if (m_job instanceof CmsPublishJobFinished) {
                return new Date(((CmsPublishJobFinished) m_job).getStartTime());
            } else if (m_job instanceof CmsPublishJobRunning) {
                return new Date(((CmsPublishJobRunning) m_job).getStartTime());
            }
            return null;
        }

        /**
         * Gets the job state.
         *
         * @return the job state
         */
        @SuppressWarnings("synthetic-access")
        public String getStatus() {
            if (m_state == null) {
                if (m_job instanceof CmsPublishJobFinished) {
                    m_state = getState((CmsPublishJobFinished) m_job);
                } else if (m_job instanceof CmsPublishJobRunning) {
                    m_state = STATE_RUNNING;
                } else if (m_job instanceof CmsPublishJobEnqueued) {
                    m_state = STATE_ENQUEUE;
                } else {
                    m_state = STATE_ERROR;
                    LOG.error("Invalid job type: " + m_job);
                }
            }
            return m_state;
        }

        /**
         * Gets the user friendly label for the state.
         *
         * @return the user friendly state description
         */
        @SuppressWarnings("synthetic-access")
        public String getStatusLocale() {
            String state = getStatus();
            String key = STATUS_MESSAGES.get(state);
            if (key == null) {
                LOG.error("KEY is null for state " + state);
            }
            return CmsVaadinUtils.getMessageText(key);
        }

        /**
         * Gets the stop date for the job.
         *
         * @return the stop date
         */
        public Date getStop() {
            if (m_job instanceof CmsPublishJobFinished) {
                return new Date(((CmsPublishJobFinished) m_job).getFinishTime());
            }
            return null;
        }

        /**
         * Gets the name of the user who started the job.
         *
         * @return the user name for the job
         */
        public String getUser() {
            return m_job.getUserName(A_CmsUI.getCmsObject());
        }
    }

    /**
     * Menu entry for showing report.<p>
     */
    clreplaced EntryReport implements I_CmsSimpleContextMenuEntry<Set<String>>, I_CmsSimpleContextMenuEntry.I_HasCssStyles {

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object)
         */
        public void executeAction(Set<String> data) {
            showReportDialog(data.iterator().next());
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry.I_HasCssStyles#getStyles()
         */
        public String getStyles() {
            return ValoTheme.LABEL_BOLD;
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getreplacedle(java.util.Locale)
         */
        public String getreplacedle(Locale locale) {
            return CmsVaadinUtils.getMessageText(Messages.GUI_PQUEUE_REPORT_0);
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object)
         */
        public CmsMenuItemVisibilityMode getVisibility(Set<String> data) {
            return (data != null) && (data.size() == 1) ? CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE : CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
        }
    }

    /**
     * Menu entry for showing resources.<p>
     */
    clreplaced EntryResources implements I_CmsSimpleContextMenuEntry<Set<String>> {

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object)
         */
        public void executeAction(Set<String> data) {
            showResourceDialog(data.iterator().next());
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getreplacedle(java.util.Locale)
         */
        public String getreplacedle(Locale locale) {
            return CmsVaadinUtils.getMessageText(Messages.GUI_PQUEUE_RESOURCES_0);
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object)
         */
        public CmsMenuItemVisibilityMode getVisibility(Set<String> data) {
            return (data != null) && (data.size() == 1) ? CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE : CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
        }
    }

    /**
     * Menu entry for option to abort publish job.<p>
     */
    clreplaced EntryStop implements I_CmsSimpleContextMenuEntry<Set<String>>, I_CmsSimpleContextMenuEntry.I_HasCssStyles {

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object)
         */
        public void executeAction(Set<String> data) {
            String jobid = data.iterator().next();
            CmsPublishJobBase job = OpenCms.getPublishManager().getJobByPublishHistoryId(new CmsUUID(jobid));
            if (job instanceof CmsPublishJobEnqueued) {
                try {
                    OpenCms.getPublishManager().abortPublishJob(A_CmsUI.getCmsObject(), (CmsPublishJobEnqueued) job, true);
                    CmsAppWorkplaceUi.get().reload();
                } catch (CmsException e) {
                    LOG.error("Error on aborting publish job.", e);
                }
            }
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry.I_HasCssStyles#getStyles()
         */
        public String getStyles() {
            return ValoTheme.LABEL_BOLD;
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getreplacedle(java.util.Locale)
         */
        public String getreplacedle(Locale locale) {
            return CmsVaadinUtils.getMessageText(Messages.GUI_PQUEUE_STOP_0);
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object)
         */
        public CmsMenuItemVisibilityMode getVisibility(Set<String> data) {
            return (data != null) && (data.size() == 1) ? CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE : CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
        }
    }

    /**
     * Error status icon.
     */
    public static final String ICON_ERROR = "apps/publishqueue/state_error.png";

    /**
     * Ok status icon.
     */
    public static final String ICON_OK = "apps/publishqueue/state_ok.png";

    /**
     * Warning status icon.
     */
    public static final String ICON_WARNINGS = "apps/publishqueue/state_warning.png";

    /**
     * list action id constant.
     */
    public static final String LIST_ACTION_COUNT = "ac";

    /**
     * list action id constant.
     */
    public static final String LIST_ACTION_END = "ae";

    /**
     * list action id constant.
     */
    public static final String LIST_ACTION_PROJECT = "ap";

    /**
     * list action id constant.
     */
    public static final String LIST_ACTION_START = "as";

    /**
     * list action id constant.
     */
    public static final String LIST_ACTION_STATE_ERR = "ate";

    /**
     * list action id constant.
     */
    public static final String LIST_ACTION_STATE_OK = "ato";

    /**
     * list action id constant.
     */
    public static final String LIST_ACTION_VIEW = "av";

    /**
     * list id constant.
     */
    public static final String LIST_ID = "lppq";

    /**
     * The logger for this clreplaced.
     */
    static Log LOG = CmsLog.getLog(CmsQueuedTable.clreplaced.getName());

    /**
     * table column.
     */
    private static final String PROP_FILESCOUNT = "filesCount";

    /**
     * table column.
     */
    private static final String PROP_ICON = "icon";

    /**
     * table column.
     */
    private static final String PROP_PROJECT = "project";

    /**
     * resources column.
     */
    private static final String PROP_RESOURCES = "resources";

    /**
     * table column.
     */
    private static final String PROP_START = "start";

    /**
     * table column.
     */
    private static final String PROP_STATUS = "status";

    private static final String PROP_SORT_TYPE = "sortType";

    /**
     * table column.
     */
    private static final String PROP_STATUS_LOCALE = "statusLocale";

    /**
     * table column.
     */
    private static final String PROP_STOP = "stop";

    /**
     * table column.
     */
    private static final String PROP_USER = "user";

    /**
     * vaadin serial id.
     */
    private static final long serialVersionUID = 7507300060974348158L;

    /**
     * Publish job state constant.
     */
    private static final String STATE_ERROR = "error";

    /**
     * Publish job state constant.
     */
    private static final String STATE_OK = "ok";

    /**
     * Publish job state constant.
     */
    private static final String STATE_WARNING = "warning";

    /**
     * Publish job state constant.
     */
    private static final String STATE_RUNNING = "running";

    /**
     * Publish job state constant.
     */
    private static final String STATE_ENQUEUE = "queue";

    /**
     * Publish job state constant.
     */
    private static final Map<String, String> STATUS_MESSAGES = getStatusMap();

    /**
     * Container.
     */
    BeanItemContainer<Row> m_container;

    /**
     * Instance of calling clreplaced.
     */
    CmsPublishQueue m_manager;

    /**
     * The context menu.
     */
    CmsContextMenu m_menu;

    /**
     * The available menu entries.
     */
    private List<I_CmsSimpleContextMenuEntry<Set<String>>> m_menuEntries;

    /**
     * The available menu entries.
     */
    private List<I_CmsSimpleContextMenuEntry<Set<String>>> m_menuEntriesEnq;

    /**
     * Default constructor.<p>
     *
     * @param manager instance of calling clreplaced
     */
    public CmsQueuedTable(CmsPublishQueue manager) {
        m_manager = manager;
        setSizeFull();
        setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_PQUEUE_PQUEUE_HIST_0));
        m_menu = new CmsContextMenu();
        m_menu.setAsTableContextMenu(this);
        m_container = new BeanItemContainer<Row>(Row.clreplaced);
        setContainerDataSource(m_container);
        // sereplacedemIconPropertyId(PROP_ICON);
        // setRowHeaderMode(RowHeaderMode.ICON_ONLY);
        setColumnHeader(PROP_STATUS_LOCALE, "");
        setColumnHeader(PROP_RESOURCES, CmsVaadinUtils.getMessageText(Messages.GUI_PQUEUE_RESOURCES_0));
        setColumnHeader(PROP_PROJECT, CmsVaadinUtils.getMessageText(Messages.GUI_PQUEUE_PROJECT_0));
        setColumnHeader(PROP_START, CmsVaadinUtils.getMessageText(Messages.GUI_PQUEUE_STARTDATE_0));
        setColumnHeader(PROP_STOP, CmsVaadinUtils.getMessageText(Messages.GUI_PQUEUE_ENDDATE_0));
        setColumnHeader(PROP_USER, CmsVaadinUtils.getMessageText(Messages.GUI_PQUEUE_USER_0));
        setColumnHeader(PROP_FILESCOUNT, CmsVaadinUtils.getMessageText(Messages.GUI_PQUEUE_SIZE_0));
        setVisibleColumns(PROP_STATUS_LOCALE, PROP_PROJECT, PROP_START, PROP_STOP, PROP_USER, PROP_RESOURCES, PROP_FILESCOUNT);
        setColumnWidth(PROP_START, 200);
        setColumnWidth(PROP_STOP, 200);
        setColumnWidth(PROP_RESOURCES, 550);
        sereplacedemIconPropertyId(PROP_ICON);
        setRowHeaderMode(RowHeaderMode.ICON_ONLY);
        setColumnWidth(null, 40);
        setSelectable(true);
        addItemClickListener(new ItemClickListener() {

            /**
             * vaadin serial id.
             */
            private static final long serialVersionUID = -7394790444104979594L;

            public void itemClick(ItemClickEvent event) {
                onItemClick(event, event.gereplacedemId(), event.getPropertyId());
            }
        });
        setCellStyleGenerator(new CellStyleGenerator() {

            private static final long serialVersionUID = 1L;

            public String getStyle(Table source, Object itemId, Object propertyId) {
                if (PROP_RESOURCES.equals(propertyId)) {
                    return " " + OpenCmsTheme.HOVER_COLUMN;
                }
                if (PROP_PROJECT.equals(propertyId) & !(itemId instanceof CmsPublishJobEnqueued)) {
                    return " " + OpenCmsTheme.HOVER_COLUMN;
                }
                if (PROP_STATUS_LOCALE.equals(propertyId)) {
                    if (STATE_OK.equals(source.gereplacedem(itemId).gereplacedemProperty(PROP_STATUS).getValue())) {
                        return OpenCmsTheme.TABLE_COLUMN_BOX_GREEN;
                    }
                    if (STATE_WARNING.equals(source.gereplacedem(itemId).gereplacedemProperty(PROP_STATUS).getValue())) {
                        return OpenCmsTheme.TABLE_COLUMN_BOX_ORANGE;
                    }
                    if (STATE_ERROR.equals(source.gereplacedem(itemId).gereplacedemProperty(PROP_STATUS).getValue())) {
                        return OpenCmsTheme.TABLE_COLUMN_BOX_RED;
                    }
                    if (STATE_RUNNING.equals(source.gereplacedem(itemId).gereplacedemProperty(PROP_STATUS).getValue())) {
                        return OpenCmsTheme.TABLE_COLUMN_BOX_DARKGRAY;
                    }
                    if (STATE_ENQUEUE.equals(source.gereplacedem(itemId).gereplacedemProperty(PROP_STATUS).getValue())) {
                        return OpenCmsTheme.TABLE_COLUMN_BOX_GRAY;
                    }
                }
                return null;
            }
        });
        // addGeneratedColumn(PROP_RESOURCES, new CmsResourcesCellGenerator(50));
        loadJobs();
    }

    /**
     * Returns the status message map.<p>
     *
     * @return the status message map
     */
    private static Map<String, String> getStatusMap() {
        Map<String, String> map = new HashMap<String, String>();
        map.put(STATE_OK, Messages.GUI_PQUEUE_STATUS_OK_0);
        map.put(STATE_WARNING, Messages.GUI_PQUEUE_STATUS_WARNING_0);
        map.put(STATE_ERROR, Messages.GUI_PQUEUE_STATUS_ERROR_0);
        map.put(STATE_RUNNING, Messages.GUI_PQUEUE_STATUS_RUNNING_0);
        map.put(STATE_ENQUEUE, Messages.GUI_PQUEUE_STATUS_ENQUEUE_0);
        return map;
    }

    /**
     * Filters the table according to given search string.<p>
     *
     * @param search string to be looked for.
     */
    public void filterTable(String search) {
        m_container.removeAllContainerFilters();
        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(search)) {
            m_container.addContainerFilter(new Or(new SimpleStringFilter(PROP_USER, search, true, false), new SimpleStringFilter(PROP_RESOURCES, search, true, false), new SimpleStringFilter(PROP_PROJECT, search, true, false)));
        }
    }

    /**
     * Show report dialog.<p>
     *
     * @param jobid to show report for
     */
    protected void showReportDialog(String jobid) {
        CmsPublishReport pReport = new CmsPublishReport(jobid);
        final Window window = CmsBasicDialog.prepareWindow(DialogWidth.wide);
        CmsBasicDialog dialog = new CmsBasicDialog();
        dialog.addButton(new Button(CmsVaadinUtils.getMessageText(org.opencms.workplace.Messages.GUI_DIALOG_BUTTON_CLOSE_0), new com.vaadin.ui.Button.ClickListener() {

            private static final long serialVersionUID = -4216949392648631634L;

            public void buttonClick(com.vaadin.ui.Button.ClickEvent event) {
                window.close();
            }
        }), true);
        dialog.setContent(pReport);
        window.setContent(dialog);
        window.setCaption(pReport.getCaption());
        A_CmsUI.get().addWindow(window);
    }

    /**
     * Show resource dialog.<p>
     *
     * @param jobid to show resources for
     */
    protected void showResourceDialog(String jobid) {
        CmsPublishResources pResources = new CmsPublishResources(jobid);
        final Window window = CmsBasicDialog.prepareWindow(DialogWidth.wide);
        CmsBasicDialog dialog = new CmsBasicDialog();
        dialog.addButton(new Button(CmsVaadinUtils.getMessageText(org.opencms.workplace.Messages.GUI_DIALOG_BUTTON_CLOSE_0), new com.vaadin.ui.Button.ClickListener() {

            private static final long serialVersionUID = -4216949392648631634L;

            public void buttonClick(com.vaadin.ui.Button.ClickEvent event) {
                window.close();
            }
        }), true);
        dialog.setContent(pResources);
        window.setContent(dialog);
        window.setCaption(pResources.getCaption());
        A_CmsUI.get().addWindow(window);
    }

    /**
     * Returns the available menu entries.<p>
     *
     * @return the menu entries
     */
    List<I_CmsSimpleContextMenuEntry<Set<String>>> getMenuEntries() {
        if (getValue() instanceof CmsPublishJobEnqueued) {
            if (m_menuEntriesEnq == null) {
                m_menuEntriesEnq = new ArrayList<I_CmsSimpleContextMenuEntry<Set<String>>>();
                m_menuEntriesEnq.add(new EntryStop());
                m_menuEntriesEnq.add(new EntryResources());
            }
            return m_menuEntriesEnq;
        }
        if (m_menuEntries == null) {
            m_menuEntries = new ArrayList<I_CmsSimpleContextMenuEntry<Set<String>>>();
            m_menuEntries.add(new EntryReport());
            m_menuEntries.add(new EntryResources());
        }
        return m_menuEntries;
    }

    /**
     * Handles the table item clicks, including clicks on images inside of a table item.<p>
     *
     * @param event the click event
     * @param itemId of the clicked row
     * @param propertyId column id
     */
    void onItemClick(MouseEvents.ClickEvent event, Object itemId, Object propertyId) {
        setValue(null);
        select(itemId);
        if (event.getButton().equals(MouseButton.RIGHT) || (propertyId == null)) {
            m_menu.setEntries(getMenuEntries(), Collections.singleton(((((Row) getValue()).getJob()).getPublishHistoryId()).getStringValue()));
            m_menu.openForTable(event, itemId, propertyId, CmsQueuedTable.this);
        } else if (event.getButton().equals(MouseButton.LEFT) && PROP_RESOURCES.equals(propertyId)) {
            showResourceDialog((((Row) getValue()).getJob()).getPublishHistoryId().getStringValue());
        } else if (event.getButton().equals(MouseButton.LEFT) && PROP_PROJECT.equals(propertyId)) {
            if (!(getValue() instanceof CmsPublishJobEnqueued)) {
                showReportDialog(((((Row) getValue()).getJob()).getPublishHistoryId().getStringValue()));
            }
        }
    }

    /**
     * Returns the state of the given publish job.<p>
     *
     * @param publishJob the publish job to get the state for
     * @return the state of the given publish job
     */
    private String getState(CmsPublishJobFinished publishJob) {
        byte[] reportBytes = null;
        try {
            reportBytes = OpenCms.getPublishManager().getReportContents(publishJob);
        } catch (CmsException e) {
            // Can't read report -> error
            return STATE_ERROR;
        }
        if (reportBytes != null) {
            String report = new String(reportBytes);
            if (report.indexOf("<span clreplaced='err'>") > -1) {
                // Report contains error span
                return STATE_ERROR;
            }
            if (report.indexOf("<span clreplaced='warn'>") > -1) {
                // Report contains warning span
                return STATE_WARNING;
            }
        }
        // no warning or error state detected -> ok
        return STATE_OK;
    }

    /**
     * Fills the table with finished publish jobs.<p>
     */
    private void loadJobs() {
        List<CmsPublishJobFinished> publishJobs;
        if (OpenCms.getRoleManager().hasRole(A_CmsUI.getCmsObject(), CmsRole.ROOT_ADMIN)) {
            publishJobs = OpenCms.getPublishManager().getPublishHistory();
        } else {
            publishJobs = OpenCms.getPublishManager().getPublishHistory(A_CmsUI.getCmsObject().getRequestContext().getCurrentUser());
        }
        for (CmsPublishJobFinished job : publishJobs) {
            m_container.addBean(new Row(job, 0));
        }
        // Sort table according to start time of jobs
        m_container.sort(new String[] { PROP_START }, new boolean[] { false });
        List<CmsPublishJobBase> jobs = new ArrayList<CmsPublishJobBase>();
        // a) running jobs
        if (OpenCms.getPublishManager().isRunning()) {
            CmsPublishJobRunning currentJob = OpenCms.getPublishManager().getCurrentPublishJob();
            if (currentJob != null) {
                m_container.addBean(new Row(currentJob, 1));
            }
        }
        int i = 0;
        for (CmsPublishJobBase job : OpenCms.getPublishManager().getPublishQueue()) {
            m_container.addBean(new Row(job, 2 + i));
            i += 1;
        }
        m_container.sort(new String[] { PROP_SORT_TYPE, PROP_START }, new boolean[] { false, false });
    }
}

19 View Complete Implementation : CmsJobTable.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Table used to display scheduled jobs, together with buttons for modifying the jobs.<p>
 * The columns containing the buttons are implemented as generated columns.
 */
public clreplaced CmsJobTable extends Table {

    /**
     * Property columns of table, including their Messages for header.<p>
     */
    protected enum TableProperty {

        /**
         * Clreplaced name column.
         */
        clreplacedName("clreplacedName", org.opencms.workplace.tools.scheduler.Messages.GUI_JOBS_LIST_COL_CLreplaced_0),
        /**
         * icon column.
         */
        icon("icon", null),
        /**
         * last execution date column.
         */
        lastExecution("lastExecution", org.opencms.workplace.tools.scheduler.Messages.GUI_JOBS_LIST_COL_LASTEXE_0),
        /**
         * Name column.
         */
        name("name", org.opencms.workplace.tools.scheduler.Messages.GUI_JOBS_LIST_COL_NAME_0),
        /**
         * next execution date column.
         */
        nextExecution("nextExecution", org.opencms.workplace.tools.scheduler.Messages.GUI_JOBS_LIST_COL_NEXTEXE_0);

        /**
         * Message for the header.
         */
        private String m_header;

        /**
         * Name of column.
         */
        private String m_name;

        /**
         * private constructor.<p>
         *
         * @param propName name of property
         * @param header message
         */
        private TableProperty(String propName, String header) {
            m_header = header;
            m_name = propName;
        }

        /**
         * returns property from it's name used for table column ids.<p>
         *
         * @param propName to looked up
         * @return the TableProperty
         */
        static TableProperty get(String propName) {
            for (TableProperty prop : TableProperty.values()) {
                if (prop.toString().equals(propName)) {
                    return prop;
                }
            }
            return null;
        }

        /**
         * Returns all columns with header.<p>
         *
         * @return set of TableProperty
         */
        static Set<TableProperty> withHeader() {
            Set<TableProperty> ret = new HashSet<TableProperty>();
            for (TableProperty prop : TableProperty.values()) {
                if (prop.getMessageKey() != null) {
                    ret.add(prop);
                }
            }
            return ret;
        }

        /**
         * @see java.lang.Enum#toString()
         */
        @Override
        public String toString() {
            return m_name;
        }

        /**
         * Returns the message key.<p>
         *
         * @return message
         */
        String getMessageKey() {
            return m_header;
        }
    }

    /**
     * Enum representing the actions for which buttons exist in the table rows.<p>
     */
    enum Action {

        /**
         * Enable / disable.
         */
        activation(org.opencms.workplace.tools.scheduler.Messages.GUI_JOBS_LIST_ACTION_MACTIVATE_NAME_0, org.opencms.workplace.tools.scheduler.Messages.GUI_JOBS_LIST_ACTION_MDEACTIVATE_NAME_0),
        /**
         * Create new job from template.
         */
        copy(org.opencms.workplace.tools.scheduler.Messages.GUI_JOBS_LIST_ACTION_COPY_NAME_0, ""),
        /**
         * Deletes the job.
         */
        delete(org.opencms.workplace.tools.scheduler.Messages.GUI_JOBS_LIST_ACTION_DELETE_NAME_0, ""),
        /**
         * Edits the job.
         */
        /**
         * Message constant for key in the resource bundle.
         */
        edit(org.opencms.workplace.tools.scheduler.Messages.GUI_JOBS_LIST_ACTION_EDIT_NAME_0, ""),
        /**
         * Executes the job immediately.
         */
        run(org.opencms.workplace.tools.scheduler.Messages.GUI_JOBS_LIST_ACTION_EXECUTE_NAME_0, "");

        /**
         * The message key.
         */
        private String m_key;

        /**
         * The message key for activated case.
         */
        private String m_keyActivated;

        /**
         * Creates a new action.<p>
         *
         * @param key the message key for the action
         * @param activatedKey an (optional) message key
         */
        private Action(String key, String activatedKey) {
            m_key = key;
            m_keyActivated = activatedKey;
        }

        /**
         * Returns an activated key.
         *
         * @return a message key
         */
        String getActivatedMessageKey() {
            return CmsStringUtil.isEmptyOrWhitespaceOnly(m_keyActivated) ? m_key : m_keyActivated;
        }

        /**
         * Gets the message key for the action.<p>
         *
         * @return the message key
         */
        String getMessageKey() {
            return m_key;
        }
    }

    /**
     * The activate job context menu entry.<p>
     */
    clreplaced ActivateEntry implements I_CmsSimpleContextMenuEntry<Set<String>> {

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object)
         */
        public void executeAction(Set<String> data) {
            CmsScheduledJobInfo job = (((Set<CmsJobBean>) getValue()).iterator().next()).getJob();
            CmsScheduledJobInfo jobClone = job.clone();
            jobClone.setActive(!job.isActive());
            m_manager.writeElement(jobClone);
            reloadJobs();
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getreplacedle(java.util.Locale)
         */
        public String getreplacedle(Locale locale) {
            return CmsVaadinUtils.getMessageText(Action.activation.getMessageKey());
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object)
         */
        public CmsMenuItemVisibilityMode getVisibility(Set<String> data) {
            if ((data == null) || (data.size() > 1) || (m_manager.getElement(data.iterator().next()) == null)) {
                return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
            }
            @SuppressWarnings("unchecked")
            CmsScheduledJobInfo job = (((Set<CmsJobBean>) getValue()).iterator().next()).getJob();
            return !job.isActive() ? CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE : CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
        }
    }

    /**
     * The copy job context menu entry.<p>
     */
    clreplaced CopyEntry implements I_CmsSimpleContextMenuEntry<Set<String>> {

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object)
         */
        public void executeAction(Set<String> data) {
            m_manager.openEditDialog(data.iterator().next(), true);
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getreplacedle(java.util.Locale)
         */
        public String getreplacedle(Locale locale) {
            return CmsVaadinUtils.getMessageText(Action.copy.getMessageKey());
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object)
         */
        public CmsMenuItemVisibilityMode getVisibility(Set<String> data) {
            return (data != null) && (data.size() == 1) && (m_manager.getElement(data.iterator().next()) != null) ? CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE : CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
        }
    }

    /**
     * The activate job context menu entry.<p>
     */
    clreplaced DeActivateEntry implements I_CmsSimpleContextMenuEntry<Set<String>> {

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object)
         */
        public void executeAction(Set<String> data) {
            CmsScheduledJobInfo job = (((Set<CmsJobBean>) getValue()).iterator().next()).getJob();
            CmsScheduledJobInfo jobClone = job.clone();
            jobClone.setActive(!job.isActive());
            m_manager.writeElement(jobClone);
            reloadJobs();
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getreplacedle(java.util.Locale)
         */
        public String getreplacedle(Locale locale) {
            return CmsVaadinUtils.getMessageText(Action.activation.getActivatedMessageKey());
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object)
         */
        public CmsMenuItemVisibilityMode getVisibility(Set<String> data) {
            if ((data == null) || (data.size() > 1) || (m_manager.getElement(data.iterator().next()) == null)) {
                return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
            }
            @SuppressWarnings("unchecked")
            CmsScheduledJobInfo job = (((Set<CmsJobBean>) getValue()).iterator().next()).getJob();
            return job.isActive() ? CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE : CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
        }
    }

    /**
     * The delete job context menu entry.<p>
     */
    clreplaced DeleteEntry implements I_CmsSimpleContextMenuEntry<Set<String>> {

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object)
         */
        @SuppressWarnings("unchecked")
        public void executeAction(Set<String> data) {
            String jobNames = "";
            final List<String> jobIds = new ArrayList<String>();
            List<CmsResourceInfo> jobInfos = new ArrayList<CmsResourceInfo>();
            for (CmsJobBean job : (Set<CmsJobBean>) getValue()) {
                jobIds.add(job.getJob().getId());
                jobNames += job.getName() + ", ";
                jobInfos.add(getJobInfo(job.getName(), job.getClreplacedName()));
            }
            if (!jobNames.isEmpty()) {
                jobNames = jobNames.substring(0, jobNames.length() - 2);
            }
            CmsConfirmationDialog.show(CmsVaadinUtils.getMessageText(Action.delete.getMessageKey()), CmsVaadinUtils.getMessageText(Messages.GUI_SCHEDULER_CONFIRM_DELETE_1, jobNames), new Runnable() {

                public void run() {
                    m_manager.deleteElements(jobIds);
                    reloadJobs();
                }
            }).displayResourceInfoDirectly(jobInfos);
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getreplacedle(java.util.Locale)
         */
        public String getreplacedle(Locale locale) {
            return CmsVaadinUtils.getMessageText(Action.delete.getMessageKey());
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object)
         */
        public CmsMenuItemVisibilityMode getVisibility(Set<String> data) {
            return (data != null) && (data.size() > 0) && (m_manager.getElement(data.iterator().next()) != null) ? CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE : CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
        }
    }

    /**
     * The edit job context menu entry.<p>
     */
    clreplaced EditEntry implements I_CmsSimpleContextMenuEntry<Set<String>>, I_CmsSimpleContextMenuEntry.I_HasCssStyles {

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object)
         */
        public void executeAction(Set<String> data) {
            m_manager.openEditDialog(data.iterator().next(), false);
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry.I_HasCssStyles#getStyles()
         */
        public String getStyles() {
            return ValoTheme.LABEL_BOLD;
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getreplacedle(java.util.Locale)
         */
        public String getreplacedle(Locale locale) {
            return CmsVaadinUtils.getMessageText(Action.edit.getMessageKey());
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object)
         */
        public CmsMenuItemVisibilityMode getVisibility(Set<String> data) {
            return (data != null) && (data.size() == 1) && (m_manager.getElement(data.iterator().next()) != null) ? CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE : CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
        }
    }

    /**
     * The delete job context menu entry.<p>
     */
    clreplaced RunEntry implements I_CmsSimpleContextMenuEntry<Set<String>> {

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object)
         */
        public void executeAction(Set<String> data) {
            @SuppressWarnings("unchecked")
            final CmsScheduledJobInfo job = ((Set<CmsJobBean>) getValue()).iterator().next().getJob();
            CmsConfirmationDialog.show(CmsVaadinUtils.getMessageText(Action.run.getMessageKey()), CmsVaadinUtils.getMessageText(Messages.GUI_SCHEDULER_CONFIRM_EXECUTE_1, job.getJobName()), new Runnable() {

                public void run() {
                    m_manager.runJob(job);
                }
            }).displayResourceInfoDirectly(Collections.singletonList(getJobInfo(job.getJobName(), job.getClreplacedName())));
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getreplacedle(java.util.Locale)
         */
        public String getreplacedle(Locale locale) {
            return CmsVaadinUtils.getMessageText(Action.run.getMessageKey());
        }

        /**
         * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object)
         */
        public CmsMenuItemVisibilityMode getVisibility(Set<String> data) {
            return (data != null) && (data.size() == 1) && (m_manager.getElement(data.iterator().next()) != null) ? CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE : CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
        }
    }

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

    /**
     * Serial version id.
     */
    private static final long serialVersionUID = 1L;

    /**
     * The job manager instance.
     */
    public CmsJobManagerApp m_manager;

    /**
     * Bean container for the table.
     */
    protected BeanItemContainer<CmsJobBean> m_beanContainer;

    /**
     * The context menu.
     */
    private CmsContextMenu m_menu;

    /**
     * The available menu entries.
     */
    private List<I_CmsSimpleContextMenuEntry<Set<String>>> m_menuEntries;

    /**
     * Creates a new instance.<p>
     *
     * @param manager the job manager instance
     */
    public CmsJobTable(CmsJobManagerApp manager) {
        m_manager = manager;
        m_beanContainer = new BeanItemContainer<CmsJobBean>(CmsJobBean.clreplaced);
        setContainerDataSource(m_beanContainer);
        setVisibleColumns(TableProperty.clreplacedName.toString(), TableProperty.name.toString(), TableProperty.lastExecution.toString(), TableProperty.nextExecution.toString());
        sereplacedemIconPropertyId(TableProperty.icon.toString());
        setRowHeaderMode(RowHeaderMode.ICON_ONLY);
        setColumnWidth(null, 40);
        for (TableProperty prop : TableProperty.withHeader()) {
            setColumnExpandRatio(prop.toString(), 1);
            setColumnHeader(prop.toString(), CmsVaadinUtils.getMessageText(prop.getMessageKey()));
        }
        setSortContainerPropertyId(TableProperty.name.toString());
        getVisibleColumns();
        setSelectable(true);
        setMultiSelect(true);
        addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = -4738296706762013443L;

            public void itemClick(ItemClickEvent event) {
                onItemClick(event, event.gereplacedemId(), event.getPropertyId());
            }
        });
        m_menu = new CmsContextMenu();
        m_menu.setAsTableContextMenu(this);
        setCellStyleGenerator(new CellStyleGenerator() {

            private static final long serialVersionUID = 1L;

            public String getStyle(Table source, Object itemId, Object propertyId) {
                if (TableProperty.clreplacedName.toString().equals(propertyId)) {
                    return " " + OpenCmsTheme.HOVER_COLUMN;
                }
                @SuppressWarnings("unchecked")
                CmsScheduledJobInfo job = ((BeanItem<CmsJobBean>) source.gereplacedem(itemId)).getBean().getJob();
                if (TableProperty.name.toString().equals(propertyId) & job.isActive()) {
                    return " " + OpenCmsTheme.IN_NAVIGATION;
                }
                return null;
            }
        });
    }

    /**
     * Returns the resource info box to the given job.<p>
     *
     * @param name the job name
     * @param clreplacedName the job clreplaced
     *
     * @return the info box component
     */
    public static CmsResourceInfo getJobInfo(String name, String clreplacedName) {
        return new CmsResourceInfo(name, clreplacedName, new CmsCssIcon(OpenCmsTheme.ICON_JOB));
    }

    /**
     * Returns the available menu entries.<p>
     *
     * @return the menu entries
     */
    public List<I_CmsSimpleContextMenuEntry<Set<String>>> getMenuEntries() {
        if (m_menuEntries == null) {
            m_menuEntries = new ArrayList<I_CmsSimpleContextMenuEntry<Set<String>>>();
            m_menuEntries.add(new EditEntry());
            m_menuEntries.add(new ActivateEntry());
            m_menuEntries.add(new DeActivateEntry());
            m_menuEntries.add(new CopyEntry());
            m_menuEntries.add(new DeleteEntry());
            m_menuEntries.add(new RunEntry());
        }
        return m_menuEntries;
    }

    /**
     * Reloads the job table data.<p>
     */
    public void reloadJobs() {
        m_beanContainer.removeAllItems();
        for (CmsScheduledJobInfo job : m_manager.getAllElements()) {
            m_beanContainer.addBean(new CmsJobBean(job));
        }
        sort();
        refreshRowCache();
    }

    /**
     * Sets the menu entries.<p>
     *
     * @param newEntries to be set
     */
    public void setMenuEntries(List<I_CmsSimpleContextMenuEntry<Set<String>>> newEntries) {
        m_menuEntries = newEntries;
    }

    /**
     * Calls the edit formular to edit a job.<p>
     *
     * @param jobId to be edited.
     */
    void editJob(String jobId) {
        String stateEdit = CmsJobManagerApp.PATH_NAME_EDIT;
        stateEdit = A_CmsWorkplaceApp.addParamToState(stateEdit, CmsJobManagerApp.PARAM_JOB_ID, jobId);
        CmsAppWorkplaceUi.get().showApp(CmsScheduledJobsAppConfig.APP_ID, stateEdit);
    }

    /**
     * Handles the table item clicks, including clicks on images inside of a table item.<p>
     *
     * @param event the click event
     * @param itemId of the clicked row
     * @param propertyId column id
     */
    @SuppressWarnings("unchecked")
    void onItemClick(MouseEvents.ClickEvent event, Object itemId, Object propertyId) {
        if (!event.isCtrlKey() && !event.isShiftKey()) {
            changeValueIfNotMultiSelect(itemId);
            // don't interfere with multi-selection using control key
            if (event.getButton().equals(MouseButton.RIGHT) || (propertyId == null)) {
                Set<String> jobIds = new HashSet<String>();
                for (CmsJobBean job : (Set<CmsJobBean>) getValue()) {
                    jobIds.add(job.getJob().getId());
                }
                m_menu.setEntries(getMenuEntries(), jobIds);
                m_menu.openForTable(event, itemId, propertyId, this);
            } else if (event.getButton().equals(MouseButton.LEFT) && TableProperty.clreplacedName.toString().equals(propertyId)) {
                String jobId = ((Set<CmsJobBean>) getValue()).iterator().next().getJob().getId();
                m_manager.defaultAction(jobId);
            }
        }
    }

    /**
     * Checks value of table and sets it new if needed:<p>
     * if multiselect: new itemId is in current Value? -> no change of value<p>
     * no multiselect and multiselect, but new item not selected before: set value to new item<p>
     *
     * @param itemId if of clicked item
     */
    private void changeValueIfNotMultiSelect(Object itemId) {
        @SuppressWarnings("unchecked")
        Set<String> value = (Set<String>) getValue();
        if (value == null) {
            select(itemId);
        } else if (!value.contains(itemId)) {
            setValue(null);
            select(itemId);
        }
    }
}

19 View Complete Implementation : CmsWorkplaceServerWidget.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Layout for workplace server configuration.<p>
 */
public clreplaced CmsWorkplaceServerWidget extends FormLayout {

    /**
     * vaadin serial id.
     */
    private static final long serialVersionUID = -2972167045879745058L;

    /**
     * vaadin component.
     */
    private ComboBox m_encryption;

    /**
     * vaadin component.
     */
    private ComboBox m_server;

    /**
     * ItemContainer.
     */
    BeanItemContainer<CmsSite> m_serverContainer;

    /**
     * Flag to protect changes of ValueChangeListener.
     */
    protected boolean m_do_not_change = false;

    /**
     * Public constructor.<p>
     *
     * @param sites all sites
     * @param server current server
     */
    public CmsWorkplaceServerWidget(List<CmsSite> sites, String server) {
        CmsVaadinUtils.readAndLocalizeDesign(this, CmsVaadinUtils.getWpMessagesForCurrentLocale(), null);
        CmsSSLMode sslMode = OpenCms.getSiteManager().getSSLModeForWorkplaceServer(server);
        m_encryption.setContainerDataSource(CmsEditSiteForm.getSSLModeContainer("caption", false, sslMode));
        m_encryption.sereplacedemCaptionPropertyId("caption");
        m_encryption.setNullSelectionAllowed(false);
        m_encryption.setNewItemsAllowed(false);
        m_encryption.select(CmsSSLMode.NO);
        m_serverContainer = setUpWorkplaceComboBox(sites, m_server, false, server, sslMode);
        m_encryption.select(sslMode);
        m_encryption.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = -2628646995757479728L;

            public void valueChange(ValueChangeEvent event) {
                if (m_do_not_change) {
                    return;
                }
                m_do_not_change = true;
                adjustServerPrefix();
                m_do_not_change = false;
            }
        });
        m_server.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 6670411745575147230L;

            public void valueChange(ValueChangeEvent event) {
                if (m_do_not_change) {
                    return;
                }
                m_do_not_change = true;
                adjustSSL();
                m_do_not_change = false;
            }
        });
        adjustSSL();
    }

    /**
     * Sets the combo box for workplace.<p>
     *
     * @param allSites alls available sites
     * @param combo combo box to fill
     * @param nullselect if true, nothing is selected
     * @param defaultValue if set, this value gets chosen
     * @param sslMode CmsSSLMode
     * @return BeanItemContainer
     */
    private static BeanItemContainer<CmsSite> setUpWorkplaceComboBox(List<CmsSite> allSites, final ComboBox combo, boolean nullselect, String defaultValue, CmsSSLMode sslMode) {
        final List<CmsSite> modSites = new ArrayList<CmsSite>();
        CmsSite siteWithDefaultURL = null;
        String defaultURL = defaultValue;
        for (CmsSite site : allSites) {
            CmsSite si = new CmsSite("dummy", site.getUrl());
            si.setSSLMode(site.getSSLMode());
            modSites.add(si);
            if (defaultValue != null) {
                if (defaultURL.equals(si.getUrl())) {
                    // SSL sensitive ('http'!='https')
                    siteWithDefaultURL = si;
                }
            }
        }
        if (defaultValue != null) {
            if (siteWithDefaultURL == null) {
                siteWithDefaultURL = new CmsSite("dummy", defaultURL);
                siteWithDefaultURL.setSSLMode(sslMode);
                modSites.add(0, siteWithDefaultURL);
            }
        }
        final BeanItemContainer<CmsSite> objects = new BeanItemContainer<CmsSite>(CmsSite.clreplaced, modSites);
        combo.setContainerDataSource(objects);
        combo.setNullSelectionAllowed(nullselect);
        combo.sereplacedemCaptionPropertyId("url");
        combo.setValue(siteWithDefaultURL);
        combo.setNewItemsAllowed(true);
        combo.setImmediate(true);
        combo.setNewItemHandler(new NewItemHandler() {

            private static final long serialVersionUID = -4760590374697520609L;

            public void addNewItem(String newItemCaption) {
                CmsSite newItem = new CmsSite("dummy", newItemCaption);
                newItem.setSSLMode(newItemCaption.contains("https:") ? CmsSSLMode.MANUAL : CmsSSLMode.NO);
                objects.addBean(newItem);
                combo.select(newItem);
            }
        });
        return objects;
    }

    /**
     * Gets the server url.<p>
     *
     * @return String
     */
    public String getServer() {
        if (m_server.getValue() == null) {
            return "";
        }
        return ((CmsSite) m_server.getValue()).getUrl();
    }

    /**
     * Gets the SSL Mode.<p>
     *
     * @return CmsSSLMode
     */
    public CmsSSLMode getSSLMode() {
        return (CmsSSLMode) m_encryption.getValue();
    }

    /**
     * Adjustes the server prefixes according to SSL setting.<p>
     */
    protected void adjustServerPrefix() {
        CmsSSLMode mode = (CmsSSLMode) m_encryption.getValue();
        if (simpleReturn(mode)) {
            return;
        }
        String toBeReplaced = "http:";
        String newString = "https:";
        if (mode.equals(CmsSSLMode.NO) | mode.equals(CmsSSLMode.SECURE_SERVER)) {
            toBeReplaced = "https:";
            newString = "http:";
        }
        if (((CmsSite) m_server.getValue()).getUrl().contains(toBeReplaced)) {
            String newURL = ((CmsSite) m_server.getValue()).getUrl().replaceAll(toBeReplaced, newString);
            CmsSite newSite = new CmsSite("dummy", newURL);
            if (!m_serverContainer.containsId(newSite)) {
                m_serverContainer.addItem(newSite);
            }
            m_server.select(newSite);
        }
    }

    /**
     * Adjustes the SSL according to server name.<p>
     */
    protected void adjustSSL() {
        if (simpleReturn(null)) {
            return;
        }
        CmsSSLMode siteMode = ((CmsSite) m_server.getValue()).getSSLMode();
        // Set mode according to site, don't allow Secure Server
        m_encryption.setValue(siteMode.equals(CmsSSLMode.SECURE_SERVER) ? CmsSSLMode.NO : siteMode);
    }

    /**
     * Checks if adjust methods can early return.<p>
     *
     * @param mode to be checked.
     * @return true if no adjustment is needed
     */
    private boolean simpleReturn(CmsSSLMode mode) {
        if (m_server.getValue() == null) {
            return true;
        }
        if (mode != null) {
            if (mode.equals(CmsSSLMode.NO)) {
                if (((CmsSite) m_server.getValue()).getUrl().contains("http:")) {
                    return true;
                }
            } else {
                if (((CmsSite) m_server.getValue()).getUrl().contains("https:")) {
                    return true;
                }
            }
        }
        return false;
    }
}

19 View Complete Implementation : EditDataDiffPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced EditDataDiffPanel extends AbstractComponentEditPanel {

    private static final long serialVersionUID = 1L;

    Table enreplacedyTable = new Table();

    BeanItemContainer<EnreplacedySettings> enreplacedySettingsContainer = new BeanItemContainer<EnreplacedySettings>(EnreplacedySettings.clreplaced);

    List<EnreplacedySettings> enreplacedySettings = new ArrayList<EnreplacedySettings>();

    Table attributeTable = new Table();

    BeanItemContainer<AttributeSettings> attributeSettingsContainer = new BeanItemContainer<AttributeSettings>(AttributeSettings.clreplaced);

    List<AttributeSettings> attributeSettings = new ArrayList<AttributeSettings>();

    TextField enreplacedyFilterField;

    Button editButton;

    EditAttributesWindow attributeWindow;

    Set<EnreplacedySettings> selectedItemIds;

    protected void buildUI() {
        buildButtonBar();
        buildEnreplacedyTable();
        fillEnreplacedyContainer();
        updateEnreplacedyTable(null);
        buildAttributeWindow();
    }

    protected void buildButtonBar() {
        ButtonBar buttonBar = new ButtonBar();
        addComponent(buttonBar);
        if (!readOnly) {
            editButton = buttonBar.addButton("Edit Columns", FontAwesome.EDIT);
            editButton.addClickListener(new EditButtonClickListener());
        }
        enreplacedyFilterField = buttonBar.addFilter();
        enreplacedyFilterField.addTextChangeListener(event -> updateEnreplacedyTable(event.getText()));
        if (!readOnly) {
            Button moveUpButton = buttonBar.addButton("Move Up", FontAwesome.ARROW_UP);
            moveUpButton.addClickListener(new MoveUpClickListener());
            Button moveDownButton = buttonBar.addButton("Move Down", FontAwesome.ARROW_DOWN);
            moveDownButton.addClickListener(new MoveDownClickListener());
            Button moveTopButton = buttonBar.addButton("Move Top", FontAwesome.ANGLE_DOUBLE_UP);
            moveTopButton.addClickListener(new MoveTopClickListener());
            Button moveBottomButton = buttonBar.addButton("Move Bottom", FontAwesome.ANGLE_DOUBLE_DOWN);
            moveBottomButton.addClickListener(new MoveBottomClickListener());
            Button cutButton = buttonBar.addButton("Cut", FontAwesome.CUT);
            cutButton.addClickListener(new CutClickListener());
            Button pasteButton = buttonBar.addButton("Paste", FontAwesome.PASTE);
            pasteButton.addClickListener(new PasteClickListener());
        }
        addComponent(buttonBar);
    }

    @SuppressWarnings("unchecked")
    protected Set<EnreplacedySettings> getSelectedItems() {
        return (Set<EnreplacedySettings>) enreplacedyTable.getValue();
    }

    protected EnreplacedySettings getSelectedItem() {
        Set<EnreplacedySettings> selectedItems = getSelectedItems();
        if (selectedItems != null && selectedItems.size() == 1) {
            return selectedItems.iterator().next();
        }
        return null;
    }

    clreplaced EditButtonClickListener implements ClickListener {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {
            if (getSelectedItem() != null) {
                refreshAttributeContainer((EnreplacedySettings) getSelectedItem());
                updateAttributeTable();
                attributeWindow.show();
            }
        }
    }

    protected void buildEnreplacedyTable() {
        enreplacedyTable.setContainerDataSource(enreplacedySettingsContainer);
        enreplacedyTable.setSelectable(true);
        enreplacedyTable.setSortEnabled(false);
        enreplacedyTable.setImmediate(true);
        enreplacedyTable.setSizeFull();
        enreplacedyTable.addGeneratedColumn("enreplacedyName", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                EnreplacedySettings setting = (EnreplacedySettings) itemId;
                RelationalModel model = (RelationalModel) component.getInputModel();
                ModelEnreplacedy enreplacedy = model.getEnreplacedyById(setting.getEnreplacedyId());
                return UiUtils.getName(enreplacedyFilterField.getValue(), enreplacedy.getName());
            }
        });
        enreplacedyTable.setVisibleColumns(new Object[] { "enreplacedyName", "addEnabled", "updateEnabled", "deleteEnabled" });
        enreplacedyTable.setColumnWidth("enreplacedyName", 250);
        enreplacedyTable.setColumnHeaders(new String[] { "Enreplacedy Name", "Add Enabled", "Chg Enabled", "Del Enabled" });
        enreplacedyTable.setColumnExpandRatio("enreplacedyName", 1);
        enreplacedyTable.setTableFieldFactory(new EditEnreplacedyFieldFactory());
        enreplacedyTable.setEditable(true);
        enreplacedyTable.setMultiSelect(true);
        if (!readOnly) {
            enreplacedyTable.setDragMode(TableDragMode.MULTIROW);
            enreplacedyTable.setDropHandler(new TableDropHandler());
        }
        enreplacedyTable.setCellStyleGenerator(new TableCellStyleGenerator());
        addComponent(enreplacedyTable);
        setExpandRatio(enreplacedyTable, 1.0f);
    }

    clreplaced TableCellStyleGenerator implements CellStyleGenerator {

        public String getStyle(Table source, Object itemId, Object propertyId) {
            if (propertyId != null && selectedItemIds != null && selectedItemIds.contains(itemId)) {
                return "highlight";
            }
            return null;
        }
    }

    protected void fillEnreplacedyContainer() {
        if (component.getInputModel() != null) {
            for (ModelEnreplacedy enreplacedy : ((RelationalModel) component.getInputModel()).getModelEnreplacedies()) {
                ComponentEnreplacedySetting insert = component.getSingleEnreplacedySetting(enreplacedy.getId(), DataDiff.ENreplacedY_ADD_ENABLED);
                ComponentEnreplacedySetting update = component.getSingleEnreplacedySetting(enreplacedy.getId(), DataDiff.ENreplacedY_CHG_ENABLED);
                ComponentEnreplacedySetting delete = component.getSingleEnreplacedySetting(enreplacedy.getId(), DataDiff.ENreplacedY_DEL_ENABLED);
                ComponentEnreplacedySetting ordinal = component.getSingleEnreplacedySetting(enreplacedy.getId(), DataDiff.ENreplacedY_ORDER);
                boolean insertEnabled = insert != null ? Boolean.parseBoolean(insert.getValue()) : true;
                boolean updateEnabled = update != null ? Boolean.parseBoolean(update.getValue()) : true;
                boolean deleteEnabled = delete != null ? Boolean.parseBoolean(delete.getValue()) : true;
                Integer order = ordinal != null ? Integer.parseInt(ordinal.getValue()) : 0;
                enreplacedySettings.add(new EnreplacedySettings(enreplacedy.getId(), insertEnabled, updateEnabled, deleteEnabled, order));
            }
            Collections.sort(enreplacedySettings, new Comparator<EnreplacedySettings>() {

                public int compare(EnreplacedySettings o1, EnreplacedySettings o2) {
                    return new Integer(o1.getOrdinalSetting()).compareTo(new Integer(o2.getOrdinalSetting()));
                }
            });
        }
    }

    protected void updateEnreplacedyTable(String filter) {
        filter = filter != null ? filter.toLowerCase() : null;
        enreplacedyFilterField.setValue(filter);
        enreplacedyTable.removeAllItems();
        for (EnreplacedySettings enreplacedySetting : enreplacedySettings) {
            RelationalModel model = (RelationalModel) component.getInputModel();
            ModelEnreplacedy enreplacedy = model.getEnreplacedyById(enreplacedySetting.getEnreplacedyId());
            if (isBlank(filter) || enreplacedy.getName().toLowerCase().contains(filter)) {
                enreplacedyTable.addItem(enreplacedySetting);
            }
        }
    }

    protected void moveItemsTo(Set<EnreplacedySettings> itemIds, int index) {
        if (index >= 0 && index < enreplacedySettingsContainer.gereplacedemIds().size() && itemIds.size() > 0) {
            int firsreplacedemIndex = enreplacedySettingsContainer.indexOfId(itemIds.iterator().next());
            if (index != firsreplacedemIndex) {
                for (EnreplacedySettings itemId : itemIds) {
                    boolean movingUp = index < enreplacedySettingsContainer.indexOfId(itemId);
                    enreplacedySettingsContainer.removeItem(itemId);
                    enreplacedySettingsContainer.addItemAt(index, itemId);
                    if (movingUp) {
                        index++;
                    }
                }
                calculatePositions();
                saveOrdinalSettings();
            }
        }
    }

    protected void saveOrdinalSettings() {
        String attrName = DataDiff.ENreplacedY_ORDER;
        int ordinal = 1;
        for (EnreplacedySettings record : enreplacedySettingsContainer.gereplacedemIds()) {
            saveSetting(record.getEnreplacedyId(), attrName, String.valueOf(ordinal));
            ordinal++;
        }
    }

    protected void saveSetting(String enreplacedyId, String name, String value) {
        ComponentEnreplacedySetting setting = component.getSingleEnreplacedySetting(enreplacedyId, name);
        if (setting == null) {
            setting = new ComponentEnreplacedySetting(enreplacedyId, name, value);
            setting.setComponentId(component.getId());
            component.addEnreplacedySetting(setting);
            context.getConfigurationService().save(setting);
        } else if (!StringUtils.equals(setting.getValue(), value)) {
            setting.setValue(value);
            context.getConfigurationService().save(setting);
        }
    }

    protected void calculatePositions() {
        boolean needsRefreshed = false;
        int ordinal = 1;
        for (EnreplacedySettings record : enreplacedySettingsContainer.gereplacedemIds()) {
            if (record.getOrdinalSetting() != ordinal) {
                record.setOrdinalSetting(ordinal);
                needsRefreshed = true;
            }
            ordinal++;
        }
        if (needsRefreshed) {
            enreplacedyTable.refreshRowCache();
        }
    }

    clreplaced EditEnreplacedyFieldFactory implements TableFieldFactory {

        private static final long serialVersionUID = 1L;

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            final EnreplacedySettings settings = (EnreplacedySettings) itemId;
            if (propertyId.equals("addEnabled")) {
                return createEnreplacedyCheckBox(settings, DataDiff.ENreplacedY_ADD_ENABLED);
            } else if (propertyId.equals("updateEnabled")) {
                return createEnreplacedyCheckBox(settings, DataDiff.ENreplacedY_CHG_ENABLED);
            } else if (propertyId.equals("deleteEnabled")) {
                return createEnreplacedyCheckBox(settings, DataDiff.ENreplacedY_DEL_ENABLED);
            } else {
                return null;
            }
        }
    }

    protected CheckBox createEnreplacedyCheckBox(final EnreplacedySettings settings, final String key) {
        final CheckBox checkBox = new CheckBox();
        checkBox.setImmediate(true);
        checkBox.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                ComponentEnreplacedySetting setting = component.getSingleEnreplacedySetting(settings.getEnreplacedyId(), key);
                String oldValue = setting == null ? Boolean.TRUE.toString() : setting.getValue();
                if (setting == null) {
                    setting = new ComponentEnreplacedySetting(settings.getEnreplacedyId(), component.getId(), key, Boolean.TRUE.toString());
                    component.addEnreplacedySetting(setting);
                }
                setting.setValue(checkBox.getValue().toString());
                if (!oldValue.equals(setting.getValue())) {
                    context.getConfigurationService().save(setting);
                }
            }
        });
        checkBox.setReadOnly(readOnly);
        return checkBox;
    }

    public static clreplaced EnreplacedySettings implements Serializable {

        private static final long serialVersionUID = 1L;

        String enreplacedyId;

        boolean addEnabled;

        boolean updateEnabled;

        boolean deleteEnabled;

        int ordinalSetting;

        public EnreplacedySettings(String enreplacedyId, boolean insertEnabled, boolean updateEnabled, boolean deleteEnabled, int ordinal) {
            this.enreplacedyId = enreplacedyId;
            this.addEnabled = insertEnabled;
            this.updateEnabled = updateEnabled;
            this.deleteEnabled = deleteEnabled;
            this.ordinalSetting = ordinal;
        }

        public void setAddEnabled(boolean insertEnabled) {
            this.addEnabled = insertEnabled;
        }

        public boolean isAddEnabled() {
            return addEnabled;
        }

        public void setUpdateEnabled(boolean updateEnabled) {
            this.updateEnabled = updateEnabled;
        }

        public boolean isUpdateEnabled() {
            return updateEnabled;
        }

        public void setDeleteEnabled(boolean deleteEnabled) {
            this.deleteEnabled = deleteEnabled;
        }

        public boolean isDeleteEnabled() {
            return deleteEnabled;
        }

        public String getEnreplacedyId() {
            return enreplacedyId;
        }

        public void setEnreplacedyId(String enreplacedyId) {
            this.enreplacedyId = enreplacedyId;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof EnreplacedySettings) {
                return enreplacedyId.equals(((EnreplacedySettings) obj).getEnreplacedyId());
            } else {
                return super.equals(obj);
            }
        }

        @Override
        public int hashCode() {
            return enreplacedyId.hashCode();
        }

        public int getOrdinalSetting() {
            return ordinalSetting;
        }

        public void setOrdinalSetting(int ordinalSetting) {
            this.ordinalSetting = ordinalSetting;
        }
    }

    // attribute window and support
    protected void buildAttributeWindow() {
        attributeWindow = new EditAttributesWindow();
    }

    clreplaced EditAttributesWindow extends ResizableWindow {

        private static final long serialVersionUID = 1L;

        public EditAttributesWindow() {
            super("Edit Columns to Compare");
            setWidth(800f, Unit.PIXELS);
            setHeight(600f, Unit.PIXELS);
            content.setMargin(true);
            buildAttributeTable();
            addComponent(buildButtonFooter(buildCloseButton()));
        }

        private void buildAttributeTable() {
            attributeTable.setContainerDataSource(attributeSettingsContainer);
            attributeTable.setSelectable(true);
            attributeTable.setSortEnabled(false);
            attributeTable.setImmediate(true);
            attributeTable.setSortEnabled(false);
            attributeTable.setSizeFull();
            attributeTable.addGeneratedColumn("attributeName", new ColumnGenerator() {

                private static final long serialVersionUID = 1L;

                @Override
                public Object generateCell(Table source, Object itemId, Object columnId) {
                    AttributeSettings setting = (AttributeSettings) itemId;
                    RelationalModel model = (RelationalModel) component.getInputModel();
                    ModelAttrib attribute = model.getAttributeById(setting.getAttributeId());
                    return UiUtils.getName(enreplacedyFilterField.getValue(), attribute.getName());
                }
            });
            attributeTable.setVisibleColumns(new Object[] { "attributeName", "compareEnabled" });
            attributeTable.setColumnWidth("attributeName", 250);
            attributeTable.setColumnHeaders(new String[] { "Attribute Name", "Compare Enabled" });
            attributeTable.setColumnExpandRatio("attributeName", 1);
            attributeTable.setTableFieldFactory(new EditAttributeFieldFactory());
            attributeTable.setEditable(true);
            addComponent(attributeTable, 1);
        }
    }

    private void refreshAttributeContainer(EnreplacedySettings selectedRow) {
        attributeSettings.clear();
        ModelEnreplacedy enreplacedy = ((RelationalModel) component.getInputModel()).getEnreplacedyById(selectedRow.getEnreplacedyId());
        for (ModelAttrib attribute : enreplacedy.getModelAttributes()) {
            ComponentAttribSetting compare = component.getSingleAttributeSetting(attribute.getId(), DataDiff.ATTRIBUTE_COMPARE_ENABLED);
            boolean compareEnabled = compare != null ? Boolean.parseBoolean(compare.getValue()) : true;
            attributeSettings.add(new AttributeSettings(attribute.getId(), compareEnabled, attribute.isPk() == true ? true : false));
        }
    }

    protected void updateAttributeTable() {
        attributeTable.removeAllItems();
        for (AttributeSettings attributeSetting : attributeSettings) {
            attributeTable.addItem(attributeSetting);
        }
    }

    clreplaced EditAttributeFieldFactory implements TableFieldFactory {

        private static final long serialVersionUID = 1L;

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            final AttributeSettings settings = (AttributeSettings) itemId;
            if (propertyId.equals("compareEnabled")) {
                return createAttributeCheckBox(settings, DataDiff.ATTRIBUTE_COMPARE_ENABLED);
            } else {
                return null;
            }
        }
    }

    protected CheckBox createAttributeCheckBox(final AttributeSettings settings, final String key) {
        final CheckBox checkBox = new CheckBox();
        checkBox.setImmediate(true);
        if (settings.isPrimaryKey()) {
            checkBox.setEnabled(false);
        }
        checkBox.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                ComponentAttribSetting setting = component.getSingleAttributeSetting(settings.getAttributeId(), key);
                String oldValue = setting == null ? Boolean.TRUE.toString() : setting.getValue();
                if (setting == null) {
                    setting = new ComponentAttribSetting(settings.getAttributeId(), component.getId(), key, Boolean.TRUE.toString());
                    component.addAttributeSetting(setting);
                }
                setting.setValue(checkBox.getValue().toString());
                if (!oldValue.equals(setting.getValue())) {
                    context.getConfigurationService().save(setting);
                }
            }
        });
        checkBox.setReadOnly(readOnly);
        return checkBox;
    }

    public static clreplaced AttributeSettings implements Serializable {

        private static final long serialVersionUID = 1L;

        boolean primaryKey;

        String attributeId;

        boolean compareEnabled;

        public AttributeSettings(String attributeId, boolean compareEnabled, boolean primaryKey) {
            this.attributeId = attributeId;
            this.compareEnabled = compareEnabled;
            this.primaryKey = primaryKey;
        }

        public void setCompareEnabled(boolean compareEnabled) {
            this.compareEnabled = compareEnabled;
        }

        public boolean isCompareEnabled() {
            return compareEnabled;
        }

        public String getAttributeId() {
            return attributeId;
        }

        public void setAttributeId(String attributeId) {
            this.attributeId = attributeId;
        }

        public void setPrimaryKey(boolean primaryKey) {
            this.primaryKey = primaryKey;
        }

        public boolean isPrimaryKey() {
            return primaryKey;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof AttributeSettings) {
                return attributeId.equals(((AttributeSettings) obj).getAttributeId());
            } else {
                return super.equals(obj);
            }
        }
    }

    clreplaced MoveUpClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<EnreplacedySettings> itemIds = getSelectedItems();
            if (itemIds.size() > 0 && itemIds != null) {
                EnreplacedySettings firsreplacedem = itemIds.iterator().next();
                int index = enreplacedySettingsContainer.indexOfId(firsreplacedem) - 1;
                moveItemsTo(getSelectedItems(), index);
            }
        }
    }

    clreplaced MoveDownClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<EnreplacedySettings> itemIds = getSelectedItems();
            if (itemIds.size() > 0 && itemIds != null) {
                EnreplacedySettings lasreplacedem = null;
                Iterator<EnreplacedySettings> iter = itemIds.iterator();
                while (iter.hasNext()) {
                    lasreplacedem = iter.next();
                }
                int index = enreplacedySettingsContainer.indexOfId(lasreplacedem) + 1;
                moveItemsTo(getSelectedItems(), index);
            }
        }
    }

    clreplaced MoveTopClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            moveItemsTo(getSelectedItems(), 0);
        }
    }

    clreplaced MoveBottomClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            moveItemsTo(getSelectedItems(), enreplacedySettingsContainer.size() - 1);
        }
    }

    clreplaced CutClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<EnreplacedySettings> itemIds = getSelectedItems();
            selectedItemIds = new LinkedHashSet<EnreplacedySettings>(itemIds);
            for (EnreplacedySettings itemId : itemIds) {
                enreplacedyTable.unselect(itemId);
            }
            enreplacedyTable.refreshRowCache();
        }
    }

    clreplaced PasteClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<EnreplacedySettings> itemIds = getSelectedItems();
            if (itemIds.size() > 0 && selectedItemIds != null) {
                int index = enreplacedySettingsContainer.indexOfId(itemIds.iterator().next());
                moveItemsTo(selectedItemIds, index);
                selectedItemIds = null;
            }
        }
    }

    clreplaced TableDropHandler implements DropHandler {

        public void drop(DragAndDropEvent event) {
            AbstractSelectTargetDetails targetDetails = (AbstractSelectTargetDetails) event.getTargetDetails();
            Transferable transferable = event.getTransferable();
            if (transferable.getSourceComponent() == enreplacedyTable) {
                EnreplacedySettings target = (EnreplacedySettings) targetDetails.gereplacedemIdOver();
                moveItemsTo(getSelectedItems(), enreplacedySettingsContainer.indexOfId(target));
            }
        }

        public AcceptCriterion getAcceptCriterion() {
            return AcceptAll.get();
        }
    }
}

19 View Complete Implementation : EditExcelReaderPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
public clreplaced EditExcelReaderPanel extends AbstractComponentEditPanel {

    private static final long serialVersionUID = 1L;

    Grid grid;

    BeanItemContainer<Record> container;

    @Override
    protected void buildUI() {
        buildGrid();
        refresh();
    }

    protected void buildGrid() {
        grid = new Grid();
        grid.setSelectionMode(SelectionMode.NONE);
        grid.setSizeFull();
        grid.setEditorEnabled(!readOnly);
        container = new BeanItemContainer<Record>(Record.clreplaced);
        grid.setContainerDataSource(container);
        grid.setColumnOrder("enreplacedyName", "attributeName", "excelMapping");
        HeaderRow filterRow = grid.appendHeaderRow();
        addColumn("enreplacedyName", filterRow);
        addColumn("attributeName", filterRow);
        TextField tfExcelMapping = new TextField();
        tfExcelMapping.addBlurListener(e -> saveExcelMappingSettings());
        tfExcelMapping.setWidth(100, Unit.PERCENTAGE);
        tfExcelMapping.setImmediate(true);
        grid.getColumn("excelMapping").setEditorField(tfExcelMapping).setExpandRatio(1);
        addShowPopulatedFilter("excelMapping", filterRow);
        grid.setEditorBuffered(false);
        addComponent(grid);
        setExpandRatio(grid, 1);
    }

    protected void addColumn(String propertyId, HeaderRow filterRow) {
        grid.getColumn(propertyId).setEditable(false);
        HeaderCell cell = filterRow.getCell(propertyId);
        TextField filterField = new TextField();
        filterField.setInputPrompt("Filter");
        filterField.setImmediate(true);
        filterField.addStyleName(ValoTheme.TEXTFIELD_TINY);
        filterField.setWidth(100, Unit.PERCENTAGE);
        filterField.addTextChangeListener(change -> {
            container.removeContainerFilters(propertyId);
            if (!change.getText().isEmpty()) {
                container.addContainerFilter(new SimpleStringFilter(propertyId, change.getText(), true, false));
            }
        });
        cell.setComponent(filterField);
    }

    protected void addShowPopulatedFilter(String propertyId, HeaderRow filterRow) {
        HeaderCell cell = filterRow.getCell(propertyId);
        CheckBox group = new CheckBox("Show Set Only");
        group.setImmediate(true);
        group.addValueChangeListener(l -> {
            container.removeContainerFilters(propertyId);
            if (group.getValue()) {
                container.addContainerFilter(new And(new Not(new Compare.Equal(propertyId, "")), new Not(new IsNull(propertyId))));
            }
        });
        group.addStyleName(ValoTheme.CHECKBOX_SMALL);
        cell.setComponent(group);
    }

    protected void saveExcelMappingSettings() {
        for (Object obj : container.gereplacedemIds()) {
            Record record = (Record) obj;
            if (record.modelAttribute != null) {
                saveAttributeSetting(record.modelAttribute.getId(), ExcelFileReader.SETTING_EXCEL_MAPPING, StringUtils.trimToNull(record.getExcelMapping()));
            }
        }
    }

    protected void saveAttributeSetting(String attributeId, String name, String value) {
        ComponentAttribSetting setting = component.getSingleAttributeSetting(attributeId, name);
        if (setting == null && value != null) {
            setting = new ComponentAttribSetting(attributeId, name, value);
            setting.setComponentId(component.getId());
            component.addAttributeSetting(setting);
            context.getConfigurationService().save(setting);
        } else if (setting != null && !StringUtils.equals(setting.getValue(), value)) {
            if (value == null) {
                setting.setValue(value);
                context.getConfigurationService().delete(setting);
            } else {
                setting.setValue(value);
                context.getConfigurationService().save(setting);
            }
        }
    }

    public clreplaced Record implements Serializable {

        private static final long serialVersionUID = 1L;

        ModelEnreplacedy modelEnreplacedy;

        ModelAttrib modelAttribute;

        String excelMapping = "";

        public Record(ModelEnreplacedy modelEnreplacedy, ModelAttrib modelAttribute) {
            this.modelEnreplacedy = modelEnreplacedy;
            this.modelAttribute = modelAttribute;
            if (modelAttribute != null) {
                ComponentAttribSetting setting = component.getSingleAttributeSetting(modelAttribute.getId(), ExcelFileReader.SETTING_EXCEL_MAPPING);
                if (setting != null) {
                    excelMapping = setting.getValue();
                }
            }
        }

        public int hashCode() {
            return modelEnreplacedy.hashCode() + (modelAttribute == null ? 0 : modelAttribute.hashCode());
        }

        public boolean equals(Object obj) {
            if (obj instanceof Record) {
                return hashCode() == ((Record) obj).hashCode();
            }
            return super.equals(obj);
        }

        public String getEnreplacedyName() {
            return modelEnreplacedy.getName();
        }

        public String getAttributeName() {
            if (modelAttribute != null) {
                return modelAttribute.getName();
            }
            return null;
        }

        public String getExcelMapping() {
            return excelMapping;
        }

        public void setExcelMapping(String excelMapping) {
            this.excelMapping = excelMapping;
        }
    }

    protected void refresh() {
        RelationalModel model = (RelationalModel) component.getOutputModel();
        if (model != null) {
            Collections.sort(model.getModelEnreplacedies(), new Comparator<ModelEnreplacedy>() {

                public int compare(ModelEnreplacedy enreplacedy1, ModelEnreplacedy enreplacedy2) {
                    return enreplacedy1.getName().toLowerCase().compareTo(enreplacedy2.getName().toLowerCase());
                }
            });
            for (ModelEnreplacedy enreplacedy : model.getModelEnreplacedies()) {
                for (ModelAttrib attr : enreplacedy.getModelAttributes()) {
                    container.addItem(new Record(enreplacedy, attr));
                }
            }
        }
    }
}

19 View Complete Implementation : EditExcelWriterPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced EditExcelWriterPanel extends AbstractComponentEditPanel {

    Table table = new Table();

    BeanItemContainer<RecordFormat> container = new BeanItemContainer<RecordFormat>(RecordFormat.clreplaced);

    Set<RecordFormat> selectedItemIds;

    protected void buildUI() {
        ButtonBar buttonBar = new ButtonBar();
        if (!readOnly) {
            addComponent(buttonBar);
            Button moveUpButton = buttonBar.addButton("Move Up", FontAwesome.ARROW_UP);
            moveUpButton.addClickListener(new MoveUpClickListener());
            Button moveDownButton = buttonBar.addButton("Move Down", FontAwesome.ARROW_DOWN);
            moveDownButton.addClickListener(new MoveDownClickListener());
            Button moveTopButton = buttonBar.addButton("Move Top", FontAwesome.ANGLE_DOUBLE_UP);
            moveTopButton.addClickListener(new MoveTopClickListener());
            Button moveBottomButton = buttonBar.addButton("Move Bottom", FontAwesome.ANGLE_DOUBLE_DOWN);
            moveBottomButton.addClickListener(new MoveBottomClickListener());
            Button cutButton = buttonBar.addButton("Cut", FontAwesome.CUT);
            cutButton.addClickListener(new CutClickListener());
            Button pasteButton = buttonBar.addButton("Paste", FontAwesome.PASTE);
            pasteButton.addClickListener(new PasteClickListener());
        }
        buttonBar.addButtonRight("Export", FontAwesome.DOWNLOAD, (e) -> export());
        table.setContainerDataSource(container);
        table.setSelectable(true);
        table.setSortEnabled(false);
        table.setImmediate(true);
        table.setSizeFull();
        table.setVisibleColumns(new Object[] { "enreplacedyName", "attributeName", "ordinalSetting" });
        table.setColumnHeaders(new String[] { "Enreplacedy Name", "Attribute Name", "Ordinal" });
        table.setCellStyleGenerator(new TableCellStyleGenerator());
        table.setEditable(false);
        table.setMultiSelect(true);
        if (!readOnly) {
            table.setDragMode(TableDragMode.MULTIROW);
            table.setDropHandler(new TableDropHandler());
        }
        addComponent(table);
        setExpandRatio(table, 1.0f);
        RelationalModel model = (RelationalModel) component.getInputModel();
        if (model != null) {
            model = context.getConfigurationService().findRelationalModel(model.getId());
            List<RecordFormat> attributes = new ArrayList<RecordFormat>();
            for (ModelEnreplacedy enreplacedy : model.getModelEnreplacedies()) {
                for (ModelAttrib attr : enreplacedy.getModelAttributes()) {
                    attributes.add(new RecordFormat(enreplacedy, attr));
                }
            }
            Collections.sort(attributes, new Comparator<RecordFormat>() {

                public int compare(RecordFormat o1, RecordFormat o2) {
                    return new Integer(o1.getOrdinalSetting()).compareTo(new Integer(o2.getOrdinalSetting()));
                }
            });
            for (RecordFormat recordFormat : attributes) {
                table.addItem(recordFormat);
            }
        }
        calculatePositions();
        saveOrdinalSettings();
    }

    protected void export() {
        String fileNamePrefix = component.getName().toLowerCase().replace(' ', '-');
        ExportDialog dialog = new ExportDialog(new TableV7DataProvider(table), fileNamePrefix, component.getName());
        UI.getCurrent().addWindow(dialog);
    }

    @SuppressWarnings("unchecked")
    protected Set<RecordFormat> getSelectedItems() {
        return (Set<RecordFormat>) table.getValue();
    }

    protected RecordFormat getSelectedItem() {
        Set<RecordFormat> selectedItems = getSelectedItems();
        if (selectedItems != null && selectedItems.size() == 1) {
            return selectedItems.iterator().next();
        }
        return null;
    }

    protected void calculatePositions() {
        boolean needsRefreshed = false;
        int ordinal = 1;
        for (RecordFormat record : container.gereplacedemIds()) {
            if (record.getOrdinalSetting() != ordinal) {
                record.setOrdinalSetting(ordinal);
                needsRefreshed = true;
            }
            ordinal++;
        }
        if (needsRefreshed) {
            RecordFormat record = getSelectedItem();
            if (record != null) {
                record.setFocusFieldId("transformText");
            }
            table.refreshRowCache();
        }
    }

    protected void moveItemsTo(Set<RecordFormat> itemIds, int index) {
        if (index >= 0 && index < container.gereplacedemIds().size() && itemIds.size() > 0) {
            int firsreplacedemIndex = container.indexOfId(itemIds.iterator().next());
            if (index != firsreplacedemIndex) {
                for (RecordFormat itemId : itemIds) {
                    boolean movingUp = index < container.indexOfId(itemId);
                    container.removeItem(itemId);
                    container.addItemAt(index, itemId);
                    if (movingUp) {
                        index++;
                    }
                }
                calculatePositions();
                saveOrdinalSettings();
            }
        }
    }

    protected void saveOrdinalSettings() {
        String attrName;
        attrName = ExcelFileWriter.EXCEL_WRITER_ATTRIBUTE_ORDINAL;
        int ordinal = 1;
        for (RecordFormat record : container.gereplacedemIds()) {
            saveSetting(record.getAttributeId(), attrName, String.valueOf(ordinal));
            ordinal++;
        }
    }

    protected void saveSetting(String attributeId, String name, String value) {
        ComponentAttribSetting setting = component.getSingleAttributeSetting(attributeId, name);
        if (setting == null) {
            setting = new ComponentAttribSetting(attributeId, name, value);
            setting.setComponentId(component.getId());
            component.addAttributeSetting(setting);
            context.getConfigurationService().save(setting);
        } else if (!StringUtils.equals(setting.getValue(), value)) {
            setting.setValue(value);
            context.getConfigurationService().save(setting);
        }
    }

    clreplaced MoveUpClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> itemIds = getSelectedItems();
            if (itemIds.size() > 0 && itemIds != null) {
                RecordFormat firsreplacedem = itemIds.iterator().next();
                int index = container.indexOfId(firsreplacedem) - 1;
                moveItemsTo(getSelectedItems(), index);
            }
        }
    }

    clreplaced MoveDownClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> itemIds = getSelectedItems();
            if (itemIds.size() > 0 && itemIds != null) {
                RecordFormat lasreplacedem = null;
                Iterator<RecordFormat> iter = itemIds.iterator();
                while (iter.hasNext()) {
                    lasreplacedem = iter.next();
                }
                int index = container.indexOfId(lasreplacedem) + 1;
                moveItemsTo(getSelectedItems(), index);
            }
        }
    }

    clreplaced MoveTopClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            moveItemsTo(getSelectedItems(), 0);
        }
    }

    clreplaced MoveBottomClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            moveItemsTo(getSelectedItems(), container.size() - 1);
        }
    }

    clreplaced CutClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> itemIds = getSelectedItems();
            selectedItemIds = new LinkedHashSet<RecordFormat>(itemIds);
            for (RecordFormat itemId : itemIds) {
                table.unselect(itemId);
            }
            table.refreshRowCache();
        }
    }

    clreplaced PasteClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> itemIds = getSelectedItems();
            if (itemIds.size() > 0 && selectedItemIds != null) {
                int index = container.indexOfId(itemIds.iterator().next());
                moveItemsTo(selectedItemIds, index);
                selectedItemIds = null;
            }
        }
    }

    clreplaced TableDropHandler implements DropHandler {

        public void drop(DragAndDropEvent event) {
            AbstractSelectTargetDetails targetDetails = (AbstractSelectTargetDetails) event.getTargetDetails();
            Transferable transferable = event.getTransferable();
            if (transferable.getSourceComponent() == table) {
                RecordFormat target = (RecordFormat) targetDetails.gereplacedemIdOver();
                moveItemsTo(getSelectedItems(), container.indexOfId(target));
            }
        }

        public AcceptCriterion getAcceptCriterion() {
            return AcceptAll.get();
        }
    }

    clreplaced TableCellStyleGenerator implements CellStyleGenerator {

        public String getStyle(Table source, Object itemId, Object propertyId) {
            if (propertyId != null && selectedItemIds != null && selectedItemIds.contains(itemId)) {
                return "highlight";
            }
            return null;
        }
    }

    public clreplaced RecordFormat {

        ModelEnreplacedy modelEnreplacedy;

        ModelAttrib modelAttribute;

        Map<Object, Field<?>> fields = new HashMap<Object, Field<?>>();

        Object focusFieldId;

        int ordinalSetting;

        public RecordFormat(ModelEnreplacedy modelEnreplacedy, ModelAttrib modelAttribute) {
            this.modelEnreplacedy = modelEnreplacedy;
            this.modelAttribute = modelAttribute;
            ComponentAttribSetting setting = component.getSingleAttributeSetting(modelAttribute.getId(), ExcelFileWriter.EXCEL_WRITER_ATTRIBUTE_ORDINAL);
            if (setting != null) {
                this.ordinalSetting = Integer.parseInt(setting.getValue());
            }
        }

        public int hashCode() {
            return modelEnreplacedy.hashCode() + modelAttribute.hashCode();
        }

        public boolean equals(Object obj) {
            if (obj instanceof RecordFormat) {
                return hashCode() == ((RecordFormat) obj).hashCode();
            }
            return super.equals(obj);
        }

        public String getEnreplacedyName() {
            return modelEnreplacedy.getName();
        }

        public String getAttributeName() {
            return modelAttribute.getName();
        }

        public String getAttributeId() {
            return modelAttribute.getId();
        }

        public void setFocusFieldId(Object id) {
            this.focusFieldId = id;
        }

        public Field<?> getFocusField() {
            Field<?> field = fields.get(focusFieldId);
            if (field == null) {
                field = fields.get("width");
            }
            return field;
        }

        public int getOrdinalSetting() {
            return ordinalSetting;
        }

        public void setOrdinalSetting(int ordinalSetting) {
            this.ordinalSetting = ordinalSetting;
        }
    }
}

19 View Complete Implementation : EditFormatPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced EditFormatPanel extends AbstractComponentEditPanel {

    Table table = new Table();

    BeanItemContainer<RecordFormat> container = new BeanItemContainer<RecordFormat>(RecordFormat.clreplaced);

    Set<RecordFormat> selectedItemIds;

    protected void buildUI() {
        ButtonBar buttonBar = new ButtonBar();
        if (!readOnly) {
            addComponent(buttonBar);
            Button moveUpButton = buttonBar.addButton("Move Up", FontAwesome.ARROW_UP);
            moveUpButton.addClickListener(new MoveUpClickListener());
            Button moveDownButton = buttonBar.addButton("Move Down", FontAwesome.ARROW_DOWN);
            moveDownButton.addClickListener(new MoveDownClickListener());
            Button moveTopButton = buttonBar.addButton("Move Top", FontAwesome.ANGLE_DOUBLE_UP);
            moveTopButton.addClickListener(new MoveTopClickListener());
            Button moveBottomButton = buttonBar.addButton("Move Bottom", FontAwesome.ANGLE_DOUBLE_DOWN);
            moveBottomButton.addClickListener(new MoveBottomClickListener());
            Button cutButton = buttonBar.addButton("Cut", FontAwesome.CUT);
            cutButton.addClickListener(new CutClickListener());
            Button pasteButton = buttonBar.addButton("Paste", FontAwesome.PASTE);
            pasteButton.addClickListener(new PasteClickListener());
        }
        buttonBar.addButtonRight("Export", FontAwesome.DOWNLOAD, (e) -> export());
        table.setContainerDataSource(container);
        table.setSelectable(true);
        table.setSortEnabled(false);
        table.setImmediate(true);
        table.setSizeFull();
        if (component.getType().equals(FixedLengthFormatter.TYPE) || component.getType().equals(FixedLengthParser.TYPE)) {
            table.setVisibleColumns(new Object[] { "enreplacedyName", "attributeName", "width", "startPos", "endPos", "transformText" });
            table.setColumnHeaders(new String[] { "Enreplacedy Name", "Attribute Name", "Width", "Start Position", "End Position", "Transform" });
            table.setColumnWidth("width", 75);
        } else {
            table.setVisibleColumns(new Object[] { "enreplacedyName", "attributeName", "ordinalSetting", "transformText" });
            table.setColumnHeaders(new String[] { "Enreplacedy Name", "Attribute Name", "Ordinal", "Transform" });
        }
        table.setTableFieldFactory(new EditFieldFactory());
        table.setCellStyleGenerator(new TableCellStyleGenerator());
        table.setEditable(true);
        table.setMultiSelect(true);
        if (!readOnly) {
            table.setDragMode(TableDragMode.MULTIROW);
            table.setDropHandler(new TableDropHandler());
        }
        addComponent(table);
        setExpandRatio(table, 1.0f);
        RelationalModel model = (RelationalModel) component.getInputModel();
        if (component.getType().equals(DelimitedParser.TYPE) || component.getType().equals(FixedLengthParser.TYPE)) {
            model = (RelationalModel) component.getOutputModel();
        }
        if (model != null) {
            model = context.getConfigurationService().findRelationalModel(model.getId());
            List<RecordFormat> attributes = new ArrayList<RecordFormat>();
            for (ModelEnreplacedy enreplacedy : model.getModelEnreplacedies()) {
                for (ModelAttrib attr : enreplacedy.getModelAttributes()) {
                    attributes.add(new RecordFormat(enreplacedy, attr));
                }
            }
            Collections.sort(attributes, new Comparator<RecordFormat>() {

                public int compare(RecordFormat o1, RecordFormat o2) {
                    return new Integer(o1.getOrdinalSetting()).compareTo(new Integer(o2.getOrdinalSetting()));
                }
            });
            for (RecordFormat recordFormat : attributes) {
                table.addItem(recordFormat);
            }
        }
        calculatePositions();
        saveOrdinalSettings();
        saveLengthSettings();
        saveTransformSettings();
    }

    protected void export() {
        String fileNamePrefix = component.getName().toLowerCase().replace(' ', '-');
        ExportDialog dialog = new ExportDialog(new TableV7DataProvider(table), fileNamePrefix, component.getName());
        UI.getCurrent().addWindow(dialog);
    }

    @SuppressWarnings("unchecked")
    protected Set<RecordFormat> getSelectedItems() {
        return (Set<RecordFormat>) table.getValue();
    }

    protected RecordFormat getSelectedItem() {
        Set<RecordFormat> selectedItems = getSelectedItems();
        if (selectedItems != null && selectedItems.size() == 1) {
            return selectedItems.iterator().next();
        }
        return null;
    }

    protected void calculatePositions() {
        boolean needsRefreshed = false;
        if (component.getType().equals(FixedLengthFormatter.TYPE) || component.getType().equals(FixedLengthParser.TYPE)) {
            long pos = 1;
            for (RecordFormat record : container.gereplacedemIds()) {
                if (record.getStartPos() != pos) {
                    record.setStartPos(pos);
                    needsRefreshed = true;
                }
                long endPos = pos + record.getWidth() - 1;
                if (record.getEndPos() != endPos) {
                    record.setEndPos(endPos);
                    needsRefreshed = true;
                }
                pos = endPos + 1;
            }
        } else if (component.getType().equals(DelimitedFormatter.TYPE) || component.getType().equals(DelimitedParser.TYPE)) {
            int ordinal = 1;
            for (RecordFormat record : container.gereplacedemIds()) {
                if (record.getOrdinalSetting() != ordinal) {
                    record.setOrdinalSetting(ordinal);
                    needsRefreshed = true;
                }
                ordinal++;
            }
        }
        if (needsRefreshed) {
            RecordFormat record = getSelectedItem();
            if (record != null) {
                record.setFocusFieldId("transformText");
            }
            table.refreshRowCache();
        }
    }

    protected void moveItemsTo(Set<RecordFormat> itemIds, int index) {
        if (index >= 0 && index < container.gereplacedemIds().size() && itemIds.size() > 0) {
            int firsreplacedemIndex = container.indexOfId(itemIds.iterator().next());
            if (index != firsreplacedemIndex) {
                for (RecordFormat itemId : itemIds) {
                    boolean movingUp = index < container.indexOfId(itemId);
                    container.removeItem(itemId);
                    container.addItemAt(index, itemId);
                    if (movingUp) {
                        index++;
                    }
                }
                calculatePositions();
                saveOrdinalSettings();
            }
        }
    }

    protected void saveOrdinalSettings() {
        String attrName;
        if (component.getType().equals(FixedLengthFormatter.TYPE) || component.getType().equals(FixedLengthParser.TYPE)) {
            attrName = FixedLengthFormatter.FIXED_LENGTH_FORMATTER_ATTRIBUTE_ORDINAL;
        } else {
            attrName = DelimitedFormatter.DELIMITED_FORMATTER_ATTRIBUTE_ORDINAL;
        }
        int ordinal = 1;
        for (RecordFormat record : container.gereplacedemIds()) {
            saveSetting(record.getAttributeId(), attrName, String.valueOf(ordinal));
            ordinal++;
        }
    }

    protected void saveLengthSettings() {
        if (component.getType().equals(FixedLengthFormatter.TYPE) || component.getType().equals(FixedLengthParser.TYPE)) {
            for (RecordFormat record : container.gereplacedemIds()) {
                saveSetting(record.getAttributeId(), FixedLengthFormatter.FIXED_LENGTH_FORMATTER_ATTRIBUTE_LENGTH, String.valueOf(record.getWidth()));
            }
        }
    }

    protected void saveTransformSettings() {
        String attrName;
        if (component.getType().equals(FixedLengthFormatter.TYPE) || component.getType().equals(FixedLengthParser.TYPE)) {
            attrName = FixedLengthFormatter.FIXED_LENGTH_FORMATTER_ATTRIBUTE_FORMAT_FUNCTION;
        } else {
            attrName = DelimitedFormatter.DELIMITED_FORMATTER_ATTRIBUTE_FORMAT_FUNCTION;
        }
        for (RecordFormat record : container.gereplacedemIds()) {
            saveSetting(record.getAttributeId(), attrName, record.getTransformText());
        }
    }

    protected void saveSetting(String attributeId, String name, String value) {
        ComponentAttribSetting setting = component.getSingleAttributeSetting(attributeId, name);
        if (setting == null) {
            setting = new ComponentAttribSetting(attributeId, name, value);
            setting.setComponentId(component.getId());
            component.addAttributeSetting(setting);
            context.getConfigurationService().save(setting);
        } else if (!StringUtils.equals(setting.getValue(), value)) {
            setting.setValue(value);
            context.getConfigurationService().save(setting);
        }
    }

    clreplaced MoveUpClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> itemIds = getSelectedItems();
            if (itemIds.size() > 0 && itemIds != null) {
                RecordFormat firsreplacedem = itemIds.iterator().next();
                int index = container.indexOfId(firsreplacedem) - 1;
                moveItemsTo(getSelectedItems(), index);
            }
        }
    }

    clreplaced MoveDownClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> itemIds = getSelectedItems();
            if (itemIds.size() > 0 && itemIds != null) {
                RecordFormat lasreplacedem = null;
                Iterator<RecordFormat> iter = itemIds.iterator();
                while (iter.hasNext()) {
                    lasreplacedem = iter.next();
                }
                int index = container.indexOfId(lasreplacedem) + 1;
                moveItemsTo(getSelectedItems(), index);
            }
        }
    }

    clreplaced MoveTopClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            moveItemsTo(getSelectedItems(), 0);
        }
    }

    clreplaced MoveBottomClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            moveItemsTo(getSelectedItems(), container.size() - 1);
        }
    }

    clreplaced CutClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> itemIds = getSelectedItems();
            selectedItemIds = new LinkedHashSet<RecordFormat>(itemIds);
            for (RecordFormat itemId : itemIds) {
                table.unselect(itemId);
            }
            table.refreshRowCache();
        }
    }

    clreplaced PasteClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> itemIds = getSelectedItems();
            if (itemIds.size() > 0 && selectedItemIds != null) {
                int index = container.indexOfId(itemIds.iterator().next());
                moveItemsTo(selectedItemIds, index);
                selectedItemIds = null;
            }
        }
    }

    clreplaced TableDropHandler implements DropHandler {

        public void drop(DragAndDropEvent event) {
            AbstractSelectTargetDetails targetDetails = (AbstractSelectTargetDetails) event.getTargetDetails();
            Transferable transferable = event.getTransferable();
            if (transferable.getSourceComponent() == table) {
                RecordFormat target = (RecordFormat) targetDetails.gereplacedemIdOver();
                moveItemsTo(getSelectedItems(), container.indexOfId(target));
            }
        }

        public AcceptCriterion getAcceptCriterion() {
            return AcceptAll.get();
        }
    }

    clreplaced EditFieldFactory implements TableFieldFactory {

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            final RecordFormat record = (RecordFormat) itemId;
            Field<?> field = null;
            if (propertyId.equals("width")) {
                final TextField textField = new TextField();
                textField.setWidth(100, Unit.PERCENTAGE);
                textField.setImmediate(true);
                textField.addValueChangeListener(new ValueChangeListener() {

                    public void valueChange(ValueChangeEvent event) {
                        calculatePositions();
                        saveLengthSettings();
                    }
                });
                textField.addFocusListener(new FocusListener() {

                    public void focus(FocusEvent event) {
                        focusOn(record, propertyId);
                    }
                });
                record.addField(propertyId, textField);
                field = textField;
            } else if (propertyId.equals("transformText")) {
                final ComboBox combo = new ComboBox();
                combo.setWidth(100, Unit.PERCENTAGE);
                String[] functions = ModelAttributeScriptHelper.getSignatures();
                for (String function : functions) {
                    combo.addItem(function);
                }
                combo.setPageLength(functions.length > 20 ? 20 : functions.length);
                if (record.getTransformText() != null && !combo.gereplacedemIds().contains(record.getTransformText())) {
                    combo.addItem(record.getTransformText());
                }
                combo.setImmediate(true);
                combo.setNewItemsAllowed(true);
                combo.addValueChangeListener(new ValueChangeListener() {

                    public void valueChange(ValueChangeEvent event) {
                        saveTransformSettings();
                    }
                });
                combo.addFocusListener(new FocusListener() {

                    public void focus(FocusEvent event) {
                        focusOn(record, propertyId);
                    }
                });
                record.addField(propertyId, combo);
                field = combo;
            }
            RecordFormat selected = getSelectedItem();
            if (selected == itemId && record.getFocusField() != null) {
                record.getFocusField().focus();
            }
            if (field != null) {
                field.setReadOnly(readOnly);
            }
            return field;
        }

        protected void focusOn(RecordFormat record, Object propertyId) {
            record.setFocusFieldId(propertyId);
            for (Object itemId : getSelectedItems()) {
                table.unselect(itemId);
            }
            table.select(record);
        }
    }

    clreplaced TableCellStyleGenerator implements CellStyleGenerator {

        public String getStyle(Table source, Object itemId, Object propertyId) {
            if (propertyId != null && selectedItemIds != null && selectedItemIds.contains(itemId)) {
                return "highlight";
            }
            return null;
        }
    }

    public clreplaced RecordFormat {

        ModelEnreplacedy modelEnreplacedy;

        ModelAttrib modelAttribute;

        Map<Object, Field<?>> fields = new HashMap<Object, Field<?>>();

        Object focusFieldId;

        long width = 1;

        long startPos;

        long endPos;

        String transformText = "";

        int ordinalSetting;

        public RecordFormat(ModelEnreplacedy modelEnreplacedy, ModelAttrib modelAttribute) {
            this.modelEnreplacedy = modelEnreplacedy;
            this.modelAttribute = modelAttribute;
            if (component.getType().equals(DelimitedFormatter.TYPE) || component.getType().equals(DelimitedParser.TYPE)) {
                ComponentAttribSetting setting = component.getSingleAttributeSetting(modelAttribute.getId(), DelimitedFormatter.DELIMITED_FORMATTER_ATTRIBUTE_ORDINAL);
                if (setting != null) {
                    this.ordinalSetting = Integer.parseInt(setting.getValue());
                }
                setting = component.getSingleAttributeSetting(modelAttribute.getId(), DelimitedFormatter.DELIMITED_FORMATTER_ATTRIBUTE_FORMAT_FUNCTION);
                if (setting != null) {
                    this.transformText = setting.getValue();
                }
            } else {
                ComponentAttribSetting setting = component.getSingleAttributeSetting(modelAttribute.getId(), FixedLengthFormatter.FIXED_LENGTH_FORMATTER_ATTRIBUTE_LENGTH);
                if (setting != null) {
                    this.width = Long.parseLong(setting.getValue());
                }
                setting = component.getSingleAttributeSetting(modelAttribute.getId(), FixedLengthFormatter.FIXED_LENGTH_FORMATTER_ATTRIBUTE_ORDINAL);
                if (setting != null) {
                    this.ordinalSetting = Integer.parseInt(setting.getValue());
                }
                setting = component.getSingleAttributeSetting(modelAttribute.getId(), FixedLengthFormatter.FIXED_LENGTH_FORMATTER_ATTRIBUTE_FORMAT_FUNCTION);
                if (setting != null) {
                    this.transformText = setting.getValue();
                }
            }
        }

        public int hashCode() {
            return modelEnreplacedy.hashCode() + modelAttribute.hashCode();
        }

        public boolean equals(Object obj) {
            if (obj instanceof RecordFormat) {
                return hashCode() == ((RecordFormat) obj).hashCode();
            }
            return super.equals(obj);
        }

        public String getEnreplacedyName() {
            return modelEnreplacedy.getName();
        }

        public String getAttributeName() {
            return modelAttribute.getName();
        }

        public String getAttributeId() {
            return modelAttribute.getId();
        }

        public long getWidth() {
            return width;
        }

        public void setWidth(long width) {
            this.width = width;
        }

        public String getTransformText() {
            return transformText;
        }

        public void setTransformText(String transformText) {
            this.transformText = transformText;
        }

        public long getStartPos() {
            return startPos;
        }

        public void setStartPos(long startPos) {
            this.startPos = startPos;
        }

        public long getEndPos() {
            return endPos;
        }

        public void setEndPos(long endPos) {
            this.endPos = endPos;
        }

        public void addField(Object id, Field<?> field) {
            fields.put(id, field);
        }

        public void setFocusFieldId(Object id) {
            this.focusFieldId = id;
        }

        public Field<?> getFocusField() {
            Field<?> field = fields.get(focusFieldId);
            if (field == null) {
                field = fields.get("width");
            }
            return field;
        }

        public int getOrdinalSetting() {
            return ordinalSetting;
        }

        public void setOrdinalSetting(int ordinalSetting) {
            this.ordinalSetting = ordinalSetting;
        }
    }
}

19 View Complete Implementation : EditJsonPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
public clreplaced EditJsonPanel extends AbstractComponentEditPanel {

    private static final long serialVersionUID = 1L;

    Grid grid;

    Set<String> xpathChoices;

    BeanItemContainer<Record> container;

    public final static String JSON_PATH = "json.path";

    public final static String JSON_TEMPLATE = "json.template";

    protected void buildUI() {
        ButtonBar buttonBar = new ButtonBar();
        addComponent(buttonBar);
        Button editButton = buttonBar.addButton("Edit Template", FontAwesome.FILE_CODE_O);
        editButton.addClickListener(new EditTemplateClickListener());
        buttonBar.addButtonRight("Export", FontAwesome.DOWNLOAD, (e) -> export());
        buildGrid();
        refresh();
        saveSettings();
    // buildPathChoices();
    }

    protected void export() {
        String fileNamePrefix = component.getName().toLowerCase().replace(' ', '-');
        ExportDialog dialog = new ExportDialog(new Grid7DataProvider(grid), fileNamePrefix, component.getName());
        UI.getCurrent().addWindow(dialog);
    }

    protected void buildGrid() {
        grid = new Grid();
        grid.setSelectionMode(SelectionMode.NONE);
        grid.setSizeFull();
        grid.setEditorEnabled(!readOnly);
        container = new BeanItemContainer<Record>(Record.clreplaced);
        grid.setContainerDataSource(container);
        grid.setColumns("enreplacedyName", "attributeName", "path");
        HeaderRow filterRow = grid.appendHeaderRow();
        addColumn("enreplacedyName", filterRow);
        addColumn("attributeName", filterRow);
        ComboBox combo = new ComboBox();
        combo.addValueChangeListener(e -> saveSettings());
        combo.setWidth(100, Unit.PERCENTAGE);
        combo.setImmediate(true);
        combo.setNewItemsAllowed(true);
        combo.setInvalidAllowed(true);
        combo.setTextInputAllowed(true);
        combo.setScrollToSelectedItem(true);
        combo.setFilteringMode(FilteringMode.CONTAINS);
        grid.getColumn("path").setEditorField(combo).setExpandRatio(1);
        addShowPopulatedFilter("path", filterRow);
        grid.setEditorBuffered(false);
        addComponent(grid);
        setExpandRatio(grid, 1);
    }

    protected void refresh() {
        RelationalModel model = (RelationalModel) component.getOutputModel();
        if (model != null) {
            Collections.sort(model.getModelEnreplacedies(), new Comparator<ModelEnreplacedy>() {

                public int compare(ModelEnreplacedy enreplacedy1, ModelEnreplacedy enreplacedy2) {
                    return enreplacedy1.getName().toLowerCase().compareTo(enreplacedy2.getName().toLowerCase());
                }
            });
            for (ModelEnreplacedy enreplacedy : model.getModelEnreplacedies()) {
                boolean firstAttribute = true;
                Record enreplacedyRecord = new Record(enreplacedy, null);
                for (ModelAttrib attr : enreplacedy.getModelAttributes()) {
                    if (firstAttribute) {
                        firstAttribute = false;
                        container.addItem(enreplacedyRecord);
                    }
                    container.addItem(new Record(enreplacedy, attr));
                }
                if (firstAttribute) {
                    container.addItem(enreplacedyRecord);
                }
            }
        }
    }

    protected void addShowPopulatedFilter(String propertyId, HeaderRow filterRow) {
        HeaderCell cell = filterRow.getCell(propertyId);
        CheckBox group = new CheckBox("Show Set Only");
        group.setImmediate(true);
        group.addValueChangeListener(l -> {
            container.removeContainerFilters(propertyId);
            if (group.getValue()) {
                container.addContainerFilter(new And(new Not(new Compare.Equal(propertyId, "")), new Not(new IsNull(propertyId))));
            }
        });
        group.addStyleName(ValoTheme.CHECKBOX_SMALL);
        cell.setComponent(group);
    }

    protected void addColumn(String propertyId, HeaderRow filterRow) {
        grid.getColumn(propertyId).setEditable(false);
        HeaderCell cell = filterRow.getCell(propertyId);
        TextField filterField = new TextField();
        filterField.setInputPrompt("Filter");
        filterField.setImmediate(true);
        filterField.addStyleName(ValoTheme.TEXTFIELD_TINY);
        filterField.setWidth(100, Unit.PERCENTAGE);
        filterField.addTextChangeListener(change -> {
            container.removeContainerFilters(propertyId);
            if (!change.getText().isEmpty()) {
                container.addContainerFilter(new SimpleStringFilter(propertyId, change.getText(), true, false));
            }
        });
        cell.setComponent(filterField);
    }

    protected void saveSettings() {
        for (Object obj : container.gereplacedemIds()) {
            Record record = (Record) obj;
            if (record.modelAttribute != null) {
                saveAttributeSetting(record.modelAttribute.getId(), JSON_PATH, StringUtils.trimToNull(record.getPath()));
            } else {
                saveEnreplacedySetting(record.modelEnreplacedy.getId(), JSON_PATH, StringUtils.trimToNull(record.getPath()));
            }
        }
    }

    protected void saveAttributeSetting(String attributeId, String name, String value) {
        ComponentAttribSetting setting = component.getSingleAttributeSetting(attributeId, name);
        if (setting == null && value != null) {
            setting = new ComponentAttribSetting(attributeId, name, value);
            setting.setComponentId(component.getId());
            component.addAttributeSetting(setting);
            context.getConfigurationService().save(setting);
        } else if (setting != null && !StringUtils.equals(setting.getValue(), value)) {
            if (value == null) {
                setting.setValue(value);
                context.getConfigurationService().delete(setting);
            } else {
                setting.setValue(value);
                context.getConfigurationService().save(setting);
            }
        }
    }

    protected void saveEnreplacedySetting(String enreplacedyId, String name, String value) {
        ComponentEnreplacedySetting setting = component.getSingleEnreplacedySetting(enreplacedyId, name);
        if (setting == null && value != null) {
            setting = new ComponentEnreplacedySetting(enreplacedyId, name, value);
            setting.setComponentId(component.getId());
            component.addEnreplacedySetting(setting);
            context.getConfigurationService().save(setting);
        } else if (setting != null && !StringUtils.equals(setting.getValue(), value)) {
            if (value == null) {
                setting.setValue(value);
                context.getConfigurationService().delete(setting);
            } else {
                setting.setValue(value);
                context.getConfigurationService().save(setting);
            }
        }
    }

    protected void buildPathChoices() {
    // SAXBuilder builder = new SAXBuilder();
    // builder.setXMLReaderFactory(XMLReaders.NONVALIDATING);
    // builder.setFeature("http://xml.org/sax/features/validation", false);
    // Setting setting = component.findSetting(XmlFormatter.XML_FORMATTER_TEMPLATE);
    // xpathChoices = new TreeSet<String>();
    // if (StringUtils.isNotBlank(setting.getValue())) {
    // try {
    // Doreplacedent doreplacedent = builder.build(new StringReader(setting.getValue()));
    // 
    // buildXpathChoicesFromElement("/" + doreplacedent.getRootElement().getName(),
    // doreplacedent.getRootElement());
    // } catch (Exception e) {
    // throw new RuntimeException(e);
    // }
    // }
    // 
    // ComboBox combo = (ComboBox) grid.getColumn("xpath").getEditorField();
    // combo.removeAllItems();
    // combo.addItems(xpathChoices);
    }

    // protected void buildXpathChoicesFromElement(String prefix, Element parentElement) {
    // for (Element element : parentElement.getChildren()) {
    // String text = prefix + "/" + element.getName();
    // xpathChoices.add(text);
    // for (Attribute attr : element.getAttributes()) {
    // String attrText = text + "/@" + attr.getName();
    // xpathChoices.add(attrText);
    // }
    // buildXpathChoicesFromElement(text, element);
    // }
    // }
    clreplaced EditTemplateClickListener implements ClickListener {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {
            EditTemplateWindow window = new EditTemplateWindow();
            window.show();
        }
    }

    clreplaced EditTemplateWindow extends ResizableWindow {

        private static final long serialVersionUID = 1L;

        AceEditor editor;

        public EditTemplateWindow() {
            super("Edit JSON Template");
            setWidth(800f, Unit.PIXELS);
            setHeight(600f, Unit.PIXELS);
            content.setMargin(true);
            editor = new AceEditor();
            editor.setMode(AceMode.xml);
            editor.setSizeFull();
            editor.setHighlightActiveLine(true);
            editor.setShowPrintMargin(false);
            addComponent(editor);
            content.setExpandRatio(editor, 1.0f);
            Setting templateSetting = component.findSetting(JSON_TEMPLATE);
            editor.setValue(templateSetting.getValue());
            editor.setReadOnly(readOnly);
            addComponent(buildButtonFooter(buildCloseButton()));
        }

        @Override
        public void close() {
            super.close();
            Setting templateSetting = component.findSetting(JSON_TEMPLATE);
            templateSetting.setValue(editor.getValue());
            context.getConfigurationService().save(templateSetting);
            // buildXpathChoices();
            refresh();
        }
    }

    clreplaced ImportTemplateClickListener implements ClickListener, ImportXmlListener {

        private static final long serialVersionUID = 1L;

        ImportXmlTemplateWindow importWindow;

        public void buttonClick(ClickEvent event) {
            importWindow = new ImportXmlTemplateWindow(this, component, context);
            UI.getCurrent().addWindow(importWindow);
        }

        public void onImport(String xml) {
            Setting templateSetting = component.findSetting(JSON_TEMPLATE);
            templateSetting.setValue(xml);
            context.getConfigurationService().save(templateSetting);
            importWindow.close();
            EditTemplateWindow editWindow = new EditTemplateWindow();
            editWindow.show();
        }
    }

    public clreplaced Record implements Serializable {

        private static final long serialVersionUID = 1L;

        ModelEnreplacedy modelEnreplacedy;

        ModelAttrib modelAttribute;

        String path = "";

        public Record(ModelEnreplacedy modelEnreplacedy, ModelAttrib modelAttribute) {
            this.modelEnreplacedy = modelEnreplacedy;
            this.modelAttribute = modelAttribute;
            if (modelAttribute != null) {
                ComponentAttribSetting setting = component.getSingleAttributeSetting(modelAttribute.getId(), EditJsonPanel.JSON_PATH);
                if (setting != null) {
                    path = setting.getValue();
                }
            } else {
                ComponentEnreplacedySetting setting = component.getSingleEnreplacedySetting(modelEnreplacedy.getId(), EditJsonPanel.JSON_PATH);
                if (setting != null) {
                    path = setting.getValue();
                }
            }
        }

        public int hashCode() {
            return modelEnreplacedy.hashCode() + (modelAttribute == null ? 0 : modelAttribute.hashCode());
        }

        public boolean equals(Object obj) {
            if (obj instanceof Record) {
                return hashCode() == ((Record) obj).hashCode();
            }
            return super.equals(obj);
        }

        public String getEnreplacedyName() {
            return modelEnreplacedy.getName();
        }

        public String getAttributeName() {
            if (modelAttribute != null) {
                return modelAttribute.getName();
            }
            return null;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }
    }
}

19 View Complete Implementation : RelationalHierarchicalMappingPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced RelationalHierarchicalMappingPanel extends AbstractFlowStepAwareComponentEditPanel {

    MappingDiagram diagram;

    Button removeButton;

    CheckBox srcMapFilter;

    CheckBox dstMapFilter;

    TextField srcTextFilter;

    TextField dstTextFilter;

    RelationalModel inputModel;

    HierarchicalModel outputModel;

    Table queryMappingTable = new Table();

    BeanItemContainer<EnreplacedySettings> enreplacedySettingsContainer = new BeanItemContainer<EnreplacedySettings>(EnreplacedySettings.clreplaced);

    List<EnreplacedySettings> enreplacedySettings = new ArrayList<EnreplacedySettings>();

    EditByQueryMappingWindow queryMappingWindow;

    protected void buildUI() {
        this.inputModel = (RelationalModel) component.getInputModel();
        this.outputModel = (HierarchicalModel) component.getOutputModel();
        ButtonBar buttonBar = new ButtonBar();
        if (!readOnly) {
            addComponent(buttonBar);
            Button byQueryMapButton = buttonBar.addButton("By Query Map", FontAwesome.MAP);
            removeButton = buttonBar.addButton("Remove", FontAwesome.TRASH_O);
            removeButton.setEnabled(false);
            byQueryMapButton.addClickListener(new ByQueryMapListener());
            String queryMethod = component.get(RelationalHierarchicalMapping.HIERARCHICAL_QUERY_METHOD, RelationalHierarchicalMapping.QUERY_METHOD_BY_JOIN);
            if (queryMethod.equalsIgnoreCase(RelationalHierarchicalMapping.QUERY_METHOD_BY_JOIN)) {
                byQueryMapButton.setEnabled(false);
            }
            removeButton.addClickListener(new RemoveListener());
        }
        buttonBar.addButtonRight("Export", FontAwesome.DOWNLOAD, (e) -> export());
        HorizontalLayout replacedleHeader = new HorizontalLayout();
        replacedleHeader.setSpacing(true);
        replacedleHeader.setMargin(new MarginInfo(false, true, false, true));
        replacedleHeader.setWidth(100f, Unit.PERCENTAGE);
        replacedleHeader.addComponent(new Label("<b>Input Model:</b>  " + (component.getInputModel() != null ? component.getInputModel().getName() : "?"), ContentMode.HTML));
        replacedleHeader.addComponent(new Label("<b>Output Model:</b>  " + (component.getOutputModel() != null ? component.getOutputModel().getName() : "?"), ContentMode.HTML));
        addComponent(replacedleHeader);
        HorizontalLayout filterHeader = new HorizontalLayout();
        filterHeader.setSpacing(true);
        filterHeader.setMargin(new MarginInfo(true, true, true, true));
        filterHeader.setWidth(100f, Unit.PERCENTAGE);
        HorizontalLayout srcFilterHeader = new HorizontalLayout();
        srcFilterHeader.setSpacing(true);
        srcFilterHeader.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);
        filterHeader.addComponent(srcFilterHeader);
        HorizontalLayout dstFilterHeader = new HorizontalLayout();
        dstFilterHeader.setSpacing(true);
        dstFilterHeader.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);
        filterHeader.addComponent(dstFilterHeader);
        addComponent(filterHeader);
        srcTextFilter = new TextField();
        srcTextFilter.setWidth(20, Unit.EM);
        srcTextFilter.setInputPrompt("Filter");
        srcTextFilter.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);
        srcTextFilter.setIcon(FontAwesome.SEARCH);
        srcTextFilter.setImmediate(true);
        srcTextFilter.setTextChangeEventMode(TextChangeEventMode.LAZY);
        srcTextFilter.setTextChangeTimeout(200);
        srcTextFilter.addTextChangeListener(new FilterInputTextListener());
        srcFilterHeader.addComponent(srcTextFilter);
        srcMapFilter = new CheckBox("Mapped Only");
        srcMapFilter.addValueChangeListener(new FilterSrcMapListener());
        srcFilterHeader.addComponent(srcMapFilter);
        dstTextFilter = new TextField();
        dstTextFilter.setWidth(20, Unit.EM);
        dstTextFilter.setInputPrompt("Filter");
        dstTextFilter.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);
        dstTextFilter.setIcon(FontAwesome.SEARCH);
        dstTextFilter.setImmediate(true);
        dstTextFilter.setTextChangeEventMode(TextChangeEventMode.LAZY);
        dstTextFilter.setTextChangeTimeout(200);
        dstTextFilter.addTextChangeListener(new FilterOutputTextListener());
        dstFilterHeader.addComponent(dstTextFilter);
        dstMapFilter = new CheckBox("Mapped Only");
        dstMapFilter.addValueChangeListener(new FilterDstMapListener());
        dstFilterHeader.addComponent(dstMapFilter);
        Panel panel = new Panel();
        VerticalLayout vlay = new VerticalLayout();
        vlay.setSizeFull();
        diagram = new MappingDiagram(context, component, readOnly);
        diagram.setSizeFull();
        vlay.addComponent(diagram);
        panel.setContent(vlay);
        panel.setSizeFull();
        addComponent(panel);
        setExpandRatio(panel, 1.0f);
        diagram.addListener(new EventListener());
        buildByQueryMappingWindow();
    }

    protected void buildByQueryMappingWindow() {
        queryMappingWindow = new EditByQueryMappingWindow();
    }

    @Override
    public void selected() {
        if (isNotBlank(srcTextFilter.getValue()) || srcMapFilter.getValue()) {
            diagram.filterInputModel(srcTextFilter.getValue().trim(), srcMapFilter.getValue());
        }
        if (isNotBlank(dstTextFilter.getValue()) || dstMapFilter.getValue()) {
            diagram.filterOutputModel(dstTextFilter.getValue().trim(), dstMapFilter.getValue());
        }
    }

    protected boolean fuzzyMatches(String str1, String str2) {
        int x = computeLevenshteinDistance(str1, str2);
        return x < 3;
    }

    protected int computeLevenshteinDistance(CharSequence str1, CharSequence str2) {
        int[][] distance = new int[str1.length() + 1][str2.length() + 1];
        for (int i = 0; i <= str1.length(); i++) {
            distance[i][0] = i;
        }
        for (int j = 1; j <= str2.length(); j++) {
            distance[0][j] = j;
        }
        for (int i = 1; i <= str1.length(); i++) {
            for (int j = 1; j <= str2.length(); j++) {
                distance[i][j] = minimum(distance[i - 1][j] + 1, distance[i][j - 1] + 1, distance[i - 1][j - 1] + ((str1.charAt(i - 1) == str2.charAt(j - 1)) ? 0 : 1));
            }
        }
        return distance[str1.length()][str2.length()];
    }

    protected int minimum(int a, int b, int c) {
        return Math.min(Math.min(a, b), c);
    }

    protected void export() {
        Table table = new Table();
        table.addContainerProperty("Source Enreplacedy", String.clreplaced, null);
        table.addContainerProperty("Source Attribute", String.clreplaced, null);
        table.addContainerProperty("Destination Schema Object", String.clreplaced, null);
        int itemId = 0;
        for (ComponentAttribSetting setting : component.getAttributeSettings()) {
            if (Mapping.ATTRIBUTE_MAPS_TO.equals(setting.getName())) {
            // ModelAttrib srcAttribute = component.getInputModel().getAttributeById(setting.getAttributeId());
            // ModelEnreplacedy srcEnreplacedy = component.getInputModel().getEnreplacedyById(srcAttribute.getEnreplacedyId());
            // ModelAttrib dstAttribute = component.getOutputModel().getAttributeById(setting.getValue());
            // ModelEnreplacedy dstEnreplacedy = component.getOutputModel().getEnreplacedyById(dstAttribute.getEnreplacedyId());
            // table.addItem(new Object[]{srcEnreplacedy.getName(), srcAttribute.getName(), dstEnreplacedy.getName(), dstAttribute.getName()}, itemId++);
            }
        }
        String fileNamePrefix = component.getName().toLowerCase().replace(' ', '-');
        ExportDialog dialog = new ExportDialog(new TableV7DataProvider(table), fileNamePrefix, component.getName());
        UI.getCurrent().addWindow(dialog);
    }

    clreplaced EventListener implements Listener {

        public void componentEvent(Event event) {
            if (event instanceof SelectEvent) {
                SelectEvent selectEvent = (SelectEvent) event;
                removeButton.setEnabled(selectEvent.getSelectedSourceId() != null);
            }
        }
    }

    clreplaced RemoveListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            diagram.removeSelected();
            removeButton.setEnabled(false);
        }
    }

    clreplaced ByQueryMapListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            // TODO:
            refreshEnreplacedySettingsContainer();
            updateQueryMappingTable();
            queryMappingWindow.show();
        }
    }

    clreplaced FilterInputTextListener implements TextChangeListener {

        public void textChange(TextChangeEvent event) {
            diagram.filterInputModel((String) event.getText(), srcMapFilter.getValue());
        }
    }

    clreplaced FilterOutputTextListener implements TextChangeListener {

        public void textChange(TextChangeEvent event) {
            diagram.filterOutputModel((String) event.getText(), dstMapFilter.getValue());
        }
    }

    clreplaced FilterSrcMapListener implements ValueChangeListener {

        public void valueChange(ValueChangeEvent event) {
            diagram.filterInputModel(srcTextFilter.getValue(), (boolean) event.getProperty().getValue());
        }
    }

    clreplaced FilterDstMapListener implements ValueChangeListener {

        public void valueChange(ValueChangeEvent event) {
            diagram.filterOutputModel(dstTextFilter.getValue(), (boolean) event.getProperty().getValue());
        }
    }

    clreplaced EditByQueryMappingWindow extends ResizableWindow {

        private static final long serialVersionUID = 1L;

        public EditByQueryMappingWindow() {
            super("Edit Enreplacedy Mapping to Source Reader");
            setWidth(800f, Unit.PIXELS);
            setHeight(600f, Unit.PIXELS);
            content.setMargin(true);
            buildQueryMappingTable();
            addComponent(buildButtonFooter(buildCloseButton()));
        }

        private void buildQueryMappingTable() {
            queryMappingTable.setContainerDataSource(enreplacedySettingsContainer);
            queryMappingTable.setSelectable(true);
            queryMappingTable.setSortEnabled(false);
            queryMappingTable.setImmediate(true);
            queryMappingTable.setSizeFull();
            queryMappingTable.addGeneratedColumn("enreplacedyName", new ColumnGenerator() {

                private static final long serialVersionUID = 1L;

                @Override
                public Object generateCell(Table source, Object itemId, Object columnId) {
                    EnreplacedySettings setting = (EnreplacedySettings) itemId;
                    HierarchicalModel model = (HierarchicalModel) component.getOutputModel();
                    ModelSchemaObject object = model.getObjectById(setting.getEnreplacedyId());
                    return object.getName();
                }
            });
            queryMappingTable.setVisibleColumns(new Object[] { "enreplacedyName", "sourceStep" });
            queryMappingTable.setColumnWidth("sourceStep", 350);
            queryMappingTable.setColumnHeaders(new String[] { "Enreplacedy Name", "Source Step" });
            queryMappingTable.setColumnExpandRatio("enreplacedyName", 1);
            queryMappingTable.setTableFieldFactory(new EditSourceStepFieldFactory());
            queryMappingTable.setEditable(true);
            addComponent(queryMappingTable, 1);
        }
    }

    private void refreshEnreplacedySettingsContainer() {
        enreplacedySettings.clear();
        ModelSchemaObject root = outputModel.getRootObject();
        List<ComponentEnreplacedySetting> compEnreplacedySettings = component.getEnreplacedySettings();
        Set<String> existingEnreplacedySettings = new HashSet<String>();
        for (ComponentEnreplacedySetting compEnreplacedySetting : compEnreplacedySettings) {
            if (RelationalHierarchicalMapping.ENreplacedY_TO_ORGINATING_STEP_ID.equalsIgnoreCase(compEnreplacedySetting.getName())) {
                enreplacedySettings.add(new EnreplacedySettings(compEnreplacedySetting.getEnreplacedyId(), compEnreplacedySetting.getValue()));
                existingEnreplacedySettings.add(compEnreplacedySetting.getEnreplacedyId());
            }
        }
        addEnreplacedySettings(root, existingEnreplacedySettings);
    }

    private void addEnreplacedySettings(ModelSchemaObject object, Set<String> existingEnreplacedySettings) {
        if (!existingEnreplacedySettings.contains(object.getId())) {
            enreplacedySettings.add(new EnreplacedySettings(object.getId(), null));
        }
        for (ModelSchemaObject childObject : object.getChildObjects()) {
            addEnreplacedySettings(childObject, existingEnreplacedySettings);
        }
    }

    // List<ModelEnreplacedy> enreplacedies = component.getOutputModel().getModelEnreplacedies();
    // List<ComponentEnreplacedySetting> compEnreplacedySettings = component.getEnreplacedySettings();
    // Set<String> existingEnreplacedySettings = new HashSet<String>();
    // for (ComponentEnreplacedySetting compEnreplacedySetting:compEnreplacedySettings) {
    // if (RelationalHierarchicalMapping.ENreplacedY_TO_ORGINATING_STEP_ID.equalsIgnoreCase(compEnreplacedySetting.getName())) {
    // enreplacedySettings.add(new EnreplacedySettings(compEnreplacedySetting.getEnreplacedyId(),compEnreplacedySetting.getValue()));
    // existingEnreplacedySettings.add(compEnreplacedySetting.getEnreplacedyId());
    // }
    // }
    // for (ModelEnreplacedy enreplacedy:enreplacedies) {
    // if (!existingEnreplacedySettings.contains(enreplacedy.getId())) {
    // enreplacedySettings.add(new EnreplacedySettings(enreplacedy.getId(),null));
    // }
    // }
    protected void updateQueryMappingTable() {
        queryMappingTable.removeAllItems();
        for (EnreplacedySettings enreplacedySetting : enreplacedySettings) {
            queryMappingTable.addItem(enreplacedySetting);
        }
    }

    clreplaced EditSourceStepFieldFactory implements TableFieldFactory {

        private static final long serialVersionUID = 1L;

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            final EnreplacedySettings settings = (EnreplacedySettings) itemId;
            if (propertyId.equals("sourceStep")) {
                return createSourceStepComboBox(settings, RelationalHierarchicalMapping.ENreplacedY_TO_ORGINATING_STEP_ID);
            } else {
                return null;
            }
        }
    }

    protected ComboBox createSourceStepComboBox(final EnreplacedySettings settings, final String key) {
        final ComboBox comboBox = new ComboBox();
        comboBox.setImmediate(true);
        flow = context.getConfigurationService().findFlow(flow.getId());
        List<FlowStepLink> stepLinks = flow.findFlowStepLinksWithTarget(flowStep.getId());
        for (FlowStepLink flowStepLink : stepLinks) {
            FlowStep comboStep = flow.findFlowStepWithId(flowStepLink.getSourceStepId());
            comboBox.addItem(comboStep.getId());
            comboBox.sereplacedemCaption(comboStep.getId(), comboStep.getName());
        }
        comboBox.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                ComponentEnreplacedySetting setting = component.getSingleEnreplacedySetting(settings.getEnreplacedyId(), key);
                String oldValue = setting == null ? null : setting.getValue();
                if (setting == null) {
                    setting = new ComponentEnreplacedySetting(settings.getEnreplacedyId(), component.getId(), key, null);
                    component.addEnreplacedySetting(setting);
                }
                if (comboBox.getValue() != null) {
                    setting.setValue(comboBox.getValue().toString());
                } else {
                    setting.setValue(null);
                }
                if (oldValue == null || !oldValue.equals(setting.getValue())) {
                    context.getConfigurationService().save(setting);
                }
            }
        });
        comboBox.setReadOnly(readOnly);
        comboBox.setWidth("100%");
        return comboBox;
    }

    public static clreplaced EnreplacedySettings implements Serializable {

        private static final long serialVersionUID = 1L;

        String enreplacedyId;

        String sourceStep;

        public EnreplacedySettings(String enreplacedyId, String sourceStep) {
            this.enreplacedyId = enreplacedyId;
            this.sourceStep = sourceStep;
        }

        public String getEnreplacedyId() {
            return enreplacedyId;
        }

        public void setEnreplacedyId(String enreplacedyId) {
            this.enreplacedyId = enreplacedyId;
        }

        public String getSourceStep() {
            return sourceStep;
        }

        public void setSourceStep(String sourceStep) {
            this.sourceStep = sourceStep;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof EnreplacedySettings) {
                return enreplacedyId.equals(((EnreplacedySettings) obj).getEnreplacedyId());
            } else {
                return super.equals(obj);
            }
        }
    }
}

19 View Complete Implementation : EditRdbmsWriterPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced EditRdbmsWriterPanel extends AbstractComponentEditPanel {

    Table table = new Table();

    TextField filterField;

    List<AttributeSettings> attributeSettings = new ArrayList<AttributeSettings>();

    BeanItemContainer<AttributeSettings> container = new BeanItemContainer<AttributeSettings>(AttributeSettings.clreplaced);

    protected void buildUI() {
        ButtonBar buttonBar = new ButtonBar();
        addComponent(buttonBar);
        filterField = buttonBar.addFilter();
        filterField.addTextChangeListener(new TextChangeListener() {

            @Override
            public void textChange(TextChangeEvent event) {
                filterField.setValue(event.getText());
                updateTable(event.getText());
            }
        });
        addComponent(buttonBar);
        table.setContainerDataSource(container);
        table.setSelectable(true);
        table.setSortEnabled(false);
        table.setImmediate(true);
        table.setSortEnabled(true);
        table.setSizeFull();
        table.addGeneratedColumn("enreplacedyName", new ColumnGenerator() {

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                AttributeSettings setting = (AttributeSettings) itemId;
                RelationalModel model = (RelationalModel) component.getInputModel();
                ModelAttrib attribute = model.getAttributeById(setting.getAttributeId());
                ModelEnreplacedy enreplacedy = model.getEnreplacedyById(attribute.getEnreplacedyId());
                return UiUtils.getName(filterField.getValue(), enreplacedy.getName());
            }
        });
        table.addGeneratedColumn("attributeName", new ColumnGenerator() {

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                AttributeSettings setting = (AttributeSettings) itemId;
                RelationalModel model = (RelationalModel) component.getInputModel();
                ModelAttrib attribute = model.getAttributeById(setting.getAttributeId());
                return UiUtils.getName(filterField.getValue(), attribute.getName());
            }
        });
        table.setVisibleColumns(new Object[] { "enreplacedyName", "attributeName", "insertEnabled", "updateEnabled" });
        table.setColumnWidth("enreplacedyName", 250);
        table.setColumnWidth("attributeName", 250);
        table.setColumnHeaders(new String[] { "Enreplacedy Name", "Attribute Name", "Insert Enabled", "Update Enabled" });
        table.setColumnExpandRatio("value", 1);
        table.setTableFieldFactory(new EditFieldFactory());
        table.setEditable(true);
        addComponent(table);
        setExpandRatio(table, 1.0f);
        if (component.getInputModel() != null) {
            for (ModelEnreplacedy enreplacedy : ((RelationalModel) component.getInputModel()).getModelEnreplacedies()) {
                for (ModelAttrib attr : enreplacedy.getModelAttributes()) {
                    ComponentAttribSetting insert = component.getSingleAttributeSetting(attr.getId(), RdbmsWriter.ATTRIBUTE_INSERT_ENABLED);
                    ComponentAttribSetting update = component.getSingleAttributeSetting(attr.getId(), RdbmsWriter.ATTRIBUTE_UPDATE_ENABLED);
                    boolean insertEnabled = insert != null ? Boolean.parseBoolean(insert.getValue()) : true;
                    boolean updateEnabled = update != null ? Boolean.parseBoolean(update.getValue()) : true;
                    attributeSettings.add(new AttributeSettings(attr.getId(), insertEnabled, updateEnabled));
                }
            }
            Collections.sort(attributeSettings, new Comparator<AttributeSettings>() {

                @Override
                public int compare(AttributeSettings o1, AttributeSettings o2) {
                    RelationalModel model = (RelationalModel) component.getInputModel();
                    ModelAttrib attribute1 = model.getAttributeById(o1.getAttributeId());
                    ModelEnreplacedy enreplacedy1 = model.getEnreplacedyById(attribute1.getEnreplacedyId());
                    ModelAttrib attribute2 = model.getAttributeById(o2.getAttributeId());
                    ModelEnreplacedy enreplacedy2 = model.getEnreplacedyById(attribute2.getEnreplacedyId());
                    int compare = enreplacedy1.getName().compareTo(enreplacedy2.getName());
                    if (compare == 0) {
                        compare = attribute1.getName().compareTo(attribute2.getName());
                    }
                    return compare;
                }
            });
        }
        updateTable(null);
    }

    protected void updateTable(String filter) {
        filter = filter != null ? filter.toLowerCase() : null;
        table.removeAllItems();
        for (AttributeSettings attributeSetting : attributeSettings) {
            RelationalModel model = (RelationalModel) component.getInputModel();
            ModelAttrib attribute = model.getAttributeById(attributeSetting.getAttributeId());
            ModelEnreplacedy enreplacedy = model.getEnreplacedyById(attribute.getEnreplacedyId());
            if (isBlank(filter) || enreplacedy.getName().toLowerCase().contains(filter) || attribute.getName().toLowerCase().contains(filter)) {
                table.addItem(attributeSetting);
            }
        }
    }

    clreplaced EditFieldFactory implements TableFieldFactory {

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            final AttributeSettings settings = (AttributeSettings) itemId;
            if (propertyId.equals("insertEnabled")) {
                return createCheckBox(settings, RdbmsWriter.ATTRIBUTE_INSERT_ENABLED);
            } else if (propertyId.equals("updateEnabled")) {
                return createCheckBox(settings, RdbmsWriter.ATTRIBUTE_UPDATE_ENABLED);
            } else {
                return null;
            }
        }
    }

    private CheckBox createCheckBox(final AttributeSettings settings, final String key) {
        final CheckBox checkBox = new CheckBox();
        checkBox.setImmediate(true);
        if (!readOnly) {
            checkBox.addValueChangeListener((event) -> {
                ComponentAttribSetting setting = component.getSingleAttributeSetting(settings.getAttributeId(), key);
                String oldValue = setting == null ? Boolean.TRUE.toString() : setting.getValue();
                if (setting == null) {
                    setting = new ComponentAttribSetting(settings.getAttributeId(), component.getId(), key, Boolean.TRUE.toString());
                    component.addAttributeSetting(setting);
                }
                setting.setValue(checkBox.getValue().toString());
                if (!oldValue.equals(setting.getValue())) {
                    context.getConfigurationService().save(setting);
                }
            });
        }
        checkBox.setReadOnly(readOnly);
        return checkBox;
    }

    public static clreplaced AttributeSettings {

        String attributeId;

        boolean insertEnabled;

        boolean updateEnabled;

        public AttributeSettings(String attributeId, boolean insertEnabled, boolean updateEnabled) {
            this.attributeId = attributeId;
            this.insertEnabled = insertEnabled;
            this.updateEnabled = updateEnabled;
        }

        public void setInsertEnabled(boolean insertEnabled) {
            this.insertEnabled = insertEnabled;
        }

        public boolean isInsertEnabled() {
            return insertEnabled;
        }

        public void setUpdateEnabled(boolean updateEnabled) {
            this.updateEnabled = updateEnabled;
        }

        public boolean isUpdateEnabled() {
            return updateEnabled;
        }

        public String getAttributeId() {
            return attributeId;
        }

        public void setAttributeId(String attributeId) {
            this.attributeId = attributeId;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof AttributeSettings) {
                return attributeId.equals(((AttributeSettings) obj).getAttributeId());
            } else {
                return super.equals(obj);
            }
        }

        @Override
        public int hashCode() {
            return attributeId.hashCode();
        }
    }
}

19 View Complete Implementation : EditContentRouterPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced EditContentRouterPanel extends AbstractFlowStepAwareComponentEditPanel {

    Table table = new Table();

    Button addButton;

    Button removeButton;

    BeanItemContainer<Route> container = new BeanItemContainer<Route>(Route.clreplaced);

    protected void buildUI() {
        if (!readOnly) {
            ButtonBar buttonBar = new ButtonBar();
            addComponent(buttonBar);
            addButton = buttonBar.addButton("Add", FontAwesome.PLUS);
            addButton.addClickListener((event) -> table.addItem(new Route()));
            removeButton = buttonBar.addButton("Remove", FontAwesome.TRASH_O);
            removeButton.addClickListener((event) -> {
                if (table.getValue() != null) {
                    table.removeItem(table.getValue());
                    save();
                }
            });
        }
        table.setContainerDataSource(container);
        table.setSelectable(true);
        table.setSortEnabled(false);
        table.setImmediate(true);
        table.setSizeFull();
        table.setVisibleColumns(new Object[] { "matchExpression", "targetStepId" });
        table.setColumnHeaders(new String[] { "Expression", "Target Step" });
        table.setTableFieldFactory(new EditFieldFactory());
        table.addItemClickListener((event) -> {
            if (table.getValue() != null) {
                table.setValue(null);
            }
        });
        table.setEditable(true);
        if (!readOnly) {
            table.addValueChangeListener((event) -> removeButton.setEnabled(table.getValue() != null));
        }
        addComponent(table);
        setExpandRatio(table, 1.0f);
    }

    @Override
    public void selected() {
        table.removeAllItems();
        String json = flowStep.getComponent().get(ContentRouter.SETTING_CONFIG);
        if (isNotBlank(json)) {
            try {
                List<Route> routes = new ObjectMapper().readValue(json, new TypeReference<List<Route>>() {
                });
                for (Route route : routes) {
                    table.addItem(route);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    protected void save() {
        @SuppressWarnings("unchecked")
        List<Route> routes = new ArrayList<Route>((Collection<Route>) table.gereplacedemIds());
        try {
            Setting setting = flowStep.getComponent().findSetting(ContentRouter.SETTING_CONFIG);
            setting.setValue(new ObjectMapper().writeValuereplacedtring(routes));
            context.getConfigurationService().save(setting);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    clreplaced EditFieldFactory implements TableFieldFactory {

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            final Route route = (Route) itemId;
            Field<?> field = null;
            if (propertyId.equals("matchExpression")) {
                final TextField textField = new ImmediateUpdateTextField(null) {

                    @Override
                    protected void save(String text) {
                        route.setMatchExpression(text);
                        EditContentRouterPanel.this.save();
                    }
                };
                textField.setWidth(100, Unit.PERCENTAGE);
                textField.setValue(route.getMatchExpression());
                field = textField;
            } else if (propertyId.equals("targetStepId")) {
                final ComboBox combo = new ComboBox();
                combo.setWidth(100, Unit.PERCENTAGE);
                flow = context.getConfigurationService().findFlow(flow.getId());
                List<FlowStepLink> stepLinks = flow.findFlowStepLinksWithSource(flowStep.getId());
                for (FlowStepLink flowStepLink : stepLinks) {
                    FlowStep comboStep = flow.findFlowStepWithId(flowStepLink.getTargetStepId());
                    combo.addItem(comboStep.getId());
                    combo.sereplacedemCaption(comboStep.getId(), comboStep.getName());
                    if (flowStepLink.getTargetStepId().equals(route.getTargetStepId()) || combo.getValue() == null) {
                        combo.setValue(comboStep.getId());
                    }
                }
                combo.setImmediate(true);
                combo.setNewItemsAllowed(false);
                combo.setNullSelectionAllowed(false);
                combo.addValueChangeListener(new ValueChangeListener() {

                    public void valueChange(ValueChangeEvent event) {
                        String stepId = (String) event.getProperty().getValue();
                        if (stepId != null) {
                            route.setTargetStepId(stepId);
                            EditContentRouterPanel.this.save();
                        }
                    }
                });
                field = combo;
            }
            if (field != null) {
                field.setReadOnly(readOnly);
            }
            return field;
        }
    }
}

19 View Complete Implementation : EditSorterPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced EditSorterPanel extends AbstractComponentEditPanel {

    Table table = new Table();

    BeanItemContainer<RecordFormat> container = new BeanItemContainer<RecordFormat>(RecordFormat.clreplaced);

    TextField filterTextField;

    Set<RecordFormat> selectedItemIds;

    static final String SHOW_ALL = "Show All Enreplacedies";

    static final String SHOW_POPULATED_ENreplacedIES = "Filter Populated Enreplacedes";

    protected void buildUI() {
        ButtonBar buttonBar = new ButtonBar();
        addComponent(buttonBar);
        Button moveUpButton = buttonBar.addButton("Move Up", FontAwesome.ARROW_UP);
        moveUpButton.addClickListener(new MoveUpClickListener());
        Button moveDownButton = buttonBar.addButton("Move Down", FontAwesome.ARROW_DOWN);
        moveDownButton.addClickListener(new MoveDownClickListener());
        Button moveTopButton = buttonBar.addButton("Move Top", FontAwesome.ANGLE_DOUBLE_UP);
        moveTopButton.addClickListener(new MoveTopClickListener());
        Button moveBottomButton = buttonBar.addButton("Move Bottom", FontAwesome.ANGLE_DOUBLE_DOWN);
        moveBottomButton.addClickListener(new MoveBottomClickListener());
        filterTextField = buttonBar.addFilter();
        filterTextField.addTextChangeListener(event -> updateTable(event.getText()));
        table.setContainerDataSource(container);
        table.setSelectable(true);
        table.setSortEnabled(false);
        table.setImmediate(true);
        table.setSizeFull();
        table.setVisibleColumns(new Object[] { "enreplacedyName", "attributeName", "ordinalSetting", "sortSetting" });
        table.setColumnHeaders(new String[] { "Enreplacedy Name", "Attribute Name", "Sort Order", "Sort" });
        table.setTableFieldFactory(new EditFieldFactory());
        table.setCellStyleGenerator(new TableCellStyleGenerator());
        table.setEditable(true);
        table.setMultiSelect(true);
        addComponent(table);
        setExpandRatio(table, 1.0f);
        updateTable(null);
        calculatePositions();
        saveOrdinalSettings();
        saveSortSettings();
    }

    @SuppressWarnings("unchecked")
    protected Set<RecordFormat> getSelectedItems() {
        return (Set<RecordFormat>) table.getValue();
    }

    protected RecordFormat getSelectedItem() {
        Set<RecordFormat> selectedItems = getSelectedItems();
        if (selectedItems != null && selectedItems.size() == 1) {
            return selectedItems.iterator().next();
        }
        return null;
    }

    protected void updateTable(String filter) {
        filter = filter != null ? filter.toLowerCase() : null;
        filterTextField.setValue(filter);
        table.removeAllItems();
        RelationalModel model = (RelationalModel) component.getInputModel();
        if (model != null) {
            model = context.getConfigurationService().findRelationalModel(model.getId());
            List<RecordFormat> checkedAttributes = new ArrayList<RecordFormat>();
            List<RecordFormat> attributes = new ArrayList<RecordFormat>();
            for (ModelEnreplacedy enreplacedy : model.getModelEnreplacedies()) {
                if (isBlank(filter) || enreplacedy.getName().toLowerCase().contains(filter)) {
                    for (ModelAttrib attr : enreplacedy.getModelAttributes()) {
                        RecordFormat recFormat = new RecordFormat(enreplacedy, attr);
                        if (recFormat.getSortSetting()) {
                            checkedAttributes.add(recFormat);
                        } else {
                            attributes.add(recFormat);
                        }
                    }
                }
            }
            Collections.sort(attributes, new Comparator<RecordFormat>() {

                public int compare(RecordFormat o1, RecordFormat o2) {
                    return new String(o1.getEnreplacedyName()).compareTo(new String(o2.getEnreplacedyName()));
                }
            });
            Collections.sort(checkedAttributes, new Comparator<RecordFormat>() {

                public int compare(RecordFormat o1, RecordFormat o2) {
                    int sortOrder = new String(o1.getEnreplacedyName()).compareTo(new String(o2.getEnreplacedyName()));
                    if (sortOrder != 0) {
                        return sortOrder;
                    } else {
                        return new Integer(o1.getOrdinalSetting() == 0 ? 999999 : o1.getOrdinalSetting()).compareTo(new Integer(o2.getOrdinalSetting() == 0 ? 999999 : o2.getOrdinalSetting()));
                    }
                }
            });
            for (RecordFormat recordFormat : checkedAttributes) {
                table.addItem(recordFormat);
            }
            for (RecordFormat recordFormat : attributes) {
                table.addItem(recordFormat);
            }
        }
    }

    protected void calculatePositions() {
        boolean needsRefreshed = false;
        int ordinal = 1;
        for (RecordFormat record : container.gereplacedemIds()) {
            if (record.getSortSetting()) {
                if (record.getOrdinalSetting() != ordinal) {
                    record.setOrdinalSetting(ordinal);
                    needsRefreshed = true;
                }
                ordinal++;
            } else {
                if (record.getOrdinalSetting() != 0) {
                    record.setOrdinalSetting(0);
                    needsRefreshed = true;
                }
            }
        }
        if (needsRefreshed) {
            RecordFormat record = getSelectedItem();
            if (record != null) {
                record.setFocusFieldId("sortSetting");
            }
            table.refreshRowCache();
        }
    }

    protected void moveItemsTo(Set<RecordFormat> itemIds, int index) {
        if (index >= 0 && index < container.gereplacedemIds().size() && itemIds.size() > 0) {
            int firsreplacedemIndex = container.indexOfId(itemIds.iterator().next());
            if (index != firsreplacedemIndex) {
                for (RecordFormat itemId : itemIds) {
                    boolean movingUp = index < container.indexOfId(itemId);
                    container.removeItem(itemId);
                    container.addItemAt(index, itemId);
                    if (movingUp) {
                        index++;
                    }
                }
                calculatePositions();
                saveOrdinalSettings();
            }
            table.refreshRowCache();
        }
    }

    protected void saveOrdinalSettings() {
        String attrName = Sorter.SORTER_ATTRIBUTE_ORDINAL;
        int ordinal = 1;
        for (RecordFormat record : container.gereplacedemIds()) {
            if (record.getSortSetting()) {
                saveSetting(record.getAttributeId(), attrName, String.valueOf(ordinal));
                ordinal++;
            } else {
                saveSetting(record.getAttributeId(), attrName, "0");
            }
        }
    }

    protected void saveSortSettings() {
        String attrName = Sorter.ATTRIBUTE_SORTER_ENABLED;
        for (RecordFormat record : container.gereplacedemIds()) {
            saveSetting(record.getAttributeId(), attrName, String.valueOf(record.getSortSetting()));
        }
    }

    protected void saveSetting(String attributeId, String name, String value) {
        ComponentAttribSetting setting = component.getSingleAttributeSetting(attributeId, name);
        if (setting == null) {
            setting = new ComponentAttribSetting(attributeId, name, value);
            setting.setComponentId(component.getId());
            component.addAttributeSetting(setting);
            context.getConfigurationService().save(setting);
        } else if (!StringUtils.equals(setting.getValue(), value)) {
            setting.setValue(value);
            context.getConfigurationService().save(setting);
        }
    }

    protected int getLastSorreplacedemIndex(String enreplacedyId, String attributeId, boolean isSelected) {
        int lastSorreplacedemIndex = -1;
        int lastEnreplacedySortIndex = -1;
        int lasreplacedemIndex = -1;
        int lastEnreplacedyIndex = -1;
        for (RecordFormat record : container.gereplacedemIds()) {
            if (isSelected && record.getSortSetting() && !attributeId.equals(record.getAttributeId())) {
                lastSorreplacedemIndex++;
                if (enreplacedyId.equals(record.getEnreplacedyId())) {
                    lastEnreplacedySortIndex = container.indexOfId(record);
                }
            }
            lasreplacedemIndex++;
            if (!record.getSortSetting() && enreplacedyId.equals(record.getEnreplacedyId()) && !attributeId.equals(record.getAttributeId())) {
                lastEnreplacedyIndex = container.indexOfId(record);
            }
        }
        if (isSelected) {
            if (lastEnreplacedySortIndex < lastSorreplacedemIndex && lastEnreplacedySortIndex != -1) {
                return lastEnreplacedySortIndex;
            } else {
                return lastSorreplacedemIndex;
            }
        } else {
            if (lastEnreplacedyIndex < lasreplacedemIndex && lastEnreplacedyIndex != -1) {
                return lastEnreplacedyIndex;
            } else {
                return lasreplacedemIndex;
            }
        }
    }

    clreplaced MoveUpClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> selectedSortRecords = new HashSet<RecordFormat>();
            int previousEnreplacedyLastIndex = -1;
            String selectedEnreplacedyId = "";
            for (RecordFormat record : getSelectedItems()) {
                if (record.getSortSetting()) {
                    selectedSortRecords.add(record);
                    if (selectedEnreplacedyId == "") {
                        selectedEnreplacedyId = record.getEnreplacedyId();
                    } else if (!selectedEnreplacedyId.equals(record.getEnreplacedyId())) {
                        // if an additional selected attribute is from a different enreplacedy then don't move anything
                        // can only move within one enreplacedy at a time
                        selectedSortRecords.clear();
                        break;
                    }
                }
            }
            if (selectedSortRecords.size() > 0 && selectedSortRecords != null) {
                // loop through list of selected records to see if moving an attribute into another enreplacedy
                // add the remaining attributes to keep the enreplacedy as a whole together o/w just move the attribute within the enreplacedy
                for (RecordFormat record : container.gereplacedemIds()) {
                    if (record.getSortSetting()) {
                        if (!selectedEnreplacedyId.equals(record.getEnreplacedyId())) {
                            previousEnreplacedyLastIndex = container.indexOfId(record);
                        } else {
                            break;
                        }
                    }
                }
                RecordFormat firsreplacedem = selectedSortRecords.iterator().next();
                int index = container.indexOfId(firsreplacedem) - 1;
                if (index >= 0 && index > previousEnreplacedyLastIndex) {
                    moveItemsTo(selectedSortRecords, index);
                }
            }
        }
    }

    clreplaced MoveDownClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> selectedSortRecords = new HashSet<RecordFormat>();
            int nextEnreplacedyFirstIndex = -1;
            String selectedEnreplacedyId = "";
            for (RecordFormat record : getSelectedItems()) {
                if (record.getSortSetting()) {
                    selectedSortRecords.add(record);
                    if (selectedEnreplacedyId == "") {
                        selectedEnreplacedyId = record.getEnreplacedyId();
                    } else if (!selectedEnreplacedyId.equals(record.getEnreplacedyId())) {
                        // if an additional selected attribute is from a different enreplacedy then don't move anything
                        // can only move within one enreplacedy at a time
                        selectedSortRecords.clear();
                        break;
                    }
                }
            }
            if (selectedSortRecords.size() > 0 && selectedSortRecords != null) {
                int lastSorreplacedemIndex = 0;
                for (RecordFormat record : container.gereplacedemIds()) {
                    if (record.getSortSetting()) {
                        lastSorreplacedemIndex++;
                    }
                }
                // loop through list of selected records to see if moving an attribute into another enreplacedy
                // add the remaining attributes to keep the enreplacedy as a whole together o/w just move the attribute within the enreplacedy
                Lisreplacederator<RecordFormat> allItemsIterator = container.gereplacedemIds().lisreplacederator(container.gereplacedemIds().size());
                while (allItemsIterator.hasPrevious()) {
                    RecordFormat record = allItemsIterator.previous();
                    if (record.getSortSetting()) {
                        if (!selectedEnreplacedyId.equals(record.getEnreplacedyId())) {
                            nextEnreplacedyFirstIndex = container.indexOfId(record);
                        } else {
                            break;
                        }
                    }
                }
                RecordFormat lastSorreplacedem = null;
                Iterator<RecordFormat> iter = selectedSortRecords.iterator();
                while (iter.hasNext()) {
                    lastSorreplacedem = iter.next();
                }
                int index = container.indexOfId(lastSorreplacedem) + 1;
                if (index < lastSorreplacedemIndex && (index < nextEnreplacedyFirstIndex || nextEnreplacedyFirstIndex == -1)) {
                    moveItemsTo(selectedSortRecords, index);
                }
            }
        }
    }

    clreplaced MoveTopClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> selectedSortRecords = new HashSet<RecordFormat>();
            int previousEnreplacedyLastIndex = -1;
            String selectedEnreplacedyId = "";
            for (RecordFormat record : getSelectedItems()) {
                if (record.getSortSetting()) {
                    selectedSortRecords.add(record);
                    if (selectedEnreplacedyId == "") {
                        selectedEnreplacedyId = record.getEnreplacedyId();
                    } else if (!selectedEnreplacedyId.equals(record.getEnreplacedyId())) {
                        // if an additional selected attribute is from a different enreplacedy then don't move anything
                        // can only move within one enreplacedy at a time
                        selectedSortRecords.clear();
                        break;
                    }
                }
            }
            if (selectedSortRecords.size() > 0 && selectedSortRecords != null) {
                // loop through list of selected records to see if moving an attribute into another enreplacedy
                // add the remaining attributes to keep the enreplacedy as a whole together o/w just move the attribute within the enreplacedy
                for (RecordFormat record : container.gereplacedemIds()) {
                    if (record.getSortSetting()) {
                        if (!selectedEnreplacedyId.equals(record.getEnreplacedyId())) {
                            previousEnreplacedyLastIndex = container.indexOfId(record);
                        } else {
                            break;
                        }
                    }
                }
                if (previousEnreplacedyLastIndex == -1) {
                    moveItemsTo(selectedSortRecords, 0);
                } else {
                    moveItemsTo(selectedSortRecords, previousEnreplacedyLastIndex + 1);
                }
            }
        }
    }

    clreplaced MoveBottomClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<RecordFormat> selectedSortRecords = new HashSet<RecordFormat>();
            int nextEnreplacedyFirstIndex = -1;
            String selectedEnreplacedyId = "";
            for (RecordFormat record : getSelectedItems()) {
                if (record.getSortSetting()) {
                    selectedSortRecords.add(record);
                    if (selectedEnreplacedyId == "") {
                        selectedEnreplacedyId = record.getEnreplacedyId();
                    } else if (!selectedEnreplacedyId.equals(record.getEnreplacedyId())) {
                        // if an additional selected attribute is from a different enreplacedy then don't move anything
                        // can only move within one enreplacedy at a time
                        selectedSortRecords.clear();
                        break;
                    }
                }
            }
            if (selectedSortRecords.size() > 0 && selectedSortRecords != null) {
                // loop through list of selected records to see if moving an attribute into another enreplacedy
                // add the remaining attributes to keep the enreplacedy as a whole together o/w just move the attribute within the enreplacedy
                Lisreplacederator<RecordFormat> allItemsIterator = container.gereplacedemIds().lisreplacederator(container.gereplacedemIds().size());
                while (allItemsIterator.hasPrevious()) {
                    RecordFormat record = allItemsIterator.previous();
                    if (record.getSortSetting()) {
                        if (!selectedEnreplacedyId.equals(record.getEnreplacedyId())) {
                            nextEnreplacedyFirstIndex = container.indexOfId(record);
                        } else {
                            break;
                        }
                    }
                }
                RecordFormat lastSorreplacedem = null;
                for (RecordFormat record : container.gereplacedemIds()) {
                    if (record.getSortSetting()) {
                        lastSorreplacedem = record;
                    }
                }
                if (nextEnreplacedyFirstIndex == -1) {
                    int index = container.indexOfId(lastSorreplacedem);
                    moveItemsTo(selectedSortRecords, index);
                } else {
                    moveItemsTo(selectedSortRecords, nextEnreplacedyFirstIndex - 1);
                }
            }
        }
    }

    clreplaced TableDropHandler implements DropHandler {

        public void drop(DragAndDropEvent event) {
            AbstractSelectTargetDetails targetDetails = (AbstractSelectTargetDetails) event.getTargetDetails();
            Transferable transferable = event.getTransferable();
            if (transferable.getSourceComponent() == table) {
                RecordFormat target = (RecordFormat) targetDetails.gereplacedemIdOver();
                moveItemsTo(getSelectedItems(), container.indexOfId(target));
            }
        }

        public AcceptCriterion getAcceptCriterion() {
            return AcceptAll.get();
        }
    }

    clreplaced EditFieldFactory implements TableFieldFactory {

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            final RecordFormat record = (RecordFormat) itemId;
            Field<?> field = null;
            if (propertyId.equals("sortSetting")) {
                return createAttributeCheckBox(record, Sorter.ATTRIBUTE_SORTER_ENABLED);
            }
            RecordFormat selected = getSelectedItem();
            if (selected == itemId && record.getFocusField() != null) {
                record.getFocusField().focus();
            }
            return field;
        }

        protected CheckBox createAttributeCheckBox(final RecordFormat record, final String key) {
            final CheckBox checkBox = new CheckBox();
            checkBox.setImmediate(true);
            checkBox.addValueChangeListener(new ValueChangeListener() {

                private static final long serialVersionUID = 1L;

                @Override
                public void valueChange(ValueChangeEvent event) {
                    ComponentAttribSetting setting = component.getSingleAttributeSetting(record.getAttributeId(), key);
                    String oldValue = setting == null ? Boolean.FALSE.toString() : setting.getValue();
                    if (setting == null) {
                        setting = new ComponentAttribSetting(record.getAttributeId(), component.getId(), key, Boolean.FALSE.toString());
                        component.addAttributeSetting(setting);
                    }
                    setting.setValue(checkBox.getValue().toString());
                    if (!oldValue.equals(setting.getValue())) {
                        context.getConfigurationService().save(setting);
                        Set<RecordFormat> attributes = new HashSet<>();
                        attributes.add(record);
                        if (oldValue.equals(Boolean.FALSE.toString())) {
                            moveItemsTo(attributes, getLastSorreplacedemIndex(record.getEnreplacedyId(), record.getAttributeId(), true) + 1);
                        } else {
                            moveItemsTo(attributes, getLastSorreplacedemIndex(record.getEnreplacedyId(), record.getAttributeId(), false));
                        }
                    }
                    calculatePositions();
                    saveOrdinalSettings();
                    saveSortSettings();
                }
            });
            return checkBox;
        }

        protected void focusOn(RecordFormat record, Object propertyId) {
            record.setFocusFieldId(propertyId);
            for (Object itemId : getSelectedItems()) {
                table.unselect(itemId);
            }
            table.select(record);
        }
    }

    clreplaced TableCellStyleGenerator implements CellStyleGenerator {

        public String getStyle(Table source, Object itemId, Object propertyId) {
            if (propertyId != null && selectedItemIds != null && selectedItemIds.contains(itemId)) {
                return "highlight";
            }
            return null;
        }
    }

    public clreplaced RecordFormat {

        ModelEnreplacedy modelEnreplacedy;

        ModelAttrib modelAttribute;

        Map<Object, Field<?>> fields = new HashMap<Object, Field<?>>();

        Object focusFieldId;

        boolean sortSetting = false;

        int ordinalSetting;

        public RecordFormat(ModelEnreplacedy modelEnreplacedy, ModelAttrib modelAttribute) {
            this.modelEnreplacedy = modelEnreplacedy;
            this.modelAttribute = modelAttribute;
            if (modelAttribute != null) {
                ComponentAttribSetting setting = component.getSingleAttributeSetting(modelAttribute.getId(), Sorter.SORTER_ATTRIBUTE_ORDINAL);
                if (setting != null) {
                    this.ordinalSetting = Integer.parseInt(setting.getValue());
                }
                setting = component.getSingleAttributeSetting(modelAttribute.getId(), Sorter.ATTRIBUTE_SORTER_ENABLED);
                if (setting != null) {
                    this.sortSetting = Boolean.parseBoolean(setting.getValue());
                }
            } else {
                ComponentEnreplacedySetting setting = component.getSingleEnreplacedySetting(modelEnreplacedy.getId(), Sorter.SORTER_ATTRIBUTE_ORDINAL);
                if (setting != null) {
                    this.ordinalSetting = Integer.parseInt(setting.getValue());
                }
                setting = component.getSingleEnreplacedySetting(modelEnreplacedy.getId(), Sorter.ATTRIBUTE_SORTER_ENABLED);
                if (setting != null) {
                    this.sortSetting = Boolean.parseBoolean(setting.getValue());
                }
            }
        }

        public int hashCode() {
            return modelEnreplacedy.hashCode() + modelAttribute.hashCode();
        }

        public boolean equals(Object obj) {
            if (obj instanceof RecordFormat) {
                return hashCode() == ((RecordFormat) obj).hashCode();
            }
            return super.equals(obj);
        }

        public String getEnreplacedyName() {
            return modelEnreplacedy.getName();
        }

        public String getEnreplacedyId() {
            return modelEnreplacedy.getId();
        }

        public String getAttributeName() {
            return modelAttribute.getName();
        }

        public String getAttributeId() {
            return modelAttribute.getId();
        }

        public boolean getSortSetting() {
            return sortSetting;
        }

        public void setSortSetting(boolean sortSetting) {
            this.sortSetting = sortSetting;
        }

        public void addField(Object id, Field<?> field) {
            fields.put(id, field);
        }

        public void setFocusFieldId(Object id) {
            this.focusFieldId = id;
        }

        public Field<?> getFocusField() {
            Field<?> field = fields.get(focusFieldId);
            if (field == null) {
                field = fields.get("width");
            }
            return field;
        }

        public int getOrdinalSetting() {
            return ordinalSetting;
        }

        public void setOrdinalSetting(int ordinalSetting) {
            this.ordinalSetting = ordinalSetting;
        }
    }
}

19 View Complete Implementation : EditTransformerPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced EditTransformerPanel extends AbstractComponentEditPanel {

    Table table = new Table();

    Table exportTable = new Table();

    TextField filterField;

    AbstractSelect filterPopField;

    List<ComponentAttribSetting> componentAttributes;

    BeanItemContainer<ComponentAttribSetting> container = new BeanItemContainer<ComponentAttribSetting>(ComponentAttribSetting.clreplaced);

    BeanItemContainer<Record> exportContainer = new BeanItemContainer<Record>(Record.clreplaced);

    static final String SHOW_ALL = "Show All";

    static final String SHOW_POPULATED_ENreplacedIES = "Show Enreplacedies with Transforms";

    static final String SHOW_POPULATED_ATTRIBUTES = "Show Attributes with Transforms";

    protected void buildUI() {
        ButtonBar buttonBar = new ButtonBar();
        addComponent(buttonBar);
        filterPopField = new ComboBox();
        filterPopField.addItem(SHOW_ALL);
        filterPopField.addItem(SHOW_POPULATED_ENreplacedIES);
        filterPopField.addItem(SHOW_POPULATED_ATTRIBUTES);
        if (component.getInputModel() != null) {
            for (ModelEnreplacedy enreplacedy : ((RelationalModel) component.getInputModel()).getModelEnreplacedies()) {
                filterPopField.addItem(enreplacedy.getName());
            }
        }
        filterPopField.setNullSelectionAllowed(false);
        filterPopField.setImmediate(true);
        filterPopField.setWidth(20, Unit.EM);
        filterPopField.setValue(SHOW_ALL);
        filterPopField.addValueChangeListener(event -> {
            if (isNotBlank(filterField.getValue())) {
                filterField.clear();
            }
            updateTable();
        });
        buttonBar.addLeft(filterPopField);
        buttonBar.addButtonRight("Export", FontAwesome.DOWNLOAD, (e) -> export());
        filterField = buttonBar.addFilter();
        filterField.addTextChangeListener(event -> {
            String text = event.getText();
            filterPopField.setValue(SHOW_ALL);
            updateTable(text);
        });
        addComponent(buttonBar);
        table.setContainerDataSource(container);
        table.setSelectable(true);
        table.setSortEnabled(false);
        table.setImmediate(true);
        table.setSortEnabled(true);
        table.setSizeFull();
        table.addGeneratedColumn("enreplacedyName", new ColumnGenerator() {

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                ComponentAttribSetting setting = (ComponentAttribSetting) itemId;
                RelationalModel model = (RelationalModel) component.getInputModel();
                ModelAttrib attribute = model.getAttributeById(setting.getAttributeId());
                ModelEnreplacedy enreplacedy = model.getEnreplacedyById(attribute.getEnreplacedyId());
                return UiUtils.getName(filterField.getValue(), enreplacedy.getName());
            }
        });
        table.addGeneratedColumn("attributeName", new ColumnGenerator() {

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                ComponentAttribSetting setting = (ComponentAttribSetting) itemId;
                RelationalModel model = (RelationalModel) component.getInputModel();
                ModelAttrib attribute = model.getAttributeById(setting.getAttributeId());
                return UiUtils.getName(filterField.getValue(), attribute.getName());
            }
        });
        table.addGeneratedColumn("editButton", new ColumnGenerator() {

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                ComponentAttribSetting setting = (ComponentAttribSetting) itemId;
                Button button = new Button();
                button.setIcon(FontAwesome.GEAR);
                button.addClickListener((event) -> new EditTransformWindow(setting).showAtSize(.75));
                return button;
            }
        });
        table.setVisibleColumns(new Object[] { "enreplacedyName", "attributeName", "value", "editButton" });
        table.setColumnWidth("enreplacedyName", 250);
        table.setColumnWidth("attributeName", 250);
        table.setColumnHeaders(new String[] { "Enreplacedy Name", "Attribute Name", "Transform", "Edit" });
        table.setColumnExpandRatio("value", 1);
        table.setTableFieldFactory(new EditFieldFactory());
        table.setEditable(true);
        addComponent(table);
        setExpandRatio(table, 1.0f);
        if (component.getInputModel() != null) {
            componentAttributes = component.getAttributeSettings();
            removeDeadAttributeSettings();
            for (ModelEnreplacedy enreplacedy : ((RelationalModel) component.getInputModel()).getModelEnreplacedies()) {
                for (ModelAttrib attr : enreplacedy.getModelAttributes()) {
                    boolean found = false;
                    for (ComponentAttribSetting componentAttribute : componentAttributes) {
                        if (componentAttribute.getAttributeId().equals(attr.getId()) && componentAttribute.getName().equals(Transformer.TRANSFORM_EXPRESSION)) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        componentAttributes.add(new ComponentAttribSetting(attr.getId(), component.getId(), Transformer.TRANSFORM_EXPRESSION, null));
                    }
                }
            }
            Collections.sort(componentAttributes, new Comparator<ComponentAttribSetting>() {

                @Override
                public int compare(ComponentAttribSetting o1, ComponentAttribSetting o2) {
                    RelationalModel model = (RelationalModel) component.getInputModel();
                    ModelAttrib attribute1 = model.getAttributeById(o1.getAttributeId());
                    ModelEnreplacedy enreplacedy1 = model.getEnreplacedyById(attribute1.getEnreplacedyId());
                    ModelAttrib attribute2 = model.getAttributeById(o2.getAttributeId());
                    ModelEnreplacedy enreplacedy2 = model.getEnreplacedyById(attribute2.getEnreplacedyId());
                    int compare = enreplacedy1.getName().compareTo(enreplacedy2.getName());
                    if (compare == 0) {
                        compare = attribute1.getName().compareTo(attribute2.getName());
                    }
                    return compare;
                }
            });
        }
        updateTable(null);
        exportTable.setContainerDataSource(exportContainer);
        exportTable.setVisibleColumns(new Object[] { "enreplacedyName", "attributeName", "value" });
        exportTable.setColumnHeaders(new String[] { "Enreplacedy Name", "Attribute Name", "Transform" });
    }

    protected void removeDeadAttributeSettings() {
        List<ComponentAttribSetting> toRemove = new ArrayList<ComponentAttribSetting>();
        for (ComponentAttribSetting componentAttribute : componentAttributes) {
            RelationalModel model = (RelationalModel) component.getInputModel();
            ModelAttrib attribute1 = model.getAttributeById(componentAttribute.getAttributeId());
            if (attribute1 == null) {
                /*
                 * invalid attribute. model must have changed. lets remove
                 * it
                 */
                toRemove.add(componentAttribute);
            }
        }
        for (ComponentAttribSetting componentAttributeSetting : toRemove) {
            componentAttributes.remove(componentAttributeSetting);
            context.getConfigurationService().delete(componentAttributeSetting);
        }
    }

    protected void updateTable() {
        String filter = null;
        if (SHOW_ALL.equals(filterPopField.getValue())) {
            filter = filterField.getValue();
        }
        updateTable(filter);
    }

    protected void updateTable(String filter) {
        boolean showPopulatedEnreplacedies = filterPopField.getValue().equals(SHOW_POPULATED_ENreplacedIES);
        boolean showPopulatedAttributes = filterPopField.getValue().equals(SHOW_POPULATED_ATTRIBUTES);
        if (!showPopulatedEnreplacedies && !showPopulatedAttributes && !filterPopField.getValue().equals(SHOW_ALL)) {
            filter = (String) filterPopField.getValue();
        }
        if (componentAttributes != null) {
            RelationalModel model = (RelationalModel) component.getInputModel();
            Collection<String> enreplacedyNames = new ArrayList<>();
            filter = filter != null ? filter.toLowerCase() : null;
            if (model != null) {
                table.removeAllItems();
                // loop through the attributes with transforms to get a list of
                // enreplacedies
                for (ComponentAttribSetting componentAttribute : componentAttributes) {
                    ModelAttrib attribute = model.getAttributeById(componentAttribute.getAttributeId());
                    ModelEnreplacedy enreplacedy = model.getEnreplacedyById(attribute.getEnreplacedyId());
                    if (isNotBlank(componentAttribute.getValue()) && !enreplacedyNames.contains(enreplacedy.getName())) {
                        enreplacedyNames.add(enreplacedy.getName());
                    }
                }
                for (ComponentAttribSetting componentAttribute : componentAttributes) {
                    ModelAttrib attribute = model.getAttributeById(componentAttribute.getAttributeId());
                    ModelEnreplacedy enreplacedy = model.getEnreplacedyById(attribute.getEnreplacedyId());
                    boolean populated = (showPopulatedEnreplacedies && enreplacedyNames.contains(enreplacedy.getName())) || (showPopulatedAttributes && isNotBlank(componentAttribute.getValue())) || (!showPopulatedAttributes && !showPopulatedEnreplacedies);
                    if (isBlank(filter) || enreplacedy.getName().toLowerCase().contains(filter) || attribute.getName().toLowerCase().contains(filter)) {
                        if (populated) {
                            table.addItem(componentAttribute);
                        }
                    }
                }
            }
        }
    }

    protected void export() {
        exportTable.removeAllItems();
        updateExportTable(filterField.getValue());
        String fileNamePrefix = component.getName().toLowerCase().replace(' ', '-');
        ExportDialog dialog = new ExportDialog(new TableV7DataProvider(exportTable), fileNamePrefix, component.getName());
        UI.getCurrent().addWindow(dialog);
    }

    protected void updateExportTable(String filter) {
        boolean showPopulatedEnreplacedies = filterPopField.getValue().equals(SHOW_POPULATED_ENreplacedIES);
        boolean showPopulatedAttributes = filterPopField.getValue().equals(SHOW_POPULATED_ATTRIBUTES);
        if (componentAttributes != null) {
            RelationalModel model = (RelationalModel) component.getInputModel();
            Collection<String> enreplacedyNames = new ArrayList<>();
            filter = filter != null ? filter.toLowerCase() : null;
            if (model != null) {
                exportTable.removeAllItems();
                // loop through the attributes with transforms to get a list of
                // enreplacedies
                for (ComponentAttribSetting componentAttribute : componentAttributes) {
                    ModelAttrib attribute = model.getAttributeById(componentAttribute.getAttributeId());
                    ModelEnreplacedy enreplacedy = model.getEnreplacedyById(attribute.getEnreplacedyId());
                    if (isNotBlank(componentAttribute.getValue()) && !enreplacedyNames.contains(enreplacedy.getName())) {
                        enreplacedyNames.add(enreplacedy.getName());
                    }
                }
                for (ComponentAttribSetting componentAttribute : componentAttributes) {
                    ModelAttrib attribute = model.getAttributeById(componentAttribute.getAttributeId());
                    ModelEnreplacedy enreplacedy = model.getEnreplacedyById(attribute.getEnreplacedyId());
                    boolean populated = (showPopulatedEnreplacedies && enreplacedyNames.contains(enreplacedy.getName())) || (showPopulatedAttributes && isNotBlank(componentAttribute.getValue())) || (!showPopulatedAttributes && !showPopulatedEnreplacedies);
                    if (isBlank(filter) || enreplacedy.getName().toLowerCase().contains(filter) || attribute.getName().toLowerCase().contains(filter)) {
                        if (populated) {
                            exportTable.addItem(new Record(enreplacedy, attribute));
                        }
                    }
                }
            }
        }
    }

    public clreplaced Record {

        ModelEnreplacedy modelEnreplacedy;

        ModelAttrib modelAttribute;

        String enreplacedyName = "";

        String attributeName = "";

        String value = "";

        public Record(ModelEnreplacedy modelEnreplacedy, ModelAttrib modelAttribute) {
            this.modelEnreplacedy = modelEnreplacedy;
            this.modelAttribute = modelAttribute;
            if (modelEnreplacedy != null) {
                this.enreplacedyName = modelEnreplacedy.getName();
            }
            if (modelAttribute != null) {
                this.attributeName = modelAttribute.getName();
                ComponentAttribSetting setting = component.getSingleAttributeSetting(modelAttribute.getId(), Transformer.TRANSFORM_EXPRESSION);
                if (setting != null) {
                    this.value = setting.getValue();
                }
            }
        }

        public int hashCode() {
            return modelEnreplacedy.hashCode() + modelAttribute.hashCode();
        }

        public String getEnreplacedyName() {
            return modelEnreplacedy.getName();
        }

        public String getAttributeName() {
            return modelAttribute.getName();
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

    clreplaced EditFieldFactory implements TableFieldFactory {

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            final ComponentAttribSetting setting = (ComponentAttribSetting) itemId;
            Field<?> field = null;
            if (propertyId.equals("value") && (setting.getValue() == null || !setting.getValue().contains("\n"))) {
                final ComboBox combo = new ComboBox();
                combo.setWidth(100, Unit.PERCENTAGE);
                String[] functions = ModelAttributeScriptHelper.getSignatures();
                for (String function : functions) {
                    combo.addItem(function);
                }
                combo.setPageLength(functions.length > 20 ? 20 : functions.length);
                if (setting.getValue() != null && !combo.gereplacedemIds().contains(setting.getValue())) {
                    combo.addItem(setting.getValue());
                }
                combo.setImmediate(true);
                combo.setNewItemsAllowed(true);
                combo.addValueChangeListener(new ValueChangeListener() {

                    public void valueChange(ValueChangeEvent event) {
                        setting.setValue((String) combo.getValue());
                        context.getConfigurationService().save(setting);
                    }
                });
                field = combo;
            }
            return field;
        }
    }

    clreplaced EditTransformWindow extends ResizableWindow {

        private static final long serialVersionUID = 1L;

        AceEditor editor;

        public EditTransformWindow(ComponentAttribSetting setting) {
            super("Transform");
            setWidth(800f, Unit.PIXELS);
            setHeight(600f, Unit.PIXELS);
            content.setMargin(true);
            ButtonBar buttonBar = new ButtonBar();
            addComponent(buttonBar);
            ComboBox combo = new ComboBox();
            combo.setWidth(400, Unit.PIXELS);
            String[] functions = ModelAttributeScriptHelper.getSignatures();
            for (String function : functions) {
                combo.addItem(function);
            }
            combo.setValue(combo.gereplacedemIds().iterator().next());
            combo.setNullSelectionAllowed(false);
            combo.setPageLength(functions.length > 20 ? 20 : functions.length);
            combo.setImmediate(true);
            buttonBar.addLeft(combo);
            buttonBar.addButton("Insert", FontAwesome.SIGN_IN, new ClickListener() {

                @Override
                public void buttonClick(ClickEvent event) {
                    String script = (editor.getValue() == null) ? "" : editor.getValue();
                    StringBuilder builder = new StringBuilder(script);
                    String substring = (String) combo.getValue();
                    int startPosition = editor.getCursorPosition();
                    builder.insert(startPosition, substring);
                    editor.setValue(builder.toString());
                    editor.setSelection(startPosition, startPosition + substring.length());
                    // Manually save text since TextChangeListener is not firing.
                    setting.setValue(editor.getValue());
                    EditTransformerPanel.this.context.getConfigurationService().save(setting);
                }
            });
            editor = CommonUiUtils.createAceEditor();
            editor.setMode(AceMode.java);
            editor.addValueChangeListener(new HasValue.ValueChangeListener<String>() {

                @Override
                public void valueChange(HasValue.ValueChangeEvent<String> event) {
                    setting.setValue(event.getValue());
                    EditTransformerPanel.this.context.getConfigurationService().save(setting);
                }
            });
            editor.setValue(setting.getValue());
            content.addComponent(editor);
            content.setExpandRatio(editor, 1);
            addComponent(buildButtonFooter(buildCloseButton()));
        }

        @Override
        public void close() {
            super.close();
            updateTable();
        }
    }
}

19 View Complete Implementation : EditXmlFormatPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
public clreplaced EditXmlFormatPanel extends AbstractComponentEditPanel {

    private static final long serialVersionUID = 1L;

    Grid grid;

    Set<String> xpathChoices;

    BeanItemContainer<Record> container;

    protected void buildUI() {
        ButtonBar buttonBar = new ButtonBar();
        addComponent(buttonBar);
        Button editButton = buttonBar.addButton("Edit Template", FontAwesome.FILE_CODE_O);
        editButton.addClickListener(new EditTemplateClickListener());
        Button importButton = buttonBar.addButton("Import Template", FontAwesome.DOWNLOAD);
        importButton.addClickListener(new ImportTemplateClickListener());
        buttonBar.addButtonRight("Export", FontAwesome.DOWNLOAD, (e) -> export());
        buildGrid();
        refresh();
        saveXPathSettings();
        buildXpathChoices();
    }

    protected void export() {
        String fileNamePrefix = component.getName().toLowerCase().replace(' ', '-');
        ExportDialog dialog = new ExportDialog(new Grid7DataProvider(grid), fileNamePrefix, component.getName());
        UI.getCurrent().addWindow(dialog);
    }

    protected void buildGrid() {
        grid = new Grid();
        grid.setSelectionMode(SelectionMode.NONE);
        grid.setSizeFull();
        grid.setEditorEnabled(!readOnly);
        container = new BeanItemContainer<Record>(Record.clreplaced);
        grid.setContainerDataSource(container);
        grid.setColumns("enreplacedyName", "attributeName", "xpath");
        HeaderRow filterRow = grid.appendHeaderRow();
        addColumn("enreplacedyName", filterRow);
        addColumn("attributeName", filterRow);
        ComboBox combo = new ComboBox();
        combo.addValueChangeListener(e -> saveXPathSettings());
        combo.setWidth(100, Unit.PERCENTAGE);
        combo.setImmediate(true);
        combo.setNewItemsAllowed(true);
        combo.setInvalidAllowed(true);
        combo.setTextInputAllowed(true);
        combo.setScrollToSelectedItem(true);
        combo.setFilteringMode(FilteringMode.CONTAINS);
        grid.getColumn("xpath").setEditorField(combo).setExpandRatio(1);
        addShowPopulatedFilter("xpath", filterRow);
        grid.setEditorBuffered(false);
        addComponent(grid);
        setExpandRatio(grid, 1);
    }

    protected void refresh() {
        RelationalModel model = null;
        // View is used by multiple components.
        // What model does the component use?
        if (component.getType().equals(XmlParser.TYPE)) {
            model = (RelationalModel) component.getOutputModel();
        } else if (component.getType().equals(XPathXmlParser.TYPE)) {
            model = (RelationalModel) component.getOutputModel();
        } else if (component.getType().equals(XmlFormatter.TYPE)) {
            model = (RelationalModel) component.getInputModel();
        } else {
            model = (RelationalModel) component.getInputModel();
        }
        if (model != null) {
            Collections.sort(model.getModelEnreplacedies(), new Comparator<ModelEnreplacedy>() {

                public int compare(ModelEnreplacedy enreplacedy1, ModelEnreplacedy enreplacedy2) {
                    return enreplacedy1.getName().toLowerCase().compareTo(enreplacedy2.getName().toLowerCase());
                }
            });
            for (ModelEnreplacedy enreplacedy : model.getModelEnreplacedies()) {
                boolean firstAttribute = true;
                Record enreplacedyRecord = new Record(enreplacedy, null);
                for (ModelAttrib attr : enreplacedy.getModelAttributes()) {
                    if (firstAttribute) {
                        firstAttribute = false;
                        container.addItem(enreplacedyRecord);
                    }
                    container.addItem(new Record(enreplacedy, attr));
                }
                if (firstAttribute) {
                    container.addItem(enreplacedyRecord);
                }
            }
        }
    }

    protected void addShowPopulatedFilter(String propertyId, HeaderRow filterRow) {
        HeaderCell cell = filterRow.getCell(propertyId);
        CheckBox group = new CheckBox("Show Set Only");
        group.setImmediate(true);
        group.addValueChangeListener(l -> {
            container.removeContainerFilters(propertyId);
            if (group.getValue()) {
                container.addContainerFilter(new And(new Not(new Compare.Equal(propertyId, "")), new Not(new IsNull(propertyId))));
            }
        });
        group.addStyleName(ValoTheme.CHECKBOX_SMALL);
        cell.setComponent(group);
    }

    protected void addColumn(String propertyId, HeaderRow filterRow) {
        grid.getColumn(propertyId).setEditable(false);
        HeaderCell cell = filterRow.getCell(propertyId);
        TextField filterField = new TextField();
        filterField.setInputPrompt("Filter");
        filterField.setImmediate(true);
        filterField.addStyleName(ValoTheme.TEXTFIELD_TINY);
        filterField.setWidth(100, Unit.PERCENTAGE);
        filterField.addTextChangeListener(change -> {
            container.removeContainerFilters(propertyId);
            if (!change.getText().isEmpty()) {
                container.addContainerFilter(new SimpleStringFilter(propertyId, change.getText(), true, false));
            }
        });
        cell.setComponent(filterField);
    }

    protected void saveXPathSettings() {
        for (Object obj : container.gereplacedemIds()) {
            Record record = (Record) obj;
            if (record.modelAttribute != null) {
                saveAttributeSetting(record.modelAttribute.getId(), XmlFormatter.XML_FORMATTER_XPATH, StringUtils.trimToNull(record.getXpath()));
            } else {
                saveEnreplacedySetting(record.modelEnreplacedy.getId(), XmlFormatter.XML_FORMATTER_XPATH, StringUtils.trimToNull(record.getXpath()));
            }
        }
    }

    protected void saveAttributeSetting(String attributeId, String name, String value) {
        ComponentAttribSetting setting = component.getSingleAttributeSetting(attributeId, name);
        if (setting == null && value != null) {
            setting = new ComponentAttribSetting(attributeId, name, value);
            setting.setComponentId(component.getId());
            component.addAttributeSetting(setting);
            context.getConfigurationService().save(setting);
        } else if (setting != null && !StringUtils.equals(setting.getValue(), value)) {
            if (value == null) {
                setting.setValue(value);
                context.getConfigurationService().delete(setting);
            } else {
                setting.setValue(value);
                context.getConfigurationService().save(setting);
            }
        }
    }

    protected void saveEnreplacedySetting(String enreplacedyId, String name, String value) {
        ComponentEnreplacedySetting setting = component.getSingleEnreplacedySetting(enreplacedyId, name);
        if (setting == null && value != null) {
            setting = new ComponentEnreplacedySetting(enreplacedyId, name, value);
            setting.setComponentId(component.getId());
            component.addEnreplacedySetting(setting);
            context.getConfigurationService().save(setting);
        } else if (setting != null && !StringUtils.equals(setting.getValue(), value)) {
            if (value == null) {
                setting.setValue(value);
                context.getConfigurationService().delete(setting);
            } else {
                setting.setValue(value);
                context.getConfigurationService().save(setting);
            }
        }
    }

    protected void buildXpathChoices() {
        SAXBuilder builder = new SAXBuilder();
        builder.setXMLReaderFactory(XMLReaders.NONVALIDATING);
        builder.setFeature("http://xml.org/sax/features/validation", false);
        Setting setting = component.findSetting(XmlFormatter.XML_FORMATTER_TEMPLATE);
        xpathChoices = new TreeSet<String>();
        if (StringUtils.isNotBlank(setting.getValue())) {
            try {
                Doreplacedent doreplacedent = builder.build(new StringReader(setting.getValue()));
                buildXpathChoicesFromElement("/" + doreplacedent.getRootElement().getName(), doreplacedent.getRootElement());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        ComboBox combo = (ComboBox) grid.getColumn("xpath").getEditorField();
        combo.removeAllItems();
        combo.addItems(xpathChoices);
    }

    protected void buildXpathChoicesFromElement(String prefix, Element parentElement) {
        for (Element element : parentElement.getChildren()) {
            String text = prefix + "/" + element.getName();
            xpathChoices.add(text);
            for (Attribute attr : element.getAttributes()) {
                String attrText = text + "/@" + attr.getName();
                xpathChoices.add(attrText);
            }
            buildXpathChoicesFromElement(text, element);
        }
    }

    clreplaced EditTemplateClickListener implements ClickListener {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {
            EditTemplateWindow window = new EditTemplateWindow();
            window.show();
        }
    }

    clreplaced EditTemplateWindow extends ResizableWindow {

        private static final long serialVersionUID = 1L;

        AceEditor editor;

        public EditTemplateWindow() {
            super("Edit XML Template");
            setWidth(800f, Unit.PIXELS);
            setHeight(600f, Unit.PIXELS);
            content.setMargin(true);
            editor = new AceEditor();
            editor.setMode(AceMode.xml);
            editor.setSizeFull();
            editor.setHighlightActiveLine(true);
            editor.setShowPrintMargin(false);
            addComponent(editor);
            content.setExpandRatio(editor, 1.0f);
            Setting templateSetting = component.findSetting(XmlFormatter.XML_FORMATTER_TEMPLATE);
            editor.setValue(templateSetting.getValue());
            editor.setReadOnly(readOnly);
            addComponent(buildButtonFooter(buildCloseButton()));
        }

        @Override
        public void close() {
            super.close();
            Setting templateSetting = component.findSetting(XmlFormatter.XML_FORMATTER_TEMPLATE);
            templateSetting.setValue(editor.getValue());
            context.getConfigurationService().save(templateSetting);
            buildXpathChoices();
            refresh();
        }
    }

    clreplaced ImportTemplateClickListener implements ClickListener, ImportXmlListener {

        private static final long serialVersionUID = 1L;

        ImportXmlTemplateWindow importWindow;

        public void buttonClick(ClickEvent event) {
            importWindow = new ImportXmlTemplateWindow(this, component, context);
            UI.getCurrent().addWindow(importWindow);
        }

        public void onImport(String xml) {
            Setting templateSetting = component.findSetting(XmlFormatter.XML_FORMATTER_TEMPLATE);
            templateSetting.setValue(xml);
            context.getConfigurationService().save(templateSetting);
            importWindow.close();
            EditTemplateWindow editWindow = new EditTemplateWindow();
            editWindow.show();
        }
    }

    public clreplaced Record implements Serializable {

        private static final long serialVersionUID = 1L;

        ModelEnreplacedy modelEnreplacedy;

        ModelAttrib modelAttribute;

        String xpath = "";

        public Record(ModelEnreplacedy modelEnreplacedy, ModelAttrib modelAttribute) {
            this.modelEnreplacedy = modelEnreplacedy;
            this.modelAttribute = modelAttribute;
            if (modelAttribute != null) {
                ComponentAttribSetting setting = component.getSingleAttributeSetting(modelAttribute.getId(), XmlFormatter.XML_FORMATTER_XPATH);
                if (setting != null) {
                    xpath = setting.getValue();
                }
            } else {
                ComponentEnreplacedySetting setting = component.getSingleEnreplacedySetting(modelEnreplacedy.getId(), XmlFormatter.XML_FORMATTER_XPATH);
                if (setting != null) {
                    xpath = setting.getValue();
                }
            }
        }

        public int hashCode() {
            return modelEnreplacedy.hashCode() + (modelAttribute == null ? 0 : modelAttribute.hashCode());
        }

        public boolean equals(Object obj) {
            if (obj instanceof Record) {
                return hashCode() == ((Record) obj).hashCode();
            }
            return super.equals(obj);
        }

        public String getEnreplacedyName() {
            return modelEnreplacedy.getName();
        }

        public String getAttributeName() {
            if (modelAttribute != null) {
                return modelAttribute.getName();
            }
            return null;
        }

        public String getXpath() {
            return xpath;
        }

        public void setXpath(String xpath) {
            this.xpath = xpath;
        }
    }
}

19 View Complete Implementation : PluginRepositoriesPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
@UiComponent
@UIScope
@Order(600)
@AdminMenuLink(name = "Plugin Repositories", id = "Plugin Repositories", icon = FontAwesome.DATABASE)
public clreplaced PluginRepositoriesPanel extends AbstractAdminPanel {

    Button newButton;

    Button editButton;

    Button removeButton;

    BeanItemContainer<PluginRepository> container;

    Table table;

    public PluginRepositoriesPanel() {
        ButtonBar buttonBar = new ButtonBar();
        addComponent(buttonBar);
        newButton = buttonBar.addButton("Add", FontAwesome.PLUS);
        newButton.addClickListener(new NewClickListener());
        editButton = buttonBar.addButton("Edit", FontAwesome.EDIT);
        editButton.addClickListener(new EditClickListener());
        removeButton = buttonBar.addButton("Remove", FontAwesome.TRASH_O);
        removeButton.addClickListener(new RemoveClickListener());
        container = new BeanItemContainer<PluginRepository>(PluginRepository.clreplaced);
        table = new Table();
        table.setSizeFull();
        table.setCacheRate(100);
        table.setPageLength(100);
        table.setImmediate(true);
        table.setSelectable(true);
        table.setMultiSelect(true);
        table.setContainerDataSource(container);
        table.setVisibleColumns("name", "url", "lastUpdateTime");
        table.setColumnHeaders("Name", "Url", "Updated");
        table.setColumnWidth("lastUpdateTime", UIConstants.DATETIME_WIDTH_PIXELS);
        table.addItemClickListener(new TableItemClickListener());
        table.addValueChangeListener(new TableValueChangeListener());
        table.setSortContainerPropertyId("name");
        table.setSortAscending(true);
        addComponent(table);
        setExpandRatio(table, 1.0f);
    }

    @Override
    public void selected() {
        refresh();
    }

    @Override
    public boolean closing() {
        return true;
    }

    @Override
    public void deselected() {
    }

    public void refresh() {
        container.removeAllItems();
        container.addAll(context.getPluginService().findPluginRepositories());
        table.sort();
        setButtonsEnabled();
    }

    protected void setButtonsEnabled() {
        Set<PluginRepository> selectedIds = getSelectedItems();
        boolean enabled = selectedIds.size() > 0;
        editButton.setEnabled(enabled);
        removeButton.setEnabled(enabled);
    }

    @SuppressWarnings("unchecked")
    protected Set<PluginRepository> getSelectedItems() {
        return (Set<PluginRepository>) table.getValue();
    }

    @SuppressWarnings("unchecked")
    protected PluginRepository getFirstSelectedItem() {
        Set<PluginRepository> pluginRepositorys = (Set<PluginRepository>) table.getValue();
        Iterator<PluginRepository> iter = pluginRepositorys.iterator();
        if (iter.hasNext()) {
            return iter.next();
        }
        return null;
    }

    clreplaced NewClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            PluginRepository pluginRepository = new PluginRepository();
            PluginRepositoryEditPanel editPanel = new PluginRepositoryEditPanel(context, pluginRepository);
            adminView.getTabbedPanel().addCloseableTab(pluginRepository.getId(), "Edit Repository", getIcon(), editPanel);
        }
    }

    clreplaced EditClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            PluginRepository pluginRepository = getFirstSelectedItem();
            context.getPluginService().refresh(pluginRepository);
            PluginRepositoryEditPanel editPanel = new PluginRepositoryEditPanel(context, pluginRepository);
            adminView.getTabbedPanel().addCloseableTab(pluginRepository.getId(), "Edit Repository", getIcon(), editPanel);
        }
    }

    clreplaced RemoveClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            for (PluginRepository pluginRepository : getSelectedItems()) {
                context.getConfigurationService().delete(pluginRepository);
                container.removeItem(pluginRepository);
            }
            table.setValue(null);
            setButtonsEnabled();
        }
    }

    clreplaced TableItemClickListener implements ItemClickListener {

        long lastClick;

        public void itemClick(ItemClickEvent event) {
            if (event.isDoubleClick()) {
                editButton.click();
            } else if (getSelectedItems().contains(event.gereplacedemId()) && System.currentTimeMillis() - lastClick > 500) {
                table.setValue(null);
            }
            lastClick = System.currentTimeMillis();
        }
    }

    clreplaced TableValueChangeListener implements ValueChangeListener {

        public void valueChange(ValueChangeEvent event) {
            setButtonsEnabled();
        }
    }

    @Override
    public void enter(ViewChangeEvent event) {
    }
}

19 View Complete Implementation : PluginsPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
@UiComponent
@UIScope
@Order(700)
@AdminMenuLink(name = "Plugins", id = "Plugins", icon = FontAwesome.PUZZLE_PIECE)
public clreplaced PluginsPanel extends AbstractAdminPanel {

    Button addButton;

    Button removeButton;

    Button moveUpButton;

    Button moveDownButton;

    BeanItemContainer<Plugin> container;

    Table table;

    List<Plugin> plugins;

    public PluginsPanel() {
    }

    @PostConstruct
    @Override
    public void init() {
        ButtonBar buttonBar = new ButtonBar();
        addComponent(buttonBar);
        addButton = buttonBar.addButton("Add", FontAwesome.PLUS);
        addButton.addClickListener(e -> addPlugin());
        moveUpButton = buttonBar.addButton("Move Up", FontAwesome.ARROW_UP, e -> moveUp());
        moveDownButton = buttonBar.addButton("Move Down", FontAwesome.ARROW_DOWN, e -> moveDown());
        removeButton = buttonBar.addButton("Purge Unused", FontAwesome.TRASH_O, e -> purgeUnused());
        container = new BeanItemContainer<Plugin>(Plugin.clreplaced);
        table = new Table();
        table.setSizeFull();
        table.setCacheRate(100);
        table.setImmediate(true);
        table.setSelectable(true);
        table.setMultiSelect(true);
        table.setSortEnabled(false);
        table.setContainerDataSource(container);
        table.setVisibleColumns("artifactGroup", "artifactName", "artifactVersion", "lastUpdateTime");
        table.setColumnHeaders("Group", "Name", "Version", "Updated");
        table.setColumnWidth("lastUpdateTime", UIConstants.DATETIME_WIDTH_PIXELS);
        table.addValueChangeListener(e -> setButtonsEnabled());
        addComponent(table);
        setExpandRatio(table, 1.0f);
        context.getPluginManager().refresh();
    }

    public List<Plugin> getPlugins() {
        return plugins;
    }

    @Override
    public void selected() {
        refresh();
    }

    @Override
    public boolean closing() {
        return true;
    }

    @Override
    public void deselected() {
    }

    public void refresh() {
        container.removeAllItems();
        plugins = context.getPluginService().findPlugins();
        Collections.sort(plugins, new Comparator<Plugin>() {

            @Override
            public int compare(Plugin o1, Plugin o2) {
                return new Integer(o1.getLoadOrder()).compareTo(new Integer(o2.getLoadOrder()));
            }
        });
        container.addAll(plugins);
        table.sort();
        setButtonsEnabled();
    }

    protected void setButtonsEnabled() {
        boolean enabled = getSelectedItems().size() > 0;
        moveUpButton.setEnabled(enabled);
        moveDownButton.setEnabled(enabled);
    }

    @SuppressWarnings("unchecked")
    protected Set<Plugin> getSelectedItems() {
        return (Set<Plugin>) table.getValue();
    }

    protected void moveItemsTo(Set<Plugin> itemIds, int index) {
        if (index >= 0 && index < container.gereplacedemIds().size() && itemIds.size() > 0) {
            int firsreplacedemIndex = container.indexOfId(itemIds.iterator().next());
            if (index != firsreplacedemIndex) {
                for (Plugin itemId : itemIds) {
                    boolean movingUp = index < container.indexOfId(itemId);
                    container.removeItem(itemId);
                    container.addItemAt(index, itemId);
                    if (movingUp) {
                        index++;
                    }
                }
            }
            updateLoadOrder();
            refresh();
        }
    }

    protected void updateLoadOrder() {
        List<Plugin> plugins = container.gereplacedemIds();
        int loadOrder = 1;
        for (Plugin plugin : plugins) {
            if (loadOrder != plugin.getLoadOrder()) {
                plugin.setLoadOrder(loadOrder);
                context.getPluginService().save(plugin);
            }
            loadOrder++;
        }
    }

    protected void moveUp() {
        Set<Plugin> itemIds = getSelectedItems();
        if (itemIds.size() > 0 && itemIds != null) {
            Plugin firsreplacedem = itemIds.iterator().next();
            int index = container.indexOfId(firsreplacedem) - 1;
            moveItemsTo(getSelectedItems(), index);
        }
    }

    protected void moveDown() {
        Set<Plugin> itemIds = getSelectedItems();
        if (itemIds.size() > 0 && itemIds != null) {
            Plugin lasreplacedem = null;
            Iterator<Plugin> iter = itemIds.iterator();
            while (iter.hasNext()) {
                lasreplacedem = iter.next();
            }
            int index = container.indexOfId(lasreplacedem) + 1;
            moveItemsTo(getSelectedItems(), index);
        }
    }

    protected void addPlugin() {
        PluginsPanelAddDialog dialog = new PluginsPanelAddDialog(context, PluginsPanel.this) {

            @Override
            public void close() {
                super.close();
                PluginsPanel.this.refresh();
            }
        };
        UI.getCurrent().addWindow(dialog);
    }

    protected void purgeUnused() {
        IPluginService pluginService = context.getPluginService();
        List<Plugin> plugins = pluginService.findUnusedPlugins();
        for (Plugin plugin : plugins) {
            pluginService.delete(plugin);
        /*
             * TODO: Before enabling this need to figure out logic to calculate if the
             * plug-in is required by other plug-ins that ARE currently
             * referenced
             */
        // context.getPluginManager().delete(plugin.getArtifactGroup(),
        // plugin.getArtifactName(), plugin.getArtifactVersion());
        }
        if (plugins.size() > 0) {
            refresh();
        }
    }

    @Override
    public void enter(ViewChangeEvent event) {
    }
}

19 View Complete Implementation : TagPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
@UiComponent
@UIScope
@Order(300)
@AdminMenuLink(name = "Tags", id = "Tags", icon = FontAwesome.TAG)
public clreplaced TagPanel extends AbstractAdminPanel {

    Button newButton;

    Button editButton;

    Button removeButton;

    BeanItemContainer<Tag> container;

    Table table;

    public TagPanel() {
        ButtonBar buttonBar = new ButtonBar();
        addComponent(buttonBar);
        newButton = buttonBar.addButton("New", FontAwesome.PLUS);
        newButton.addClickListener(new NewClickListener());
        editButton = buttonBar.addButton("Edit", FontAwesome.EDIT);
        editButton.addClickListener(new EditClickListener());
        removeButton = buttonBar.addButton("Remove", FontAwesome.TRASH_O);
        removeButton.addClickListener(new RemoveClickListener());
        container = new BeanItemContainer<Tag>(Tag.clreplaced);
        table = new Table();
        table.setSizeFull();
        table.setCacheRate(100);
        table.setPageLength(100);
        table.setImmediate(true);
        table.setSelectable(true);
        table.setMultiSelect(true);
        table.setContainerDataSource(container);
        table.setVisibleColumns("name", "color");
        table.setColumnHeaders("Tag Name", "Color");
        table.addItemClickListener(new TableItemClickListener());
        table.addValueChangeListener(new TableValueChangeListener());
        table.setSortContainerPropertyId("name");
        table.setSortAscending(true);
        addComponent(table);
        setExpandRatio(table, 1.0f);
    }

    @Override
    public void selected() {
        refresh();
    }

    @Override
    public boolean closing() {
        return true;
    }

    @Override
    public void deselected() {
    }

    public void refresh() {
        container.removeAllItems();
        container.addAll(context.getConfigurationService().findTags());
        table.sort();
        setButtonsEnabled();
    }

    protected void setButtonsEnabled() {
        Set<Tag> selectedIds = getSelectedItems();
        boolean enabled = selectedIds.size() > 0;
        editButton.setEnabled(enabled);
        removeButton.setEnabled(enabled);
    }

    @SuppressWarnings("unchecked")
    protected Set<Tag> getSelectedItems() {
        return (Set<Tag>) table.getValue();
    }

    @SuppressWarnings("unchecked")
    protected Tag getFirstSelectedItem() {
        Set<Tag> tags = (Set<Tag>) table.getValue();
        Iterator<Tag> iter = tags.iterator();
        if (iter.hasNext()) {
            return iter.next();
        }
        return null;
    }

    clreplaced NewClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Tag tag = new Tag();
            TagEditPanel editPanel = new TagEditPanel(context, tag);
            adminView.getTabbedPanel().addCloseableTab(tag.getId(), "Edit Tag", getIcon(), editPanel);
        }
    }

    clreplaced EditClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Tag tag = getFirstSelectedItem();
            // TODO: refresh if we want to do things like show all enreplacedies that are tagged
            // context.getOperationsService().refresh(tag);
            TagEditPanel editPanel = new TagEditPanel(context, tag);
            adminView.getTabbedPanel().addCloseableTab(tag.getId(), "Edit Tag", getIcon(), editPanel);
        }
    }

    clreplaced RemoveClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            IConfigurationService configurationService = context.getConfigurationService();
            for (Tag tag : getSelectedItems()) {
                configurationService.deleteEnreplacedyTagsForTag(tag);
                configurationService.delete(tag);
                container.removeItem(tag);
            }
            table.setValue(null);
            setButtonsEnabled();
        }
    }

    clreplaced TableItemClickListener implements ItemClickListener {

        long lastClick;

        public void itemClick(ItemClickEvent event) {
            if (event.isDoubleClick()) {
                editButton.click();
            } else if (getSelectedItems().contains(event.gereplacedemId()) && System.currentTimeMillis() - lastClick > 500) {
                table.setValue(null);
            }
            lastClick = System.currentTimeMillis();
        }
    }

    clreplaced TableValueChangeListener implements ValueChangeListener {

        public void valueChange(ValueChangeEvent event) {
            setButtonsEnabled();
        }
    }

    @Override
    public void enter(ViewChangeEvent event) {
    }
}

19 View Complete Implementation : EditDeduperPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced EditDeduperPanel extends AbstractComponentEditPanel {

    private static final long serialVersionUID = 1L;

    Table enreplacedyTable = new Table();

    BeanItemContainer<EnreplacedySettings> enreplacedySettingsContainer = new BeanItemContainer<EnreplacedySettings>(EnreplacedySettings.clreplaced);

    List<EnreplacedySettings> enreplacedySettings = new ArrayList<EnreplacedySettings>();

    Table attributeTable = new Table();

    BeanItemContainer<AttributeSettings> attributeSettingsContainer = new BeanItemContainer<AttributeSettings>(AttributeSettings.clreplaced);

    List<AttributeSettings> attributeSettings = new ArrayList<AttributeSettings>();

    TextField enreplacedyFilterField;

    Button editButton;

    EditAttributesWindow attributeWindow;

    Set<EnreplacedySettings> selectedItemIds;

    protected void buildUI() {
        buildButtonBar();
        buildEnreplacedyTable();
        fillEnreplacedyContainer();
        updateEnreplacedyTable(null);
        buildAttributeWindow();
    }

    protected void buildButtonBar() {
        ButtonBar buttonBar = new ButtonBar();
        addComponent(buttonBar);
        editButton = buttonBar.addButton("Edit Columns", FontAwesome.EDIT);
        editButton.addClickListener(new EditButtonClickListener());
        enreplacedyFilterField = buttonBar.addFilter();
        enreplacedyFilterField.addTextChangeListener(event -> updateEnreplacedyTable(event.getText()));
        addComponent(buttonBar);
    }

    @SuppressWarnings("unchecked")
    protected Set<EnreplacedySettings> getSelectedItems() {
        return (Set<EnreplacedySettings>) enreplacedyTable.getValue();
    }

    protected EnreplacedySettings getSelectedItem() {
        Set<EnreplacedySettings> selectedItems = getSelectedItems();
        if (selectedItems != null && selectedItems.size() == 1) {
            return selectedItems.iterator().next();
        }
        return null;
    }

    clreplaced EditButtonClickListener implements ClickListener {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {
            if (getSelectedItem() != null) {
                refreshAttributeContainer((EnreplacedySettings) getSelectedItem());
                updateAttributeTable();
                attributeWindow.show();
            }
        }
    }

    protected void buildEnreplacedyTable() {
        enreplacedyTable.setContainerDataSource(enreplacedySettingsContainer);
        enreplacedyTable.setSelectable(true);
        enreplacedyTable.setSortEnabled(false);
        enreplacedyTable.setImmediate(true);
        enreplacedyTable.setSizeFull();
        enreplacedyTable.addGeneratedColumn("enreplacedyName", new ColumnGenerator() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                EnreplacedySettings setting = (EnreplacedySettings) itemId;
                RelationalModel model = (RelationalModel) component.getInputModel();
                ModelEnreplacedy enreplacedy = model.getEnreplacedyById(setting.getEnreplacedyId());
                return UiUtils.getName(enreplacedyFilterField.getValue(), enreplacedy.getName());
            }
        });
        enreplacedyTable.setVisibleColumns(new Object[] { "enreplacedyName" });
        enreplacedyTable.setColumnWidth("enreplacedyName", 250);
        enreplacedyTable.setColumnHeaders(new String[] { "Enreplacedy Name" });
        enreplacedyTable.setColumnExpandRatio("enreplacedyName", 1);
        enreplacedyTable.setTableFieldFactory(new EditEnreplacedyFieldFactory());
        enreplacedyTable.setEditable(true);
        enreplacedyTable.setMultiSelect(true);
        enreplacedyTable.setDragMode(TableDragMode.MULTIROW);
        enreplacedyTable.setDropHandler(new TableDropHandler());
        enreplacedyTable.setCellStyleGenerator(new TableCellStyleGenerator());
        addComponent(enreplacedyTable);
        setExpandRatio(enreplacedyTable, 1.0f);
    }

    clreplaced TableCellStyleGenerator implements CellStyleGenerator {

        public String getStyle(Table source, Object itemId, Object propertyId) {
            if (propertyId != null && selectedItemIds != null && selectedItemIds.contains(itemId)) {
                return "highlight";
            }
            return null;
        }
    }

    protected void fillEnreplacedyContainer() {
        if (component.getInputModel() != null) {
            RelationalModel model = (RelationalModel) component.getInputModel();
            for (ModelEnreplacedy enreplacedy : model.getModelEnreplacedies()) {
                enreplacedySettings.add(new EnreplacedySettings(enreplacedy.getId()));
            }
        }
    }

    protected void updateEnreplacedyTable(String filter) {
        filter = filter != null ? filter.toLowerCase() : null;
        enreplacedyFilterField.setValue(filter);
        enreplacedyTable.removeAllItems();
        for (EnreplacedySettings enreplacedySetting : enreplacedySettings) {
            RelationalModel model = (RelationalModel) component.getInputModel();
            ModelEnreplacedy enreplacedy = model.getEnreplacedyById(enreplacedySetting.getEnreplacedyId());
            if (isBlank(filter) || enreplacedy.getName().toLowerCase().contains(filter)) {
                enreplacedyTable.addItem(enreplacedySetting);
            }
        }
    }

    protected void moveItemsTo(Set<EnreplacedySettings> itemIds, int index) {
        if (index >= 0 && index < enreplacedySettingsContainer.gereplacedemIds().size() && itemIds.size() > 0) {
            int firsreplacedemIndex = enreplacedySettingsContainer.indexOfId(itemIds.iterator().next());
            if (index != firsreplacedemIndex) {
                for (EnreplacedySettings itemId : itemIds) {
                    boolean movingUp = index < enreplacedySettingsContainer.indexOfId(itemId);
                    enreplacedySettingsContainer.removeItem(itemId);
                    enreplacedySettingsContainer.addItemAt(index, itemId);
                    if (movingUp) {
                        index++;
                    }
                }
            }
        }
    }

    protected void saveSetting(String enreplacedyId, String name, String value) {
        ComponentEnreplacedySetting setting = component.getSingleEnreplacedySetting(enreplacedyId, name);
        if (setting == null) {
            setting = new ComponentEnreplacedySetting(enreplacedyId, name, value);
            setting.setComponentId(component.getId());
            component.addEnreplacedySetting(setting);
            context.getConfigurationService().save(setting);
        } else if (!StringUtils.equals(setting.getValue(), value)) {
            setting.setValue(value);
            context.getConfigurationService().save(setting);
        }
    }

    clreplaced EditEnreplacedyFieldFactory implements TableFieldFactory {

        private static final long serialVersionUID = 1L;

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            return null;
        }
    }

    public static clreplaced EnreplacedySettings implements Serializable {

        private static final long serialVersionUID = 1L;

        String enreplacedyId;

        public EnreplacedySettings(String enreplacedyId) {
            this.enreplacedyId = enreplacedyId;
        }

        public String getEnreplacedyId() {
            return enreplacedyId;
        }

        public void setEnreplacedyId(String enreplacedyId) {
            this.enreplacedyId = enreplacedyId;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof EnreplacedySettings) {
                return enreplacedyId.equals(((EnreplacedySettings) obj).getEnreplacedyId());
            } else {
                return super.equals(obj);
            }
        }

        @Override
        public int hashCode() {
            return enreplacedyId.hashCode();
        }
    }

    // attribute window and support
    protected void buildAttributeWindow() {
        attributeWindow = new EditAttributesWindow();
    }

    clreplaced EditAttributesWindow extends ResizableWindow {

        private static final long serialVersionUID = 1L;

        public EditAttributesWindow() {
            super("Edit Columns to Dedupe on");
            setWidth(800f, Unit.PIXELS);
            setHeight(600f, Unit.PIXELS);
            content.setMargin(true);
            buildAttributeTable();
            addComponent(buildButtonFooter(buildCloseButton()));
        }

        private void buildAttributeTable() {
            attributeTable.setContainerDataSource(attributeSettingsContainer);
            attributeTable.setSelectable(true);
            attributeTable.setImmediate(true);
            attributeTable.setSortEnabled(false);
            attributeTable.setSizeFull();
            attributeTable.addGeneratedColumn("attributeName", new ColumnGenerator() {

                private static final long serialVersionUID = 1L;

                @Override
                public Object generateCell(Table source, Object itemId, Object columnId) {
                    AttributeSettings setting = (AttributeSettings) itemId;
                    RelationalModel model = (RelationalModel) component.getInputModel();
                    ModelAttrib attribute = model.getAttributeById(setting.getAttributeId());
                    return UiUtils.getName(enreplacedyFilterField.getValue(), attribute.getName());
                }
            });
            attributeTable.setVisibleColumns(new Object[] { "attributeName", "dedupeEnabled" });
            attributeTable.setColumnWidth("attributeName", 250);
            attributeTable.setColumnHeaders(new String[] { "Attribute Name", "Dedupe Enabled" });
            attributeTable.setColumnExpandRatio("attributeName", 1);
            attributeTable.setTableFieldFactory(new EditAttributeFieldFactory());
            attributeTable.setEditable(true);
            addComponent(attributeTable, 1);
        }
    }

    private void refreshAttributeContainer(EnreplacedySettings selectedRow) {
        attributeSettings.clear();
        RelationalModel model = (RelationalModel) component.getInputModel();
        ModelEnreplacedy enreplacedy = model.getEnreplacedyById(selectedRow.getEnreplacedyId());
        for (ModelAttrib attribute : enreplacedy.getModelAttributes()) {
            ComponentAttribSetting compare = component.getSingleAttributeSetting(attribute.getId(), Deduper.ATTRIBUTE_DEDUPE_ENABLED);
            boolean dedupeEnabled = compare != null ? Boolean.parseBoolean(compare.getValue()) : false;
            attributeSettings.add(new AttributeSettings(attribute.getId(), dedupeEnabled, attribute.isPk() == true ? true : false));
        }
    }

    protected void updateAttributeTable() {
        attributeTable.removeAllItems();
        for (AttributeSettings attributeSetting : attributeSettings) {
            attributeTable.addItem(attributeSetting);
        }
    }

    clreplaced EditAttributeFieldFactory implements TableFieldFactory {

        private static final long serialVersionUID = 1L;

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            final AttributeSettings settings = (AttributeSettings) itemId;
            if (propertyId.equals("dedupeEnabled")) {
                return createAttributeCheckBox(settings, Deduper.ATTRIBUTE_DEDUPE_ENABLED);
            } else {
                return null;
            }
        }
    }

    protected CheckBox createAttributeCheckBox(final AttributeSettings settings, final String key) {
        final CheckBox checkBox = new CheckBox();
        checkBox.setImmediate(true);
        checkBox.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                ComponentAttribSetting setting = component.getSingleAttributeSetting(settings.getAttributeId(), key);
                String oldValue = setting == null ? Boolean.FALSE.toString() : setting.getValue();
                if (setting == null) {
                    setting = new ComponentAttribSetting(settings.getAttributeId(), component.getId(), key, Boolean.TRUE.toString());
                    component.addAttributeSetting(setting);
                }
                setting.setValue(checkBox.getValue().toString());
                if (!oldValue.equals(setting.getValue())) {
                    context.getConfigurationService().save(setting);
                }
            }
        });
        checkBox.setReadOnly(readOnly);
        return checkBox;
    }

    public static clreplaced AttributeSettings implements Serializable {

        private static final long serialVersionUID = 1L;

        boolean primaryKey;

        String attributeId;

        boolean dedupeEnabled;

        public AttributeSettings(String attributeId, boolean dedupeEnabled, boolean primaryKey) {
            this.attributeId = attributeId;
            this.dedupeEnabled = dedupeEnabled;
            this.primaryKey = primaryKey;
        }

        public void setDedupeEnabled(boolean dedupeEnabled) {
            this.dedupeEnabled = dedupeEnabled;
        }

        public boolean isDedupeEnabled() {
            return dedupeEnabled;
        }

        public String getAttributeId() {
            return attributeId;
        }

        public void setAttributeId(String attributeId) {
            this.attributeId = attributeId;
        }

        public void setPrimaryKey(boolean primaryKey) {
            this.primaryKey = primaryKey;
        }

        public boolean isPrimaryKey() {
            return primaryKey;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof AttributeSettings) {
                return attributeId.equals(((AttributeSettings) obj).getAttributeId());
            } else {
                return super.equals(obj);
            }
        }
    }

    clreplaced TableDropHandler implements DropHandler {

        public void drop(DragAndDropEvent event) {
            AbstractSelectTargetDetails targetDetails = (AbstractSelectTargetDetails) event.getTargetDetails();
            Transferable transferable = event.getTransferable();
            if (transferable.getSourceComponent() == enreplacedyTable) {
                EnreplacedySettings target = (EnreplacedySettings) targetDetails.gereplacedemIdOver();
                moveItemsTo(getSelectedItems(), enreplacedySettingsContainer.indexOfId(target));
            }
        }

        public AcceptCriterion getAcceptCriterion() {
            return AcceptAll.get();
        }
    }
}

19 View Complete Implementation : EditFlowSettingsDialog.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
clreplaced EditFlowSettingsDialog extends ResizableWindow implements ValueChangeListener {

    ApplicationContext context;

    Flow flow;

    BeanItemContainer<FlowParameter> container;

    Table table;

    Button insertButton;

    Button removeButton;

    public EditFlowSettingsDialog(ApplicationContext context, Flow flow, boolean readOnly) {
        super("Flow Settings");
        this.context = context;
        this.flow = flow;
        Button closeButton = new Button("Close");
        closeButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
        closeButton.addClickListener(new CloseClickListener());
        addHeader("General Settings");
        FormLayout formLayout = new FormLayout();
        formLayout.setMargin(true);
        formLayout.addStyleName(ValoTheme.FORMLAYOUT_LIGHT);
        formLayout.setWidth(100, Unit.PERCENTAGE);
        addComponent(formLayout);
        ImmediateUpdateTextArea description = new ImmediateUpdateTextArea("Notes") {

            protected void save(String text) {
                flow.setNotes(text);
                context.getConfigurationService().save(flow);
            }
        };
        description.setValue(flow.getNotes());
        formLayout.addComponent(description);
        addHeader("Parameters");
        if (!readOnly) {
            ButtonBar buttonBar = new ButtonBar();
            buttonBar.addButton("Add", FontAwesome.PLUS, new AddClickListener());
            insertButton = buttonBar.addButton("Insert", FontAwesome.CHEVRON_RIGHT, new InsertClickListener());
            insertButton.setEnabled(false);
            removeButton = buttonBar.addButton("Remove", FontAwesome.TRASH_O, new RemoveClickListener());
            removeButton.setEnabled(false);
            addComponent(buttonBar);
        }
        VerticalLayout tableWrapperLayout = new VerticalLayout();
        tableWrapperLayout.setMargin(true);
        tableWrapperLayout.setSizeFull();
        table = new Table();
        table.setSizeFull();
        container = new BeanItemContainer<FlowParameter>(FlowParameter.clreplaced);
        table.setContainerDataSource(container);
        table.setSelectable(true);
        table.setSortEnabled(false);
        if (!readOnly) {
            table.setEditable(true);
            table.setDragMode(TableDragMode.ROW);
            table.setDropHandler(new TableDropHandler());
            table.setTableFieldFactory(new EditFieldFactory());
            table.addValueChangeListener(this);
        }
        table.setVisibleColumns("position", "name", "defaultValue");
        table.setColumnHeaders("#", "Name", "Default Value");
        table.setColumnExpandRatio("name", .3f);
        table.setColumnExpandRatio("defaultValue", .6f);
        tableWrapperLayout.addComponent(table);
        addComponent(tableWrapperLayout, 1);
        addComponent(buildButtonFooter(closeButton));
        List<FlowParameter> params = flow.getFlowParameters();
        Collections.sort(params, new Comparator<FlowParameter>() {

            public int compare(FlowParameter o1, FlowParameter o2) {
                return new Integer(o1.getPosition()).compareTo(new Integer(o2.getPosition()));
            }
        });
        for (FlowParameter flowParameter : params) {
            table.addItem(flowParameter);
        }
    }

    protected void addHeader(String caption) {
        HorizontalLayout componentHeaderWrapper = new HorizontalLayout();
        componentHeaderWrapper.setMargin(new MarginInfo(false, false, false, true));
        Label componentHeader = new Label(caption);
        componentHeader.addStyleName(ValoTheme.LABEL_H3);
        componentHeader.addStyleName(ValoTheme.LABEL_COLORED);
        componentHeaderWrapper.addComponent(componentHeader);
        addComponent(componentHeaderWrapper);
    }

    public void valueChange(ValueChangeEvent event) {
        removeButton.setEnabled(table.getValue() != null);
        insertButton.setEnabled(table.getValue() != null);
    }

    protected void addItem(int index) {
        FlowParameter parameter = new FlowParameter();
        parameter.setFlowId(flow.getId());
        parameter.setName("Parameter " + (index + 1));
        parameter.setPosition((index + 1));
        context.getConfigurationService().save(parameter);
        flow.getFlowParameters().add(parameter);
        container.addItemAt(index, parameter);
        table.select(parameter);
        table.setCurrentPageFirsreplacedemId(parameter);
    }

    protected void saveAllPositions() {
        @SuppressWarnings("unchecked")
        Collection<FlowParameter> parameters = (Collection<FlowParameter>) table.gereplacedemIds();
        int count = 1;
        for (FlowParameter parameter : parameters) {
            parameter.setPosition(count++);
            context.getConfigurationService().save(parameter);
        }
    }

    clreplaced AddClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            addItem(flow.getFlowParameters().size());
        }
    }

    clreplaced InsertClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            addItem(container.indexOfId((FlowParameter) table.getValue()));
            saveAllPositions();
        }
    }

    clreplaced RemoveClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            FlowParameter parameter = (FlowParameter) table.getValue();
            if (parameter != null) {
                flow.getFlowParameters().remove(parameter);
                context.getConfigurationService().delete((AbstractObject) parameter);
                int index = container.indexOfId(parameter);
                table.removeItem(parameter);
                if (index < container.size()) {
                    table.select(container.getIdByIndex(index));
                }
                saveAllPositions();
            }
        }
    }

    clreplaced CloseClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            EditFlowSettingsDialog.this.close();
        }
    }

    clreplaced EditFieldFactory implements TableFieldFactory {

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            final FlowParameter parameter = (FlowParameter) itemId;
            final TextField textField = new ImmediateUpdateTextField(null) {

                protected void save(String text) {
                    parameter.setDefaultValue(text);
                    context.getConfigurationService().save(parameter);
                }
            };
            textField.addFocusListener(new FocusListener() {

                public void focus(FocusEvent event) {
                    table.select(itemId);
                }
            });
            if (propertyId.equals("position")) {
                textField.setReadOnly(true);
                textField.setWidth(3, Unit.EM);
            } else {
                textField.setWidth(100, Unit.PERCENTAGE);
            }
            return textField;
        }
    }

    clreplaced TableDropHandler implements DropHandler {

        public void drop(DragAndDropEvent event) {
            AbstractSelectTargetDetails targetDetails = (AbstractSelectTargetDetails) event.getTargetDetails();
            Transferable transferable = event.getTransferable();
            if (transferable.getSourceComponent() == table) {
                FlowParameter target = (FlowParameter) targetDetails.gereplacedemIdOver();
                int targetIndex = container.indexOfId(target);
                FlowParameter source = (FlowParameter) transferable.getData("itemId");
                if (targetIndex == -1) {
                    targetIndex = 0;
                }
                container.removeItem(source);
                container.addItemAt(targetIndex, source);
                table.select(source);
                saveAllPositions();
            }
        }

        public AcceptCriterion getAcceptCriterion() {
            return AcceptAll.get();
        }
    }
}

19 View Complete Implementation : EditHierarchicalModelPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced EditHierarchicalModelPanel extends VerticalLayout implements IUiPanel {

    ApplicationContext context;

    TreeTable treeTable = new TreeTable();

    Table table = new Table();

    HierarchicalModel model;

    Set<Object> lastEdireplacedemIds = Collections.emptySet();

    TableColumnSelectWindow tableColumnSelectWindow;

    Button addSchemaObjectButton;

    Button editButton;

    Button removeButton;

    ShortcutListener enterKeyListener;

    boolean readOnly;

    BeanItemContainer<Record> container = new BeanItemContainer<Record>(Record.clreplaced);

    public EditHierarchicalModelPanel(ApplicationContext context, String modelId, boolean readOnly) {
        this.context = context;
        this.model = new HierarchicalModel(modelId);
        this.readOnly = readOnly;
        context.getConfigurationService().refresh(model);
        ButtonBar buttonBar1 = new ButtonBar();
        addComponent(buttonBar1);
        addSchemaObjectButton = buttonBar1.addButton("Add SchemaObject", FontAwesome.PLUS);
        addSchemaObjectButton.addClickListener(new AddSchemaObjectClickListener());
        editButton = buttonBar1.addButton("Edit", FontAwesome.EDIT);
        editButton.addClickListener(new EditClickListener());
        removeButton = buttonBar1.addButton("Remove", FontAwesome.TRASH_O);
        removeButton.addClickListener(new RemoveClickListener());
        treeTable.setSizeFull();
        treeTable.setCacheRate(100);
        treeTable.setPageLength(100);
        treeTable.setImmediate(true);
        treeTable.setSelectable(true);
        treeTable.setMultiSelect(true);
        treeTable.addGeneratedColumn("name", new ColumnGenerator() {

            public Object generateCell(Table source, Object itemId, Object columnId) {
                final AbstractNamedObject obj = (AbstractNamedObject) itemId;
                if (lastEdireplacedemIds.contains(itemId) && !readOnly) {
                    ImmediateUpdateTextField t = new ImmediateUpdateTextField(null) {

                        protected void save(String text) {
                            String newName = trim(text);
                            obj.setName(newName);
                            EditHierarchicalModelPanel.this.context.getConfigurationService().save(obj);
                        }
                    };
                    t.setWidth(100, Unit.PERCENTAGE);
                    t.setValue(obj.getName());
                    t.focus();
                    t.selectAll();
                    return t;
                } else {
                    return obj.getName();
                }
            }
        });
        treeTable.setColumnHeader("name", "Name");
        treeTable.addGeneratedColumn("description", new ColumnGenerator() {

            public Object generateCell(Table source, Object itemId, Object columnId) {
                final ModelSchemaObject obj = (ModelSchemaObject) itemId;
                if (lastEdireplacedemIds.contains(itemId) && !readOnly) {
                    ImmediateUpdateTextField t = new ImmediateUpdateTextField(null) {

                        protected void save(String text) {
                            obj.setDescription(trim(text));
                            EditHierarchicalModelPanel.this.context.getConfigurationService().save(obj);
                        }
                    };
                    t.setWidth(100, Unit.PERCENTAGE);
                    t.setValue(obj.getDescription());
                    return t;
                } else {
                    return obj.getDescription();
                }
            }
        });
        treeTable.setColumnHeader("description", "Description");
        treeTable.addGeneratedColumn("type", new ColumnGenerator() {

            public Object generateCell(Table source, Object itemId, Object columnId) {
                final ModelSchemaObject obj = (ModelSchemaObject) itemId;
                if (lastEdireplacedemIds.contains(itemId) && !readOnly) {
                    final ComboBox cbox = new ComboBox();
                    cbox.setNullSelectionAllowed(false);
                    for (HierarchicalDataType dataType : HierarchicalDataType.values()) {
                        cbox.addItem(dataType.name());
                    }
                    cbox.setValue(obj.getType());
                    cbox.addValueChangeListener(new ValueChangeListener() {

                        public void valueChange(ValueChangeEvent event) {
                            obj.setType((String) cbox.getValue());
                            EditHierarchicalModelPanel.this.context.getConfigurationService().save(obj);
                        }
                    });
                    cbox.addBlurListener(new BlurListener() {

                        public void blur(BlurEvent event) {
                            Collection<?> items = treeTable.gereplacedemIds();
                            boolean found = false;
                            for (Object item : items) {
                                if (item.equals(obj)) {
                                    found = true;
                                } else if (found) {
                                    selectOnly(item);
                                    editSelectedItem();
                                    break;
                                }
                            }
                        }
                    });
                    return cbox;
                } else {
                    return obj.getType();
                }
            }
        });
        treeTable.setColumnHeader("type", "Type");
        treeTable.addGeneratedColumn("pattern", new ColumnGenerator() {

            public Object generateCell(Table source, Object itemId, Object columnId) {
                final ModelSchemaObject obj = (ModelSchemaObject) itemId;
                if (lastEdireplacedemIds.contains(itemId) && !readOnly) {
                    ImmediateUpdateTextField t = new ImmediateUpdateTextField(null) {

                        protected void save(String text) {
                            obj.setPattern(trim(text));
                            EditHierarchicalModelPanel.this.context.getConfigurationService().save(obj);
                        }
                    };
                    t.setWidth(100, Unit.PERCENTAGE);
                    t.setValue(obj.getPattern());
                    return t;
                } else {
                    return obj.getPattern();
                }
            }
        });
        treeTable.setColumnHeader("pattern", "Pattern");
        treeTable.addItemClickListener(new TreeTableItemClickListener());
        treeTable.addValueChangeListener(new TreeTableValueChangeListener());
        enterKeyListener = new ShortcutListener("Enter", KeyCode.ENTER, null) {

            public void handleAction(Object sender, Object target) {
                lastEdireplacedemIds = Collections.emptySet();
                treeTable.refreshRowCache();
            }
        };
        addComponent(treeTable);
        setExpandRatio(treeTable, 1.0f);
        HorizontalLayout hlayout = new HorizontalLayout();
        addComponent(hlayout);
        addAll(model);
        setButtonsEnabled();
        table.setContainerDataSource(container);
        table.setVisibleColumns(new Object[] { "name", "description", "type" });
        table.setColumnHeaders(new String[] { "name", "Description", "Type" });
        expandAll(null);
    }

    protected void collapseAll() {
        for (Object itemId : treeTable.gereplacedemIds()) {
            treeTable.setCollapsed(itemId, true);
        }
    }

    protected void expandAll(ModelSchemaObject parentObject) {
        ModelSchemaObject schemaObject = null;
        if (parentObject == null) {
            for (Object itemId : treeTable.gereplacedemIds()) {
                schemaObject = (ModelSchemaObject) itemId;
            }
        } else {
            schemaObject = parentObject;
        }
        if (schemaObject != null) {
            treeTable.setCollapsed(schemaObject, false);
            for (ModelSchemaObject childObject : schemaObject.getChildObjects()) {
                expandAll(childObject);
            }
        }
    }

    public void setButtonsEnabled() {
        if (!readOnly) {
            Set<Object> selected = getSelectedItems();
            removeButton.setEnabled(selected.size() > 0);
            editButton.setEnabled(selected.size() > 0);
        } else {
            addSchemaObjectButton.setEnabled(false);
            removeButton.setEnabled(false);
            editButton.setEnabled(false);
        }
    }

    @Override
    public boolean closing() {
        return true;
    }

    @Override
    public void selected() {
        treeTable.addShortcutListener(enterKeyListener);
    }

    @Override
    public void deselected() {
        treeTable.removeShortcutListener(enterKeyListener);
    }

    protected Object getSelected() {
        if (getSelectedItems().size() > 0) {
            return getSelectedItems().iterator().next();
        } else {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    protected Set<Object> getSelectedItems() {
        return (Set<Object>) treeTable.getValue();
    }

    protected void selectOnly(Object itemId) {
        for (Object id : getSelectedItems()) {
            treeTable.unselect(id);
        }
        treeTable.select(itemId);
    }

    protected void addAll(HierarchicalModel model) {
        ModelSchemaObject rootObject = model.getRootObject();
        if (rootObject != null) {
            addSchemaObject(rootObject, null, null);
        }
    }

    protected void addSchemaObject(ModelSchemaObject schemaObject, ModelSchemaObject parent, ModelSchemaObject refObject) {
        treeTable.addItem(schemaObject);
        treeTable.setChildrenAllowed(schemaObject, true);
        treeTable.sereplacedemIcon(schemaObject, FontAwesome.CUBE);
        if (parent != null) {
            treeTable.setParent(schemaObject, parent);
        }
        for (ModelSchemaObject childObject : schemaObject.getChildObjects()) {
            addSchemaObject(childObject, schemaObject, null);
        }
    }

    protected void editSelectedItem() {
        lastEdireplacedemIds = getSelectedItems();
        treeTable.refreshRowCache();
        table.refreshRowCache();
    }

    clreplaced AddSchemaObjectClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<Object> selectedIds = getSelectedItems();
            if (selectedIds.size() > 1) {
            // TODO: pop up a message and throw an error
            // that 0 or 1 items must be selected to add an enreplacedy
            } else if (selectedIds.size() == 0 && model.getRootObject() != null && model.getRootObject().getChildObjects().size() != 0) {
            // TODO: pop up a message and throw an error
            // that if an enreplacedy already exists (root enreplacedy), the subsequent enreplacedies must be attached somewhere
            } else {
                ModelSchemaObject parentSchemaObject = null;
                if (selectedIds.size() != 0) {
                    Object itemId = selectedIds.iterator().next();
                    parentSchemaObject = (ModelSchemaObject) itemId;
                }
                // add the schema object
                ModelSchemaObject newObject = new ModelSchemaObject();
                newObject.setModelId(model.getId());
                newObject.setName("New Schema Object");
                newObject.setId(UUID.randomUUID().toString());
                if (parentSchemaObject != null) {
                    newObject.setParentId(parentSchemaObject.getId());
                }
                context.getConfigurationService().save(newObject);
                if (model.getRootObject() == null) {
                    model.setRootObject(newObject);
                } else {
                    parentSchemaObject.getChildObjects().add(newObject);
                }
                addSchemaObject(newObject, parentSchemaObject, null);
                treeTable.setCollapsed(parentSchemaObject, false);
                selectOnly(newObject);
                editSelectedItem();
            }
        }
    }

    clreplaced EditClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            editSelectedItem();
        }
    }

    clreplaced RemoveClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<Object> selectedItems = getSelectedItems();
            ConfirmDialog.show("Delete?", "Are you sure you want to delete the " + selectedItems.size() + " selected items and their children?", () -> {
                for (Object itemToDelete : selectedItems) {
                    context.getConfigurationService().delete((ModelSchemaObject) itemToDelete);
                    context.getConfigurationService().refresh(model);
                    treeTable.removeAllItems();
                    addAll(model);
                }
                return true;
            });
        }
    }

    clreplaced TreeTableItemClickListener implements ItemClickListener {

        long lastClick;

        public void itemClick(ItemClickEvent event) {
            if (event.isDoubleClick()) {
                editSelectedItem();
            } else if (System.currentTimeMillis() - lastClick > 1000 && getSelectedItems().size() > 0) {
                treeTable.setValue(null);
            }
            lastClick = System.currentTimeMillis();
        }
    }

    clreplaced TreeTableValueChangeListener implements ValueChangeListener {

        public void valueChange(ValueChangeEvent event) {
            lastEdireplacedemIds = Collections.emptySet();
            treeTable.refreshRowCache();
            setButtonsEnabled();
        }
    }

    public clreplaced Record {

        ModelSchemaObject modelSchemaObject;

        String name = "";

        String description = "";

        String type = "";

        String pattern = "";

        boolean required = false;

        public Record(ModelSchemaObject modelSchemaObject) {
            this.modelSchemaObject = modelSchemaObject;
            if (modelSchemaObject != null) {
                this.name = modelSchemaObject.getName();
                this.description = modelSchemaObject.getDescription();
                this.type = modelSchemaObject.getType();
                this.pattern = modelSchemaObject.getPattern();
                this.required = modelSchemaObject.isRequired();
            }
        }

        public int hashCode() {
            return modelSchemaObject.hashCode();
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getPattern() {
            return pattern;
        }

        public void setPattern(String pattern) {
            this.pattern = pattern;
        }

        public boolean isRequired() {
            return required;
        }

        public void setRequired(boolean required) {
            this.required = required;
        }
    }
}

19 View Complete Implementation : EditMergerPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced EditMergerPanel extends AbstractComponentEditPanel {

    Table table = new Table();

    TextField filterField;

    List<AttributeSettings> attributeSettings = new ArrayList<AttributeSettings>();

    BeanItemContainer<AttributeSettings> container = new BeanItemContainer<AttributeSettings>(AttributeSettings.clreplaced);

    protected void buildUI() {
        ButtonBar buttonBar = new ButtonBar();
        addComponent(buttonBar);
        filterField = buttonBar.addFilter();
        filterField.addTextChangeListener(new TextChangeListener() {

            @Override
            public void textChange(TextChangeEvent event) {
                filterField.setValue(event.getText());
                updateTable(event.getText());
            }
        });
        addComponent(buttonBar);
        table.setContainerDataSource(container);
        table.setSelectable(true);
        table.setSortEnabled(false);
        table.setImmediate(true);
        table.setSortEnabled(true);
        table.setSizeFull();
        table.addGeneratedColumn("enreplacedyName", new ColumnGenerator() {

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                AttributeSettings setting = (AttributeSettings) itemId;
                RelationalModel model = (RelationalModel) component.getInputModel();
                ModelAttrib attribute = model.getAttributeById(setting.getAttributeId());
                ModelEnreplacedy enreplacedy = model.getEnreplacedyById(attribute.getEnreplacedyId());
                return UiUtils.getName(filterField.getValue(), enreplacedy.getName());
            }
        });
        table.addGeneratedColumn("attributeName", new ColumnGenerator() {

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                AttributeSettings setting = (AttributeSettings) itemId;
                RelationalModel model = (RelationalModel) component.getInputModel();
                ModelAttrib attribute = model.getAttributeById(setting.getAttributeId());
                return UiUtils.getName(filterField.getValue(), attribute.getName());
            }
        });
        table.setVisibleColumns(new Object[] { "enreplacedyName", "attributeName", "joinOn" });
        table.setColumnWidth("enreplacedyName", 250);
        table.setColumnWidth("attributeName", 250);
        table.setColumnHeaders(new String[] { "Enreplacedy Name", "Attribute Name", "Join On" });
        table.setTableFieldFactory(new EditFieldFactory());
        table.setEditable(true);
        addComponent(table);
        setExpandRatio(table, 1.0f);
        if (component.getInputModel() != null) {
            RelationalModel model = (RelationalModel) component.getInputModel();
            for (ModelEnreplacedy enreplacedy : model.getModelEnreplacedies()) {
                for (ModelAttrib attr : enreplacedy.getModelAttributes()) {
                    ComponentAttribSetting joinOn = component.getSingleAttributeSetting(attr.getId(), Merger.MERGE_ATTRIBUTE);
                    boolean join = joinOn != null ? Boolean.parseBoolean(joinOn.getValue()) : false;
                    attributeSettings.add(new AttributeSettings(attr.getId(), join));
                }
            }
            Collections.sort(attributeSettings, new Comparator<AttributeSettings>() {

                @Override
                public int compare(AttributeSettings o1, AttributeSettings o2) {
                    RelationalModel model = (RelationalModel) component.getInputModel();
                    ModelAttrib attribute1 = model.getAttributeById(o1.getAttributeId());
                    ModelEnreplacedy enreplacedy1 = model.getEnreplacedyById(attribute1.getEnreplacedyId());
                    ModelAttrib attribute2 = model.getAttributeById(o2.getAttributeId());
                    ModelEnreplacedy enreplacedy2 = model.getEnreplacedyById(attribute2.getEnreplacedyId());
                    int compare = enreplacedy1.getName().compareTo(enreplacedy2.getName());
                    if (compare == 0) {
                        compare = attribute1.getName().compareTo(attribute2.getName());
                    }
                    return compare;
                }
            });
        }
        updateTable(null);
    }

    protected void updateTable(String filter) {
        filter = filter != null ? filter.toLowerCase() : null;
        table.removeAllItems();
        for (AttributeSettings attributeSetting : attributeSettings) {
            RelationalModel model = (RelationalModel) component.getInputModel();
            ModelAttrib attribute = model.getAttributeById(attributeSetting.getAttributeId());
            ModelEnreplacedy enreplacedy = model.getEnreplacedyById(attribute.getEnreplacedyId());
            if (isBlank(filter) || enreplacedy.getName().toLowerCase().contains(filter) || attribute.getName().toLowerCase().contains(filter)) {
                table.addItem(attributeSetting);
            }
        }
    }

    clreplaced EditFieldFactory implements TableFieldFactory {

        public Field<?> createField(final Container dataContainer, final Object itemId, final Object propertyId, com.vaadin.ui.Component uiContext) {
            final AttributeSettings settings = (AttributeSettings) itemId;
            if (propertyId.equals("joinOn")) {
                return createCheckBox(settings, Merger.MERGE_ATTRIBUTE);
            } else {
                return null;
            }
        }
    }

    private CheckBox createCheckBox(final AttributeSettings settings, final String key) {
        final CheckBox checkBox = new CheckBox();
        checkBox.setImmediate(true);
        checkBox.addValueChangeListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                ComponentAttribSetting setting = component.getSingleAttributeSetting(settings.getAttributeId(), key);
                String oldValue = setting == null ? Boolean.FALSE.toString() : setting.getValue();
                if (setting == null) {
                    setting = new ComponentAttribSetting(settings.getAttributeId(), component.getId(), key, Boolean.TRUE.toString());
                    component.addAttributeSetting(setting);
                }
                setting.setValue(checkBox.getValue().toString());
                if (!oldValue.equals(setting.getValue())) {
                    context.getConfigurationService().save(setting);
                }
            }
        });
        checkBox.setReadOnly(readOnly);
        return checkBox;
    }

    public static clreplaced AttributeSettings {

        String attributeId;

        boolean joinOn;

        public AttributeSettings(String attributeId, boolean joinOn) {
            this.attributeId = attributeId;
            this.joinOn = joinOn;
        }

        public void setJoinOn(boolean joinOn) {
            this.joinOn = joinOn;
        }

        public boolean isJoinOn() {
            return joinOn;
        }

        public String getAttributeId() {
            return attributeId;
        }

        public void setAttributeId(String attributeId) {
            this.attributeId = attributeId;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof AttributeSettings) {
                return attributeId.equals(((AttributeSettings) obj).getAttributeId());
            } else {
                return super.equals(obj);
            }
        }

        @Override
        public int hashCode() {
            return attributeId.hashCode();
        }
    }
}

19 View Complete Implementation : EditRelationalModelPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
@SuppressWarnings("serial")
public clreplaced EditRelationalModelPanel extends VerticalLayout implements IUiPanel {

    ApplicationContext context;

    TreeTable treeTable = new TreeTable();

    Table table = new Table();

    RelationalModel model;

    Set<Object> lastEdireplacedemIds = Collections.emptySet();

    TableColumnSelectWindow tableColumnSelectWindow;

    Button addEnreplacedyButton;

    Button addAttributeButton;

    Button editButton;

    Button removeButton;

    Button importButton;

    Button moveUpButton;

    Button moveDownButton;

    Button moveTopButton;

    Button moveBottomButton;

    TextField filterField;

    ShortcutListener enterKeyListener;

    boolean readOnly;

    BeanItemContainer<Record> container = new BeanItemContainer<Record>(Record.clreplaced);

    public EditRelationalModelPanel(ApplicationContext context, String modelId, boolean readOnly) {
        this.context = context;
        this.model = new RelationalModel(modelId);
        this.readOnly = readOnly;
        context.getConfigurationService().refresh(model);
        ButtonBar buttonBar1 = new ButtonBar();
        addComponent(buttonBar1);
        ButtonBar buttonBar2 = new ButtonBar();
        addComponent(buttonBar2);
        addEnreplacedyButton = buttonBar1.addButton("Add Enreplacedy", FontAwesome.TABLE);
        addEnreplacedyButton.addClickListener(new AddEnreplacedyClickListener());
        addAttributeButton = buttonBar1.addButton("Add Attr", FontAwesome.COLUMNS);
        addAttributeButton.addClickListener(new AddAttributeClickListener());
        editButton = buttonBar1.addButton("Edit", FontAwesome.EDIT);
        editButton.addClickListener(new EditClickListener());
        removeButton = buttonBar1.addButton("Remove", FontAwesome.TRASH_O);
        removeButton.addClickListener(new RemoveClickListener());
        moveUpButton = buttonBar2.addButton("Up", FontAwesome.ARROW_UP, e -> moveUp());
        moveDownButton = buttonBar2.addButton("Down", FontAwesome.ARROW_DOWN, e -> moveDown());
        moveTopButton = buttonBar2.addButton("Top", FontAwesome.ANGLE_DOUBLE_UP, e -> moveTop());
        moveBottomButton = buttonBar2.addButton("Bottom", FontAwesome.ANGLE_DOUBLE_DOWN, e -> moveBottom());
        importButton = buttonBar1.addButtonRight("Import ...", FontAwesome.UPLOAD, new ImportClickListener());
        buttonBar1.addButtonRight("Export...", FontAwesome.DOWNLOAD, (e) -> export());
        filterField = buttonBar2.addFilter();
        filterField.addTextChangeListener(new TextChangeListener() {

            public void textChange(TextChangeEvent event) {
                filterField.setValue(event.getText());
                treeTable.removeAllItems();
                addAll(event.getText(), EditRelationalModelPanel.this.model.getModelEnreplacedies());
            }
        });
        treeTable.setSizeFull();
        treeTable.setCacheRate(100);
        treeTable.setPageLength(100);
        treeTable.setImmediate(true);
        treeTable.setSelectable(true);
        treeTable.setMultiSelect(true);
        treeTable.addGeneratedColumn("name", new ColumnGenerator() {

            public Object generateCell(Table source, Object itemId, Object columnId) {
                final AbstractNamedObject obj = (AbstractNamedObject) itemId;
                if (lastEdireplacedemIds.contains(itemId) && !readOnly) {
                    ImmediateUpdateTextField t = new ImmediateUpdateTextField(null) {

                        protected void save(String text) {
                            String newName = trim(text);
                            boolean unique = true;
                            if (obj instanceof ModelEnreplacedy) {
                                List<ModelEnreplacedy> enreplacedies = model.getModelEnreplacedies();
                                for (ModelEnreplacedy enreplacedy : enreplacedies) {
                                    if (!enreplacedy.equals(obj) && enreplacedy.getName().equals(newName)) {
                                        unique = false;
                                    }
                                }
                            } else if (obj instanceof ModelAttrib) {
                                List<ModelAttrib> attributes = model.getEnreplacedyById(((ModelAttrib) obj).getEnreplacedyId()).getModelAttributes();
                                for (ModelAttrib attribute : attributes) {
                                    if (!attribute.equals(obj) && attribute.getName().equals(newName)) {
                                        unique = false;
                                    }
                                }
                            }
                            if (unique) {
                                obj.setName(newName);
                                EditRelationalModelPanel.this.context.getConfigurationService().save(obj);
                            } else {
                                NotifyDialog.show("Name needs to be unique", "Name needs to be unique", null, Type.WARNING_MESSAGE);
                            }
                        }
                    };
                    t.setWidth(100, Unit.PERCENTAGE);
                    t.setValue(obj.getName());
                    t.focus();
                    t.selectAll();
                    return t;
                } else {
                    return UiUtils.getName(filterField.getValue(), obj.getName());
                }
            }
        });
        treeTable.setColumnHeader("name", "Name");
        treeTable.addGeneratedColumn("description", new ColumnGenerator() {

            public Object generateCell(Table source, Object itemId, Object columnId) {
                if (itemId instanceof ModelAttrib) {
                    final ModelAttrib obj = (ModelAttrib) itemId;
                    if (lastEdireplacedemIds.contains(itemId) && !readOnly) {
                        ImmediateUpdateTextField t = new ImmediateUpdateTextField(null) {

                            protected void save(String text) {
                                obj.setDescription(trim(text));
                                EditRelationalModelPanel.this.context.getConfigurationService().save(obj);
                            }
                        };
                        t.setWidth(100, Unit.PERCENTAGE);
                        t.setValue(obj.getDescription());
                        return t;
                    } else {
                        return UiUtils.getName(filterField.getValue(), obj.getDescription());
                    }
                }
                if (itemId instanceof ModelEnreplacedy) {
                    final ModelEnreplacedy obj = (ModelEnreplacedy) itemId;
                    if (lastEdireplacedemIds.contains(itemId) && !readOnly) {
                        ImmediateUpdateTextField t = new ImmediateUpdateTextField(null) {

                            protected void save(String text) {
                                obj.setDescription(trim(text));
                                EditRelationalModelPanel.this.context.getConfigurationService().save(obj);
                            }
                        };
                        t.setWidth(100, Unit.PERCENTAGE);
                        t.setValue(obj.getDescription());
                        return t;
                    } else {
                        return UiUtils.getName(filterField.getValue(), obj.getDescription());
                    }
                } else
                    return null;
            }
        });
        treeTable.setColumnHeader("description", "Description");
        treeTable.addGeneratedColumn("type", new ColumnGenerator() {

            public Object generateCell(Table source, Object itemId, Object columnId) {
                if (itemId instanceof ModelAttrib) {
                    final ModelAttrib obj = (ModelAttrib) itemId;
                    if (lastEdireplacedemIds.contains(itemId) && !readOnly) {
                        final ComboBox cbox = new ComboBox();
                        cbox.setNullSelectionAllowed(false);
                        for (DataType dataType : DataType.values()) {
                            cbox.addItem(dataType.name());
                        }
                        cbox.setValue(obj.getType());
                        cbox.addValueChangeListener(new ValueChangeListener() {

                            public void valueChange(ValueChangeEvent event) {
                                obj.setType((String) cbox.getValue());
                                EditRelationalModelPanel.this.context.getConfigurationService().save(obj);
                            }
                        });
                        cbox.addBlurListener(new BlurListener() {

                            public void blur(BlurEvent event) {
                                Collection<?> items = treeTable.gereplacedemIds();
                                boolean found = false;
                                for (Object item : items) {
                                    if (item.equals(obj)) {
                                        found = true;
                                    } else if (found) {
                                        selectOnly(item);
                                        editSelectedItem();
                                        break;
                                    }
                                }
                            }
                        });
                        return cbox;
                    } else {
                        return obj.getType();
                    }
                } else {
                    return null;
                }
            }
        });
        treeTable.setColumnHeader("type", "Type");
        treeTable.addGeneratedColumn("pk", new ColumnGenerator() {

            public Object generateCell(Table source, Object itemId, Object columnId) {
                if (itemId instanceof ModelAttrib) {
                    final ModelAttrib obj = (ModelAttrib) itemId;
                    if (lastEdireplacedemIds.contains(itemId) && !readOnly) {
                        final CheckBox cbox = new CheckBox();
                        cbox.setValue(obj.isPk());
                        cbox.setImmediate(true);
                        cbox.addValueChangeListener(event -> togglePk(obj));
                        cbox.addBlurListener(new BlurListener() {

                            public void blur(BlurEvent event) {
                                Collection<?> items = treeTable.gereplacedemIds();
                                boolean found = false;
                                for (Object item : items) {
                                    if (item.equals(obj)) {
                                        found = true;
                                    } else if (found) {
                                        selectOnly(item);
                                        editSelectedItem();
                                        break;
                                    }
                                }
                            }
                        });
                        return cbox;
                    } else if (obj.isPk()) {
                        return new Label(FontAwesome.KEY.getHtml(), ContentMode.HTML);
                    }
                }
                return null;
            }
        });
        treeTable.setColumnHeader("pk", "PK");
        treeTable.setColumnWidth("pk", 40);
        treeTable.addItemClickListener(new TreeTableItemClickListener());
        treeTable.addValueChangeListener(new TreeTableValueChangeListener());
        enterKeyListener = new ShortcutListener("Enter", KeyCode.ENTER, null) {

            public void handleAction(Object sender, Object target) {
                lastEdireplacedemIds = Collections.emptySet();
                treeTable.refreshRowCache();
            }
        };
        addComponent(treeTable);
        setExpandRatio(treeTable, 1.0f);
        HorizontalLayout hlayout = new HorizontalLayout();
        addComponent(hlayout);
        Button collapseAll = new Button("Collapse All");
        collapseAll.addStyleName(ValoTheme.BUTTON_LINK);
        collapseAll.addStyleName(ValoTheme.BUTTON_SMALL);
        hlayout.addComponent(collapseAll);
        collapseAll.addClickListener(e -> collapseAll());
        Button expandAll = new Button("Expand All");
        expandAll.addStyleName(ValoTheme.BUTTON_LINK);
        expandAll.addStyleName(ValoTheme.BUTTON_SMALL);
        hlayout.addComponent(expandAll);
        expandAll.addClickListener(e -> expandAll());
        addAll("", model.getModelEnreplacedies());
        setButtonsEnabled();
        table.setContainerDataSource(container);
        table.setVisibleColumns(new Object[] { "enreplacedyName", "attributeName", "description", "type", "pk" });
        table.setColumnHeaders(new String[] { "Enreplacedy Name", "Attribute Name", "Description", "Type", "PK" });
        if (model.getModelEnreplacedies().size() > 10) {
            collapseAll();
        }
    }

    protected void move(boolean down, boolean toEnd) {
        ModelAttrib selected = (ModelAttrib) getSelected();
        if (selected != null) {
            ModelEnreplacedy enreplacedy = (ModelEnreplacedy) treeTable.getParent(selected);
            List<ModelAttrib> attributes = enreplacedy.getModelAttributes();
            int index = attributes.indexOf(selected);
            if (down && index < attributes.size() - 1 && !toEnd) {
                attributes.remove(selected);
                attributes.add(index + 1, selected);
            } else if (!down && index > 0 && !toEnd) {
                attributes.remove(selected);
                attributes.add(index - 1, selected);
            } else if (down) {
                attributes.remove(selected);
                attributes.add(0, selected);
            } else {
                attributes.remove(selected);
                attributes.add(selected);
            }
            index = 0;
            for (ModelAttrib modelAttribute : attributes) {
                modelAttribute.setAttributeOrder(index++);
                context.getConfigurationService().save(modelAttribute);
            }
            Collection<?> children = new ArrayList<>(treeTable.getChildren(enreplacedy));
            for (Object object : children) {
                treeTable.removeItem(object);
            }
            for (ModelAttrib modelAttribute : attributes) {
                addModelAttribute(enreplacedy, modelAttribute);
            }
            treeTable.select(selected);
        }
    }

    protected void moveDown() {
        move(true, false);
    }

    protected void moveUp() {
        move(false, false);
    }

    protected void moveTop() {
        move(true, true);
    }

    protected void moveBottom() {
        move(false, true);
    }

    protected void collapseAll() {
        for (Object itemId : treeTable.gereplacedemIds()) {
            treeTable.setCollapsed(itemId, true);
        }
    }

    protected void expandAll() {
        for (Object itemId : treeTable.gereplacedemIds()) {
            treeTable.setCollapsed(itemId, false);
        }
    }

    protected void export() {
        table.removeAllItems();
        updateExportTable(filterField.getValue(), model.getModelEnreplacedies());
        String fileNamePrefix = model.getName().toLowerCase().replace(' ', '-');
        ExportDialog dialog = new ExportDialog(new TableV7DataProvider(table), fileNamePrefix, model.getName());
        UI.getCurrent().addWindow(dialog);
    }

    protected void togglePk(ModelAttrib a) {
        a.setPk(!a.isPk());
        context.getConfigurationService().save(a);
    }

    public void setButtonsEnabled() {
        if (!readOnly) {
            Set<Object> selected = getSelectedItems();
            addAttributeButton.setEnabled(selected.size() > 0);
            removeButton.setEnabled(selected.size() > 0);
            editButton.setEnabled(selected.size() > 0);
            boolean enableMove = selected.size() == 1 && selected.iterator().next() instanceof ModelAttrib;
            moveBottomButton.setEnabled(enableMove);
            moveTopButton.setEnabled(enableMove);
            moveUpButton.setEnabled(enableMove);
            moveDownButton.setEnabled(enableMove);
        } else {
            addEnreplacedyButton.setEnabled(false);
            addAttributeButton.setEnabled(false);
            removeButton.setEnabled(false);
            editButton.setEnabled(false);
            moveBottomButton.setEnabled(false);
            moveTopButton.setEnabled(false);
            moveUpButton.setEnabled(false);
            moveDownButton.setEnabled(false);
            importButton.setEnabled(false);
        }
    }

    @Override
    public boolean closing() {
        return true;
    }

    @Override
    public void selected() {
        treeTable.addShortcutListener(enterKeyListener);
    }

    @Override
    public void deselected() {
        treeTable.removeShortcutListener(enterKeyListener);
    }

    protected Object getSelected() {
        if (getSelectedItems().size() > 0) {
            return getSelectedItems().iterator().next();
        } else {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    protected Set<Object> getSelectedItems() {
        return (Set<Object>) treeTable.getValue();
    }

    protected void selectOnly(Object itemId) {
        for (Object id : getSelectedItems()) {
            treeTable.unselect(id);
        }
        treeTable.select(itemId);
    }

    protected void add(ModelEnreplacedy modelEnreplacedy) {
        addModelEnreplacedy(modelEnreplacedy);
        for (ModelAttrib modelAttribute : modelEnreplacedy.getModelAttributes()) {
            treeTable.setChildrenAllowed(modelEnreplacedy, true);
            modelAttribute.setEnreplacedyId(modelEnreplacedy.getId());
            addModelAttribute(modelEnreplacedy, modelAttribute);
        }
        treeTable.setCollapsed(modelEnreplacedy, false);
    }

    protected void addAll(String filter, Collection<ModelEnreplacedy> modelEnreplacedyList) {
        filter = filter != null ? filter.toLowerCase() : null;
        ArrayList<ModelEnreplacedy> filteredModelEnreplacedyList = new ArrayList<ModelEnreplacedy>();
        for (ModelEnreplacedy modelEnreplacedy : modelEnreplacedyList) {
            boolean add = UiUtils.filterMatches(filter, modelEnreplacedy.getName());
            if (!add) {
                for (ModelAttrib modelAttribute : modelEnreplacedy.getModelAttributes()) {
                    add |= UiUtils.filterMatches(filter, modelAttribute.getName());
                }
            }
            if (add) {
                filteredModelEnreplacedyList.add(modelEnreplacedy);
            }
        }
        Collections.sort(filteredModelEnreplacedyList, new ModelEnreplacedySorter());
        for (ModelEnreplacedy modelEnreplacedy : filteredModelEnreplacedyList) {
            add(modelEnreplacedy);
        }
    }

    protected void updateExportTable(String filter, Collection<ModelEnreplacedy> modelEnreplacedyList) {
        filter = filter != null ? filter.toLowerCase() : null;
        ArrayList<ModelEnreplacedy> filteredModelEnreplacedyList = new ArrayList<ModelEnreplacedy>();
        for (ModelEnreplacedy modelEnreplacedy : modelEnreplacedyList) {
            boolean add = UiUtils.filterMatches(filter, modelEnreplacedy.getName());
            if (!add) {
                for (ModelAttrib modelAttribute : modelEnreplacedy.getModelAttributes()) {
                    add |= UiUtils.filterMatches(filter, modelAttribute.getName());
                }
            }
            if (add) {
                filteredModelEnreplacedyList.add(modelEnreplacedy);
            }
        }
        Collections.sort(filteredModelEnreplacedyList, new ModelEnreplacedySorter());
        for (ModelEnreplacedy modelEnreplacedy : filteredModelEnreplacedyList) {
            for (ModelAttrib modelAttribute : modelEnreplacedy.getModelAttributes()) {
                table.addItem(new Record(modelEnreplacedy, modelAttribute));
            }
        }
    }

    protected void addModelEnreplacedy(ModelEnreplacedy modelEnreplacedy) {
        treeTable.addItem(modelEnreplacedy);
        treeTable.sereplacedemIcon(modelEnreplacedy, FontAwesome.TABLE);
        treeTable.setChildrenAllowed(modelEnreplacedy, false);
    }

    protected void addModelAttribute(ModelEnreplacedy enreplacedy, ModelAttrib modelAttribute) {
        treeTable.addItem(modelAttribute);
        treeTable.sereplacedemIcon(modelAttribute, FontAwesome.COLUMNS);
        treeTable.setChildrenAllowed(enreplacedy, true);
        treeTable.setParent(modelAttribute, enreplacedy);
        treeTable.setChildrenAllowed(modelAttribute, false);
    }

    protected void editSelectedItem() {
        lastEdireplacedemIds = getSelectedItems();
        treeTable.refreshRowCache();
        table.refreshRowCache();
    }

    clreplaced AddEnreplacedyClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            ModelEnreplacedy e = new ModelEnreplacedy();
            e.setName("New Enreplacedy");
            e.setModelId(model.getId());
            model.getModelEnreplacedies().add(e);
            context.getConfigurationService().save(e);
            addModelEnreplacedy(e);
            selectOnly(e);
            editSelectedItem();
        }
    }

    clreplaced AddAttributeClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            Set<Object> itemIds = getSelectedItems();
            if (itemIds.size() > 0) {
                ModelAttrib a = new ModelAttrib();
                a.setName("New Attribute");
                a.setDataType(DataType.VARCHAR);
                Object itemId = itemIds.iterator().next();
                ModelEnreplacedy enreplacedy = null;
                if (itemId instanceof ModelEnreplacedy) {
                    enreplacedy = (ModelEnreplacedy) itemId;
                } else if (itemId instanceof ModelAttrib) {
                    enreplacedy = (ModelEnreplacedy) treeTable.getParent(itemId);
                }
                if (enreplacedy != null) {
                    a.setEnreplacedyId(enreplacedy.getId());
                    enreplacedy.addModelAttribute(a);
                    context.getConfigurationService().save(a);
                    addModelAttribute(enreplacedy, a);
                    treeTable.setCollapsed(enreplacedy, false);
                    selectOnly(a);
                    editSelectedItem();
                }
            }
        }
    }

    clreplaced EditClickListener implements ClickListener {

        public void buttonClick(ClickEvent event) {
            editSelectedItem();
        }
    }

    clreplaced RemoveClickListener implements ClickListener {

        @SuppressWarnings("unchecked")
        public void buttonClick(ClickEvent event) {
            Set<Object> itemIds = new HashSet<Object>();
            Set<Object> selectedIds = getSelectedItems();
            ConfirmDialog.show("Delete?", "Are you sure you want to delete the " + selectedIds.size() + " selected items?", () -> {
                for (Object itemId : selectedIds) {
                    Collection<Object> children = (Collection<Object>) treeTable.getContainerDataSource().getChildren(itemId);
                    if (children != null) {
                        itemIds.addAll(children);
                    }
                    itemIds.add(itemId);
                }
                for (Object itemId : itemIds) {
                    if (itemId instanceof ModelAttrib) {
                        ModelAttrib a = (ModelAttrib) itemId;
                        context.getConfigurationService().delete((ModelAttrib) itemId);
                        ModelEnreplacedy enreplacedy = (ModelEnreplacedy) treeTable.getParent(itemId);
                        enreplacedy.removeModelAttribute(a);
                        treeTable.removeItem(itemId);
                    }
                }
                for (Object itemId : itemIds) {
                    if (itemId instanceof ModelEnreplacedy) {
                        context.getConfigurationService().delete((ModelEnreplacedy) itemId);
                        treeTable.removeItem(itemId);
                        model.getModelEnreplacedies().remove(itemId);
                    }
                }
                return true;
            });
        }
    }

    clreplaced ImportClickListener implements ClickListener, TableColumnSelectListener {

        public void buttonClick(ClickEvent event) {
            if (tableColumnSelectWindow == null) {
                tableColumnSelectWindow = new TableColumnSelectWindow(context, model);
                tableColumnSelectWindow.setTableColumnSelectListener(this);
            }
            UI.getCurrent().addWindow(tableColumnSelectWindow);
        }

        public void selected(Collection<ModelEnreplacedy> modelEnreplacedyCollection) {
            HashMap<String, ModelEnreplacedy> existingModelEnreplacedies = new HashMap<String, ModelEnreplacedy>();
            for (Object itemId : treeTable.gereplacedemIds()) {
                if (itemId instanceof ModelEnreplacedy) {
                    ModelEnreplacedy modelEnreplacedy = (ModelEnreplacedy) itemId;
                    existingModelEnreplacedies.put(modelEnreplacedy.getName().toUpperCase(), modelEnreplacedy);
                }
            }
            for (ModelEnreplacedy e : modelEnreplacedyCollection) {
                ModelEnreplacedy modelEnreplacedy = existingModelEnreplacedies.get(e.getName().toUpperCase());
                if (modelEnreplacedy == null) {
                    context.getConfigurationService().save(e);
                    existingModelEnreplacedies.put(e.getName().toUpperCase(), e);
                    add(e);
                    model.getModelEnreplacedies().add(e);
                } else {
                    for (ModelAttrib a : e.getModelAttributes()) {
                        if (modelEnreplacedy.getModelAttributeByName(a.getName()) == null) {
                            a.setEnreplacedyId(modelEnreplacedy.getId());
                            context.getConfigurationService().save(a);
                            modelEnreplacedy.addModelAttribute(a);
                            addModelAttribute(modelEnreplacedy, a);
                        }
                    }
                }
            }
        }
    }

    clreplaced TreeTableItemClickListener implements ItemClickListener {

        long lastClick;

        public void itemClick(ItemClickEvent event) {
            if (event.isDoubleClick()) {
                editSelectedItem();
            } else if (System.currentTimeMillis() - lastClick > 1000 && getSelectedItems().size() > 0) {
                treeTable.setValue(null);
            }
            lastClick = System.currentTimeMillis();
        }
    }

    clreplaced TreeTableValueChangeListener implements ValueChangeListener {

        public void valueChange(ValueChangeEvent event) {
            lastEdireplacedemIds = Collections.emptySet();
            treeTable.refreshRowCache();
            setButtonsEnabled();
        }
    }

    public clreplaced Record {

        ModelEnreplacedy modelEnreplacedy;

        ModelAttrib modelAttribute;

        String enreplacedyName = "";

        String attributeName = "";

        String description = "";

        String type = "";

        String pk = "";

        public Record(ModelEnreplacedy modelEnreplacedy, ModelAttrib modelAttribute) {
            this.modelEnreplacedy = modelEnreplacedy;
            this.modelAttribute = modelAttribute;
            if (modelEnreplacedy != null) {
                this.enreplacedyName = modelEnreplacedy.getName();
            }
            if (modelAttribute != null) {
                this.attributeName = modelAttribute.getName();
                this.description = modelAttribute.getDescription();
                this.type = modelAttribute.getType();
                this.pk = modelAttribute.isPk() ? "PK" : "";
            }
        }

        public int hashCode() {
            return modelEnreplacedy.hashCode() + modelAttribute.hashCode();
        }

        public String getEnreplacedyName() {
            return modelEnreplacedy.getName();
        }

        public String getAttributeName() {
            return modelAttribute.getName();
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getPk() {
            return pk;
        }

        public void setPk(String pk) {
            this.pk = pk;
        }
    }
}

19 View Complete Implementation : ProjectVersionSettingsPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
public clreplaced ProjectVersionSettingsPanel extends Panel implements IUiPanel {

    private static final long serialVersionUID = 1L;

    final Logger log = LoggerFactory.getLogger(getClreplaced());

    ApplicationContext context;

    DesignNavigator designNavigator;

    ProjectVersion projectVersion;

    Grid componentPluginsGrid;

    BeanItemContainer<ProjectVersionPlugin> componentPluginsGridContainer;

    Button updateButton;

    Button pinButton;

    Button unpinButton;

    public ProjectVersionSettingsPanel(ProjectVersion projectVersion, ApplicationContext context, DesignNavigator projectNavigator) {
        this.setSizeFull();
        this.context = context;
        this.designNavigator = projectNavigator;
        this.projectVersion = projectVersion;
        VerticalLayout content = new VerticalLayout();
        setContent(content);
        addHeader("Project Version Settings");
        FormLayout formLayout = new FormLayout();
        formLayout.addStyleName(ValoTheme.FORMLAYOUT_LIGHT);
        DateField releaseDateField = new DateField("Release Date");
        releaseDateField.setValue(projectVersion.getReleaseDate());
        releaseDateField.setEnabled(false);
        formLayout.addComponent(releaseDateField);
        CheckBox archiveCheckBox = new CheckBox("Archived");
        archiveCheckBox.setImmediate(true);
        archiveCheckBox.setValue(projectVersion.isArchived());
        archiveCheckBox.addValueChangeListener(e -> toggleArchived(e));
        formLayout.addComponent(archiveCheckBox);
        content.addComponent(formLayout);
        addHeader("Component Plugin Settings");
        ButtonBar buttonBar = new ButtonBar();
        content.addComponent(buttonBar);
        buttonBar.addButton("Refresh", Icons.REFRESH, (event) -> refreshPlugins());
        updateButton = buttonBar.addButton("Update", Icons.UPDATE, (event) -> update());
        pinButton = buttonBar.addButton("Pin", FontAwesome.CHECK_CIRCLE_O, (event) -> pin(true));
        unpinButton = buttonBar.addButton("Unpin", FontAwesome.CIRCLE_O, (event) -> pin(false));
        componentPluginsGrid = new Grid();
        componentPluginsGrid.setSelectionMode(SelectionMode.MULTI);
        componentPluginsGrid.setHeightMode(HeightMode.ROW);
        componentPluginsGrid.setWidth(100, Unit.PERCENTAGE);
        componentPluginsGrid.addColumn("definitionType", String.clreplaced).setHeaderCaption("Plugin Type").setEditable(false);
        componentPluginsGrid.addColumn("definitionName", String.clreplaced).setHeaderCaption("Name").setEditable(false);
        componentPluginsGrid.addColumn("definitionTypeId", String.clreplaced).setHeaderCaption("Type").setEditable(false);
        componentPluginsGrid.addColumn("pluginId", String.clreplaced).setHeaderCaption("Plugin").setEditable(false);
        componentPluginsGrid.addColumn("enabled", Boolean.clreplaced).setHeaderCaption("Enabled").setWidth(75);
        componentPluginsGrid.addColumn("pinVersion", Boolean.clreplaced).setHeaderCaption("Pin Version").setWidth(95);
        final double VERSION_WIDTH = 190;
        componentPluginsGrid.addColumn("artifactVersion", String.clreplaced).setHeaderCaption("Version").setWidth(VERSION_WIDTH).setEditable(false);
        componentPluginsGrid.addColumn("updatesAvailable", String.clreplaced).setHeaderCaption("").setWidth(55).setEditable(false).setRenderer(new HtmlRenderer());
        componentPluginsGrid.addSelectionListener((event) -> setButtonsEnabled());
        componentPluginsGridContainer = new BeanItemContainer<>(ProjectVersionPlugin.clreplaced);
        GeneratedPropertyContainer gpcontainer = new GeneratedPropertyContainer(componentPluginsGridContainer);
        gpcontainer.addGeneratedProperty("pluginId", new PropertyValueGenerator<String>() {

            private static final long serialVersionUID = 1L;

            @Override
            public String getValue(Item item, Object itemId, Object propertyId) {
                ProjectVersionPlugin plugin = (ProjectVersionPlugin) itemId;
                return String.format("%s:%s", plugin.getArtifactGroup(), plugin.getArtifactName());
            }

            @Override
            public Clreplaced<String> getType() {
                return String.clreplaced;
            }
        });
        gpcontainer.addGeneratedProperty("updatesAvailable", new PropertyValueGenerator<String>() {

            private static final long serialVersionUID = 1L;

            @Override
            public String getValue(Item item, Object itemId, Object propertyId) {
                ProjectVersionPlugin plugin = (ProjectVersionPlugin) itemId;
                return !plugin.getArtifactVersion().equals(plugin.getLatestArtifactVersion()) ? "<span clreplaced='warn' replacedle='Updates Available'>" + FontAwesome.WARNING.getHtml() + "</span>" : "";
            }

            @Override
            public Clreplaced<String> getType() {
                return String.clreplaced;
            }
        });
        componentPluginsGrid.setContainerDataSource(gpcontainer);
        componentPluginsGrid.getEditorFieldGroup().addCommitHandler(new PostCommitHandler(() -> {
            ProjectVersionPlugin item = (ProjectVersionPlugin) componentPluginsGrid.getEditedItemId();
            IConfigurationService configurationService = context.getConfigurationService();
            configurationService.save(item);
            componentPluginsGrid.markAsDirty();
        }));
        content.addComponent(componentPluginsGrid);
        VerticalLayout spacer = new VerticalLayout();
        content.addComponent(spacer);
        content.setExpandRatio(spacer, 1);
        refresh();
        setButtonsEnabled();
    }

    protected void refreshPlugins() {
        context.getDefinitionFactory().refresh(projectVersion.getId());
        populateContainer();
    }

    protected void addHeader(String caption) {
        HorizontalLayout componentHeaderWrapper = new HorizontalLayout();
        componentHeaderWrapper.setMargin(new MarginInfo(false, false, false, true));
        Label componentHeader = new Label(caption);
        componentHeader.addStyleName(ValoTheme.LABEL_H3);
        componentHeader.addStyleName(ValoTheme.LABEL_COLORED);
        componentHeaderWrapper.addComponent(componentHeader);
        ((AbstractLayout) getContent()).addComponent(componentHeaderWrapper);
    }

    protected void toggleArchived(ValueChangeEvent event) {
        context.getConfigurationService().save(projectVersion);
        designNavigator.refresh();
    }

    protected void setButtonsEnabled() {
        boolean readOnly = context.isReadOnly(projectVersion, Privilege.DESIGN);
        Collection<Object> selectedRows = componentPluginsGrid.getSelectedRows();
        boolean updatesAvailable = false;
        for (Object object : selectedRows) {
            ProjectVersionPlugin plugin = (ProjectVersionPlugin) object;
            updatesAvailable |= plugin.isUpdateAvailable();
        }
        boolean selected = selectedRows.size() > 0 && !readOnly;
        updateButton.setEnabled(updatesAvailable && !readOnly);
        pinButton.setEnabled(selected);
        unpinButton.setEnabled(selected);
    }

    protected void refresh() {
        populateContainer();
    }

    protected void update() {
        Collection<Object> selectedRows = componentPluginsGrid.getSelectedRows();
        for (Object object : selectedRows) {
            ProjectVersionPlugin plugin = (ProjectVersionPlugin) object;
            if (plugin.isUpdateAvailable()) {
                plugin.setArtifactVersion(plugin.getLatestArtifactVersion());
                context.getConfigurationService().save(plugin);
            }
        }
        refresh();
        populateContainer();
        setButtonsEnabled();
    }

    protected void pin(boolean value) {
        Collection<Object> selectedRows = componentPluginsGrid.getSelectedRows();
        for (Object object : selectedRows) {
            ProjectVersionPlugin plugin = (ProjectVersionPlugin) object;
            plugin.setPinVersion(value);
            context.getConfigurationService().save(plugin);
        }
        populateContainer();
    }

    protected void populateContainer() {
        IConfigurationService configurationService = context.getConfigurationService();
        List<ProjectVersionPlugin> plugins = configurationService.findProjectVersionComponentPlugins(projectVersion.getId());
        componentPluginsGridContainer.removeAllItems();
        componentPluginsGridContainer.addAll(plugins);
        componentPluginsGrid.setHeightByRows(componentPluginsGridContainer.size() > 0 ? componentPluginsGridContainer.size() : 1);
    }

    public ProjectVersion getProjectVersion() {
        return projectVersion;
    }

    @Override
    public void selected() {
    }

    @Override
    public void deselected() {
    }

    @Override
    public boolean closing() {
        return true;
    }
}

19 View Complete Implementation : WhereUsedPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
public clreplaced WhereUsedPanel extends Panel implements IUiPanel {

    private static final long serialVersionUID = 1L;

    final Logger log = LoggerFactory.getLogger(getClreplaced());

    ApplicationContext context;

    DesignNavigator designNavigator;

    String whereUsedType;

    String whereUsedObjectId;

    String whereUsedObjectName;

    Grid componentWhereUsedGrid;

    Button openButton;

    BeanItemContainer<WhereUsed> componentWhereUsedGridContainer;

    public WhereUsedPanel(String whereUsedType, String whereUsedObjectId, String whereUsedObjectName, ApplicationContext context, DesignNavigator projectNavigator) {
        this.setSizeFull();
        this.context = context;
        this.designNavigator = projectNavigator;
        this.whereUsedType = whereUsedType;
        this.whereUsedObjectId = whereUsedObjectId;
        this.whereUsedObjectName = whereUsedObjectName;
        VerticalLayout content = new VerticalLayout();
        setContent(content);
        addHeader(whereUsedType + " - Where Used");
        ButtonBar buttonBar = new ButtonBar();
        content.addComponent(buttonBar);
        openButton = buttonBar.addButton("Open Flow", Icons.FLOW, (event) -> openFlow());
        buttonBar.addButtonRight("Export", FontAwesome.DOWNLOAD, (event) -> export());
        componentWhereUsedGrid = new Grid();
        componentWhereUsedGrid.setSelectionMode(SelectionMode.SINGLE);
        componentWhereUsedGrid.setHeightMode(HeightMode.ROW);
        componentWhereUsedGrid.setWidth(100, Unit.PERCENTAGE);
        // adding hidden column of id because the export does not allow only one column in output
        componentWhereUsedGrid.addColumn("objectId", String.clreplaced).setHeaderCaption("Id").setEditable(false).setHidden(true);
        componentWhereUsedGrid.addColumn("projectName", String.clreplaced).setHeaderCaption("Project").setEditable(false);
        if (!"ProjectVersion".equals(whereUsedType)) {
            componentWhereUsedGrid.addColumn("flowName", String.clreplaced).setHeaderCaption("Flow").setEditable(false);
            componentWhereUsedGrid.addColumn("componentName", String.clreplaced).setHeaderCaption("Component").setEditable(false);
        }
        componentWhereUsedGridContainer = new BeanItemContainer<>(WhereUsed.clreplaced);
        GeneratedPropertyContainer gpcontainer = new GeneratedPropertyContainer(componentWhereUsedGridContainer);
        componentWhereUsedGrid.setContainerDataSource(gpcontainer);
        componentWhereUsedGrid.getEditorFieldGroup().addCommitHandler(new PostCommitHandler(() -> {
            WhereUsed item = (WhereUsed) componentWhereUsedGrid.getEditedItemId();
            IConfigurationService configurationService = context.getConfigurationService();
            configurationService.save(item);
            componentWhereUsedGrid.markAsDirty();
        }));
        content.addComponent(componentWhereUsedGrid);
        VerticalLayout spacer = new VerticalLayout();
        content.addComponent(spacer);
        content.setExpandRatio(spacer, 1);
        populateContainer();
        setButtonsEnabled();
    }

    protected void openFlow() {
        String flowId = "";
        String flowName = "";
        Object selected = ((SingleSelectionModel) componentWhereUsedGrid.getSelectionModel()).getSelectedRow();
        if (selected != null) {
            flowId = componentWhereUsedGrid.getContainerDataSource().gereplacedem(selected).gereplacedemProperty("objectId").getValue().toString();
            flowName = componentWhereUsedGrid.getContainerDataSource().gereplacedem(selected).gereplacedemProperty("flowName").getValue().toString();
            EditFlowPanel flowLayout = new EditFlowPanel(context, flowId, designNavigator, designNavigator.tabs);
            designNavigator.tabs.addCloseableTab(flowId, flowName, Icons.FLOW, flowLayout);
        }
    }

    protected void export() {
        String fileNamePrefix = whereUsedObjectName.toLowerCase().replace(' ', '-') + "-where-used";
        ExportDialog dialog = new ExportDialog(new Grid7DataProvider(componentWhereUsedGrid), fileNamePrefix, whereUsedObjectName);
        UI.getCurrent().addWindow(dialog);
    }

    protected void addHeader(String caption) {
        HorizontalLayout componentHeaderWrapper = new HorizontalLayout();
        componentHeaderWrapper.setMargin(new MarginInfo(false, false, false, true));
        Label componentHeader = new Label(caption);
        componentHeader.addStyleName(ValoTheme.LABEL_H3);
        componentHeader.addStyleName(ValoTheme.LABEL_COLORED);
        componentHeaderWrapper.addComponent(componentHeader);
        ((AbstractLayout) getContent()).addComponent(componentHeaderWrapper);
    }

    protected void populateContainer() {
        IConfigurationService configurationService = context.getConfigurationService();
        List<WhereUsed> whereUsed = null;
        if ("Model".equals(whereUsedType)) {
            whereUsed = configurationService.findModelWhereUsed(whereUsedObjectId);
        } else if ("Resource".equals(whereUsedType)) {
            whereUsed = configurationService.findResourceWhereUsed(whereUsedObjectId);
        } else if ("Flow".equals(whereUsedType)) {
            whereUsed = configurationService.findFlowWhereUsed(whereUsedObjectId);
        } else if ("ProjectVersion".equals(whereUsedType)) {
            whereUsed = configurationService.findProjectVersionWhereUsed(whereUsedObjectId);
        }
        componentWhereUsedGridContainer.removeAllItems();
        componentWhereUsedGridContainer.addAll(whereUsed);
        componentWhereUsedGrid.setHeightByRows(componentWhereUsedGridContainer.size() > 0 ? componentWhereUsedGridContainer.size() : 1);
    }

    @Override
    public void selected() {
    }

    @Override
    public void deselected() {
    }

    @Override
    public boolean closing() {
        return true;
    }

    protected void setButtonsEnabled() {
        boolean enableButton = true;
        if ("ProjectVersion".equals(whereUsedType)) {
            enableButton = false;
        }
        openButton.setEnabled(enableButton);
    }
}

19 View Complete Implementation : ManageView.java
Copyright GNU General Public License v3.0
Author : JumpMind
@UiComponent
@UIScope
@TopBarLink(category = Category.Manage, name = "Manage", id = "manage", icon = FontAwesome.GEARS, menuOrder = 25)
public clreplaced ManageView extends HorizontalLayout implements View, IUiPanel, IBackgroundRefreshable<Object> {

    final Logger log = LoggerFactory.getLogger(getClreplaced());

    private static final String ANY = "<Any>";

    private static final long serialVersionUID = 1L;

    static final int DEFAULT_LIMIT = 100;

    @Autowired
    ApplicationContext context;

    ManageNavigator manageNavigator;

    TabbedPanel tabs;

    BeanItemContainer<Execution> executionContainer = new BeanItemContainer<Execution>(Execution.clreplaced);

    Table table;

    Button viewButton;

    AbstractSelect statusSelect;

    int limit = DEFAULT_LIMIT;

    @SuppressWarnings("serial")
    @PostConstruct
    protected void init() {
        viewButton = new Button("View Log");
        viewButton.setEnabled(false);
        viewButton.addClickListener(new ClickListener() {

            public void buttonClick(ClickEvent event) {
                viewLog(table.getValue());
            }
        });
        VerticalLayout mainTab = new VerticalLayout();
        mainTab.setSizeFull();
        HorizontalLayout header = new HorizontalLayout();
        header.addComponent(viewButton);
        header.setComponentAlignment(viewButton, Alignment.BOTTOM_RIGHT);
        statusSelect = new ComboBox("Status");
        statusSelect.setNewItemsAllowed(false);
        statusSelect.setNullSelectionAllowed(false);
        statusSelect.addItem(ANY);
        statusSelect.setValue(ANY);
        for (ExecutionStatus status : ExecutionStatus.values()) {
            statusSelect.addItem(status.toString());
        }
        ;
        statusSelect.addValueChangeListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                refreshUI(getBackgroundData(), true);
            }
        });
        header.addComponent(statusSelect);
        header.setComponentAlignment(statusSelect, Alignment.BOTTOM_RIGHT);
        HorizontalLayout limitLayout = new HorizontalLayout();
        limitLayout.setSpacing(true);
        Label limitLabel = new Label("Limit:");
        limitLayout.addComponent(limitLabel);
        limitLayout.setComponentAlignment(limitLabel, Alignment.MIDDLE_CENTER);
        TextField limitField = new TextField(null, String.valueOf(DEFAULT_LIMIT));
        limitField.setWidth("5em");
        limitField.setImmediate(true);
        limitField.setTextChangeEventMode(TextChangeEventMode.LAZY);
        limitField.setTextChangeTimeout(200);
        limitField.addTextChangeListener(new TextChangeListener() {

            public void textChange(TextChangeEvent event) {
                try {
                    limit = Integer.parseInt(event.getText());
                } catch (Exception e) {
                }
                refreshUI(getBackgroundData(), true);
            }
        });
        limitLayout.addComponent(limitField);
        limitLayout.setComponentAlignment(limitField, Alignment.BOTTOM_RIGHT);
        header.addComponent(limitLayout);
        header.setComponentAlignment(limitLayout, Alignment.BOTTOM_RIGHT);
        header.setExpandRatio(limitLayout, 1.0f);
        TextField filterField = new TextField();
        filterField.setInputPrompt("Filter");
        filterField.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);
        filterField.setIcon(FontAwesome.SEARCH);
        filterField.setImmediate(true);
        filterField.setTextChangeEventMode(TextChangeEventMode.LAZY);
        filterField.setTextChangeTimeout(200);
        filterField.addTextChangeListener(new TextChangeListener() {

            public void textChange(TextChangeEvent event) {
                executionContainer.removeAllContainerFilters();
                if (!StringUtils.isBlank(event.getText())) {
                    executionContainer.addContainerFilter(new MultiPropertyFilter(event.getText(), new String[] { "agentName", "hostName", "flowName", "status", "startTime", "endTime" }));
                }
            }
        });
        header.addComponent(filterField);
        header.setComponentAlignment(filterField, Alignment.BOTTOM_RIGHT);
        header.setSpacing(true);
        header.setMargin(true);
        header.setWidth("100%");
        mainTab.addComponent(header);
        table = new Table();
        table.setContainerDataSource(executionContainer);
        table.setSelectable(true);
        table.setMultiSelect(false);
        table.setSizeFull();
        table.setColumnCollapsingAllowed(true);
        table.addItemClickListener(new ItemClickListener() {

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    viewLog(event.gereplacedemId());
                }
            }
        });
        table.setVisibleColumns(new Object[] { "agentName", "deploymentName", "hostName", "status", "startTime", "endTime", "createBy", "parameters" });
        table.setColumnHeaders(new String[] { "Agent", "Deployment", "Host", "Status", "Start", "End", "Caller", "Parameters" });
        table.setColumnWidth("agentName", 250);
        table.setColumnWidth("deploymentName", 250);
        table.setColumnWidth("hostName", 145);
        table.setColumnWidth("status", 90);
        table.setColumnWidth("startTime", 170);
        table.setColumnWidth("endTime", 170);
        table.setColumnWidth("createBy", 100);
        table.setColumnWidth("parameters", 5000);
        table.setColumnCollapsed("hostName", true);
        table.setSortContainerPropertyId("startTime");
        table.setSortAscending(false);
        table.addValueChangeListener((event) -> viewButton.setEnabled(table.getValue() != null));
        mainTab.addComponent(table);
        mainTab.setExpandRatio(table, 1.0f);
        tabs = new TabbedPanel();
        tabs.setMainTab("Executions", Icons.EXECUTION, mainTab);
        HorizontalSplitPanel split = new HorizontalSplitPanel();
        split.setSizeFull();
        split.setSplitPosition(UIConstants.DEFAULT_LEFT_SPLIT, Unit.PIXELS, false);
        manageNavigator = new ManageNavigator(FolderType.AGENT, context);
        manageNavigator.addValueChangeListener((event) -> {
            Object currentSelection = manageNavigator.getCurrentSelection();
            if (currentSelection != null) {
                if (statusSelect.isReadOnly()) {
                    statusSelect.setReadOnly(false);
                    statusSelect.setValue(ANY);
                }
                if (currentSelection.equals(ManageNavigator.CURRENTLY_RUNNING)) {
                    statusSelect.setValue(ExecutionStatus.RUNNING.name());
                    statusSelect.setReadOnly(true);
                } else if (currentSelection.equals(ManageNavigator.IN_ERROR)) {
                    statusSelect.setValue(ExecutionStatus.ERROR.name());
                    statusSelect.setReadOnly(true);
                }
            }
            refreshUI(getBackgroundData(), true);
        });
        split.setFirstComponent(manageNavigator);
        VerticalLayout container = new VerticalLayout();
        container.setSizeFull();
        container.addComponent(tabs);
        split.setSecondComponent(container);
        addComponent(split);
        setSizeFull();
        context.getBackgroundRefresherService().register(this);
    }

    @Override
    public void enter(ViewChangeEvent event) {
        manageNavigator.refresh();
    }

    @Override
    public boolean closing() {
        context.getBackgroundRefresherService().unregister(this);
        return true;
    }

    @Override
    public void selected() {
    }

    @Override
    public void deselected() {
    }

    @Override
    public Object onBackgroundDataRefresh() {
        return getBackgroundData();
    }

    @Override
    public void onBackgroundUIRefresh(Object backgroundData) {
        refreshUI(backgroundData, false);
    }

    @Override
    public void onUIError(Throwable ex) {
        CommonUiUtils.notify(ex);
    }

    public Object getBackgroundData() {
        Object currentSelection = manageNavigator.getCurrentSelection();
        Object currentSelectionParent = manageNavigator.getCurrentSelectionParent();
        if (currentSelection != null) {
            Map<String, Object> params = new HashMap<String, Object>();
            if (!currentSelection.equals(ManageNavigator.CURRENTLY_RUNNING) && !currentSelection.equals(ManageNavigator.IN_ERROR)) {
                if (currentSelection instanceof Agent) {
                    params.put("agentId", ((Agent) currentSelection).getId());
                } else if (currentSelection instanceof AgentName) {
                    params.put("agentId", ((AgentName) currentSelection).getId());
                } else if (currentSelection instanceof FlowName) {
                    params.put("flowId", ((FlowName) currentSelection).getId());
                } else if (currentSelection instanceof AgentDeploy) {
                    params.put("deploymentId", ((AgentDeploy) currentSelection).getId());
                } else if (currentSelection instanceof AgentDeploymentSummary) {
                    params.put("deploymentId", ((AgentDeploymentSummary) currentSelection).getId());
                }
            }
            if (currentSelectionParent instanceof Agent) {
                params.put("agentId", ((Agent) currentSelectionParent).getId());
            } else if (currentSelectionParent instanceof AgentName) {
                params.put("agentId", ((AgentName) currentSelectionParent).getId());
            }
            if (!statusSelect.getValue().equals(ANY)) {
                params.put("status", statusSelect.getValue());
            }
            if (params.size() > 0) {
                return context.getExecutionService().findExecutions(params, limit);
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    protected void refreshUI(Object obj, boolean tabToFront) {
        List<Execution> data = (List<Execution>) obj;
        if (needsUpdated(data)) {
            Object currentTableSelection = table.getValue();
            table.setValue(null);
            table.removeAllItems();
            if (data != null) {
                executionContainer.addAll((List<Execution>) data);
                table.sort();
                table.setValue(currentTableSelection);
                table.refreshRowCache();
            }
            viewButton.setEnabled(table.getValue() != null);
            if (tabToFront) {
                tabs.mainTabToTop();
            }
        }
    }

    protected boolean needsUpdated(List<Execution> data) {
        boolean needsUpdated = false;
        List<Execution> all = data != null ? new ArrayList<Execution>(data) : new ArrayList<Execution>(0);
        @SuppressWarnings("unchecked")
        Collection<Execution> tableValues = (Collection<Execution>) table.gereplacedemIds();
        if (all.size() != tableValues.size()) {
            log.debug("new execution count = " + all.size() + ", old execution count = " + tableValues.size());
            needsUpdated = true;
        }
        if (!needsUpdated) {
            for (Execution execution : tableValues) {
                if (execution.getExecutionStatus() == ExecutionStatus.RUNNING) {
                    for (Execution newExecution : all) {
                        if (newExecution.equals(execution) && newExecution.getExecutionStatus() != execution.getExecutionStatus()) {
                            needsUpdated = true;
                            break;
                        }
                    }
                }
            }
        }
        if (!needsUpdated) {
            all.removeAll(tableValues);
            log.debug("different execution count = " + all.size());
            needsUpdated = all.size() > 0;
        }
        return needsUpdated;
    }

    protected void viewLog(Object item) {
        Execution execution = (Execution) item;
        ExecutionRunPanel logPanel = new ExecutionRunPanel(execution.getId(), context, tabs, null);
        tabs.addCloseableTab(execution.getId(), "Log " + execution.getFlowName(), Icons.LOG, logPanel);
        logPanel.onBackgroundUIRefresh(logPanel.onBackgroundDataRefresh());
    }
}

19 View Complete Implementation : SearchOptionsPanel.java
Copyright Apache License 2.0
Author : korpling
/**
 * @author Thomas Krause {@literal <[email protected]>}
 * @author Benjamin Weißenfels {@literal <[email protected]>}
 */
public clreplaced SearchOptionsPanel extends FormLayout {

    public static final String NULL_SEGMENTATION_VALUE = "tokens (default)";

    public static final String KEY_DEFAULT_CONTEXT_SEGMENTATION = "default-context-segmentation";

    public static final String KEY_DEFAULT_BASE_TEXT_SEGMENTATION = "default-base-text-segmentation";

    public static final String KEY_MAX_CONTEXT_LEFT = "max-context-left";

    public static final String KEY_MAX_CONTEXT_RIGHT = "max-context-right";

    public static final String KEY_CONTEXT_STEPS = "context-steps";

    public static final String KEY_DEFAULT_CONTEXT = "default-context";

    public static final String KEY_RESULT_PER_PAGE = "results-per-page";

    public static final String DEFAULT_CONFIG = "default-config";

    public static final int DEFAULT_CONTEXT = 5;

    public static final int DEFAULT_CONTEXT_STEPS = 5;

    public static final int DEFAULT_MAX_CONTEXT = 20;

    private static final Logger log = LoggerFactory.getLogger(SearchOptionsPanel.clreplaced);

    private final ComboBox cbLeftContext;

    private final ComboBox cbRightContext;

    private final ComboBox cbResultsPerPage;

    private final ComboBox cbSegmentation;

    private final HelpButton segmentationHelp;

    private final ComboBox cbOrder;

    private final ComboBox cbQueryLanguage;

    // TODO: make this configurable
    private static final List<Integer> PREDEFINED_PAGE_SIZES = ImmutableList.of(1, 2, 5, 10, 20, 25);

    public static final List<Integer> PREDEFINED_CONTEXTS = ImmutableList.of(0, 1, 2, 5, 10, 20);

    private final ProgressBar pbLoadConfig;

    private final BeanItemContainer<OrderType> orderContainer = new BeanItemContainer<>(OrderType.clreplaced, Lists.newArrayList(OrderType.values()));

    private final IndexedContainer contextContainerLeft = new IndexedContainer();

    private final IndexedContainer contextContainerRight = new IndexedContainer();

    private final IndexedContainer segmentationContainer = new IndexedContainer();

    private final IndexedContainer resultsPerPageContainer = new IndexedContainer();

    private final BeanItemContainer<QueryLanguage> queryLanguage = new BeanItemContainer<>(QueryLanguage.clreplaced, Lists.newArrayList(QueryLanguage.values()));

    private final AtomicInteger maxLeftContext = new AtomicInteger(Integer.MAX_VALUE);

    private final AtomicInteger maxRightContext = new AtomicInteger(Integer.MAX_VALUE);

    private boolean updateStateFromConfig = true;

    private QueryUIState state;

    public SearchOptionsPanel() {
        setWidth("100%");
        setHeight("-1px");
        pbLoadConfig = new ProgressBar();
        pbLoadConfig.setIndeterminate(true);
        pbLoadConfig.setCaption("Loading search options...");
        addComponent(pbLoadConfig);
        cbLeftContext = new ComboBox("Left Context", contextContainerLeft);
        cbRightContext = new ComboBox("Right Context", contextContainerRight);
        cbResultsPerPage = new ComboBox("Results Per Page", resultsPerPageContainer);
        cbLeftContext.setNullSelectionAllowed(false);
        cbRightContext.setNullSelectionAllowed(false);
        cbResultsPerPage.setNullSelectionAllowed(false);
        cbLeftContext.setNewItemsAllowed(true);
        cbRightContext.setNewItemsAllowed(true);
        cbResultsPerPage.setNewItemsAllowed(true);
        cbLeftContext.setTextInputAllowed(true);
        cbRightContext.setTextInputAllowed(true);
        cbResultsPerPage.setTextInputAllowed(true);
        cbLeftContext.setImmediate(true);
        cbRightContext.setImmediate(true);
        cbResultsPerPage.setImmediate(true);
        cbSegmentation = new ComboBox("Show context in", segmentationContainer);
        cbSegmentation.setTextInputAllowed(false);
        cbSegmentation.setNullSelectionAllowed(true);
        cbSegmentation.setNewItemsAllowed(true);
        cbSegmentation.setNullSelectionItemId(NULL_SEGMENTATION_VALUE);
        cbSegmentation.addItem(NULL_SEGMENTATION_VALUE);
        cbSegmentation.setDescription("If corpora with multiple " + "context definitions are selected, a list of available context units will be " + "displayed. By default context is calculated in ‘tokens’ " + "(e.g. 5 minimal units to the left and right of a search result). " + "Some corpora might offer further context definitions, e.g. in " + "syllables, word forms belonging to different speakers, normalized or " + "diplomatic segmentations of a mreplacedcript, etc.");
        segmentationHelp = new HelpButton<Object>(cbSegmentation);
        cbOrder = new ComboBox("Order", orderContainer);
        cbOrder.setNewItemsAllowed(false);
        cbOrder.setNullSelectionAllowed(false);
        cbOrder.setImmediate(true);
        cbQueryLanguage = new ComboBox("Query Language", queryLanguage);
        cbQueryLanguage.setNewItemsAllowed(false);
        cbQueryLanguage.setNullSelectionAllowed(false);
        cbQueryLanguage.setImmediate(true);
        cbQueryLanguage.sereplacedemCaption(QueryLanguage.AQL, "AQL (latest)");
        cbQueryLanguage.sereplacedemCaption(QueryLanguage.AQL_QUIRKS_V3, "AQL (compatibility mode)");
        cbLeftContext.setVisible(false);
        cbRightContext.setVisible(false);
        cbResultsPerPage.setVisible(false);
        cbOrder.setVisible(false);
        segmentationHelp.setVisible(false);
        addComponent(cbLeftContext);
        addComponent(cbRightContext);
        addComponent(segmentationHelp);
        addComponent(cbResultsPerPage);
        addComponent(cbOrder);
        addComponent(cbQueryLanguage);
    }

    @Override
    public void attach() {
        super.attach();
        contextContainerLeft.sereplacedemSorter(new IntegerIDSorter());
        contextContainerRight.sereplacedemSorter(new IntegerIDSorter());
        resultsPerPageContainer.sereplacedemSorter(new IntegerIDSorter());
        resultsPerPageContainer.removeAllItems();
        for (Integer i : PREDEFINED_PAGE_SIZES) {
            resultsPerPageContainer.addItem(i);
        }
        if (getUI() instanceof AnnisUI) {
            AnnisUI ui = (AnnisUI) getUI();
            state = ui.getQueryState();
            Background.run(new CorpusConfigUpdater(ui, state.getSelectedCorpora().getValue(), false));
            cbLeftContext.setNewItemHandler(new CustomContext(maxLeftContext, contextContainerLeft, state.getLeftContext()));
            cbRightContext.setNewItemHandler(new CustomContext(maxRightContext, contextContainerRight, state.getRightContext()));
            cbResultsPerPage.setNewItemHandler(new CustomResultSize(resultsPerPageContainer, state.getLimit()));
            cbLeftContext.setPropertyDataSource(state.getLeftContext());
            cbRightContext.setPropertyDataSource(state.getRightContext());
            cbResultsPerPage.setPropertyDataSource(state.getLimit());
            cbSegmentation.setPropertyDataSource(state.getContextSegmentation());
            orderContainer.removeAllItems();
            for (OrderType t : OrderType.values()) {
                orderContainer.addItem(t);
            }
            cbOrder.setPropertyDataSource(state.getOrder());
            cbQueryLanguage.setPropertyDataSource(state.getQueryLanguage());
        }
    }

    public void updateSearchPanelConfigurationInBackground(final Set<String> corpora, final AnnisUI ui) {
        setLoadingState(true);
        // remove custom adjustments
        contextContainerLeft.removeAllItems();
        contextContainerRight.removeAllItems();
        cbSegmentation.removeAllItems();
        // reload the config in the background
        Background.run(new CorpusConfigUpdater(ui, corpora, true));
    }

    private static Integer getInteger(String key, CorpusConfig config) {
        String s = config.getConfig(key);
        if (s != null) {
            return Integer.parseInt(s);
        }
        return null;
    }

    private static List<String> getSegmentationNamesFromService(Set<String> corpora, UI ui) {
        List<String> segNames = new ArrayList<>();
        WebResource service = Helper.getAnnisWebResource(ui);
        if (service != null) {
            for (String corpus : corpora) {
                try {
                    SegmentationList segList = service.path("query").path("corpora").path(Helper.encodeJersey(corpus)).path("segmentation-names").get(SegmentationList.clreplaced);
                    segNames.addAll(segList.getSegmentatioNames());
                } catch (UniformInterfaceException ex) {
                    if (ex.getResponse().getStatus() == 403) {
                        log.debug("Did not have access rights to query segmentation names for corpus", ex);
                    } else {
                        log.warn("Could not query segmentation names for corpus", ex);
                    }
                }
            }
        }
        return segNames;
    }

    private void updateSegmentations(String segment, List<String> segNames, boolean updateValue) {
        cbSegmentation.setNullSelectionItemId(NULL_SEGMENTATION_VALUE);
        cbSegmentation.addItem(NULL_SEGMENTATION_VALUE);
        if ("tok".equalsIgnoreCase(segment)) {
            if (state != null && updateValue) {
                state.getContextSegmentation().setValue(null);
            }
        } else if (segment != null) {
            cbSegmentation.addItem(segment);
            if (state != null && updateValue) {
                cbSegmentation.setValue(segment);
            }
        }
        if (segNames != null && !segNames.isEmpty()) {
            for (String s : segNames) {
                if (!s.equalsIgnoreCase(segment)) {
                    cbSegmentation.addItem(s);
                }
            }
        }
    }

    /**
     * If all values of a specific corpus property have the same value, this value
     * is returned, otherwise the value of the default configuration is choosen.
     *
     * @param key
     *                    The property key.
     * @param corpora
     *                    Specifies the selected corpora.
     * @return A value defined in the copurs.properties file or in the
     *         admin-service.properties
     */
    private String mergeConfigValue(String key, Set<String> corpora, CorpusConfigMap corpusConfigurations) {
        Set<String> values = new TreeSet<>();
        for (String corpus : corpora) {
            CorpusConfig config = corpusConfigurations.get(corpus);
            if (config != null) {
                String v = config.getConfig(key);
                if (v != null) {
                    values.add(v);
                }
            }
        }
        if (values.size() > 1 || values.isEmpty()) {
            // fallback to the default values
            CorpusConfig defaultConfig = corpusConfigurations.get(DEFAULT_CONFIG);
            if (defaultConfig != null && defaultConfig.containsKey(key)) {
                return defaultConfig.getConfig(key);
            }
        }
        // ok, just return the first value as a fallback of the fallback
        if (!values.isEmpty()) {
            return values.iterator().next();
        }
        return null;
    }

    /**
     * Builds a single config for selection of one or muliple corpora.
     *
     * @param corpora
     *                                 Specifies the combination of corpora, for
     *                                 which the config is calculated.
     * @param corpusConfigurations
     *                                 A map containg the known corpus
     *                                 configurations.
     * @return A new config which takes into account the segementation of all
     *         selected corpora.
     */
    private CorpusConfig mergeConfigs(Set<String> corpora, CorpusConfigMap corpusConfigurations) {
        CorpusConfig corpusConfig = new CorpusConfig();
        // calculate the left and right context.
        String leftCtx = mergeConfigValue(KEY_MAX_CONTEXT_LEFT, corpora, corpusConfigurations);
        String rightCtx = mergeConfigValue(KEY_MAX_CONTEXT_RIGHT, corpora, corpusConfigurations);
        corpusConfig.setConfig(KEY_MAX_CONTEXT_LEFT, leftCtx);
        corpusConfig.setConfig(KEY_MAX_CONTEXT_RIGHT, rightCtx);
        // calculate the default-context
        corpusConfig.setConfig(KEY_CONTEXT_STEPS, mergeConfigValue(KEY_CONTEXT_STEPS, corpora, corpusConfigurations));
        corpusConfig.setConfig(KEY_DEFAULT_CONTEXT, mergeConfigValue(KEY_DEFAULT_CONTEXT, corpora, corpusConfigurations));
        // get the results per page
        corpusConfig.setConfig(KEY_RESULT_PER_PAGE, mergeConfigValue(KEY_RESULT_PER_PAGE, corpora, corpusConfigurations));
        corpusConfig.setConfig(KEY_DEFAULT_CONTEXT_SEGMENTATION, checkSegments(KEY_DEFAULT_CONTEXT_SEGMENTATION, corpora, corpusConfigurations));
        corpusConfig.setConfig(KEY_DEFAULT_BASE_TEXT_SEGMENTATION, checkSegments(KEY_DEFAULT_BASE_TEXT_SEGMENTATION, corpora, corpusConfigurations));
        return corpusConfig;
    }

    /**
     * Checks, if all selected corpora have the same default segmentation layer. If
     * not the tok layer is taken, because every corpus has this one.
     *
     * @param key
     *                    the key for the segementation config, must be
     *                    {@link #KEY_DEFAULT_BASE_TEXT_SEGMENTATION} or
     *                    {@link #KEY_DEFAULT_CONTEXT_SEGMENTATION}.
     * @param corpora
     *                    the corpora which has to be checked.
     * @return "tok" or a segment which is defined in all corpora.
     */
    private String checkSegments(String key, Set<String> corpora, CorpusConfigMap corpusConfigurations) {
        String segmentation = null;
        for (String corpus : corpora) {
            CorpusConfig c = null;
            if (corpusConfigurations.containsConfig(corpus)) {
                c = corpusConfigurations.get(corpus);
            } else {
                c = corpusConfigurations.get(DEFAULT_CONFIG);
            }
            // do nothing if not even default config is set
            if (c == null) {
                continue;
            }
            String tmpSegment = c.getConfig(key);
            /**
             * If no segment is set in the corpus config use always the tok segment.
             */
            if (tmpSegment == null) {
                return corpusConfigurations.get(DEFAULT_CONFIG).getConfig(key);
            }
            if (segmentation == null) {
                segmentation = tmpSegment;
                continue;
            }
            if (// return the default config
            !segmentation.equals(tmpSegment)) {
                return corpusConfigurations.get(DEFAULT_CONFIG).getConfig(key);
            }
        }
        if (segmentation == null) {
            return corpusConfigurations.get(DEFAULT_CONFIG).getConfig(key);
        } else {
            return segmentation;
        }
    }

    /**
     * Updates context combo boxes.
     *
     * @param c
     *                             the container, which is updated.
     * @param maxCtx
     *                             the larges context values until context steps are
     *                             calculated.
     * @param ctxSteps
     *                             the step range.
     * @param keepCustomValues
     *                             If this is true all custom values are kept.
     */
    private void updateContext(Container c, int maxCtx, int ctxSteps, boolean keepCustomValues) {
        if (!keepCustomValues) {
            c.removeAllItems();
        }
        for (Integer i : PREDEFINED_CONTEXTS) {
            if (i < maxCtx) {
                c.addItem(i);
            }
        }
        for (int step = ctxSteps; step < maxCtx; step += ctxSteps) {
            c.addItem(step);
        }
        c.addItem(maxCtx);
    }

    private void setLoadingState(boolean isLoading) {
        pbLoadConfig.setVisible(isLoading);
        cbLeftContext.setVisible(!isLoading);
        cbRightContext.setVisible(!isLoading);
        cbResultsPerPage.setVisible(!isLoading);
        cbOrder.setVisible(!isLoading);
        segmentationHelp.setVisible(!isLoading);
    }

    public boolean isUpdateStateFromConfig() {
        return updateStateFromConfig;
    }

    public void setUpdateStateFromConfig(boolean updateStateFromConfig) {
        this.updateStateFromConfig = updateStateFromConfig;
    }

    private static clreplaced CustomResultSize implements AbstractSelect.NewItemHandler {

        private final IndexedContainer container;

        private final Property<Integer> prop;

        public CustomResultSize(IndexedContainer container, Property<Integer> prop) {
            this.container = container;
            this.prop = prop;
        }

        @Override
        public void addNewItem(String resultPerPage) {
            try {
                int i = Integer.parseInt((String) resultPerPage);
                if (i < 1) {
                    throw new IllegalArgumentException("result number has to be a positive number greater or equal than 1");
                }
                container.addItem(i);
                container.sort(null, null);
                prop.setValue(i);
            } catch (NumberFormatException ex) {
                Notification.show("invalid result per page input", "Please enter valid numbers [0-9]", Notification.Type.WARNING_MESSAGE);
            } catch (IllegalArgumentException ex) {
                Notification.show("invalid result per page input", ex.getMessage(), Notification.Type.WARNING_MESSAGE);
            }
        }
    }

    private clreplaced CorpusConfigUpdater implements Runnable {

        private final AnnisUI ui;

        private final Set<String> corpora;

        private final QueryUIState state;

        private final boolean corpusSelectionChanged;

        public CorpusConfigUpdater(AnnisUI ui, Set<String> corpora, boolean corpusSelectionChanged) {
            this.ui = ui;
            this.state = ui.getQueryState();
            this.corpora = corpora;
            this.corpusSelectionChanged = corpusSelectionChanged;
        }

        @Override
        public void run() {
            final List<String> segmentations = getSegmentationNamesFromService(corpora, ui);
            final Set<String> corporaWithDefault = new TreeSet<>(corpora);
            corporaWithDefault.add(DEFAULT_CONFIG);
            final CorpusConfigMap corpusConfigs = new CorpusConfigMap();
            for (String c : corporaWithDefault) {
                corpusConfigs.put(c, ui.getCorpusConfigWithCache(c));
            }
            // if there are not any defaults create them
            if (!corpusConfigs.containsConfig(DEFAULT_CONFIG)) {
                CorpusConfig defaultConfig = new CorpusConfig();
                defaultConfig.setConfig(KEY_MAX_CONTEXT_LEFT, "" + DEFAULT_MAX_CONTEXT);
                defaultConfig.setConfig(KEY_MAX_CONTEXT_RIGHT, "" + DEFAULT_MAX_CONTEXT);
                defaultConfig.setConfig(KEY_CONTEXT_STEPS, "" + DEFAULT_CONTEXT_STEPS);
                defaultConfig.setConfig(KEY_RESULT_PER_PAGE, "10");
                defaultConfig.setConfig(KEY_DEFAULT_CONTEXT, "" + DEFAULT_CONTEXT);
                defaultConfig.setConfig(KEY_DEFAULT_CONTEXT_SEGMENTATION, "tok");
                defaultConfig.setConfig(KEY_DEFAULT_BASE_TEXT_SEGMENTATION, "tok");
                corpusConfigs.put(DEFAULT_CONFIG, defaultConfig);
            }
            // update GUI
            ui.access(new Runnable() {

                @Override
                public void run() {
                    setLoadingState(false);
                    CorpusConfig c = mergeConfigs(corpora, corpusConfigs);
                    Integer resultsPerPage = getInteger(KEY_RESULT_PER_PAGE, c);
                    Integer leftCtx = getInteger(KEY_MAX_CONTEXT_LEFT, c);
                    if (leftCtx != null) {
                        maxLeftContext.set(leftCtx);
                    }
                    Integer rightCtx = getInteger(KEY_MAX_CONTEXT_RIGHT, c);
                    if (rightCtx != null) {
                        maxRightContext.set(rightCtx);
                    }
                    Integer defaultCtx = getInteger(KEY_DEFAULT_CONTEXT, c);
                    Integer ctxSteps = getInteger(KEY_CONTEXT_STEPS, c);
                    String segment = c.getConfig(KEY_DEFAULT_CONTEXT_SEGMENTATION);
                    updateContext(contextContainerLeft, leftCtx == null ? DEFAULT_CONTEXT : leftCtx, ctxSteps == null ? DEFAULT_CONTEXT_STEPS : ctxSteps, true);
                    updateContext(contextContainerRight, rightCtx == null ? DEFAULT_CONTEXT : rightCtx, ctxSteps == null ? DEFAULT_CONTEXT_STEPS : ctxSteps, true);
                    if (defaultCtx != null && updateStateFromConfig && corpusSelectionChanged) {
                        state.getLeftContext().setValue(defaultCtx);
                        state.getRightContext().setValue(defaultCtx);
                    }
                    updateSegmentations(segment, segmentations, updateStateFromConfig && !corpora.isEmpty());
                    if (resultsPerPage != null && updateStateFromConfig && corpusSelectionChanged) {
                        state.getLimit().setValue(resultsPerPage);
                    }
                    // reset if corpus selection has changed
                    if (corpusSelectionChanged) {
                        updateStateFromConfig = true;
                    }
                }
            });
        }
    }

    private static clreplaced CustomContext implements AbstractSelect.NewItemHandler {

        private final AtomicInteger maxCtx;

        private final IndexedContainer container;

        private final Property<Integer> prop;

        public CustomContext(AtomicInteger maxCtx, IndexedContainer container, Property<Integer> prop) {
            this.maxCtx = maxCtx;
            this.container = container;
            this.prop = prop;
        }

        @Override
        public void addNewItem(String context) {
            try {
                int i = Integer.parseInt((String) context);
                if (i < 0) {
                    throw new IllegalArgumentException("context has to be a positive number or 0");
                }
                if (i > maxCtx.get()) {
                    throw new IllegalArgumentException("The context is greater than, than the max value defined in the corpus property file.");
                }
                // everything ok, add the value
                container.addItem(i);
                container.sort(null, null);
                prop.setValue(i);
            } catch (NumberFormatException ex) {
                Notification.show("invalid context input", "Please enter valid numbers [0-9]", Notification.Type.WARNING_MESSAGE);
            } catch (IllegalArgumentException ex) {
                Notification.show("invalid context input", ex.getMessage(), Notification.Type.WARNING_MESSAGE);
            }
        }
    }

    public static clreplaced IntegerIDSorter implements ItemSorter {

        @Override
        public void setSortProperties(Container.Sortable container, Object[] propertyId, boolean[] ascending) {
        // does nothing
        }

        @Override
        public int compare(Object itemId1, Object itemId2) {
            if (itemId1 instanceof Integer && itemId2 instanceof Integer) {
                return Integer.compare((Integer) itemId1, (Integer) itemId2);
            }
            return 0;
        }
    }
}

19 View Complete Implementation : CorpusBrowserPanel.java
Copyright Apache License 2.0
Author : korpling
/**
 * @author Thomas Krause {@literal <[email protected]>}
 */
@DesignRoot
public clreplaced CorpusBrowserPanel extends Panel {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(CorpusBrowserPanel.clreplaced);

    private final static Escaper urlPathEscape = UrlEscapers.urlPathSegmentEscaper();

    /**
     */
    private static final long serialVersionUID = -1029743017413951838L;

    private AnnisCorpus corpus;

    private ExampleTable tblNodeAnno;

    private BeanItemContainer<CorpusBrowserEntry> containerNodeAnno;

    private Label lblNoNodeAnno;

    private ExampleTable tblEdgeTypes;

    private BeanItemContainer<CorpusBrowserEntry> containerEdgeType;

    private Label lblNoEdgeTypes;

    private ExampleTable tblEdgeAnno;

    private BeanItemContainer<CorpusBrowserEntry> containerEdgeAnno;

    private Label lblNoEdgeAnno;

    private ExampleTable tblMetaAnno;

    private BeanItemContainer<CorpusBrowserEntry> containerMetaAnno;

    private Label lblNoMetaAnno;

    private CitationLinkGenerator citationGenerator;

    private QueryController controller;

    private ProgressBar progress;

    private Accordion accordion;

    private VerticalLayout layout;

    public CorpusBrowserPanel() {
        this(null, null);
    }

    public CorpusBrowserPanel(final AnnisCorpus corpus, QueryController controller) {
        super("Available annotations");
        this.corpus = corpus;
        this.controller = controller;
        Design.read("CorpusBrowserPanel.html", this);
        containerNodeAnno = new BeanItemContainer<>(CorpusBrowserEntry.clreplaced);
        containerNodeAnno.sereplacedemSorter(new ExampleSorter());
        containerEdgeType = new BeanItemContainer<>(CorpusBrowserEntry.clreplaced);
        containerEdgeType.sereplacedemSorter(new ExampleSorter());
        containerEdgeAnno = new BeanItemContainer<>(CorpusBrowserEntry.clreplaced);
        containerEdgeAnno.sereplacedemSorter(new ExampleSorter());
        containerMetaAnno = new BeanItemContainer<>(CorpusBrowserEntry.clreplaced);
        containerMetaAnno.sereplacedemSorter(new ExampleSorter());
        citationGenerator = new CitationLinkGenerator();
        tblNodeAnno.addValueChangeListener(new ExampleListener());
        tblEdgeTypes.addValueChangeListener(new ExampleListener());
        tblEdgeAnno.addValueChangeListener(new ExampleListener());
        tblMetaAnno.addValueChangeListener(new ExampleListener());
        tblNodeAnno.setContainerDataSource(containerNodeAnno);
        tblEdgeAnno.setContainerDataSource(containerEdgeAnno);
        tblEdgeTypes.setContainerDataSource(containerEdgeType);
        tblMetaAnno.setContainerDataSource(containerMetaAnno);
        tblNodeAnno.setCitationLinkGenerator(citationGenerator);
        tblEdgeAnno.setCitationLinkGenerator(citationGenerator);
        tblEdgeTypes.setCitationLinkGenerator(citationGenerator);
        tblMetaAnno.setCitationLinkGenerator(citationGenerator);
        tblNodeAnno.setSortContainerPropertyId("name");
        tblEdgeTypes.setSortContainerPropertyId("name");
        tblEdgeAnno.setSortContainerPropertyId("name");
        accordion.setVisible(false);
        progress.setSizeFull();
        layout.setSizeFull();
        layout.setComponentAlignment(progress, Alignment.MIDDLE_CENTER);
    }

    @Override
    public void attach() {
        super.attach();
        Background.run(new AnnotationFetcher(UI.getCurrent()));
    }

    private clreplaced AnnotationFetcher implements Runnable {

        private final UI ui;

        public AnnotationFetcher(UI ui) {
            this.ui = ui;
        }

        @Override
        public void run() {
            final List<AnnisAttribute> attributes = corpus == null ? new LinkedList<AnnisAttribute>() : fetchAnnos(corpus.getName(), ui);
            ((AnnisUI) getUI()).access(new Runnable() {

                @Override
                public void run() {
                    progress.setVisible(false);
                    accordion.setVisible(true);
                    boolean stripNodeAnno = true;
                    boolean stripEdgeName = true;
                    boolean stripEdgeAnno = true;
                    HashSet<String> nodeAnnoNames = new HashSet<>();
                    HashSet<String> edgeAnnoNames = new HashSet<>();
                    HashSet<String> edgeNames = new HashSet<>();
                    HashSet<String> fullEdgeNames = new HashSet<>();
                    boolean hasDominance = false;
                    boolean hasEmptyDominance = false;
                    // do some preparations first
                    for (AnnisAttribute a : attributes) {
                        if (a.getType() == AnnisAttribute.Type.node) {
                            // check for ambiguous names
                            String name = killNamespace(a.getName());
                            if (nodeAnnoNames.contains(name)) {
                                stripNodeAnno = false;
                            }
                            nodeAnnoNames.add(name);
                        } else if (a.getType() == AnnisAttribute.Type.edge) {
                            fullEdgeNames.add(a.getEdgeName());
                            // check if we need to add the general dominance example edge
                            if (a.getSubtype() == AnnisAttribute.SubType.d) {
                                hasDominance = true;
                                if (a.getEdgeName() == null || a.getEdgeName().isEmpty()) {
                                    hasEmptyDominance = true;
                                }
                            }
                            String annoName = killNamespace(a.getName());
                            if (edgeAnnoNames.contains(annoName)) {
                                stripEdgeAnno = false;
                            }
                            edgeAnnoNames.add(annoName);
                        }
                    }
                    // check if collected edge names are unique
                    for (String edgeName : fullEdgeNames) {
                        String name = killNamespace(edgeName);
                        if (edgeNames.contains(name)) {
                            stripEdgeName = false;
                        }
                        edgeNames.add(name);
                    }
                    if (hasDominance && !hasEmptyDominance) {
                        CorpusBrowserEntry cbe = new CorpusBrowserEntry();
                        cbe.setName("(dominance)");
                        cbe.setCorpus(corpus);
                        cbe.setExample("node & node & #1 > #2");
                        containerEdgeType.addBean(cbe);
                    }
                    // second round, fill the actual containers
                    Set<String> metaAnnosKey = new HashSet<>();
                    for (AnnisAttribute a : attributes) {
                        // if the annotation name is already in the example skip this.
                        if (a.getType() == AnnisAttribute.Type.meta && !metaAnnosKey.contains(killNamespace(a.getName()))) {
                            String name = killNamespace(a.getName());
                            metaAnnosKey.add(name);
                            CorpusBrowserEntry cbe = new CorpusBrowserEntry();
                            cbe.setName(name);
                            cbe.setExample("node @* " + name + "=\"" + getFirst(a.getValueSet()) + "\"");
                            cbe.setCorpus(corpus);
                            containerMetaAnno.addBean(cbe);
                        }
                        if (a.getType() == AnnisAttribute.Type.node) {
                            String name = stripNodeAnno ? killNamespace(a.getName()) : a.getName();
                            CorpusBrowserEntry cbe = new CorpusBrowserEntry();
                            cbe.setName(name);
                            cbe.setExample(name + "=\"" + getFirst(a.getValueSet()) + "\"");
                            cbe.setCorpus(corpus);
                            containerNodeAnno.addBean(cbe);
                        } else if (a.getType() == AnnisAttribute.Type.edge) {
                            // edge type entry (multiple entries will be removed automatically)
                            CorpusBrowserEntry cbeEdgeType = new CorpusBrowserEntry();
                            String name = stripEdgeName ? killNamespace(a.getEdgeName()) : a.getEdgeName();
                            if ((name == null || name.isEmpty()) && a.getSubtype() == AnnisAttribute.SubType.d) {
                                cbeEdgeType.setName("(dominance)");
                            } else {
                                cbeEdgeType.setName(name);
                            }
                            cbeEdgeType.setCorpus(corpus);
                            if (a.getSubtype() == AnnisAttribute.SubType.p) {
                                cbeEdgeType.setExample("node & node & #1 ->" + killNamespace(name) + " #2");
                            } else if (a.getSubtype() == AnnisAttribute.SubType.d) {
                                cbeEdgeType.setExample("node & node & #1 >" + killNamespace(name) + " #2");
                            }
                            containerEdgeType.addBean(cbeEdgeType);
                            // the edge annotation entry
                            if (!a.getValueSet().isEmpty()) {
                                CorpusBrowserEntry cbeEdgeAnno = new CorpusBrowserEntry();
                                String edgeAnno = stripEdgeAnno ? killNamespace(a.getName()) : a.getName();
                                cbeEdgeAnno.setName(edgeAnno);
                                cbeEdgeAnno.setCorpus(corpus);
                                if (a.getSubtype() == AnnisAttribute.SubType.p) {
                                    cbeEdgeAnno.setExample("node & node & #1 ->" + killNamespace(a.getEdgeName()) + "[" + killNamespace(a.getName()) + "=\"" + getFirst(a.getValueSet()) + "\"] #2");
                                } else if (a.getSubtype() == AnnisAttribute.SubType.d) {
                                    cbeEdgeAnno.setExample("node & node & #1 >[" + killNamespace(a.getName()) + "=\"" + getFirst(a.getValueSet()) + "\"] #2");
                                }
                                containerEdgeAnno.addBean(cbeEdgeAnno);
                            }
                        }
                    }
                    if (containerNodeAnno.size() == 0) {
                        lblNoNodeAnno.setVisible(true);
                        tblNodeAnno.setVisible(false);
                        ;
                    }
                    if (tblEdgeAnno.getContainerDataSource().size() == 0) {
                        lblNoEdgeAnno.setVisible(true);
                        tblEdgeAnno.setVisible(false);
                    }
                    if (tblEdgeTypes.getContainerDataSource().size() == 0) {
                        lblNoEdgeTypes.setVisible(true);
                        tblEdgeTypes.setVisible(false);
                    }
                    if (tblMetaAnno.getContainerDataSource().size() == 0) {
                        lblNoMetaAnno.setVisible(true);
                        tblMetaAnno.setVisible(false);
                    }
                }
            });
        }
    }

    private List<AnnisAttribute> fetchAnnos(String toplevelCorpus, UI ui) {
        Collection<AnnisAttribute> result = new ArrayList<>();
        try {
            WebResource service = Helper.getAnnisWebResource(ui);
            if (service != null) {
                WebResource query = service.path("query").path("corpora").path(urlPathEscape.escape(toplevelCorpus)).path("annotations").queryParam("fetchvalues", "true").queryParam("onlymostfrequentvalues", "true");
                result = query.get(new AnnisAttributeListType());
            }
        } catch (UniformInterfaceException | ClientHandlerException ex) {
            log.error(null, ex);
            if (!AnnisBaseUI.handleCommonError(ex, "fetch example annotations")) {
                Notification.show("Remote exception: " + ex.getLocalizedMessage(), Notification.Type.WARNING_MESSAGE);
            }
        }
        return new LinkedList<>(result);
    }

    public clreplaced ExampleListener implements ValueChangeListener {

        @Override
        public void valueChange(ValueChangeEvent event) {
            CorpusBrowserEntry cbe = (CorpusBrowserEntry) event.getProperty().getValue();
            Set<String> corpusNameSet = new HashSet<>();
            if (corpus != null) {
                corpusNameSet.add(corpus.getName());
            }
            if (controller != null && cbe != null) {
                controller.setQuery(new Query(cbe.getExample(), QueryLanguage.AQL, corpusNameSet));
            }
        }
    }

    public static clreplaced ExampleSorter extends DefaulreplacedemSorter {

        @Override
        protected int compareProperty(Object propertyId, boolean sortDirection, Item item1, Item item2) {
            if ("name".equals(propertyId)) {
                String val1 = (String) item1.gereplacedemProperty(propertyId).getValue();
                String val2 = (String) item2.gereplacedemProperty(propertyId).getValue();
                if (sortDirection) {
                    return val1.compareToIgnoreCase(val2);
                } else {
                    return val2.compareToIgnoreCase(val1);
                }
            } else {
                return super.compareProperty(propertyId, sortDirection, item1, item2);
            }
        }
    }

    private String killNamespace(String qName) {
        if (qName == null) {
            return "";
        }
        String[] splitted = qName.split(":");
        return splitted[splitted.length - 1];
    }

    private String getFirst(Collection<String> list) {
        Iterator<String> it = list.iterator();
        return it.hasNext() ? it.next() : null;
    }

    private static clreplaced AnnisAttributeListType extends GenericType<List<AnnisAttribute>> {

        public AnnisAttributeListType() {
        }
    }
}

19 View Complete Implementation : ExampleQueriesPanel.java
Copyright Apache License 2.0
Author : korpling
/**
 * Wraps the auto generated queries.
 *
 * @author Benjamin Weißenfels {@literal <[email protected]>}
 */
public clreplaced ExampleQueriesPanel extends CssLayout {

    private final String COLUMN_EXAMPLE_QUERY = "exampleQuery";

    private final String COLUMN_OPEN_CORPUS_BROWSER = "open corpus browser";

    private final String COLUMN_DESCRIPTION = "description";

    // main ui window
    private final AnnisUI ui;

    private final Table table;

    private final ProgressBar loadingIndicator;

    /**
     * Bean Container for example queries. Key is the corpus name.
     */
    private final BeanItemContainer<ExampleQuery> egContainer;

    // gets the
    private final static Logger log = LoggerFactory.getLogger(ExampleQueriesPanel.clreplaced);

    // reference to the tab which holds this component
    private TabSheet.Tab tab;

    // hold the parent tab of annis3
    private final HelpPanel parentTab;

    private static final Resource SEARCH_ICON = FontAwesome.SEARCH;

    public ExampleQueriesPanel(AnnisUI ui, HelpPanel parentTab) {
        super();
        this.ui = ui;
        this.parentTab = parentTab;
        loadingIndicator = new ProgressBar();
        loadingIndicator.setIndeterminate(true);
        loadingIndicator.setCaption("Loading example queries...");
        loadingIndicator.setVisible(false);
        addComponent(loadingIndicator);
        table = new Table();
        table.setVisible(true);
        // 
        egContainer = new BeanItemContainer<>(ExampleQuery.clreplaced);
        table.setContainerDataSource(egContainer);
        addComponent(table);
        setUpTable();
    }

    /**
     * Sets some layout properties.
     */
    private void setUpTable() {
        setSizeFull();
        // expand the table
        table.setSizeFull();
        // Allow selecting items from the table.
        table.setSelectable(false);
        // Send changes in selection immediately to server.
        table.setImmediate(true);
        // set custom style
        table.addStyleName("example-queries-table");
        // put stripes to the table
        table.addStyleName(ChameleonTheme.TABLE_STRIPED);
        // configure columns
        table.addGeneratedColumn(COLUMN_OPEN_CORPUS_BROWSER, new ShowCorpusBrowser());
        table.addGeneratedColumn(COLUMN_EXAMPLE_QUERY, new QueryColumn());
        table.addGeneratedColumn(COLUMN_DESCRIPTION, new Table.ColumnGenerator() {

            @Override
            public Object generateCell(Table source, Object itemId, Object columnId) {
                ExampleQuery eQ = (ExampleQuery) itemId;
                Label l = new Label(eQ.getDescription());
                l.setContentMode(ContentMode.TEXT);
                l.addStyleName(Helper.CORPUS_FONT_FORCE);
                return l;
            }
        });
        table.setVisibleColumns(new Object[] { COLUMN_EXAMPLE_QUERY, COLUMN_DESCRIPTION, COLUMN_OPEN_CORPUS_BROWSER });
        table.setColumnExpandRatio(table.getVisibleColumns()[0], 0.40f);
        table.setColumnExpandRatio(table.getVisibleColumns()[1], 0.40f);
        table.setColumnHeader(table.getVisibleColumns()[0], "Example Query");
        table.setColumnHeader(table.getVisibleColumns()[1], "Description");
        table.setColumnHeader(table.getVisibleColumns()[2], "open corpus browser");
    }

    /**
     * Add items if there are any and put the example query tab in the foreground.
     */
    private void addItems(List<ExampleQuery> examples) {
        if (examples != null && examples.size() > 0) {
            egContainer.addAll(examples);
            showTab();
        } else {
            hideTabSheet();
        }
    }

    /**
     * Shows the tab and put into the foreground, if no query is executed yet.
     */
    private void showTab() {
        if (parentTab != null) {
            tab = parentTab.getTab(this);
            if (tab != null) {
                // FIXME: this should be added by the constructor or by the panel that adds this
                // tab
                // tab.getComponent().addStyleName("example-queries-tab");
                tab.setEnabled(true);
                if (!(parentTab.getSelectedTab() instanceof ResultViewPanel)) {
                    parentTab.setSelectedTab(tab);
                }
            }
        }
    }

    private void hideTabSheet() {
        if (parentTab != null) {
            tab = parentTab.getTab(this);
            if (tab != null) {
                tab.setEnabled(false);
            }
        }
    }

    private Component getOpenCorpusPanel(final String corpusName) {
        final Button btn = new Button(corpusName);
        btn.setStyleName(BaseTheme.BUTTON_LINK);
        btn.addClickListener(new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                CorpusListPanel corpusList = ui.getSearchView().getControlPanel().getCorpusList();
                corpusList.initCorpusBrowser(corpusName, btn);
            }
        });
        return btn;
    }

    /**
     * Loads the available example queries for a specific corpus.
     *
     * @param corpusNames
     *                        Specifies the corpora example queries are fetched for.
     *                        If it is null or empty all available example queries
     *                        are fetched.
     */
    private static List<ExampleQuery> loadExamplesFromRemote(Set<String> corpusNames, UI ui) {
        List<ExampleQuery> result = new LinkedList<>();
        WebResource service = Helper.getAnnisWebResource(ui);
        try {
            if (corpusNames == null || corpusNames.isEmpty()) {
                result = service.path("query").path("corpora").path("example-queries").get(new GenericType<List<ExampleQuery>>() {
                });
            } else {
                String concatedCorpusNames = StringUtils.join(corpusNames, ",");
                result = service.path("query").path("corpora").path("example-queries").queryParam("corpora", concatedCorpusNames).get(new GenericType<List<ExampleQuery>>() {
                });
            }
        } catch (UniformInterfaceException ex) {
        // ignore
        } catch (ClientHandlerException ex) {
            log.error("problems with getting example queries from remote for {}", corpusNames, ex);
        }
        return result;
    }

    /**
     * Sets the selected corpora and causes a reload
     *
     * @param selectedCorpora
     *                            Specifies the corpora example queries are fetched
     *                            for. If it is null, all available example queries
     *                            are fetched.
     */
    public void setSelectedCorpusInBackground(final Set<String> selectedCorpora) {
        loadingIndicator.setVisible(true);
        table.setVisible(false);
        Background.run(new ExampleFetcher(selectedCorpora, UI.getCurrent()));
    }

    private clreplaced ExampleFetcher implements Runnable {

        private final Set<String> selectedCorpora;

        private UI ui;

        public ExampleFetcher(Set<String> selectedCorpora, UI ui) {
            this.selectedCorpora = selectedCorpora;
            this.ui = ui;
        }

        @Override
        public void run() {
            final List<ExampleQuery> result = new LinkedList<>();
            try {
                result.addAll(loadExamplesFromRemote(selectedCorpora, ui));
            } finally {
                ui.access(new Runnable() {

                    @Override
                    public void run() {
                        loadingIndicator.setVisible(false);
                        table.setVisible(true);
                        try {
                            table.removeAllItems();
                            addItems(result);
                        } catch (Exception ex) {
                            log.error("removing or adding of example queries failed for {}", selectedCorpora, ex);
                        }
                    }
                });
            }
        }
    }

    private clreplaced QueryColumn implements Table.ColumnGenerator {

        @Override
        public Object generateCell(Table source, Object itemId, Object columnId) {
            final ExampleQuery eQ = (ExampleQuery) itemId;
            Button btn = new Button();
            btn.setDescription("show corpus browser for " + eQ.getCorpusName());
            btn.addStyleName(ChameleonTheme.BUTTON_LINK);
            btn.setIcon(SEARCH_ICON);
            btn.setCaption(eQ.getExampleQuery());
            btn.setDescription("show results for \"" + eQ.getExampleQuery() + "\" in " + eQ.getCorpusName());
            btn.addStyleName(Helper.CORPUS_FONT_FORCE);
            btn.addClickListener(new Button.ClickListener() {

                @Override
                public void buttonClick(Button.ClickEvent event) {
                    if (ui != null) {
                        ControlPanel controlPanel = ui.getSearchView().getControlPanel();
                        QueryPanel queryPanel;
                        if (controlPanel == null) {
                            log.error("controlPanel is not initialized");
                            return;
                        }
                        queryPanel = controlPanel.getQueryPanel();
                        if (queryPanel == null) {
                            log.error("queryPanel is not initialized");
                            return;
                        }
                        Set<String> corpusNameSet = new HashSet<>();
                        corpusNameSet.add(eQ.getCorpusName());
                        if (ui.getQueryController() != null) {
                            ui.getQueryController().setQuery(new Query(eQ.getExampleQuery(), QueryLanguage.AQL, corpusNameSet));
                            // ensure the selected corpus is shown
                            ui.getSearchView().getControlPanel().getCorpusList().scrollToSelectedCorpus();
                            // execute query
                            ui.getQueryController().executeSearch(true, true);
                        }
                    }
                }
            });
            return btn;
        }
    }

    private clreplaced ShowCorpusBrowser implements Table.ColumnGenerator {

        @Override
        public Object generateCell(Table source, Object itemId, Object columnId) {
            ExampleQuery eQ = (ExampleQuery) itemId;
            return getOpenCorpusPanel(eQ.getCorpusName());
        }
    }
}

19 View Complete Implementation : MetaDataPanel.java
Copyright Apache License 2.0
Author : korpling
private void loadTable(String item, List<Annotation> metaData) {
    BeanItemContainer<Annotation> metaContainer = new BeanItemContainer<>(Annotation.clreplaced);
    metaContainer.addAll(metaData);
    if (corpusAnnotationTable != null) {
        layout.removeComponent(corpusAnnotationTable);
    }
    layout.removeComponent(emptyLabel);
    corpusAnnotationTable = setupTable(metaContainer);
    corpusAnnotationTable.setHeight(100, Unit.PERCENTAGE);
    corpusAnnotationTable.setWidth(100, Unit.PERCENTAGE);
    layout.addComponent(corpusAnnotationTable);
    layout.setExpandRatio(corpusAnnotationTable, 1.0f);
}

19 View Complete Implementation : MetaDataPanel.java
Copyright Apache License 2.0
Author : korpling
private List<BeanItemContainer<Annotation>> putInBeanContainer(Map<Integer, List<Annotation>> splittedAnnotationsList) {
    List<BeanItemContainer<Annotation>> listOfBeanItemCon = new ArrayList<>();
    for (List<Annotation> list : splittedAnnotationsList.values()) {
        BeanItemContainer<Annotation> metaContainer = new BeanItemContainer<>(Annotation.clreplaced);
        metaContainer.addAll(list);
        listOfBeanItemCon.add(metaContainer);
    }
    return listOfBeanItemCon;
}

19 View Complete Implementation : QueryUIState.java
Copyright Apache License 2.0
Author : korpling
/**
 * Helper clreplaced to bundle all query relevant state information of the UI.
 *
 * @author Thomas Krause {@literal <[email protected]>}
 */
public clreplaced QueryUIState implements Serializable {

    public enum QueryType {

        COUNT, FIND, FREQUENCY, EXPORT
    }

    private final ObjectProperty<String> aql = new ObjectProperty<>("");

    private final ObjectProperty<Set<String>> selectedCorpora = new ObjectProperty<Set<String>>(new LinkedHashSet<String>());

    private final ObjectProperty<Integer> leftContext = new ObjectProperty<>(5);

    private final ObjectProperty<Integer> rightContext = new ObjectProperty<>(5);

    private final ObjectProperty<Integer> limit = new ObjectProperty<>(10);

    private final ObjectProperty<Long> offset = new ObjectProperty<>(0l);

    private final ObjectProperty<String> visibleBaseText = new ObjectProperty<>(null, String.clreplaced);

    private final ObjectProperty<String> contextSegmentation = new ObjectProperty<>(null, String.clreplaced);

    private final ObjectProperty<OrderType> order = new ObjectProperty<>(OrderType.ascending);

    private final ObjectProperty<QueryLanguage> queryLanguage = new ObjectProperty<>(QueryLanguage.AQL);

    private final ObjectProperty<Set<Long>> selectedMatches = new ObjectProperty<Set<Long>>(new TreeSet<Long>());

    private final ObjectProperty<Clreplaced<? extends ExporterPlugin>> exporter = new ObjectProperty<Clreplaced<? extends ExporterPlugin>>(CSVExporter.clreplaced);

    private final ObjectProperty<List<String>> exportAnnotationKeys = new ObjectProperty<List<String>>(new ArrayList<String>());

    private final ObjectProperty<String> exportParameters = new ObjectProperty<>("");

    private final ObjectProperty<Boolean> alignmc = new ObjectProperty<Boolean>(false);

    private transient Map<QueryType, Future<?>> executedTasks;

    private final BeanContainer<Integer, UserGeneratedFrequencyEntry> frequencyTableDefinition = new BeanContainer<>(UserGeneratedFrequencyEntry.clreplaced);

    private final BeanItemContainer<Query> history = new BeanItemContainer<>(Query.clreplaced);

    private final BeanContainer<String, AnnisCorpus> availableCorpora = new BeanContainer<>(AnnisCorpus.clreplaced);

    public QueryUIState() {
        initTransients();
        availableCorpora.setBeanIdProperty("name");
        availableCorpora.sereplacedemSorter(new CorpusSorter());
    }

    private void initTransients() {
        executedTasks = new EnumMap<>(QueryType.clreplaced);
    }

    private void readObject(java.io.ObjectInputStream in) throws IOException, ClreplacedNotFoundException {
        in.defaultReadObject();
        initTransients();
    }

    public ObjectProperty<String> getAql() {
        return aql;
    }

    public ObjectProperty<Set<String>> getSelectedCorpora() {
        return selectedCorpora;
    }

    public ObjectProperty<Integer> getLeftContext() {
        return leftContext;
    }

    public ObjectProperty<Integer> getRightContext() {
        return rightContext;
    }

    public ObjectProperty<Integer> getLimit() {
        return limit;
    }

    public ObjectProperty<Long> getOffset() {
        return offset;
    }

    public ObjectProperty<Set<Long>> getSelectedMatches() {
        return selectedMatches;
    }

    public ObjectProperty<String> getVisibleBaseText() {
        return visibleBaseText;
    }

    public ObjectProperty<String> getContextSegmentation() {
        return contextSegmentation;
    }

    public Map<QueryType, Future<?>> getExecutedTasks() {
        return executedTasks;
    }

    public BeanItemContainer<Query> getHistory() {
        return history;
    }

    public ObjectProperty<Clreplaced<? extends ExporterPlugin>> getExporter() {
        return exporter;
    }

    public ObjectProperty<List<String>> getExportAnnotationKeys() {
        return exportAnnotationKeys;
    }

    public ObjectProperty<String> getExportParameters() {
        return exportParameters;
    }

    public ObjectProperty<Boolean> getAlignmc() {
        return alignmc;
    }

    public BeanContainer<Integer, UserGeneratedFrequencyEntry> getFrequencyTableDefinition() {
        return frequencyTableDefinition;
    }

    public ObjectProperty<OrderType> getOrder() {
        return order;
    }

    public BeanContainer<String, AnnisCorpus> getAvailableCorpora() {
        return availableCorpora;
    }

    public ObjectProperty<QueryLanguage> getQueryLanguage() {
        return queryLanguage;
    }
}

19 View Complete Implementation : AbstractPagedBeanTable.java
Copyright GNU Affero General Public License v3.0
Author : MyCollab
private void createTable() {
    tableItem = new Table();
    tableItem.setWidth("100%");
    tableItem.addStyleName(ValoTheme.TABLE_NO_VERTICAL_LINES);
    tableItem.addStyleName(ValoTheme.TABLE_NO_HORIZONTAL_LINES);
    tableItem.setSortEnabled(false);
    // set column generator
    for (Map.Entry<Object, ColumnGenerator> entry : columnGenerators.entrySet()) {
        tableItem.addGeneratedColumn(entry.getKey(), entry.getValue());
    }
    if (StringUtils.isNotBlank((String) sortColumnId)) {
        tableItem.setColumnIcon(sortColumnId, isAscending ? VaadinIcons.CARET_DOWN : VaadinIcons.CARET_UP);
    }
    tableItem.addHeaderClickListener(headerClickEvent -> {
        String propertyId = (String) headerClickEvent.getPropertyId();
        if (propertyId.equals("selected")) {
            return;
        }
        if (searchRequest != null) {
            S searchCriteria = searchRequest.getSearchCriteria();
            if (sortColumnId == null) {
                sortColumnId = propertyId;
                searchCriteria.setOrderFields(Collections.singletonList(new SearchCriteria.OrderField(propertyId, SearchCriteria.DESC)));
                isAscending = false;
            } else if (propertyId.equals(sortColumnId)) {
                isAscending = !isAscending;
                String direction = (isAscending) ? SearchCriteria.ASC : SearchCriteria.DESC;
                searchCriteria.setOrderFields(Collections.singletonList(new SearchCriteria.OrderField(propertyId, direction)));
            } else {
                sortColumnId = propertyId;
                searchCriteria.setOrderFields(Collections.singletonList(new SearchCriteria.OrderField(propertyId, SearchCriteria.DESC)));
                isAscending = false;
            }
            setSearchCriteria(searchCriteria);
        }
    });
    BeanItemContainer<B> container = new BeanItemContainer<>(type, currentListData);
    tableItem.setPageLength(0);
    tableItem.setContainerDataSource(container);
    displayTableColumns();
    if (this.getComponentCount() > 0) {
        final Component component0 = this.getComponent(0);
        if (component0 instanceof Table) {
            this.replaceComponent(component0, tableItem);
        } else {
            this.addComponent(tableItem, 0);
        }
    } else {
        this.addComponent(tableItem, 0);
    }
    this.setExpandRatio(tableItem, 1);
}

19 View Complete Implementation : FilterableListContainerTest.java
Copyright Apache License 2.0
Author : viritin
@Test
@Ignore(value = "we know BeanItemContainer filtering is veeery slow, re-activate to investigate possible enhancements in the core.")
public void testFilterStd() {
    System.out.println("\n Testing BeanItemContainer from core Vaadin (with Filter)");
    long initial = reportMemoryUsage();
    long ms = System.currentTimeMillis();
    BeanItemContainer<Person> lc = new BeanItemContainer<>(Person.clreplaced, persons);
    System.out.println("After creation with " + amount + " beans (took " + (System.currentTimeMillis() - ms) + ")");
    long after = reportMemoryUsage();
    System.err.println("Delta (bytes)" + (after - initial));
    doTests(lc, initial);
}

19 View Complete Implementation : TableUsageExample.java
Copyright Apache License 2.0
Author : viritin
public void tableAsBeanSelector() {
    Table table = new Table();
    BeanItemContainer<Enreplacedy> beanItemContainer = new BeanItemContainer<>(Enreplacedy.clreplaced);
    beanItemContainer.addAll(findBeans());
    table.setContainerDataSource(beanItemContainer);
    table.setVisibleColumns("property", "another");
    table.setColumnHeaders("Property 1", "Second");
    table.setSelectable(true);
    table.setImmediate(true);
    table.addValueChangeListener(new Property.ValueChangeListener() {

        @Override
        public void valueChange(Property.ValueChangeEvent event) {
            Enreplacedy enreplacedy = (Enreplacedy) event.getProperty().getValue();
            editEnreplacedy(enreplacedy);
        }
    });
    MTable<Enreplacedy> t = new MTable(findBeans()).withProperties("property", "another").withColumnHeaders("Property 1", "Second").withValueChangeListener(new MValueChangeListener<Enreplacedy>() {

        private static final long serialVersionUID = 382491506910830168L;

        @Override
        public void valueChange(MValueChangeEvent<Enreplacedy> event) {
            editEnreplacedy(event.getValue());
        }
    });
}

18 View Complete Implementation : CmsModuleTable.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Reloads the table data.<p>
 */
public void reload() {
    List<CmsModule> modules = OpenCms.getModuleManager().getAllInstalledModules();
    @SuppressWarnings("unchecked")
    BeanItemContainer<CmsModuleRow> container = (BeanItemContainer<CmsModuleRow>) getContainerDataSource();
    container.removeAllItems();
    List<CmsModuleRow> newRows = Lists.newArrayList();
    for (CmsModule module : modules) {
        CmsModuleRow row = new CmsModuleRow(module);
        newRows.add(row);
    }
    container.addAll(newRows);
    sort();
    updateCounter();
}

18 View Complete Implementation : QueryPanel.java
Copyright Apache License 2.0
Author : korpling
/**
 * @author thomas
 */
public clreplaced QueryPanel extends GridLayout implements ValueChangeListener {

    public static final int MAX_HISTORY_MENU_ITEMS = 5;

    // the view name
    public static final String NAME = "query";

    private AqlCodeEditor txtQuery;

    private TextArea txtStatus;

    private Button btShowResult;

    // private Button btShowResultNewTab;
    private PopupButton btHistory;

    private final ListSelect lstHistory;

    private final QueryUIState state;

    private ProgressBar piCount;

    private String lastPublicStatus;

    private Window historyWindow;

    private PopupButton btMoreActions;

    private FrequencyQueryPanel frequencyPanel;

    private final AnnisUI ui;

    private final BeanItemContainer<Query> historyContainer = new BeanItemContainer<>(Query.clreplaced);

    public QueryPanel(final AnnisUI ui) {
        super(4, 5);
        this.ui = ui;
        this.lastPublicStatus = "Welcome to ANNIS! " + "A tutorial is available on the right side.";
        this.state = ui.getQueryState();
        setSpacing(true);
        setMargin(false);
        setRowExpandRatio(0, 1.0f);
        setColumnExpandRatio(0, 0.0f);
        setColumnExpandRatio(1, 0.1f);
        setColumnExpandRatio(2, 0.0f);
        setColumnExpandRatio(3, 0.0f);
        txtQuery = new AqlCodeEditor();
        txtQuery.setPropertyDataSource(state.getAql());
        txtQuery.setInputPrompt("Please enter AQL query");
        txtQuery.addStyleName("query");
        if (ui.getInstanceFont() == null) {
            txtQuery.addStyleName("default-query-font");
            txtQuery.setTextareaStyle("default-query-font");
        } else {
            txtQuery.addStyleName(Helper.CORPUS_FONT);
            txtQuery.setTextareaStyle(Helper.CORPUS_FONT);
        }
        txtQuery.addStyleName("keyboardInput");
        txtQuery.setWidth("100%");
        txtQuery.setHeight(15f, Unit.EM);
        txtQuery.setTextChangeTimeout(500);
        final VirtualKeyboardCodeEditor virtualKeyboard;
        if (ui.getInstanceConfig().getKeyboardLayout() == null) {
            virtualKeyboard = null;
        } else {
            virtualKeyboard = new VirtualKeyboardCodeEditor();
            virtualKeyboard.setKeyboardLayout(ui.getInstanceConfig().getKeyboardLayout());
            virtualKeyboard.extend(txtQuery);
        }
        txtStatus = new TextArea();
        txtStatus.setValue(this.lastPublicStatus);
        txtStatus.setWidth("100%");
        txtStatus.setHeight(4.0f, Unit.EM);
        txtStatus.addStyleName("border-layout");
        txtStatus.setReadOnly(true);
        piCount = new ProgressBar();
        piCount.setIndeterminate(true);
        piCount.setEnabled(false);
        piCount.setVisible(false);
        btShowResult = new Button("Search");
        btShowResult.setIcon(FontAwesome.SEARCH);
        btShowResult.setWidth("100%");
        btShowResult.addClickListener(new ShowResultClickListener());
        btShowResult.setDescription("<strong>Show Result</strong><br />Ctrl + Enter", ContentMode.HTML);
        btShowResult.setClickShortcut(KeyCode.ENTER, ModifierKey.CTRL);
        btShowResult.setDisableOnClick(true);
        VerticalLayout historyListLayout = new VerticalLayout();
        historyListLayout.setSizeUndefined();
        lstHistory = new ListSelect();
        lstHistory.setWidth("200px");
        lstHistory.setNullSelectionAllowed(false);
        lstHistory.setValue(null);
        lstHistory.addValueChangeListener((ValueChangeListener) this);
        lstHistory.setImmediate(true);
        lstHistory.setContainerDataSource(historyContainer);
        lstHistory.sereplacedemCaptionPropertyId("query");
        lstHistory.addStyleName(Helper.CORPUS_FONT);
        Button btShowMoreHistory = new Button("Show more details", new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                if (historyWindow == null) {
                    historyWindow = new Window("History");
                    historyWindow.setModal(false);
                    historyWindow.setWidth("400px");
                    historyWindow.setHeight("250px");
                }
                historyWindow.setContent(new HistoryPanel(state.getHistory(), ui.getQueryController()));
                if (UI.getCurrent().getWindows().contains(historyWindow)) {
                    historyWindow.bringToFront();
                } else {
                    UI.getCurrent().addWindow(historyWindow);
                }
            }
        });
        btShowMoreHistory.setWidth("100%");
        historyListLayout.addComponent(lstHistory);
        historyListLayout.addComponent(btShowMoreHistory);
        historyListLayout.setExpandRatio(lstHistory, 1.0f);
        historyListLayout.setExpandRatio(btShowMoreHistory, 0.0f);
        btHistory = new PopupButton("History");
        btHistory.setContent(historyListLayout);
        btHistory.setDescription("<strong>Show History</strong><br />" + "Either use the short overview (arrow down) or click on the button " + "for the extended view.", ContentMode.HTML);
        Button btShowKeyboard = null;
        if (virtualKeyboard != null) {
            btShowKeyboard = new Button();
            btShowKeyboard.setWidth("100%");
            btShowKeyboard.setDescription("Click to show a virtual keyboard");
            btShowKeyboard.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
            btShowKeyboard.addStyleName(ValoTheme.BUTTON_SMALL);
            btShowKeyboard.setIcon(new ClreplacedResource(VirtualKeyboardCodeEditor.clreplaced, "keyboard.png"));
            btShowKeyboard.addClickListener(new ShowKeyboardClickListener(virtualKeyboard));
        }
        final JSClipboard clipboard = new JSClipboard();
        Button btCopy = new Button("");
        btCopy.setWidth("100%");
        btCopy.setDescription("Copy query to clipboard");
        btCopy.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
        btCopy.addStyleName(ValoTheme.BUTTON_SMALL);
        btCopy.setIcon(FontAwesome.COPY);
        clipboard.apply(btCopy, txtQuery);
        clipboard.setText(state.getAql().getValue());
        state.getAql().addValueChangeListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                clipboard.setText(event.getProperty().getValue().toString());
            }
        });
        clipboard.addSuccessListener(new JSClipboard.SuccessListener() {

            @Override
            public void onSuccess() {
                Notification.show("Copied AQL to clipboard");
            }
        });
        Button btShowQueryBuilder = new Button("Query<br />Builder");
        btShowQueryBuilder.setHtmlContentAllowed(true);
        btShowQueryBuilder.addStyleName(ValoTheme.BUTTON_SMALL);
        btShowQueryBuilder.addStyleName(ValoTheme.BUTTON_ICON_ALIGN_TOP);
        btShowQueryBuilder.setIcon(new ThemeResource("images/tango-icons/32x32/doreplacedent-properties.png"));
        btShowQueryBuilder.addClickListener(new ShowQueryBuilderClickListener(ui));
        VerticalLayout moreActionsLayout = new VerticalLayout();
        moreActionsLayout.setWidth("250px");
        btMoreActions = new PopupButton("More");
        btMoreActions.setContent(moreActionsLayout);
        // btShowResultNewTab = new Button("Search (open in new tab)");
        // btShowResultNewTab.setWidth("100%");
        // btShowResultNewTab.addClickListener(new ShowResultInNewTabClickListener());
        // btShowResultNewTab.setDescription("<strong>Show Result and open result in new tab</strong><br />Ctrl + Shift + Enter");
        // btShowResultNewTab.setDisableOnClick(true);
        // btShowResultNewTab.setClickShortcut(KeyCode.ENTER, ModifierKey.CTRL, ModifierKey.SHIFT);
        // moreActionsLayout.addComponent(btShowResultNewTab);
        Button btShowExport = new Button("Export", new ShowExportClickListener(ui));
        btShowExport.setIcon(FontAwesome.DOWNLOAD);
        btShowExport.setWidth("100%");
        moreActionsLayout.addComponent(btShowExport);
        Button btShowFrequency = new Button("Frequency replacedysis", new ShowFrequencyClickListener(ui));
        btShowFrequency.setIcon(FontAwesome.BAR_CHART_O);
        btShowFrequency.setWidth("100%");
        moreActionsLayout.addComponent(btShowFrequency);
        /*
     * We use the grid layout for a better rendering efficiency, but this comes
     * with the cost of some complexity when defining the positions of the
     * elements in the layout.
     * 
     * This grid hopefully helps a little bit in understanding the "magic"
     * numbers better.
     * 
     * Q: Query text field
     * QB: Button to toggle query builder // TODO
     * KEY: Button to show virtual keyboard
     * COPY: Button for copying the text
     * SEA: "Search" button
     * MOR: "More actions" button 
     * HIST: "History" button
     * STAT: Text field with the real status
     * PROG: indefinite progress bar (spinning circle)
     * 
     *  \   0  |  1  |  2  |  3  
     * --+-----+---+---+---+-----
     * 0 |  Q  |  Q  |  Q  | QB 
     * --+-----+-----+-----+-----
     * 1 |  Q  |  Q  |  Q  | KEY 
     * --+-----+-----+-----+-----
     * 2 |  Q  |  Q  |  Q  | COPY
     * --+-----+-----+-----+-----
     * 3 | SEA | MOR | HIST|     
     * --+-----+-----+-----+-----
     * 4 | STAT| STAT| STAT| PROG
     */
        addComponent(txtQuery, 0, 0, 2, 2);
        addComponent(txtStatus, 0, 4, 2, 4);
        addComponent(btShowResult, 0, 3);
        addComponent(btMoreActions, 1, 3);
        addComponent(btHistory, 2, 3);
        addComponent(piCount, 3, 4);
        addComponent(btShowQueryBuilder, 3, 0);
        if (btShowKeyboard != null) {
            addComponent(btShowKeyboard, 3, 1);
            addComponent(btCopy, 3, 2);
        } else {
            addComponent(btCopy, 3, 1);
        }
        // alignment
        setRowExpandRatio(0, 0.0f);
        setRowExpandRatio(1, 0.0f);
        setRowExpandRatio(2, 1.0f);
        setColumnExpandRatio(0, 1.0f);
        setColumnExpandRatio(1, 0.0f);
        setColumnExpandRatio(2, 0.0f);
        setColumnExpandRatio(3, 0.0f);
    // setComponentAlignment(btShowQueryBuilder, Alignment.BOTTOM_CENTER);
    }

    @Override
    public void attach() {
        super.attach();
        IDGenerator.replacedignIDForFields(QueryPanel.this, btShowResult, btMoreActions);
    }

    public void updateShortHistory() {
        historyContainer.removeAllItems();
        int counter = 0;
        for (Query q : state.getHistory().gereplacedemIds()) {
            if (counter >= MAX_HISTORY_MENU_ITEMS) {
                break;
            } else {
                historyContainer.addBean(q);
            }
            counter++;
        }
    }

    public void setQuery(String query) {
        if (txtQuery != null) {
            txtQuery.setValue(query);
        }
    }

    public String getQuery() {
        if (txtQuery != null) {
            return (String) txtQuery.getValue();
        }
        return "";
    }

    public void setNodes(List<NodeDesc> nodes) {
        txtQuery.setNodes(nodes);
    }

    public void setErrors(List<AqlParseError> errors) {
        txtQuery.setErrors(errors);
    }

    public void notifyFrequencyTabClose() {
        txtQuery.removeTextChangeListener(frequencyPanel);
        frequencyPanel = null;
    }

    @Override
    public void valueChange(ValueChangeEvent event) {
        btHistory.setPopupVisible(false);
        Object q = event.getProperty().getValue();
        if (ui != null && ui.getQueryController() != null && q instanceof Query) {
            ui.getQueryController().setQuery((Query) q);
        }
    }

    public clreplaced ShowResultClickListener implements Button.ClickListener {

        @Override
        public void buttonClick(ClickEvent event) {
            if (ui != null && ui.getQueryController() != null) {
                ui.getQueryController().executeSearch(true, true);
            }
        }
    }

    // public clreplaced ShowResultInNewTabClickListener implements Button.ClickListener
    // {
    // 
    // @Override
    // public void buttonClick(ClickEvent event)
    // {
    // if(controller != null)
    // {
    // controller.setQuery((txtQuery.getValue()));
    // controller.executeQuery(false);
    // }
    // }
    // }
    public void setCountIndicatorEnabled(boolean enabled) {
        if (piCount != null && btShowResult != null && txtStatus != null) {
            if (enabled) {
                if (!piCount.isVisible()) {
                    piCount.setVisible(true);
                    piCount.setEnabled(true);
                }
            }
            btShowResult.setEnabled(!enabled);
        // btShowResultNewTab.setEnabled(!enabled);
        }
    }

    public void setStatus(String status) {
        if (txtStatus != null) {
            txtStatus.setReadOnly(false);
            txtStatus.setValue(status);
            lastPublicStatus = status;
            txtStatus.setReadOnly(true);
        }
    }

    public void setStatus(String status, String resultStatus) {
        if (txtStatus != null) {
            txtStatus.setReadOnly(false);
            txtStatus.setValue(status + resultStatus);
            lastPublicStatus = status;
            txtStatus.setReadOnly(true);
        }
    }

    private static clreplaced ShowKeyboardClickListener implements ClickListener {

        private final VirtualKeyboardCodeEditor virtualKeyboard;

        public ShowKeyboardClickListener(VirtualKeyboardCodeEditor virtualKeyboard) {
            this.virtualKeyboard = virtualKeyboard;
        }

        @Override
        public void buttonClick(ClickEvent event) {
            virtualKeyboard.show();
        }
    }

    private clreplaced ShowExportClickListener implements ClickListener {

        private AnnisUI ui;

        private ExportPanel panel;

        public ShowExportClickListener(AnnisUI ui) {
            this.ui = ui;
        }

        @Override
        public void buttonClick(ClickEvent event) {
            if (panel == null) {
                panel = new ExportPanel(QueryPanel.this, ui.getQueryController(), state, ui);
            }
            final TabSheet tabSheet = ui.getSearchView().getMainTab();
            Tab tab = tabSheet.getTab(panel);
            if (tab == null) {
                tab = tabSheet.addTab(panel, "Export");
                tab.setIcon(FontAwesome.DOWNLOAD);
            }
            tab.setClosable(true);
            tabSheet.setSelectedTab(panel);
            btMoreActions.setPopupVisible(false);
        }
    }

    private clreplaced ShowFrequencyClickListener implements ClickListener {

        private AnnisUI ui;

        public ShowFrequencyClickListener(AnnisUI ui) {
            this.ui = ui;
        }

        @Override
        public void buttonClick(ClickEvent event) {
            if (frequencyPanel == null) {
                frequencyPanel = new FrequencyQueryPanel(ui.getQueryController(), state);
                txtQuery.addTextChangeListener(frequencyPanel);
            }
            final TabSheet tabSheet = ui.getSearchView().getMainTab();
            Tab tab = tabSheet.getTab(frequencyPanel);
            if (tab == null) {
                tab = tabSheet.addTab(frequencyPanel, "Frequency replacedysis");
                tab.setIcon(FontAwesome.BAR_CHART_O);
            }
            tab.setClosable(true);
            tabSheet.setSelectedTab(frequencyPanel);
            btMoreActions.setPopupVisible(false);
        }
    }

    private static clreplaced ShowQueryBuilderClickListener implements ClickListener {

        private QueryBuilderChooser queryBuilder;

        private AnnisUI ui;

        public ShowQueryBuilderClickListener(AnnisUI ui) {
            this.ui = ui;
        }

        @Override
        public void buttonClick(ClickEvent event) {
            if (queryBuilder == null) {
                queryBuilder = new QueryBuilderChooser(ui.getQueryController(), ui, ui.getInstanceConfig());
            }
            final TabSheet tabSheet = ui.getSearchView().getMainTab();
            Tab tab = tabSheet.getTab(queryBuilder);
            if (tab == null) {
                tab = tabSheet.addTab(queryBuilder, "Query Builder", new ThemeResource("images/tango-icons/16x16/doreplacedent-properties.png"));
                ui.addAction(new ShortcutListener("^Query builder") {

                    @Override
                    public void handleAction(Object sender, Object target) {
                        if (queryBuilder != null && tabSheet.getTab(queryBuilder) != null) {
                            tabSheet.setSelectedTab(queryBuilder);
                        }
                    }
                });
            }
            tab.setClosable(true);
            tabSheet.setSelectedTab(queryBuilder);
        }
    }

    public String getLastPublicStatus() {
        return lastPublicStatus;
    }

    public ProgressBar getPiCount() {
        return piCount;
    }
}

18 View Complete Implementation : ShareSingleMatchGenerator.java
Copyright Apache License 2.0
Author : korpling
/**
 * @author Thomas Krause {@literal <[email protected]>}
 */
public clreplaced ShareSingleMatchGenerator extends Window implements SelectionEvent.SelectionListener {

    private final static Logger log = LoggerFactory.getLogger(ShareSingleMatchGenerator.clreplaced);

    private final VerticalLayout layout;

    private final Grid visSelector;

    private final VerticalLayout generatedLinks;

    private final Property<String> directURL;

    private final Property<String> iframeCode;

    private final BrowserFrame preview;

    private final TextArea txtDirectURL;

    private final TextArea txtIFrameCode;

    private final BeanItemContainer<ResolverEntry> visContainer;

    private final Match match;

    private final PagedResultQuery query;

    private final String segmentation;

    private final PluginSystem ps;

    public ShareSingleMatchGenerator(List<ResolverEntry> visualizers, Match match, PagedResultQuery query, String segmentation, PluginSystem ps) {
        this.match = match;
        this.query = query;
        this.segmentation = segmentation;
        this.ps = ps;
        setResizeLazy(true);
        directURL = new ObjectProperty<>("");
        iframeCode = new ObjectProperty<>("");
        visContainer = new BeanItemContainer<>(ResolverEntry.clreplaced);
        visContainer.addAll(visualizers);
        txtDirectURL = new TextArea(directURL);
        txtDirectURL.setCaption("Link for publications");
        txtDirectURL.setWidth("100%");
        txtDirectURL.setHeight("-1px");
        txtDirectURL.addStyleName(ValoTheme.TEXTFIELD_LARGE);
        txtDirectURL.addStyleName("shared-text");
        txtDirectURL.setWordwrap(true);
        txtDirectURL.setReadOnly(true);
        txtIFrameCode = new TextArea(iframeCode);
        txtIFrameCode.setCaption("Code for embedding visualization into web page");
        txtIFrameCode.setWidth("100%");
        txtIFrameCode.setHeight("-1px");
        txtIFrameCode.addStyleName(ValoTheme.TEXTFIELD_LARGE);
        txtIFrameCode.addStyleName("shared-text");
        txtIFrameCode.setWordwrap(true);
        txtIFrameCode.setReadOnly(true);
        preview = new BrowserFrame();
        preview.setCaption("Preview");
        preview.addStyleName("shared-text");
        preview.setSizeFull();
        generatedLinks = new VerticalLayout(txtDirectURL, txtIFrameCode, preview);
        generatedLinks.setComponentAlignment(txtDirectURL, Alignment.TOP_LEFT);
        generatedLinks.setComponentAlignment(txtIFrameCode, Alignment.TOP_LEFT);
        generatedLinks.setExpandRatio(preview, 1.0f);
        generatedLinks.setSpacing(false);
        visSelector = new Grid(visContainer);
        visSelector.setCaption("Select visualization");
        visSelector.setHeight("100%");
        visSelector.setColumns("displayName");
        visSelector.setSelectionMode(Grid.SelectionMode.SINGLE);
        visSelector.addSelectionListener(ShareSingleMatchGenerator.this);
        visSelector.select(visContainer.getIdByIndex(0));
        visSelector.setWidth("300px");
        visSelector.getColumn("displayName").setSortable(false);
        generatedLinks.setSizeFull();
        Label infoText = new Label("<p style=\"font-size: 18px\" >" + "<strong>Share your match:</strong> " + "1. Choose the visualization to share. 2. Copy the generated link or code. " + "3. Share this link with your peers or include the code in your website. " + "</p>", ContentMode.HTML);
        HorizontalLayout hLayout = new HorizontalLayout(visSelector, generatedLinks);
        hLayout.setSizeFull();
        hLayout.setSpacing(false);
        hLayout.setExpandRatio(generatedLinks, 1.0f);
        Button btClose = new Button("Close");
        btClose.setSizeUndefined();
        btClose.addClickListener(new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                getUI().removeWindow(ShareSingleMatchGenerator.this);
            }
        });
        layout = new VerticalLayout(infoText, hLayout, btClose);
        layout.setSizeFull();
        layout.setExpandRatio(hLayout, 1.0f);
        layout.setSpacing(false);
        layout.setComponentAlignment(btClose, Alignment.MIDDLE_CENTER);
        setContent(layout);
    }

    private URI generatorURLForVisualizer(ResolverEntry entry) {
        String appContext = Helper.getContext(UI.getCurrent());
        URI appURI = UI.getCurrent().getPage().getLocation();
        UriBuilder result = UriBuilder.fromUri(appURI).replacePath(appContext).path("embeddedvis").path(Helper.encodeJersey(entry.getVisType())).fragment("");
        if (entry.getNamespace() != null) {
            result = result.queryParam("embedded_ns", Helper.encodeJersey(entry.getNamespace()));
        }
        // test if the request was made from a sub-instance
        String nonContextPath = appURI.getPath().substring(appContext.length());
        if (!nonContextPath.isEmpty()) {
            if (nonContextPath.startsWith("/")) {
                nonContextPath = nonContextPath.substring(1);
            }
            result = result.queryParam(EmbeddedVisUI.KEY_INSTANCE, nonContextPath);
        }
        UriBuilder serviceURL = UriBuilder.fromUri(Helper.getAnnisWebResource(UI.getCurrent()).path("query").getURI());
        VisualizerPlugin visPlugin = ps.getVisualizer(entry.getVisType());
        if (visPlugin != null && visPlugin.isUsingText()) {
            // generate a service URL that gets the whole doreplacedent
            URI firstID = match.getSaltIDs().get(0);
            String pathreplacedtring = firstID.getRawPath();
            List<String> path = Splitter.on('/').omitEmptyStrings().trimResults().splitToList(pathreplacedtring);
            String corpusName = path.get(0);
            String doreplacedentName = path.get(path.size() - 1);
            try {
                corpusName = URLDecoder.decode(corpusName, "UTF-8");
                doreplacedentName = URLDecoder.decode(doreplacedentName, "UTF-8");
                ;
            } catch (UnsupportedEncodingException ex) {
                log.warn("Could not decode URL", ex);
            }
            // apply any node annotation filters if possible
            if (visPlugin instanceof FilteringVisualizerPlugin) {
                List<String> visAnnos = ((FilteringVisualizerPlugin) visPlugin).getFilteredNodeAnnotationNames(corpusName, doreplacedentName, entry.getMappings(), UI.getCurrent());
                if (visAnnos != null) {
                    Set<String> annos = new HashSet<>(visAnnos);
                    // always add the matched node annotation as well
                    for (String matchedAnno : match.getAnnos()) {
                        if (!matchedAnno.isEmpty()) {
                            annos.add(matchedAnno);
                        }
                    }
                    serviceURL = serviceURL.queryParam("filternodeanno", Joiner.on(",").join(annos));
                }
            }
            serviceURL = serviceURL.path("graph").path(Helper.encodePath(corpusName)).path(Helper.encodePath(doreplacedentName));
            // add the original match so the embedded visualizer can add it
            // (since we use the graph query it will not be included in the Salt XMI itself)
            result = result.queryParam(EmbeddedVisUI.KEY_MATCH, Helper.encodeJersey(match.toString()));
        } else {
            // default to the subgraph URL for this specific match
            serviceURL = serviceURL.path("search").path("subgraph").queryParam("match", Helper.encodeJersey(match.toString())).queryParam("left", query.getLeftContext()).queryParam("right", query.getRightContext());
            if (query.getSegmentation() != null) {
                serviceURL = serviceURL.queryParam("segmentation", query.getSegmentation());
            }
        }
        // add the URL where to fetch the graph from
        result = result.queryParam(EmbeddedVisUI.KEY_SALT, Helper.encodeQueryParam(serviceURL.build().toASCIIString()));
        // add the current view as "return back" parameter
        result = result.queryParam(EmbeddedVisUI.KEY_SEARCH_INTERFACE, appURI.toASCIIString());
        if (segmentation != null) {
            result = result.queryParam(EmbeddedVisUI.KEY_BASE_TEXT, segmentation);
        }
        // add all mappings as parameter
        for (String key : entry.getMappings().stringPropertyNames()) {
            if (!key.startsWith(EmbeddedVisUI.KEY_PREFIX)) {
                String value = Helper.encodeJersey(entry.getMappings().getProperty(key));
                result = result.queryParam(key, value);
            }
        }
        return result.build();
    }

    @Override
    public void select(SelectionEvent event) {
        Set<Object> selected = event.getSelected();
        if (selected.isEmpty()) {
            generatedLinks.setVisible(false);
        } else {
            generatedLinks.setVisible(true);
            URI url = generatorURLForVisualizer((ResolverEntry) selected.iterator().next());
            String shortURL = Helper.shortenURL(url, UI.getCurrent());
            directURL.setValue(shortURL);
            iframeCode.setValue("<iframe height=\"300px\" width=\"100%\" src=\"" + shortURL + "\"></iframe>");
            preview.setSource(new ExternalResource(shortURL));
        }
    }
}

18 View Complete Implementation : DynaBeanBasedContainerTest.java
Copyright Apache License 2.0
Author : viritin
@Test
@Ignore(value = "We know BeanItemContainer uses lots of memory and is slow, uncomment to verify possible fixes from core.")
public void testMemoryUsageStd() {
    System.out.println("\n Testing BeanItemContainer from core Vaadin");
    long initial = reportMemoryUsage();
    long ms = System.currentTimeMillis();
    BeanItemContainer lc = new BeanItemContainer<>(persons);
    System.out.println("After creation (took " + (System.currentTimeMillis() - ms) + ")");
    long after = reportMemoryUsage();
    System.err.println("Delta (bytes)" + (after - initial));
    ms = System.currentTimeMillis();
    for (int i = 0; i < amount; i++) {
        Item item = lc.gereplacedem(persons.get(i));
        String str;
        str = item.gereplacedemProperty("firstName").toString();
    }
    System.out.println("After loop (took " + (System.currentTimeMillis() - ms) + ")");
    after = reportMemoryUsage();
    System.err.println("Delta (bytes)" + (after - initial));
    // call to avoid GC:n the whole container
    lc.gereplacedemIds();
    System.out.println("After GC");
    after = reportMemoryUsage();
    System.err.println("Delta (bytes)" + (after - initial));
}

15 View Complete Implementation : MetaDataPanel.java
Copyright Apache License 2.0
Author : korpling
private Table setupTable(BeanItemContainer<Annotation> metaData) {
    final BeanItemContainer<Annotation> mData = metaData;
    mData.sort(new Object[] { "namespace", "name" }, new boolean[] { true, true });
    Table tblMeta = new Table();
    tblMeta.setContainerDataSource(mData);
    tblMeta.addGeneratedColumn("genname", new MetaTableNameGenerator(mData));
    tblMeta.addGeneratedColumn("genvalue", new MetaTableValueGenerator(mData));
    tblMeta.setVisibleColumns("genname", "genvalue");
    tblMeta.setColumnHeaders("Name", "Value");
    tblMeta.setSizeFull();
    tblMeta.setColumnWidth("genname", -1);
    tblMeta.setColumnExpandRatio("genvalue", 1.0f);
    tblMeta.addStyleName(ChameleonTheme.TABLE_STRIPED);
    return tblMeta;
}

14 View Complete Implementation : CmsFileHistorySettings.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Fills the combo box to choose the number of versions which shouls be stored.<p>
 */
private void setupVersionComboBox() {
    // Setup beans
    List<ComboBoxVersionsBean> beans = new ArrayList<ComboBoxVersionsBean>();
    // Disabled
    beans.add(new ComboBoxVersionsBean(CmsFileHistoryApp.NUMBER_VERSIONS_DISABLED));
    // 1-10
    for (int i = 1; i <= 10; i++) {
        beans.add(new ComboBoxVersionsBean(i));
    }
    // 15-50
    for (int i = 15; i <= 50; i += 5) {
        beans.add(new ComboBoxVersionsBean(i));
    }
    // Unlimited
    beans.add(new ComboBoxVersionsBean(CmsFileHistoryApp.NUMBER_VERSIONS_UNLIMITED));
    BeanItemContainer<ComboBoxVersionsBean> objects = new BeanItemContainer<ComboBoxVersionsBean>(ComboBoxVersionsBean.clreplaced, beans);
    m_numberVersions.setContainerDataSource(objects);
    m_numberVersions.sereplacedemCaptionPropertyId("displayValue");
    m_numberVersions.setNullSelectionAllowed(false);
    m_numberVersions.setTextInputAllowed(false);
    m_numberVersions.setPageLength(beans.size());
    int numberHistoryVersions = OpenCms.getSystemInfo().getHistoryVersions();
    m_numberVersions.setValue(beans.get(beans.indexOf(new ComboBoxVersionsBean(numberHistoryVersions))));
}

14 View Complete Implementation : CmsGlobalForm.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Set up of combo box for default uri.<p>
 *
 * @param allSites alls available sites
 */
private void setUpDefaultUriComboBox(List<CmsSite> allSites) {
    BeanItemContainer<CmsSite> objects = new BeanItemContainer<CmsSite>(CmsSite.clreplaced, allSites);
    m_fieldDefaultURI.setContainerDataSource(objects);
    m_fieldDefaultURI.setNullSelectionAllowed(false);
    m_fieldDefaultURI.setTextInputAllowed(false);
    m_fieldDefaultURI.sereplacedemCaptionPropertyId("replacedle");
    // set value
    String siteRoot = OpenCms.getSiteManager().getDefaultUri();
    if (siteRoot.endsWith("/")) {
        siteRoot = siteRoot.substring(0, siteRoot.length() - 1);
    }
    CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot);
    m_fieldDefaultURI.setValue(site);
}

14 View Complete Implementation : MetaDataPanel.java
Copyright Apache License 2.0
Author : korpling
@Override
public void attach() {
    super.attach();
    final UI ui = UI.getCurrent();
    if (doreplacedentName == null) {
        Callable<List<Annotation>> backgroundJob = () -> {
            return getAllSubcorpora(toplevelCorpusName, ui);
        };
        Background.runWithCallback(backgroundJob, new FutureCallback<List<Annotation>>() {

            public void onSuccess(List<Annotation> result) {
                layout.removeComponent(progress);
                docs = result;
                HorizontalLayout selectionLayout = new HorizontalLayout();
                Label selectLabel = new Label("Select corpus/doreplacedent: ");
                corpusSelection = new ComboBox();
                selectionLayout.addComponents(selectLabel, corpusSelection);
                layout.addComponent(selectionLayout);
                selectLabel.setSizeUndefined();
                corpusSelection.setWidth(100, Unit.PERCENTAGE);
                corpusSelection.setHeight("-1px");
                corpusSelection.addValueChangeListener(MetaDataPanel.this);
                selectionLayout.setWidth(100, Unit.PERCENTAGE);
                selectionLayout.setHeight("-1px");
                selectionLayout.setSpacing(true);
                selectionLayout.setComponentAlignment(selectLabel, Alignment.MIDDLE_LEFT);
                selectionLayout.setComponentAlignment(corpusSelection, Alignment.MIDDLE_LEFT);
                selectionLayout.setExpandRatio(selectLabel, 0.4f);
                selectionLayout.setExpandRatio(corpusSelection, 0.6f);
                corpusSelection.addItem(toplevelCorpusName);
                corpusSelection.select(toplevelCorpusName);
                corpusSelection.setNullSelectionAllowed(false);
                corpusSelection.setImmediate(true);
                for (Annotation c : docs) {
                    corpusSelection.addItem(c.getName());
                }
            }

            @Override
            public void onFailure(Throwable t) {
                ExceptionDialog.show(t, "Could not get meta data.", ui);
                layout.removeComponent(progress);
            }
        });
    } else {
        layout.removeComponent(progress);
        Map<Integer, List<Annotation>> hashMData = splitListAnnotations();
        List<BeanItemContainer<Annotation>> l = putInBeanContainer(hashMData);
        Accordion accordion = new Accordion();
        accordion.setSizeFull();
        // set output to none if no metadata are available
        if (l.isEmpty()) {
            addEmptyLabel();
        } else {
            for (BeanItemContainer<Annotation> item : l) {
                String corpusName = item.getIdByIndex(0).getCorpusName();
                String path = toplevelCorpusName.equals(corpusName) ? "corpus: " + corpusName : "doreplacedent: " + corpusName;
                if (item.gereplacedemIds().isEmpty()) {
                    accordion.addTab(new Label("none"), path);
                } else {
                    accordion.addTab(setupTable(item), path);
                }
            }
            layout.addComponent(accordion);
        }
    }
}

14 View Complete Implementation : DynaBeanBasedContainerTest.java
Copyright Apache License 2.0
Author : viritin
@Test
@Ignore("Irrelevant with V8")
public void testEmptyList() {
    List<Person> l = new ArrayList<>();
    // Test with BeanItemContainer
    System.out.println("BeanItemContainer with empty list");
    BeanItemContainer<Person> bc = new BeanItemContainer<>(Person.clreplaced, l);
    System.out.println("   container size=" + bc.size());
    System.out.print("Properties: ");
    for (String p : bc.getContainerPropertyIds()) {
        System.out.print(p + " ");
    }
    // Test ListContainer with setCollection call
    System.out.println("\n\nListContainer with empty list via setCollection");
    ListContainer<Person> lc = new ListContainer<>(Person.clreplaced);
    lc.setCollection(l);
    System.out.println("   container size=" + lc.size());
    System.out.print("Properties: ");
    for (String p : lc.getContainerPropertyIds()) {
        System.out.print(p + " ");
    }
    // Test ListContainer with setCollection call
    System.out.println("\n\nListContainer with Clreplaced<T>, Collection<T> constructor");
    lc = new ListContainer<>(Person.clreplaced, l);
    System.out.println("   container size=" + lc.size());
    System.out.print("Properties: ");
    for (String p : lc.getContainerPropertyIds()) {
        System.out.print(p + " ");
    }
    Person per = new Person();
    per.setFirstName("First");
    per.setLastName("Lastname");
    per.setAge(r.nextInt(100));
    lc.addItem(per);
    System.out.println("\n   container size after addItem = " + lc.size());
    Person per2 = new Person();
    per2.setFirstName("Firs");
    per2.setLastName("Lastnam");
    per2.setAge(r.nextInt(100));
    l.add(per2);
    System.out.println("   container size after add = " + lc.size());
    // Test ListContainer with constructor that takes the List -- empty List
    // will cause zarro properties
    System.out.println("\n\nListContainer with empty list via Collection<T> constructor");
    l = new ArrayList<>();
    lc = new ListContainer<>(l);
    System.out.println("   container size=" + lc.size());
    System.out.println("Properties: none should print due to exception");
    replacedert.replacedertEquals(0, lc.getContainerPropertyIds().size());
}

13 View Complete Implementation : CmsWorkplaceServerWidget.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Sets the combo box for workplace.<p>
 *
 * @param allSites alls available sites
 * @param combo combo box to fill
 * @param nullselect if true, nothing is selected
 * @param defaultValue if set, this value gets chosen
 * @param sslMode CmsSSLMode
 * @return BeanItemContainer
 */
private static BeanItemContainer<CmsSite> setUpWorkplaceComboBox(List<CmsSite> allSites, final ComboBox combo, boolean nullselect, String defaultValue, CmsSSLMode sslMode) {
    final List<CmsSite> modSites = new ArrayList<CmsSite>();
    CmsSite siteWithDefaultURL = null;
    String defaultURL = defaultValue;
    for (CmsSite site : allSites) {
        CmsSite si = new CmsSite("dummy", site.getUrl());
        si.setSSLMode(site.getSSLMode());
        modSites.add(si);
        if (defaultValue != null) {
            if (defaultURL.equals(si.getUrl())) {
                // SSL sensitive ('http'!='https')
                siteWithDefaultURL = si;
            }
        }
    }
    if (defaultValue != null) {
        if (siteWithDefaultURL == null) {
            siteWithDefaultURL = new CmsSite("dummy", defaultURL);
            siteWithDefaultURL.setSSLMode(sslMode);
            modSites.add(0, siteWithDefaultURL);
        }
    }
    final BeanItemContainer<CmsSite> objects = new BeanItemContainer<CmsSite>(CmsSite.clreplaced, modSites);
    combo.setContainerDataSource(objects);
    combo.setNullSelectionAllowed(nullselect);
    combo.sereplacedemCaptionPropertyId("url");
    combo.setValue(siteWithDefaultURL);
    combo.setNewItemsAllowed(true);
    combo.setImmediate(true);
    combo.setNewItemHandler(new NewItemHandler() {

        private static final long serialVersionUID = -4760590374697520609L;

        public void addNewItem(String newItemCaption) {
            CmsSite newItem = new CmsSite("dummy", newItemCaption);
            newItem.setSSLMode(newItemCaption.contains("https:") ? CmsSSLMode.MANUAL : CmsSSLMode.NO);
            objects.addBean(newItem);
            combo.select(newItem);
        }
    });
    return objects;
}

13 View Complete Implementation : ExportPanel.java
Copyright Apache License 2.0
Author : korpling
/**
 * @author Thomas Krause {@literal <[email protected]>}
 */
public clreplaced ExportPanel extends GridLayout {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(ExportPanel.clreplaced);

    private final ComboBox cbLeftContext;

    private final ComboBox cbRightContext;

    private final TextField txtAnnotationKeys;

    private final TextField txtParameters;

    private final BeanItemContainer<Clreplaced> exporterClreplacedContainer = new BeanItemContainer<>(Clreplaced.clreplaced);

    private final ComboBox cbExporter;

    private final Button btDownload;

    private final Button btExport;

    private final Button btCancel;

    private final QueryPanel queryPanel;

    private File tmpOutputFile;

    private final ProgressBar progressBar;

    private final Label progressLabel;

    private FileDownloader downloader;

    private final transient EventBus eventBus;

    private transient Stopwatch exportTime = Stopwatch.createUnstarted();

    private final QueryController controller;

    private UI ui;

    private final QueryUIState state;

    private final FormLayout formLayout;

    private final Label lblHelp;

    private final PluginSystem ps;

    private final CheckBox cbAlignmc;

    public ExportPanel(QueryPanel queryPanel, QueryController controller, QueryUIState state, PluginSystem ps) {
        super(2, 3);
        this.queryPanel = queryPanel;
        this.controller = controller;
        this.state = state;
        this.ps = ps;
        this.eventBus = new EventBus();
        this.eventBus.register(ExportPanel.this);
        this.formLayout = new FormLayout();
        formLayout.setWidth("-1px");
        setWidth("99%");
        setHeight("-1px");
        setColumnExpandRatio(0, 0.0f);
        setColumnExpandRatio(1, 1.0f);
        cbExporter = new ComboBox("Exporter");
        cbExporter.setNewItemsAllowed(false);
        cbExporter.setNullSelectionAllowed(false);
        cbExporter.setImmediate(true);
        cbExporter.setPropertyDataSource(controller.getState().getExporter());
        cbExporter.setContainerDataSource(exporterClreplacedContainer);
        cbExporter.addValueChangeListener(new ExporterSelectionHelpListener());
        formLayout.addComponent(cbExporter);
        addComponent(formLayout, 0, 0);
        lblHelp = new Label();
        lblHelp.setContentMode(ContentMode.HTML);
        addComponent(lblHelp, 1, 0);
        cbLeftContext = new ComboBox("Left Context");
        cbRightContext = new ComboBox("Right Context");
        cbLeftContext.setNullSelectionAllowed(false);
        cbRightContext.setNullSelectionAllowed(false);
        cbLeftContext.setNewItemsAllowed(true);
        cbRightContext.setNewItemsAllowed(true);
        cbLeftContext.addValidator(new IntegerRangeValidator("must be a number", Integer.MIN_VALUE, Integer.MAX_VALUE));
        cbRightContext.addValidator(new IntegerRangeValidator("must be a number", Integer.MIN_VALUE, Integer.MAX_VALUE));
        for (Integer i : SearchOptionsPanel.PREDEFINED_CONTEXTS) {
            cbLeftContext.addItem(i);
            cbRightContext.addItem(i);
        }
        cbLeftContext.setValue(5);
        cbRightContext.setValue(5);
        formLayout.addComponent(cbLeftContext);
        formLayout.addComponent(cbRightContext);
        txtAnnotationKeys = new TextField("Annotation Keys");
        txtAnnotationKeys.setDescription("Some exporters will use this comma " + "seperated list of annotation keys to limit the exported data to these " + "annotations.");
        formLayout.addComponent(new HelpButton<String>(txtAnnotationKeys));
        txtParameters = new TextField("Parameters");
        txtParameters.setDescription("You can input special parameters " + "for certain exporters. See the description of each exporter " + "(‘?’ button above) for specific parameter settings.");
        formLayout.addComponent(new HelpButton<String>(txtParameters));
        // check box for match-with-context exporter
        cbAlignmc = new CheckBox("align matches" + "<br/>" + "by node number");
        cbAlignmc.setCaptionAsHtml(true);
        cbAlignmc.setDescription("Click here to align export result by node number.");
        cbAlignmc.setEnabled(true);
        formLayout.addComponent(cbAlignmc);
        btExport = new Button("Perform Export");
        btExport.setIcon(FontAwesome.PLAY);
        btExport.setDisableOnClick(true);
        btExport.addClickListener(new ExportButtonListener());
        btCancel = new Button("Cancel Export");
        btCancel.setIcon(FontAwesome.TIMES_CIRCLE);
        btCancel.setEnabled(false);
        btCancel.addClickListener(new CancelButtonListener());
        btDownload = new Button("Download");
        btDownload.setDescription("Click here to start the actual download.");
        btDownload.setIcon(FontAwesome.DOWNLOAD);
        btDownload.setDisableOnClick(true);
        btDownload.setEnabled(false);
        HorizontalLayout layoutExportButtons = new HorizontalLayout(btExport, btCancel, btDownload);
        addComponent(layoutExportButtons, 0, 1, 1, 1);
        VerticalLayout vLayout = new VerticalLayout();
        addComponent(vLayout, 0, 2, 1, 2);
        progressBar = new ProgressBar();
        progressBar.setVisible(false);
        progressBar.setIndeterminate(true);
        vLayout.addComponent(progressBar);
        progressLabel = new Label();
        vLayout.addComponent(progressLabel);
        if (state != null) {
            cbLeftContext.setPropertyDataSource(state.getLeftContext());
            cbRightContext.setPropertyDataSource(state.getRightContext());
            cbExporter.setPropertyDataSource(state.getExporter());
            txtAnnotationKeys.setConverter(new CommaSeperatedStringConverterList());
            txtAnnotationKeys.setPropertyDataSource(state.getExportAnnotationKeys());
            txtParameters.setPropertyDataSource(state.getExportParameters());
            cbAlignmc.setPropertyDataSource(state.getAlignmc());
        }
    }

    @Override
    public void attach() {
        super.attach();
        this.ui = UI.getCurrent();
        if (this.ui instanceof AnnisBaseUI) {
            PluginManagerUtil util = new PluginManagerUtil(((AnnisBaseUI) getUI()).getPluginManager());
            for (ExporterPlugin e : util.getPlugins(ExporterPlugin.clreplaced)) {
                exporterClreplacedContainer.addItem(e.getClreplaced());
            }
        }
        exporterClreplacedContainer.sort(new Object[] { "simpleName" }, new boolean[] { true });
        cbExporter.sereplacedemCaptionMode(ItemCaptionMode.PROPERTY);
        cbExporter.sereplacedemCaptionPropertyId("simpleName");
        if (exporterClreplacedContainer.size() > 0) {
            cbExporter.setValue(exporterClreplacedContainer.getIdByIndex(0));
        }
    }

    public clreplaced ExporterSelectionHelpListener implements Property.ValueChangeListener {

        @Override
        public void valueChange(ValueChangeEvent event) {
            @SuppressWarnings("unchecked")
            ExporterPlugin exporter = ps.getExporter((Clreplaced<? extends ExporterPlugin>) event.getProperty().getValue());
            if (exporter != null) {
                btCancel.setVisible(exporter.isCancelable());
                cbAlignmc.setVisible(exporter.isAlignable());
                String helpMessage = exporter.getHelpMessage();
                if (helpMessage != null) {
                    lblHelp.setValue(helpMessage);
                } else {
                    lblHelp.setValue("No help available for this exporter");
                }
                cbLeftContext.setVisible(exporter.needsContext());
                cbRightContext.setVisible(exporter.needsContext());
            } else {
                btCancel.setVisible(false);
                cbAlignmc.setVisible(false);
                cbLeftContext.setVisible(false);
                cbRightContext.setVisible(false);
                lblHelp.setValue("No valid exporter selected");
            }
        }
    }

    @Subscribe
    public void handleExportProgress(final Integer exports) {
        if (ui != null) {
            // if we ui access() here it seems to confuse the isInterrupted() flag
            // of the parent thread and cancelling won't work any longer
            ui.accessSynchronously(new Runnable() {

                @Override
                public void run() {
                    if (exportTime != null && exportTime.isRunning()) {
                        progressLabel.setValue("exported " + exports + " items in " + exportTime.toString());
                    } else {
                        progressLabel.setValue("exported " + exports + " items");
                    }
                }
            });
        }
    }

    @Override
    public void detach() {
        super.detach();
        if (tmpOutputFile != null && tmpOutputFile.exists()) {
            if (!tmpOutputFile.delete()) {
                log.warn("Could not delete {}", tmpOutputFile.getAbsolutePath());
            }
        }
    }

    public void showResult(File currentTmpFile, Exception exportError) {
        btExport.setEnabled(true);
        btCancel.setEnabled(false);
        progressBar.setVisible(false);
        progressLabel.setValue("");
        // copy the result to the clreplaced member in order to delete if
        // when not longer needed
        tmpOutputFile = currentTmpFile;
        // 
        if (exportError instanceof CacheException | exportError instanceof IllegalStateException | exportError instanceof ClreplacedCastException) {
            Notification.show(exportError.getMessage(), Notification.Type.ERROR_MESSAGE);
        } else if (tmpOutputFile == null) {
            Notification.show("Could not create the Exporter", "The server logs might contain more information about this " + "so you should contact the provider of this ANNIS installation " + "for help.", Notification.Type.ERROR_MESSAGE);
        } else if (exportError instanceof InterruptedException) {
            // we were aborted, don't do anything
            Notification.show("Export cancelled", Notification.Type.WARNING_MESSAGE);
        } else {
            if (downloader != null && btDownload.getExtensions().contains(downloader)) {
                btDownload.removeExtension(downloader);
            }
            downloader = new FileDownloader(new FileResource(tmpOutputFile));
            downloader.extend(btDownload);
            btDownload.setEnabled(true);
            Notification.show("Export finished", "Click on the button right to the export button to actually download the file.", Notification.Type.HUMANIZED_MESSAGE);
        }
    }

    private clreplaced ExportButtonListener implements Button.ClickListener {

        @Override
        public void buttonClick(ClickEvent event) {
            // clean up old export
            if (tmpOutputFile != null && tmpOutputFile.exists()) {
                if (!tmpOutputFile.delete()) {
                    log.warn("Could not delete {}", tmpOutputFile.getAbsolutePath());
                }
            }
            tmpOutputFile = null;
            @SuppressWarnings("unchecked")
            final ExporterPlugin exporter = ps.getExporter((Clreplaced<? extends ExporterPlugin>) cbExporter.getValue());
            if (exporter != null) {
                if ("".equals(queryPanel.getQuery())) {
                    Notification.show("Empty query", Notification.Type.WARNING_MESSAGE);
                    btExport.setEnabled(true);
                    return;
                } else if (state.getSelectedCorpora().getValue().isEmpty()) {
                    Notification.show("Please select a corpus", Notification.Type.WARNING_MESSAGE);
                    btExport.setEnabled(true);
                    return;
                }
                btDownload.setEnabled(false);
                progressBar.setVisible(true);
                progressLabel.setValue("");
                if (exporter.isCancelable()) {
                    btCancel.setEnabled(true);
                    btCancel.setDisableOnClick(true);
                }
                controller.executeExport(ExportPanel.this, eventBus);
                if (exportTime == null) {
                    exportTime = Stopwatch.createUnstarted();
                }
                exportTime.reset();
                exportTime.start();
            }
        }
    }

    private clreplaced CancelButtonListener implements Button.ClickListener {

        @Override
        public void buttonClick(ClickEvent event) {
            controller.cancelExport();
        }
    }
}

11 View Complete Implementation : ListContainerLoopPerformanceTest.java
Copyright Apache License 2.0
Author : viritin
public void loopAllEnreplacediesAndPropertiesWithBeanItemContainer() throws IOException {
    NullOutputStream nullOutputStream = new NullOutputStream();
    List<Person> listOfPersons = Service.getListOfPersons(100 * 1000);
    long currentTimeMillis = System.currentTimeMillis();
    BeanItemContainer<Person> c = new BeanItemContainer<>(Person.clreplaced, listOfPersons);
    Collection<?> ids = c.getContainerPropertyIds();
    for (int i = 0; i < c.size(); i++) {
        Item item = c.gereplacedem(listOfPersons.get(i));
        for (Object propertyId : ids) {
            Property itemProperty = item.gereplacedemProperty(propertyId);
            final Object value = itemProperty.getValue();
            nullOutputStream.write(value.toString().getBytes());
            LOG.log(Level.FINEST, "Property: %s", value);
        }
    }
    // ~ 350ms in 1.34, MacBook Pro (Retina, Mid 2012) 2.3Gz i7
    // ~ + 3-10ms in 1.35, when changing ListContainer to use PropertyUtils instead of WrapDynaBean
    LOG.log(Level.INFO, "BIC from core: Looping all properties in 100 000 Items took {0}ms", (System.currentTimeMillis() - currentTimeMillis));
}

10 View Complete Implementation : ExecutionRunPanel.java
Copyright GNU General Public License v3.0
Author : JumpMind
public clreplaced ExecutionRunPanel extends VerticalLayout implements IUiPanel, IBackgroundRefreshable<Object> {

    private static final long serialVersionUID = 1L;

    final protected Logger log = LoggerFactory.getLogger(getClreplaced());

    IExecutionService executionService;

    VerticalSplitPanel splitPanel;

    Grid stepTable = new Grid();

    RunDiagram diagram;

    Panel flowPanel;

    AbstractLayout diagramLayout;

    Flow flow;

    List<AbstractObject> selected = new ArrayList<AbstractObject>();

    Grid logTable;

    BeanContainer<String, ExecutionStep> stepContainer = new BeanContainer<String, ExecutionStep>(ExecutionStep.clreplaced);

    BeanItemContainer<ExecutionStepLog> logContainer = new BeanItemContainer<ExecutionStepLog>(ExecutionStepLog.clreplaced);

    Label flowLabel = new Label();

    Label statusLabel = new Label("", ContentMode.HTML);

    Label startLabel = new Label();

    Button downloadLink;

    Label endLabel = new Label();

    Button removeButton;

    Button cancelButton;

    Button rerunButton;

    CheckBox showDiagramCheckbox;

    TextField limitField;

    String executionId;

    ApplicationContext context;

    TabbedPanel parentTabSheet;

    IFlowRunnable flowRunnable;

    boolean lastDataRefreshWasDone = false;

    List<SortOrder> lastSortOrder;

    Label status;

    float lastPosition = 50;

    // Must be set to 99. Not sure why 100 doesn't work.
    final static float MAX_PANEL_POSITION = 99;

    public ExecutionRunPanel(String executionId, ApplicationContext context, TabbedPanel parentTabSheet) {
        this(executionId, context, parentTabSheet, null);
    }

    public ExecutionRunPanel(String executionId, ApplicationContext context, TabbedPanel parentTabSheet, IFlowRunnable flowRunnable) {
        this.executionService = context.getExecutionService();
        this.executionId = executionId;
        this.context = context;
        this.parentTabSheet = parentTabSheet;
        this.flowRunnable = flowRunnable;
        Execution execution = executionService.findExecution(executionId);
        this.flow = context.getConfigurationService().findFlow(execution.getFlowId());
        HorizontalLayout topBar = new HorizontalLayout();
        topBar.setMargin(new MarginInfo(true, true, false, true));
        topBar.setWidth(100, Unit.PERCENTAGE);
        HorizontalLayout left = new HorizontalLayout();
        topBar.addComponent(left);
        HorizontalLayout right = new HorizontalLayout();
        right.setSpacing(true);
        topBar.addComponent(right);
        topBar.setComponentAlignment(right, Alignment.MIDDLE_RIGHT);
        Label limitLabel = new Label("Max Log Messages To Show :");
        right.addComponent(limitLabel);
        right.setComponentAlignment(limitLabel, Alignment.MIDDLE_RIGHT);
        limitField = new ImmediateUpdateTextField(null) {

            private static final long serialVersionUID = 1L;

            @Override
            protected void save(String text) {
                Setting setting = context.getUser().findSetting(UserSetting.SETTING_MAX_LOG_MESSAGE_TO_SHOW);
                setting.setValue(Integer.toString(getMaxToShow(text)));
                context.getConfigurationService().save(setting);
            }
        };
        limitField.setWidth("5em");
        limitField.setValue(context.getUser().get(UserSetting.SETTING_MAX_LOG_MESSAGE_TO_SHOW, "1000"));
        right.addComponent(limitField);
        right.setComponentAlignment(limitField, Alignment.MIDDLE_RIGHT);
        showDiagramCheckbox = new CheckBox("Show Diagram");
        showDiagramCheckbox.addValueChangeListener((event) -> {
            if (showDiagramCheckbox.getValue()) {
                showDiagram();
            } else {
                showDetails();
            }
        });
        right.addComponent(showDiagramCheckbox);
        right.setComponentAlignment(showDiagramCheckbox, Alignment.MIDDLE_RIGHT);
        addComponent(topBar);
        ButtonBar buttonBar = new ButtonBar();
        rerunButton = buttonBar.addButton("Rerun", Icons.RUN, event -> rerun());
        rerunButton.setVisible(false);
        removeButton = buttonBar.addButton("Remove", Icons.DELETE, event -> remove());
        removeButton.setVisible(false);
        cancelButton = buttonBar.addButton("Cancel", Icons.CANCEL, event -> cancel());
        addComponent(buttonBar);
        HorizontalLayout header1 = new HorizontalLayout();
        header1.addComponent(new Label("<b>Flow:</b>", ContentMode.HTML));
        header1.addComponent(flowLabel);
        header1.addComponent(new Label("<b>Start:</b>", ContentMode.HTML));
        header1.addComponent(startLabel);
        header1.setSpacing(true);
        header1.setMargin(new MarginInfo(false, true, false, true));
        header1.setWidth("100%");
        addComponent(header1);
        HorizontalLayout header2 = new HorizontalLayout();
        header2.addComponent(new Label("<b>Status:</b>", ContentMode.HTML));
        header2.addComponent(statusLabel);
        header2.addComponent(new Label("<b>End:</b>", ContentMode.HTML));
        header2.addComponent(endLabel);
        header2.setSpacing(true);
        header2.setMargin(new MarginInfo(false, true, true, true));
        header2.setWidth("100%");
        addComponent(header2);
        stepContainer.setBeanIdProperty("id");
        diagramLayout = new VerticalLayout();
        diagramLayout.setWidth(10000, Unit.PIXELS);
        diagramLayout.setHeight(10000, Unit.PIXELS);
        flowPanel = new Panel();
        flowPanel.setSizeFull();
        flowPanel.addStyleName(ValoTheme.PANEL_WELL);
        // Wrapper fixes issue with the diagram not expanding inside the scroll panel.
        DragAndDropWrapper wrapper = new DragAndDropWrapper(diagramLayout);
        wrapper.setSizeUndefined();
        flowPanel.setContent(wrapper);
        stepTable.setSelectionMode(SelectionMode.SINGLE);
        stepTable.setSizeFull();
        stepTable.addColumn("componentName", String.clreplaced).setHeaderCaption("Component Name").setWidth(250);
        stepTable.addColumn("threadNumber", Integer.clreplaced).setHeaderCaption("Thread").setWidth(100);
        stepTable.addColumn("status", String.clreplaced).setHeaderCaption("Status").setWidth(120);
        stepTable.addColumn("payloadReceived", Integer.clreplaced).setHeaderCaption("Payload Recvd").setWidth(120);
        stepTable.addColumn("messagesReceived", Integer.clreplaced).setHeaderCaption("Msgs Recvd").setWidth(100);
        stepTable.addColumn("messagesProduced", Integer.clreplaced).setHeaderCaption("Msgs Sent").setWidth(100);
        stepTable.addColumn("payloadProduced", Integer.clreplaced).setHeaderCaption("Payload Sent").setWidth(120);
        stepTable.addColumn("startTime", Date.clreplaced).setHeaderCaption("Start").setWidth(120).setMaximumWidth(170).setRenderer(new DateRenderer(UIConstants.TIME_FORMAT));
        stepTable.addColumn("endTime", Date.clreplaced).setHeaderCaption("End").setWidth(120).setMaximumWidth(170).setRenderer(new DateRenderer(UIConstants.TIME_FORMAT));
        stepTable.addColumn("handleDurationString", String.clreplaced).setHeaderCaption("Run Duration").setWidth(140);
        stepTable.addColumn("queueDurationString", String.clreplaced).setHeaderCaption("Wait Duration").setWidth(140);
        stepTable.setContainerDataSource(stepContainer);
        stepTable.addSelectionListener(event -> {
            String stepId = (String) stepTable.getSelectedRow();
            logContainer.removeAllItems();
            List<ExecutionStepLog> logs = executionService.findExecutionStepLogs(stepId, getMaxToShow());
            logContainer.addAll(logs);
            downloadLink.setVisible(logs.size() > 0);
            setLogMinimized(logContainer.size() == 0);
            updateStatus();
        });
        HeaderRow stepTableFilterHeader = stepTable.appendHeaderRow();
        HeaderCell componentNameFilterCell = stepTableFilterHeader.getCell("componentName");
        TextField componentNameFilterField = new TextField();
        componentNameFilterField.setInputPrompt("Filter");
        componentNameFilterField.addStyleName(ValoTheme.TEXTFIELD_TINY);
        componentNameFilterField.setWidth("100%");
        componentNameFilterField.addTextChangeListener(change -> {
            stepContainer.removeContainerFilters("componentName");
            if (!change.getText().isEmpty())
                stepContainer.addContainerFilter(new SimpleStringFilter("componentName", change.getText(), true, false));
        });
        componentNameFilterCell.setComponent(componentNameFilterField);
        logTable = new Grid();
        logTable.addColumn("level", String.clreplaced).setHeaderCaption("Level").setWidth(110).setMaximumWidth(200);
        logTable.addColumn("createTime", Date.clreplaced).setHeaderCaption("Time").setWidth(120).setMaximumWidth(200).setRenderer(new DateRenderer(UIConstants.TIME_FORMAT));
        logTable.addColumn("logText", String.clreplaced).setHeaderCaption("Message").setExpandRatio(1);
        logTable.setContainerDataSource(logContainer);
        logTable.setSizeFull();
        logTable.addItemClickListener(event -> logTableCellClicked(logTable, event));
        logTable.addSortListener(event -> {
            lastSortOrder = event.getSortOrder();
        });
        HeaderRow filteringHeader = logTable.appendHeaderRow();
        HeaderCell logTextFilterCell = filteringHeader.getCell("logText");
        TextField filterField = new TextField();
        filterField.setInputPrompt("Filter");
        filterField.addStyleName(ValoTheme.TEXTFIELD_TINY);
        filterField.setWidth("100%");
        // Update filter When the filter input is changed
        filterField.addTextChangeListener(change -> {
            // Can't modify filters so need to replace
            logContainer.removeContainerFilters("logText");
            // (Re)create the filter if necessary
            if (!change.getText().isEmpty())
                logContainer.addContainerFilter(new SimpleStringFilter("logText", change.getText(), true, false));
        });
        logTextFilterCell.setComponent(filterField);
        HeaderCell levelFilterCell = filteringHeader.getCell("level");
        ComboBox levelFilter = new ComboBox();
        levelFilter.setWidth(8, Unit.EM);
        levelFilter.setNullSelectionAllowed(true);
        LogLevel[] levels = LogLevel.values();
        for (LogLevel logLevel : levels) {
            levelFilter.addItem(logLevel.name());
        }
        levelFilter.addValueChangeListener(change -> {
            logContainer.removeContainerFilters("level");
            String text = (String) levelFilter.getValue();
            if (isNotBlank(text)) {
                logContainer.addContainerFilter(new SimpleStringFilter("level", text, true, false));
            }
        });
        levelFilterCell.setComponent(levelFilter);
        levelFilter.addStyleName(ValoTheme.COMBOBOX_TINY);
        VerticalLayout logLayout = new VerticalLayout();
        logLayout.setSizeFull();
        logLayout.addComponent(logTable);
        logLayout.setExpandRatio(logTable, 1);
        HorizontalLayout statusBar = new HorizontalLayout();
        statusBar.addStyleName(ValoTheme.PANEL_WELL);
        statusBar.setMargin(new MarginInfo(true, true, true, true));
        statusBar.setWidth(100, Unit.PERCENTAGE);
        status = new Label("", ContentMode.HTML);
        statusBar.addComponent(status);
        statusBar.setComponentAlignment(status, Alignment.MIDDLE_LEFT);
        logLayout.addComponent(statusBar);
        downloadLink = new Button("Download", FontAwesome.DOWNLOAD);
        downloadLink.addClickListener(e -> download());
        downloadLink.addStyleName(ValoTheme.BUTTON_LINK);
        statusBar.addComponent(downloadLink);
        statusBar.setComponentAlignment(downloadLink, Alignment.MIDDLE_RIGHT);
        splitPanel = new VerticalSplitPanel();
        splitPanel.setFirstComponent(flowPanel);
        splitPanel.setSecondComponent(logLayout);
        splitPanel.setSplitPosition(50, Unit.PERCENTAGE);
        splitPanel.setSizeFull();
        addComponent(splitPanel);
        setExpandRatio(splitPanel, 1.0f);
        showDiagramCheckbox.setValue(context.getUser().getBoolean(UserSetting.SETTING_SHOW_RUN_DIAGRAM, true));
        if (!showDiagramCheckbox.getValue()) {
            showDetails();
        }
        context.getBackgroundRefresherService().register(this);
    }

    protected void download() {
        String stepId = null;
        if (showDiagramCheckbox.getValue()) {
            if (diagram.getSelectedNodeIds().size() > 0) {
                String flowStepId = diagram.getSelectedNodeIds().get(0);
                ExecutionData data = getExecutionData();
                if (data != null) {
                    ExecutionStep executionStep = data.findExecutionStep(flowStepId);
                    if (executionStep != null) {
                        stepId = executionStep.getId();
                    }
                }
            }
        } else {
            stepId = (String) stepTable.getSelectedRow();
        }
        if (stepId != null) {
            final File file = executionService.getExecutionStepLog(stepId);
            StreamSource ss = new StreamSource() {

                private static final long serialVersionUID = 1L;

                public InputStream getStream() {
                    try {
                        return new FileInputStream(file);
                    } catch (Exception e) {
                        log.error("Failed to download log file", e);
                        CommonUiUtils.notify("Failed to download log file", Type.ERROR_MESSAGE);
                        return null;
                    }
                }
            };
            StreamResource resource = new StreamResource(ss, file.getName());
            final String KEY = "export";
            setResource(KEY, resource);
            Page.getCurrent().open(ResourceReference.create(resource, this, KEY).getURL(), null);
        }
    }

    protected void redrawFlow() {
        if (diagram != null) {
            diagramLayout.removeComponent(diagram);
        }
        diagram = new RunDiagram();
        diagram.setSizeFull();
        diagram.addListener(new RunDiagramChangedListener());
        diagram.setNodes(getNodes());
        setLogMinimized(diagram.getSelectedNodeIds().size() == 0);
        diagramLayout.addComponent(diagram);
    }

    protected List<Node> getNodes() {
        ExecutionData executionData = getExecutionData();
        List<FlowStep> flowSteps = flow.getFlowSteps();
        List<FlowStepLink> links = flow.getFlowStepLinks();
        List<Node> list = new ArrayList<Node>();
        int activeSteps = 0;
        for (FlowStep step : flowSteps) {
            if (step.getComponent().getBoolean(AbstractComponentRuntime.ENABLED, true)) {
                activeSteps++;
            }
        }
        // If the execution steps don't match the flow steps, wait and try
        // again.  The execution log steps may not be persisted yet.
        for (int i = 0; i < 5; i++) {
            if (executionData.steps.size() == activeSteps) {
                break;
            } else {
                AppUtils.sleep(200);
                executionData = getExecutionData();
            }
        }
        for (FlowStep flowStep : flowSteps) {
            Node node = new Node();
            String name = flowStep.getComponent().getName();
            String type = flowStep.getComponent().getType();
            boolean enabled = flowStep.getComponent().getBoolean(AbstractComponentRuntime.ENABLED, true);
            String imageText = String.format("<img style=\"display: block; margin-left: auto; margin-right: auto\" src=\"data:image/png;base64,%s\"/>", UiUtils.getBase64RepresentationOfImageForComponentType(flow.getProjectVersionId(), type, context));
            node.setText(imageText);
            node.setName(name);
            node.setEnabled(enabled);
            node.setId(flowStep.getId());
            node.setX(flowStep.getX());
            node.setY(flowStep.getY());
            ExecutionStep executionStep = executionData.findExecutionStep(flowStep.getId());
            if (node.isEnabled() && executionStep != null) {
                node.setEnreplacediesProcessed(executionStep.getEnreplacediesProcessed());
                node.setMessagesRecieved(executionStep.getMessagesReceived());
                node.setMessagesSent(executionStep.getMessagesProduced());
                node.setStatus(executionStep.getExecutionStatus().toString());
                node.setInputLabel(Long.toString(executionStep.getMessagesReceived()));
                node.setOutputLabel(Long.toString(executionStep.getMessagesProduced()));
            } else if (!node.isEnabled()) {
                node.setInputLabel("-");
                node.setOutputLabel("-");
            } else {
                // Show the detail screen if the flow does not match the
                // historical execution.
                showDetails();
                showDiagramCheckbox.setEnabled(false);
                showDiagramCheckbox.setDescription("The flow has been modified since the execution. The flow cannot be viewed.");
            }
            for (FlowStepLink link : links) {
                if (link.getSourceStepId().equals(node.getId())) {
                    node.getTargetNodeIds().add(link.getTargetStepId());
                }
            }
            list.add(node);
        }
        return list;
    }

    protected void logTableCellClicked(Grid logTable, ItemClickEvent event) {
        if (event.isDoubleClick()) {
            Object object = event.getPropertyId();
            if (!object.toString().equals("")) {
                Object prop = event.getPropertyId();
                String header = logTable.getColumn(prop).getHeaderCaption();
                Property<?> p = event.gereplacedem().gereplacedemProperty(prop);
                if (p != null) {
                    String data = String.valueOf(p.getValue());
                    new ReadOnlyTextAreaDialog(header, data, false).showAtSize(.5);
                }
            }
        }
    }

    @Override
    public boolean closing() {
        context.getBackgroundRefresherService().unregister(this);
        return true;
    }

    @Override
    public void selected() {
    }

    @Override
    public void deselected() {
    }

    protected void rerun() {
        parentTabSheet.closeTab(executionId);
        flowRunnable.runFlow();
    }

    protected void remove() {
        ConfirmDialog.show("Delete Execution?", "Are you sure you want to delete this execution?", () -> {
            context.getExecutionService().deleteExecution(executionId);
            parentTabSheet.closeTab(executionId);
            return true;
        });
    }

    protected void cancel() {
        ConfirmDialog.show("Cancel Execution?", "Are you sure you want to cancel this execution?", () -> {
            context.getAgentManager().cancel(executionId);
            cancelButton.setEnabled(false);
            return true;
        });
    }

    protected void showDiagram() {
        splitPanel.setFirstComponent(flowPanel);
        Setting setting = context.getUser().findSetting(UserSetting.SETTING_SHOW_RUN_DIAGRAM);
        setting.setValue("true");
        context.getConfigurationService().save(setting);
        redrawFlow();
    }

    protected void showDetails() {
        splitPanel.setFirstComponent(stepTable);
        setLogMinimized(stepTable.getSelectedRows().isEmpty());
        Setting setting = context.getUser().findSetting(UserSetting.SETTING_SHOW_RUN_DIAGRAM);
        setting.setValue("false");
        context.getConfigurationService().save(setting);
    }

    @Override
    public Object onBackgroundDataRefresh() {
        if (!lastDataRefreshWasDone) {
            return getExecutionData();
        } else {
            return null;
        }
    }

    @Override
    public void onBackgroundUIRefresh(Object backgroundData) {
        if (backgroundData != null) {
            refreshUI((ExecutionData) backgroundData);
        }
    }

    public void onUIError(Throwable ex) {
        CommonUiUtils.notify(ex);
    }

    protected ExecutionData getExecutionData() {
        ExecutionData data = new ExecutionData();
        data.execution = executionService.findExecution(executionId);
        data.steps = executionService.findExecutionSteps(executionId);
        this.flow = context.getConfigurationService().findFlow(data.execution.getFlowId());
        String selected = (String) stepTable.getSelectedRow();
        data.logs = executionService.findExecutionStepLogs(selected, getMaxToShow());
        return data;
    }

    protected int getMaxToShow() {
        return getMaxToShow(limitField.getValue());
    }

    protected int getMaxToShow(String text) {
        try {
            return Integer.parseInt(text);
        } catch (Exception e) {
            return 100;
        }
    }

    clreplaced RunDiagramChangedListener implements Listener {

        private static final long serialVersionUID = 1L;

        @Override
        public void componentEvent(Event e) {
            if (e instanceof NodeSelectedEvent) {
                NodeSelectedEvent event = (NodeSelectedEvent) e;
                List<String> nodeIds = event.getNodeIds();
                ExecutionData data = getExecutionData();
                Set<String> stepIds = new HashSet<String>(nodeIds.size());
                for (String id : nodeIds) {
                    ExecutionStep step = data.findExecutionStep(id);
                    if (step != null) {
                        stepIds.add(step.getId());
                    }
                }
                logContainer.removeAllItems();
                List<ExecutionStepLog> logs = executionService.findExecutionStepLogs(stepIds, getMaxToShow());
                logContainer.addAll(logs);
                setLogMinimized(logContainer.size() == 0);
                updateStatus();
            }
        }
    }

    protected void setLogMinimized(boolean minimize) {
        float position = splitPanel.getSplitPosition();
        if (minimize && position != MAX_PANEL_POSITION) {
            lastPosition = position;
            splitPanel.setSplitPosition(MAX_PANEL_POSITION, Unit.PERCENTAGE);
        } else if (!minimize && position == MAX_PANEL_POSITION) {
            splitPanel.setSplitPosition(lastPosition, Unit.PERCENTAGE);
        }
    }

    protected void updateStatus() {
        boolean max = logContainer.gereplacedemIds().size() >= getMaxToShow();
        if (max) {
            status.setValue("<span style='color:red'>Displaying only " + logContainer.gereplacedemIds().size() + " messages.  Adjust max number of log message to show more.</span>");
        } else {
            status.setValue("<span>Displaying " + logContainer.gereplacedemIds().size() + " messages</span>");
        }
    }

    protected boolean isDone() {
        boolean done = ExecutionStatus.isDone(statusLabel.getValue());
        if (done) {
            List<String> ids = stepContainer.gereplacedemIds();
            for (String id : ids) {
                ExecutionStep step = stepContainer.gereplacedem(id).getBean();
                if (!ExecutionStatus.isDone(step.getStatus())) {
                    done = false;
                }
            }
        }
        return done;
    }

    @SuppressWarnings("unchecked")
    protected void refreshUI(ExecutionData data) {
        if (!lastDataRefreshWasDone) {
            flowLabel.setValue(data.execution.getFlowName());
            startLabel.setValue(formatDate(data.execution.getStartTime()));
            if (data.execution.getStatus() != null) {
                if (data.execution.getStatus().equals(ExecutionStatus.ERROR.name())) {
                    statusLabel.setStyleName("error");
                    statusLabel.setValue(FontAwesome.WARNING.getHtml() + " " + data.execution.getStatus());
                } else if (data.execution.getStatus().equals(ExecutionStatus.DONE.name())) {
                    statusLabel.setStyleName("done");
                    statusLabel.setValue(FontAwesome.CHECK.getHtml() + " " + data.execution.getStatus());
                } else if (data.execution.getStatus().equals(ExecutionStatus.RUNNING.name())) {
                    statusLabel.setStyleName("running");
                    statusLabel.setValue(FontAwesome.SPINNER.getHtml() + " " + data.execution.getStatus());
                } else {
                    statusLabel.setStyleName("");
                    statusLabel.setValue(data.execution.getStatus());
                }
            }
            endLabel.setValue(formatDate(data.execution.getEndTime()));
            if (showDiagramCheckbox.getValue()) {
                redrawFlow();
            }
            String selected = (String) stepTable.getSelectedRow();
            if (stepContainer.size() != data.steps.size()) {
                stepContainer.removeAllItems();
                stepContainer.addAll(data.steps);
            } else {
                for (ExecutionStep step : data.steps) {
                    BeanItem<ExecutionStep> item = stepContainer.gereplacedem(step.getId());
                    item.gereplacedemProperty("status").setValue(step.getStatus());
                    item.gereplacedemProperty("payloadReceived").setValue(step.getPayloadReceived());
                    item.gereplacedemProperty("messagesReceived").setValue(step.getMessagesReceived());
                    item.gereplacedemProperty("messagesProduced").setValue(step.getMessagesProduced());
                    item.gereplacedemProperty("payloadProduced").setValue(step.getPayloadProduced());
                    item.gereplacedemProperty("endTime").setValue(step.getEndTime());
                    item.gereplacedemProperty("startTime").setValue(step.getStartTime());
                    item.gereplacedemProperty("handleDuration").setValue(step.getHandleDuration());
                    item.gereplacedemProperty("queueDuration").setValue(step.getQueueDuration());
                }
            }
            if (selected == null && data.steps.size() > 0) {
                stepTable.select(selected);
            }
            List<ExecutionStepLog> logMessages = new ArrayList<>(logContainer.gereplacedemIds());
            List<ExecutionStepLog> newLogMessages = new ArrayList<>(data.logs);
            for (ExecutionStepLog logMsg : logMessages) {
                newLogMessages.remove(logMsg);
            }
            if (newLogMessages.size() > 0) {
                logContainer.addAll(newLogMessages);
                if (lastSortOrder != null) {
                    logTable.setSortOrder(lastSortOrder);
                }
                updateStatus();
            }
            lastDataRefreshWasDone = isDone();
            rerunButton.setVisible(lastDataRefreshWasDone && flowRunnable != null);
            removeButton.setVisible(lastDataRefreshWasDone);
            cancelButton.setVisible(!lastDataRefreshWasDone);
        }
    }

    protected String formatDate(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aa");
        if (date != null) {
            return df.format(date);
        }
        return "";
    }

    public clreplaced ExecutionData {

        public Execution execution;

        public List<ExecutionStep> steps;

        public List<ExecutionStepLog> logs;

        ExecutionStep findExecutionStep(String id) {
            ExecutionStep executionStep = null;
            for (ExecutionStep s : steps) {
                if (s.getFlowStepId().equals(id)) {
                    executionStep = s;
                    break;
                }
            }
            return executionStep;
        }
    }

    public clreplaced ComponentNameColumnGenerator implements ColumnGenerator {

        private static final long serialVersionUID = 1L;

        @SuppressWarnings("unchecked")
        public Object generateCell(com.vaadin.v7.ui.Table source, Object itemId, Object columnId) {
            BeanItem<ExecutionStepLog> logItem = (BeanItem<ExecutionStepLog>) source.gereplacedem(itemId);
            String executionStepId = (String) logItem.gereplacedemProperty("executionStepId").getValue();
            BeanItem<ExecutionStep> stepItem = stepContainer.gereplacedem(executionStepId);
            return new Label((String) stepItem.gereplacedemProperty("componentName").getValue());
        }
    }
}

9 View Complete Implementation : CmsBeanTableBuilder.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Sets up a table and uses the given beans to fill its rows, but does not actually create the table instance; it uses the preplaceded in table instance instead.<p>
 *
 * @param table the table to set up
 * @param beans the beans to display in the table
 */
public void buildTable(Table table, List<T> beans) {
    BeanItemContainer<T> container = new BeanItemContainer<T>(m_clreplaced);
    List<String> visibleCols = Lists.newArrayList();
    for (ColumnBean column : m_columns) {
        String propName = column.getProperty().getName();
        String columnHeader = column.getInfo().header();
        String localizedHeader = CmsVaadinUtils.getMessageText(columnHeader);
        if (CmsMessages.isUnknownKey(localizedHeader)) {
            localizedHeader = columnHeader;
        }
        localizedHeader = m_macroResolver.resolveMacros(localizedHeader);
        table.setColumnHeader(propName, localizedHeader);
        if (Button.clreplaced.isreplacedignableFrom(column.getProperty().getPropertyType())) {
            table.setColumnAlignment(propName, Align.CENTER);
        }
        visibleCols.add(propName);
    }
    table.setContainerDataSource(container);
    table.setVisibleColumns(visibleCols.toArray());
    for (ColumnBean column : m_columns) {
        Column info = column.getInfo();
        String name = column.getProperty().getName();
        if (info.width() >= 0) {
            table.setColumnWidth(name, info.width());
        }
        if (info.expandRatio() >= 0) {
            table.setColumnExpandRatio(name, info.expandRatio());
        }
    }
    for (T bean : beans) {
        container.addBean(bean);
    }
}