com.vaadin.ui.ComboBox - java examples

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

102 Examples 7

19 View Complete Implementation : BaseDeploymentSpecWindow.java
Copyright Apache License 2.0
Author : opensecuritycontroller
private void populateNetworks(ComboBox networkComboBox, List<OsNetworkDto> networkList) {
    try {
        networkComboBox.removeAllItems();
        if (networkList != null) {
            // Calling List Network Service
            BeanItemContainer<OsNetworkDto> networkListContainer = new BeanItemContainer<>(OsNetworkDto.clreplaced, networkList);
            networkComboBox.setContainerDataSource(networkListContainer);
            networkComboBox.sereplacedemCaptionPropertyId("name");
            if (networkList.size() > 0) {
                networkComboBox.select(networkListContainer.getIdByIndex(0));
            }
        }
    } catch (Exception e) {
        ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
        log.error("Error getting Network List", e);
    }
}

19 View Complete Implementation : FormHelper.java
Copyright GNU General Public License v3.0
Author : rlsutton1
public ComboBox bindEnumField(String fieldLabel, String fieldName, Clreplaced<?> clazz) {
    ComboBox field = bindEnumField(form, group, fieldLabel, fieldName, clazz);
    this.fieldList.add(field);
    return field;
}

19 View Complete Implementation : FormUtils.java
Copyright Apache License 2.0
Author : chelu
public static ComboBox newComboBox(List<?> elements, String sortProperty, String caption) {
    Collections.sort(elements, new PropertyComparator(sortProperty));
    ComboBox combo = new ComboBox(caption);
    addItemList(combo, elements);
    return combo;
}

19 View Complete Implementation : ReportParameterEnum.java
Copyright GNU General Public License v3.0
Author : rlsutton1
public clreplaced ReportParameterEnum<T extends Enum<T>> extends ReportParameter<Enum<T>> {

    private ComboBox field;

    private Clreplaced<T> enumClreplaced;

    /**
     * @param caption
     * @param defaultValue
     * @param parameterName
     * @param enumClreplaced
     */
    public ReportParameterEnum(String caption, T defaultValue, String parameterName, Clreplaced<T> enumClreplaced) {
        super(caption, parameterName);
        field = new ComboBox(caption);
        this.enumClreplaced = enumClreplaced;
        field.setContainerDataSource(FormHelper.createContainerFromEnumClreplaced("value", enumClreplaced));
        field.setNewItemsAllowed(false);
        field.setNullSelectionAllowed(false);
        field.setTextInputAllowed(false);
        field.setValue(defaultValue);
    }

    @Override
    public String getValue(String parameterName) {
        return field.getValue().toString();
    }

    @Override
    public Component getComponent() {
        return field;
    }

    @Override
    public boolean shouldExpand() {
        return false;
    }

    @Override
    public void setDefaultValue(Enum<T> defaultValue) {
        field.setValue(defaultValue);
    }

    @Override
    public String getExpectedParameterClreplacedName() {
        return String.clreplaced.getCanonicalName();
    }

    @Override
    public String getDisplayValue(String parameterName) {
        return getValue(null);
    }

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

    @Override
    public void setValuereplacedtring(String value, String parameterName) {
        field.setValue(Enum.valueOf(enumClreplaced, value));
    }

    @Override
    public boolean isDateField() {
        return false;
    }

    @Override
    public DateParameterType getDateParameterType() {
        throw new RuntimeException("Not implemented");
    }

    @Override
    public String getSaveMetaData() {
        return "";
    }

    @Override
    public void applySaveMetaData(String metaData) {
    // NO OP
    }

    @Override
    public String getMetaDataComment() {
        return "";
    }
}

19 View Complete Implementation : MultiColumnFormLayout.java
Copyright GNU General Public License v3.0
Author : rlsutton1
public ComboBox bindComboBox(String fieldLabel, String fieldName, Collection<?> options) {
    ComboBox field = formHelper.bindComboBox(this, fieldName, fieldLabel, options);
    this.fieldList.add(field);
    return field;
}

19 View Complete Implementation : FormUtils.java
Copyright Apache License 2.0
Author : chelu
/**
 * Add a link on primary and dependent ComboBoxes by property name.
 * When selection changes on primary use propertyName to get a Collection and fill dependent ComboBox with it
 * @param primary ComboBox when selection changes
 * @param dependent ComboBox that are filled with collection
 * @param propertyName the property name for get the collection from primary selected item
 */
public static void link(final ComboBox primary, final ComboBox dependent, final String propertyName) {
    link(primary, dependent, propertyName, false);
}

19 View Complete Implementation : FormHelper.java
Copyright GNU General Public License v3.0
Author : rlsutton1
public <M> ComboBox bindEnumField(AbstractLayout form, ValidatingFieldGroup<E> group, String fieldLabel, SingularAttribute<E, M> member, Clreplaced<?> clazz) {
    ComboBox field = bindEnumField(form, group, fieldLabel, member.getName(), clazz);
    this.fieldList.add(field);
    return field;
}

19 View Complete Implementation : ComboBoxFieldBuilder.java
Copyright Apache License 2.0
Author : chelu
/**
 * {@inheritDoc}
 */
public Field<?> build(Clreplaced<?> clazz, String name) {
    ComboBox combo = new ComboBox();
    fillComboBox(combo, clazz, name);
    combo.sereplacedemCaptionMode(ItemCaptionMode.ID);
    return combo;
}

19 View Complete Implementation : MultiColumnFormLayout.java
Copyright GNU General Public License v3.0
Author : rlsutton1
/**
 * Deprecated - Use EnreplacedyFieldBuilder instead
 *
 * @param fieldLabel
 * @param fieldName
 * @param listClazz
 * @param listFieldName
 * @return
 */
@Deprecated
public <L extends CrudEnreplacedy> ComboBox bindEnreplacedyField(String fieldLabel, SingularAttribute<E, L> fieldName, Clreplaced<L> listClazz, SingularAttribute<L, ?> listFieldName) {
    ComboBox field = formHelper.bindEnreplacedyField(this, fieldGroup, fieldLabel, fieldName, listClazz, listFieldName);
    this.fieldList.add(field);
    return field;
}

19 View Complete Implementation : OldLoginView.java
Copyright GNU General Public License v3.0
Author : antoniomaria
private ComboBox createLanguageSelector() {
    ComboBox languageSelector = new ComboBox("com.vaadin.demo.dashboard.DashboardUI.Language");
    languageSelector.setImmediate(true);
    languageSelector.setNullSelectionAllowed(false);
    addLocale(Locale.ENGLISH, languageSelector);
    addLocale(Locale.FRENCH, languageSelector);
    addLocale(new Locale("es"), languageSelector);
    // languageSelector.setValue(I18NStaticService.getI18NServive().getLocale());
    /*-languageSelector.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                Locale locale = (Locale) (event.getProperty().getValue());
                I18NStaticService.getI18NServive().setLocale(locale);
                getUI().requestRepaintAll();
            }
        });*/
    return languageSelector;
}

19 View Complete Implementation : MultiColumnFormLayout.java
Copyright GNU General Public License v3.0
Author : rlsutton1
public <M> ComboBox bindEnumField(String fieldLabel, SingularAttribute<E, M> member, Clreplaced<?> clazz) {
    ComboBox field = formHelper.bindEnumField(this, fieldGroup, fieldLabel, member, clazz);
    this.fieldList.add(field);
    return field;
}

19 View Complete Implementation : MultiColumnFormLayout.java
Copyright GNU General Public License v3.0
Author : rlsutton1
// public ColorPickerField bindColorPicker(iColorFactory factory, String
// fieldLabel, SingularAttribute<E, iColor> member)
// {
// ColorPickerField field = formHelper.bindColorPickerField(this,
// fieldGroup, factory, fieldLabel, member);
// this.fieldList.add(field);
// return field;
// }
/**
 * Deprecated - Use EnreplacedyFieldBuilder instead
 *
 * @param fieldLabel
 * @param fieldName
 *            - name of primary enreplacedies member field that holds the foreign
 *            enreplacedy
 * @param listClazz
 *            - Clreplaced of the foreign enreplacedy
 * @param listFieldName
 *            - name of the field to display in the combo box from the
 *            foreign enreplacedy
 * @return
 */
@Deprecated
public <L extends CrudEnreplacedy> ComboBox bindEnreplacedyField(String fieldLabel, String fieldName, Clreplaced<L> listClazz, String listFieldName) {
    ComboBox field = formHelper.bindEnreplacedyField(this, fieldGroup, fieldLabel, fieldName, listClazz, listFieldName);
    this.fieldList.add(field);
    return field;
}

19 View Complete Implementation : BaseDeploymentSpecWindow.java
Copyright Apache License 2.0
Author : opensecuritycontroller
@Override
public void initForm() {
    this.form.addComponent(getName());
    this.form.addComponent(getProjects());
    this.form.addComponent(getRegion());
    this.form.addComponent(getUserOptions());
    this.form.addComponent(getOptionTable());
    List<ComboBox> networks = getNetworkComboBoxes();
    for (ComboBox combobox : networks) {
        this.form.addComponent(combobox);
    }
    this.form.addComponent(getIPPool());
    this.form.addComponent(getCount());
    this.form.addComponent(getSharedCheckBox());
    this.name.focus();
    getCount().setEnabled(false);
}

19 View Complete Implementation : MainApplicationUI.java
Copyright The Unlicense
Author : rolandkrueger
/**
 * Creates the ComboBox for selecting the current language.
 */
private ComboBox createLanguageSelector() {
    ComboBox languageSelector = new ComboBox();
    languageSelector.setContainerDataSource(getLanguageItems());
    languageSelector.sereplacedemCaptionPropertyId("caption");
    languageSelector.sereplacedemIconPropertyId("icon");
    languageSelector.setImmediate(true);
    languageSelector.setNullSelectionAllowed(false);
    languageSelector.addValueChangeListener(new Property.ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            Locale locale = (Locale) event.getProperty().getValue();
            if (locale.equals(currentLocale)) {
                return;
            }
            currentLocale = locale;
            buildMainLayout();
        }
    });
    languageSelector.select(currentLocale);
    return languageSelector;
}

19 View Complete Implementation : FormUtils.java
Copyright Apache License 2.0
Author : chelu
/**
 * Fill combo with a list of objects removing all items.
 *
 * @param data list to fill with.
 * @param clear true if clear all items before adding new ones.
 */
public static void fillCombo(ComboBox combo, List<?> data) {
    fillCombo(combo, data, true);
}

19 View Complete Implementation : FormUtils.java
Copyright Apache License 2.0
Author : chelu
/**
 * Add a link on primary and dependent ComboBoxes by property name.
 * When selection changes on primary use propertyName to get a Collection and fill dependent ComboBox with it
 * @param primary ComboBox when selection changes
 * @param dependent ComboBox that are filled with collection
 * @param propertyName the property name for get the collection from primary selected item
 * @param addNull if true, add a null as first combobox item
 */
@SuppressWarnings("rawtypes")
public static void link(final ComboBox primary, final ComboBox dependent, final String propertyName, final boolean addNull) {
    primary.addValueChangeListener(new ValueChangeListener() {

        public void valueChange(ValueChangeEvent event) {
            Object selected = event.getProperty().getValue();
            if (selected != null) {
                BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(selected);
                if (wrapper.isReadableProperty(propertyName)) {
                    Collection items = (Collection) wrapper.getPropertyValue(propertyName);
                    dependent.removeAllItems();
                    if (addNull)
                        dependent.addItem(null);
                    for (Object item : items) dependent.addItem(item);
                } else {
                    log.error("Can't write on propety '" + propertyName + "' of clreplaced: '" + selected.getClreplaced() + "'");
                }
            }
        }
    });
}

19 View Complete Implementation : TimeZoneSelectionField.java
Copyright GNU Affero General Public License v3.0
Author : MyCollab
/**
 * @author MyCollab Ltd.
 * @since 1.0
 */
public clreplaced TimeZoneSelectionField extends CustomField<String> {

    private boolean isVerticalDisplay;

    private StringValueComboBox areaSelection;

    private ComboBox<TimezoneVal> timezoneSelection;

    public TimeZoneSelectionField(boolean isVerticalDisplay) {
        this.isVerticalDisplay = isVerticalDisplay;
        areaSelection = new StringValueComboBox(false, TimezoneVal.getAreas());
        areaSelection.addValueChangeListener((ValueChangeListener) event -> setCboTimeZone(areaSelection.getValue()));
        timezoneSelection = new ComboBox<>();
        timezoneSelection.setWidth(WebThemes.FORM_CONTROL_WIDTH);
        String area = areaSelection.getSelectedItem().orElse(null);
        areaSelection.setValue(area);
        setCboTimeZone(area);
        doSetValue(ZoneId.systemDefault().getId());
    }

    @Override
    protected Component initContent() {
        return (isVerticalDisplay) ? new MVerticalLayout(areaSelection, timezoneSelection).withMargin(false) : new MHorizontalLayout(areaSelection, timezoneSelection);
    }

    private void setCboTimeZone(String area) {
        Collection<TimezoneVal> timeZones = TimezoneVal.getTimezoneInAreas(area);
        timezoneSelection.sereplacedems(timeZones);
        timezoneSelection.sereplacedemCaptionGenerator((ItemCaptionGenerator<TimezoneVal>) timezone -> timezone.getDisplayName());
    }

    @Override
    public String getValue() {
        TimezoneVal value = timezoneSelection.getValue();
        return (value != null) ? value.getId() : null;
    }

    @Override
    protected void doSetValue(String zoneId) {
        TimezoneVal tzVal = new TimezoneVal(zoneId);
        areaSelection.setValue(tzVal.getArea());
        timezoneSelection.setValue(tzVal);
    }
}

19 View Complete Implementation : MultiColumnFormLayout.java
Copyright GNU General Public License v3.0
Author : rlsutton1
public ComboBox bindEnumField(String fieldLabel, String fieldName, Clreplaced<?> clazz) {
    ComboBox field = formHelper.bindEnumField(this, fieldGroup, fieldLabel, fieldName, clazz);
    this.fieldList.add(field);
    return field;
}

18 View Complete Implementation : EmailTargetLine.java
Copyright GNU General Public License v3.0
Author : rlsutton1
clreplaced EmailTargetLine {

    ComboBox targetTypeCombo;

    ComboBox targetAddress;

    Button actionButton;

    public int row;
}

18 View Complete Implementation : OldLoginView.java
Copyright GNU General Public License v3.0
Author : antoniomaria
private void addLocale(Locale locale, ComboBox languageSelector) {
    languageSelector.addItem(locale);
    languageSelector.sereplacedemCaption(locale, "XX");
}

18 View Complete Implementation : RangeEditorComponent.java
Copyright Apache License 2.0
Author : apache
private void setupComboText(final ComboBox box, final TextField text) {
    // 
    // Respond to combo changes
    // 
    box.addValueChangeListener(new ValueChangeListener() {

        private static final long serialVersionUID = 1L;

        @Override
        public void valueChange(ValueChangeEvent event) {
            // 
            // Get the new value
            // 
            String property = (String) box.getValue();
            // 
            // Get our constraint object
            // 
            ConstraintValue value = (ConstraintValue) box.getData();
            // 
            // Update our object
            // 
            if (property == null) {
                // 
                // Clear the text field and disable it
                // 
                text.setEnabled(false);
                text.setValue(null);
            } else {
                // 
                // Change the property name
                // 
                value.setProperty(property);
                // 
                // Focus to the text field and enable it
                // 
                text.setEnabled(true);
                text.focus();
            }
        }
    });
}

18 View Complete Implementation : MainView.java
Copyright GNU General Public License v3.0
Author : AskNowQA
@SuppressWarnings("serial")
public clreplaced MainView extends VerticalLayout implements ViewContainer, TBSLProgressListener {

    private static final int REFRESH_INTERVAL = 1000;

    private VerticalLayout mainPanel;

    private View currentView;

    private Embedded knowledgebaseLogo;

    private NativeSelect tbslSelector;

    private NativeButton executeButton;

    // private TextField questionField;
    private ComboBox questionBox;

    private VerticalLayout resultHolderPanel;

    private Table resultTable;

    private ComboBox propertySelector;

    private HorizontalLayout feedbackPanel;

    private Label feedbackLabel;

    private NativeButton wrongSolutionButton;

    private boolean executing = false;

    private Answer answer;

    private Refresher refresher;

    private Button refineButton;

    private List<Object> positiveMarkedRows;

    private List<Object> negativeMarkedRows;

    VerticalLayout l;

    public MainView() {
        setSizeFull();
        // createHeader();
        createMainPanel();
        // createFooter();
        reset();
        UserSession.getManager().setProgressListener(this);
        refresher = new Refresher();
        refresher.setRefreshInterval(REFRESH_INTERVAL);
        refresher.setEnabled(false);
        refresher.addListener(new RefreshListener() {

            @Override
            public void refresh(Refresher source) {
                if (!executing) {
                    // stop polling
                    source.setEnabled(false);
                    executeButton.setEnabled(true);
                    showAnswer(answer);
                }
            }
        });
        addComponent(refresher);
    }

    @Override
    public void attach() {
        createFooter();
    }

    public void initWithParams(String endpoint, String question) {
        System.out.println("init with params");
        if (endpoint.equals("dbpedia")) {
            tbslSelector.select(TbslDbpedia.INSTANCE);
        } else if (endpoint.equals("oxford")) {
            tbslSelector.select(TbslOxford.INSTANCE);
            // }
            questionBox.addItem(question);
            questionBox.setValue(question);
            onExecuteQuery();
        }
    }

    private void createHeader() {
        HorizontalLayout header = new HorizontalLayout();
        header.addStyleName("header");
        header.setWidth("100%");
        header.setHeight(null);
        addComponent(header);
        Resource res = new ThemeResource("images/sparql2nl_logo.gif");
        Label pad = new Label();
        pad.setWidth("100%");
        pad.setIcon(res);
        pad.addStyleName("blub");
    // header.addComponent(pad);
    // header.setExpandRatio(pad, 1f);
    }

    private void createFooter() {
        try {
            CustomLayout footer = new CustomLayout(this.getClreplaced().getClreplacedLoader().getResourcereplacedtream("footer.html"));
            footer.addStyleName("footer");
            footer.setWidth("100%");
            footer.setHeight(null);
            addComponent(footer);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void createMainPanel() {
        mainPanel = new VerticalLayout();
        mainPanel.setSpacing(true);
        mainPanel.setSizeFull();
        addComponent(mainPanel);
        setExpandRatio(mainPanel, 1f);
        // top part
        Component inputForm = createInputComponent();
        inputForm.setWidth("60%");
        inputForm.setHeight("100%");
        VerticalLayout inputFormHolder = new VerticalLayout();
        inputFormHolder.addStyleName("input-form");
        inputFormHolder.setHeight(null);
        inputFormHolder.setWidth("100%");
        inputFormHolder.addComponent(inputForm);
        inputFormHolder.setComponentAlignment(inputForm, Alignment.MIDDLE_CENTER);
        mainPanel.addComponent(inputFormHolder);
        mainPanel.setComponentAlignment(inputFormHolder, Alignment.MIDDLE_CENTER);
        // middle part
        resultHolderPanel = new VerticalLayout();
        resultHolderPanel.setWidth("80%");
        resultHolderPanel.setHeight("100%");
        mainPanel.addComponent(resultHolderPanel);
        mainPanel.setComponentAlignment(resultHolderPanel, Alignment.MIDDLE_CENTER);
        mainPanel.setExpandRatio(resultHolderPanel, 0.8f);
        // refine button, only visible if constraints running QTL algorithm are satisfied
        refineButton = new Button("Refine");
        refineButton.setVisible(false);
        refineButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                onRefineResult();
            }
        });
        mainPanel.addComponent(refineButton);
        mainPanel.setComponentAlignment(refineButton, Alignment.MIDDLE_CENTER);
    }

    private Component createInputComponent() {
        HorizontalLayout l = new HorizontalLayout();
        l.setSpacing(true);
        Component kbSelector = createSelectTBSLComponent();
        kbSelector.setWidth("150px");
        kbSelector.setHeight("100px");
        l.addComponent(kbSelector);
        VerticalLayout right = new VerticalLayout();
        right.setSizeFull();
        right.setHeight("100px");
        right.setSpacing(true);
        l.addComponent(right);
        l.setExpandRatio(right, 1f);
        HorizontalLayout rightTop = new HorizontalLayout();
        rightTop.setSpacing(true);
        rightTop.setHeight(null);
        rightTop.setWidth("100%");
        right.addComponent(rightTop);
        questionBox = new ComboBox();
        questionBox.setWidth("100%");
        questionBox.setHeight(null);
        questionBox.setImmediate(true);
        questionBox.setNewItemsAllowed(true);
        questionBox.setInputPrompt("Enter your question.");
        questionBox.addListener(new Property.ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                onExecuteQuery();
            }
        });
        questionBox.addShortcutListener(new ShortcutListener("run", ShortcutAction.KeyCode.ENTER, null) {

            @Override
            public void handleAction(Object sender, Object target) {
                onExecuteQuery();
            }
        });
        rightTop.addComponent(questionBox);
        rightTop.setExpandRatio(questionBox, 1f);
        addExampleQuestions();
        executeButton = new NativeButton("Run");
        executeButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                onExecuteQuery();
            }
        });
        rightTop.addComponent(executeButton);
        Component feedbackComponent = createFeedbackComponent();
        right.addComponent(feedbackComponent);
        right.setExpandRatio(feedbackComponent, 1f);
        right.setComponentAlignment(feedbackComponent, Alignment.MIDDLE_CENTER);
        return l;
    }

    private Component createFeedbackComponent() {
        feedbackPanel = new HorizontalLayout();
        feedbackPanel.setSpacing(true);
        feedbackPanel.setSizeFull();
        feedbackPanel.addStyleName("white-border");
        feedbackPanel.addStyleName("shadow-label");
        feedbackPanel.setWidth("95%");
        feedbackPanel.setHeight("80%");
        feedbackPanel.setVisible(false);
        feedbackLabel = new Label(" ", Label.CONTENT_XHTML);
        feedbackLabel.setContentMode(Label.CONTENT_XHTML);
        feedbackLabel.addStyleName("status-label");
        feedbackLabel.setSizeFull();
        feedbackPanel.addComponent(feedbackLabel);
        feedbackPanel.setExpandRatio(feedbackLabel, 1f);
        feedbackPanel.setComponentAlignment(feedbackLabel, Alignment.MIDDLE_CENTER);
        wrongSolutionButton = new NativeButton("Wrong!");
        wrongSolutionButton.setWidth("60px");
        wrongSolutionButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                Window otherSolutionsWindow = createOtherSolutionsWindow();
                getApplication().getMainWindow().addWindow(otherSolutionsWindow);
            }
        });
        wrongSolutionButton.addStyleName("shift-left");
        // wrongSolutionButton.setVisible(false);
        // feedbackPanel.addComponent(wrongSolutionButton);
        // feedbackPanel.setComponentAlignment(wrongSolutionButton, Alignment.MIDDLE_CENTER);
        return feedbackPanel;
    }

    private Window createOtherSolutionsWindow() {
        final Window otherSolutionsWindow = new Window();
        otherSolutionsWindow.setWidth("700px");
        otherSolutionsWindow.setHeight("700px");
        otherSolutionsWindow.addListener(new Window.CloseListener() {

            @Override
            public void windowClose(CloseEvent e) {
                MainView.this.getApplication().getMainWindow().removeWindow(otherSolutionsWindow);
            }
        });
        VerticalLayout content = new VerticalLayout();
        content.setSizeFull();
        content.setSpacing(true);
        otherSolutionsWindow.setContent(content);
        Label label = new Label("Did you mean?");
        label.setHeight(null);
        label.addStyleName("did-you-mean-header");
        content.addComponent(label);
        final List<Entry<String, String>> otherSolutions = UserSession.getManager().getMoreSolutions();
        final Table table = new Table();
        table.setSizeFull();
        table.setImmediate(true);
        table.addContainerProperty("solution", Label.clreplaced, null);
        table.setColumnHeaderMode(Table.COLUMN_HEADER_MODE_HIDDEN);
        content.addComponent(table);
        content.setExpandRatio(table, 1f);
        Item item;
        for (Entry<String, String> sol : otherSolutions) {
            item = table.addItem(sol);
            item.gereplacedemProperty("solution").setValue(sol);
        }
        table.addGeneratedColumn("solution", new ColumnGenerator() {

            @Override
            public Component generateCell(Table source, final Object itemId, Object columnId) {
                final Entry<String, String> entry = (Entry<String, String>) itemId;
                HorizontalLayout c = new HorizontalLayout();
                c.setHeight("30px");
                c.setWidth(null);
                c.addStyleName("tweet");
                VerticalLayout buttons = new VerticalLayout();
                buttons.setHeight("100%");
                buttons.addStyleName("buttons");
                Button posExampleButton = new Button();
                posExampleButton.setIcon(new ThemeResource("images/thumb_up.png"));
                posExampleButton.addStyleName(BaseTheme.BUTTON_LINK);
                posExampleButton.setDescription("Click if this is what you intended.");
                posExampleButton.addListener(new Button.ClickListener() {

                    @Override
                    public void buttonClick(ClickEvent event) {
                        MainView.this.getApplication().getMainWindow().removeWindow(otherSolutionsWindow);
                        Answer newAnswer = UserSession.getManager().createAnswer(entry.getKey());
                        resultHolderPanel.removeAllComponents();
                        showAnswer(newAnswer);
                    }
                });
                buttons.addComponent(posExampleButton);
                c.addComponent(buttons);
                Label solutionLabel = new Label(entry.getValue());
                solutionLabel.addStyleName("other-solution-label");
                c.addComponent(solutionLabel);
                return c;
            }
        });
        // more button
        final Button moreButton = new Button("More");
        moreButton.setHeight(null);
        moreButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                List<Entry<String, String>> moreOtherSolutions = UserSession.getManager().getMoreSolutions(otherSolutions.size() + 1);
                if (moreOtherSolutions.size() < 10) {
                    moreButton.setEnabled(false);
                }
                Item item;
                for (Entry<String, String> sol : moreOtherSolutions) {
                    item = table.addItem(sol);
                    item.gereplacedemProperty("solution").setValue(sol);
                }
                otherSolutions.addAll(moreOtherSolutions);
            }
        });
        content.addComponent(moreButton);
        content.setComponentAlignment(moreButton, Alignment.MIDDLE_CENTER);
        return otherSolutionsWindow;
    }

    private Component createSelectTBSLComponent() {
        l = new VerticalLayout();
        l.setSpacing(true);
        l.setSizeFull();
        IndexedContainer ic = new IndexedContainer();
        ic.addContainerProperty("label", String.clreplaced, null);
        for (ExtendedTBSL tbsl : UserSession.getManager().tbsls) {
            ic.addItem(tbsl).gereplacedemProperty("label").setValue(tbsl.getLabel());
        }
        tbslSelector = new NativeSelect();
        tbslSelector.addStyleName("borderless");
        tbslSelector.setWidth("100%");
        tbslSelector.setHeight(null);
        tbslSelector.setNullSelectionAllowed(false);
        tbslSelector.setContainerDataSource(ic);
        tbslSelector.setImmediate(true);
        tbslSelector.addListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                onChangeKnowledgebase();
            }
        });
        l.addComponent(tbslSelector);
        knowledgebaseLogo = new Embedded("");
        knowledgebaseLogo.setType(Embedded.TYPE_IMAGE);
        knowledgebaseLogo.setHeight("50px");
        l.addComponent(knowledgebaseLogo);
        l.setComponentAlignment(knowledgebaseLogo, Alignment.MIDDLE_CENTER);
        l.setExpandRatio(knowledgebaseLogo, 1f);
        return l;
    }

    private void addExampleQuestions() {
        questionBox.removeAllItems();
        List<String> exampleQuestions = UserSession.getManager().getActiveTBSL().getExampleQuestions();
        for (String question : exampleQuestions) {
            questionBox.addItem(question);
        }
    }

    public void reset() {
        tbslSelector.setValue(UserSession.getManager().getActiveTBSL());
    }

    private void onChangeKnowledgebase() {
        ExtendedTBSL ekb = (ExtendedTBSL) tbslSelector.getValue();
        if (ekb.getIcon() != null) {
            knowledgebaseLogo.setSource(ekb.getIcon());
            knowledgebaseLogo.setDescription(ekb.getTBSL().getKnowledgebase().getDescription());
        }
        UserSession.getManager().setKnowledgebase(ekb);
        addExampleQuestions();
    }

    private void onExecuteQuery() {
        resultHolderPanel.removeAllComponents();
        final String question = (String) questionBox.getValue();
        if (question != null) {
            executeButton.setEnabled(false);
            resetFeedback();
            showFeedback(true);
            final TBSLManager man = UserSession.getManager();
            executing = true;
            refresher.setEnabled(true);
            new Thread(new Runnable() {

                @Override
                public void run() {
                    answer = man.answerQuestion(question);
                    executing = false;
                }
            }).start();
        }
    // showAnswer(answer);
    }

    private void onAddTableColumn(final String propertyURI) {
        // UserSession.getManager().fillItems(propertyURI);
        Object[] visibleColumnsArray = resultTable.getVisibleColumns();
        List<Object> visibleColumns;
        if (visibleColumnsArray == null) {
            visibleColumns = new ArrayList<Object>();
            visibleColumns.add("object");
        } else {
            visibleColumns = new ArrayList<Object>(Arrays.asList(visibleColumnsArray));
        }
        resultTable.addContainerProperty(propertyURI, Object.clreplaced, null);
        for (Object itemId : resultTable.gereplacedemIds()) {
            resultTable.gereplacedem(itemId).gereplacedemProperty(propertyURI).setValue(((BasicResulreplacedem) itemId).getValue(propertyURI));
        }
        final boolean isDataProperty = UserSession.getManager().isDataProperty(propertyURI);
        // if(!UserSession.getManager().isDataProperty(propertyURI)){
        resultTable.addGeneratedColumn(propertyURI, new Table.ColumnGenerator() {

            public Component generateCell(Table source, Object itemId, Object columnId) {
                String html = "";
                BasicResulreplacedem item = (BasicResulreplacedem) itemId;
                Set<Object> dataValues = (Set<Object>) item.getData().get(propertyURI);
                if (dataValues != null) {
                    for (Object value : dataValues) {
                        if (isDataProperty) {
                            html += value.toString();
                        } else {
                            String uri = (String) value;
                            html += "<a href=\"" + uri + "\" target=\"_blank\">" + Labels.getLabelForResource(uri) + "</a>";
                        }
                        html += "<br>";
                    }
                    Label content = new Label(html, Label.CONTENT_XHTML);
                    content.setHeight("180px");
                    return content;
                }
                return null;
            }
        });
        resultTable.setColumnWidth(propertyURI, -1);
        // }
        resultTable.setColumnHeader(propertyURI, Labels.getLabel(propertyURI) + (isDataProperty ? " \u2599" : ""));
        visibleColumns.add(propertyURI);
        resultTable.setVisibleColumns(visibleColumns.toArray());
        if (propertySelector != null) {
            propertySelector.removeItem(propertyURI);
            propertySelector.setValue(null);
        }
    }

    @Override
    public void activate(View view) {
        mainPanel.replaceComponent((Component) currentView, (Component) view);
        currentView = view;
        mainPanel.setExpandRatio((Component) currentView, 1f);
    }

    @Override
    public void deactivate(View view) {
    // TODO Auto-generated method stub
    }

    @Override
    public void message(String message) {
        feedbackLabel.setValue("<div>" + message + "</div>");
    }

    @Override
    public void finished(Answer answer) {
        this.answer = answer;
        executing = false;
    }

    private void showTable(List<BasicResulreplacedem> result, List<String> prominentProperties, Map<String, Integer> additionalProperties) {
        resultTable = new Table();
        resultTable.setSizeFull();
        resultTable.setHeight("100%");
        resultTable.setImmediate(true);
        resultTable.setColumnCollapsingAllowed(true);
        resultTable.setColumnReorderingAllowed(true);
        resultTable.addContainerProperty("uri", Label.clreplaced, null);
        resultTable.addContainerProperty("label", String.clreplaced, null);
        resultTable.addContainerProperty("description", String.clreplaced, null);
        resultTable.addContainerProperty("image", String.clreplaced, null);
        Item tabItem;
        for (BasicResulreplacedem item : result) {
            // resultTable.addItem(
            // new Object[] { item.getUri(), item.getLabel(), item.getDescription(),
            // item.getImageURL() }, item);
            tabItem = resultTable.addItem(item);
            tabItem.gereplacedemProperty("uri").setValue(item.getUri());
            tabItem.gereplacedemProperty("label").setValue(item.getLabel());
            tabItem.gereplacedemProperty("description").setValue(item.getDescription());
            tabItem.gereplacedemProperty("image").setValue(item.getImageURL());
            if (item.getData() != null) {
                for (Entry<String, Object> entry : item.getData().entrySet()) {
                    if (entry.getValue() != null) {
                        resultTable.addContainerProperty(entry.getKey(), entry.getValue().getClreplaced(), null);
                        tabItem.gereplacedemProperty(entry.getKey()).setValue(entry.getValue());
                    }
                }
            }
        }
        if (additionalProperties.isEmpty()) {
            resultTable.setColumnHeaderMode(Table.COLUMN_HEADER_MODE_HIDDEN);
        }
        positiveMarkedRows = new ArrayList<Object>();
        negativeMarkedRows = new ArrayList<Object>();
        final CellStyleGenerator styleGen = new Table.CellStyleGenerator() {

            public String getStyle(Object itemId, Object propertyId) {
                for (Object row : positiveMarkedRows) {
                    if (row.equals(itemId)) {
                        return "green";
                    }
                }
                for (Object row : negativeMarkedRows) {
                    if (row.equals(itemId)) {
                        return "red";
                    }
                }
                return null;
            }
        };
        resultTable.setCellStyleGenerator(styleGen);
        resultTable.addGeneratedColumn("object", new ColumnGenerator() {

            @Override
            public Component generateCell(Table source, final Object itemId, Object columnId) {
                BasicResulreplacedem item = (BasicResulreplacedem) itemId;
                ExtendedTBSL ekb = UserSession.getManager().getActiveTBSL();
                HorizontalLayout c = null;
                try {
                    c = (HorizontalLayout) ekb.getInfoBoxClreplaced().getConstructor(BasicResulreplacedem.clreplaced).newInstance(item);
                    ((InfoLabel) c).addFeedBackListener(new FeedBackListener() {

                        @Override
                        public void positiveExampleSelected(BasicResulreplacedem item) {
                            if (positiveMarkedRows.contains(item)) {
                                positiveMarkedRows.remove(item);
                            } else {
                                negativeMarkedRows.remove(item);
                                positiveMarkedRows.add(itemId);
                            }
                            resultTable.setCellStyleGenerator(styleGen);
                            enableRefinement(positiveMarkedRows.size() >= 3);
                        }

                        @Override
                        public void negativeExampleSelected(BasicResulreplacedem item) {
                            if (negativeMarkedRows.contains(item)) {
                                negativeMarkedRows.remove(item);
                            } else {
                                positiveMarkedRows.remove(item);
                                negativeMarkedRows.add(itemId);
                            }
                            resultTable.setCellStyleGenerator(styleGen);
                        }
                    });
                    c.setHeight("180px");
                    c.setWidth(null);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                }
                return c;
            }
        });
        List<Object> visibleColumns = new ArrayList<Object>();
        visibleColumns.add("object");
        // 
        resultTable.setColumnHeader("object", "");
        resultTable.setVisibleColumns(visibleColumns.toArray());
        resultTable.setColumnWidth("object", -1);
        for (String prominentProperty : prominentProperties) {
            onAddTableColumn(prominentProperty);
        }
        PortalLayout pl = new PortalLayout();
        pl.addComponent(resultTable);
        pl.setClosable(resultTable, false);
        pl.setCollapsible(resultTable, false);
        pl.setSizeFull();
        HorizontalLayout header = new HorizontalLayout();
        header.setSizeUndefined();
        header.setSpacing(true);
        pl.setHeaderComponent(resultTable, header);
        List<String> existingProperties = new ArrayList<String>(prominentProperties);
        existingProperties.addAll(additionalProperties.keySet());
        if (canShowMap(existingProperties)) {
            NativeButton showMapButton = new NativeButton();
            showMapButton.addStyleName("borderless");
            showMapButton.addStyleName("map-button");
            Resource icon = new ThemeResource("images/map2.png");
            // showMapButton.setIcon(icon);
            showMapButton.setDescription("Show in map.");
            showMapButton.setHeight("100%");
            showMapButton.addListener(new Button.ClickListener() {

                @Override
                public void buttonClick(ClickEvent event) {
                    onShowMap();
                }
            });
            header.addComponent(showMapButton);
        }
        if (!additionalProperties.isEmpty()) {
            Label l = new Label("Show also ");
            l.setHeight("100%");
            l.addStyleName("white-font");
            propertySelector = new ComboBox();
            final IndexedContainer ic = new IndexedContainer();
            ic.addContainerProperty("label", String.clreplaced, null);
            for (Entry<String, Integer> entry : additionalProperties.entrySet()) {
                String propertyURI = entry.getKey();
                ic.addItem(propertyURI).gereplacedemProperty("label").setValue(Labels.getLabel(propertyURI));
            }
            propertySelector.setContainerDataSource(ic);
            propertySelector.setWidth("200px");
            propertySelector.sereplacedemCaptionPropertyId("label");
            propertySelector.setFilteringMode(Filtering.FILTERINGMODE_STARTSWITH);
            propertySelector.setImmediate(true);
            propertySelector.addListener(new Property.ValueChangeListener() {

                @Override
                public void valueChange(ValueChangeEvent event) {
                    String propertyURI = event.getProperty().toString();
                    if (propertyURI != null) {
                        UserSession.getManager().fillItems(propertyURI);
                        onAddTableColumn(propertyURI);
                    }
                }
            });
            header.addComponent(l);
            header.addComponent(propertySelector);
            header.setSpacing(true);
            header.setComponentAlignment(propertySelector, Alignment.MIDDLE_LEFT);
        } else if (UserSession.getManager().activeTBSL == ExtendedTBSL.DBPEDIA) {
            Label l = new Label("Sort by ");
            l.setHeight("100%");
            l.addStyleName("white-font");
            NativeSelect sortSelector = new NativeSelect();
            sortSelector.setImmediate(true);
            sortSelector.addContainerProperty("label", String.clreplaced, null);
            sortSelector.sereplacedemCaptionPropertyId("label");
            for (SortProperty sort : SortProperty.values()) {
                sortSelector.addItem(sort).gereplacedemProperty("label").setValue(sort.getLabel());
            }
            sortSelector.addListener(new Property.ValueChangeListener() {

                @Override
                public void valueChange(ValueChangeEvent event) {
                    SortProperty sortProp = (SortProperty) event.getProperty().getValue();
                    resultTable.sort(new Object[] { sortProp.getId() }, new boolean[] { sortProp.isAscending() });
                }
            });
            NativeButton showDiagramButton = new NativeButton();
            showDiagramButton.addStyleName("borderless");
            showDiagramButton.setHeight("100%");
            showDiagramButton.addStyleName("diagram-button");
            // showDiagramButton.setIcon(new ThemeResource("images/diagram.png"));
            showDiagramButton.setDescription("Visualize price.");
            showDiagramButton.addListener(new Button.ClickListener() {

                @Override
                public void buttonClick(ClickEvent event) {
                    onShowChart("http://diadem.cs.ox.ac.uk/ontologies/real-estate#hasPrice");
                }
            });
            header.addComponent(showDiagramButton);
            header.addComponent(l);
            header.addComponent(sortSelector);
            header.setSpacing(true);
            header.setComponentAlignment(sortSelector, Alignment.MIDDLE_LEFT);
        }
        resultTable.addListener(new Table.HeaderClickListener() {

            private static final long serialVersionUID = 2927158541717666732L;

            public void headerClick(HeaderClickEvent event) {
                String column = (String) event.getPropertyId();
                System.out.println(column);
                onShowChart(column);
            }
        });
        resultHolderPanel.addComponent(pl);
    }

    private boolean canShowMap(List<String> existingProperties) {
        return UserSession.getManager().activeTBSL == ExtendedTBSL.DBPEDIA || (existingProperties.contains("http://www.w3.org/2003/01/geo/wgs84_pos#lat") && existingProperties.contains("http://www.w3.org/2003/01/geo/wgs84_pos#long"));
    }

    private void onShowMap() {
        String queryString = UserSession.getManager().getLearnedSPARQLQuery();
        Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
        query = JENAUtils.writeOutPrefixes(query);
        String targetVar = query.getProjectVars().get(0).getVarName();
        Knowledgebase kb = UserSession.getManager().getActiveTBSL().getTBSL().getKnowledgebase();
        if (kb instanceof LocalKnowledgebase) {
            return;
        }
        String serviceURI = ((RemoteKnowledgebase) kb).getEndpoint().getURL().toString();
        String url = "";
        try {
            url = Manager.getInstance().getSemMapURL() + "?query=" + URLEncoder.encode(query.toString().replaceAll("[\n\r]", " "), "UTF-8") + "&var=" + targetVar + "&service-uri=" + EscapeUtils.encodeURIComponent(serviceURI);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println(url);
        Embedded e = new Embedded("", new ExternalResource(url));
        e.setAlternateText("Linked Geo Data View");
        e.setType(Embedded.TYPE_BROWSER);
        e.setSizeFull();
        final Window w = new Window("Linked Geo Data View");
        VerticalLayout mainLayout = new VerticalLayout();
        mainLayout.setSizeFull();
        w.setContent(mainLayout);
        w.setHeight("95%");
        w.setWidth("95%");
        w.center();
        mainLayout.addComponent(e);
        w.addListener(new Window.CloseListener() {

            @Override
            public void windowClose(CloseEvent e) {
                MainView.this.getApplication().getMainWindow().removeWindow(w);
            }
        });
        getApplication().getMainWindow().addWindow(w);
    }

    private void onShowChart(String propertyURI) {
        Map<String, Set<Object>> data = UserSession.getManager().getDataForProperty(propertyURI);
        XSDDatatype datatype = UserSession.getManager().getDatatype(propertyURI);
        Map<String, String> uri2Label = new HashMap<String, String>();
        for (Entry<String, BasicResulreplacedem> entry : UserSession.getManager().getUri2Items().entrySet()) {
            uri2Label.put(entry.getKey(), entry.getValue().getLabel());
        }
        final Window w;
        if (propertyURI.equals("http://diadem.cs.ox.ac.uk/ontologies/real-estate#hasPrice")) {
            w = new OxfordPriceChartWindow(UserSession.getManager().getCurrentQuestion(), propertyURI, uri2Label, data);
        } else {
            w = Charts.getChart(UserSession.getManager().getCurrentQuestion(), propertyURI, datatype, uri2Label, data);
        }
        if (w != null) {
            w.addListener(new Window.CloseListener() {

                @Override
                public void windowClose(CloseEvent e) {
                    MainView.this.getApplication().getMainWindow().removeWindow(w);
                }
            });
            getApplication().getMainWindow().addWindow(w);
        }
    }

    private void showAnswer(Answer answer) {
        if (!answer.isBoolean()) {
            SelectAnswer sAnswer = (SelectAnswer) answer;
            List<BasicResulreplacedem> result = sAnswer.gereplacedems();
            List<String> prominentProperties = sAnswer.getProminentProperties();
            Map<String, Integer> additionalProperties = sAnswer.getAdditionalProperties();
            // show the result in a table
            showTable(result, prominentProperties, additionalProperties);
        } else {
        // TODO show boolean answer
        }
    }

    private void enableRefinement(boolean enabled) {
        refineButton.setVisible(enabled);
    }

    private void onRefineResult() {
        List<String> posExamples = new ArrayList<String>();
        for (Object row : positiveMarkedRows) {
            posExamples.add(((BasicResulreplacedem) row).getUri());
        }
        List<String> negExamples = new ArrayList<String>();
        for (Object row : negativeMarkedRows) {
            negExamples.add(((BasicResulreplacedem) row).getUri());
        }
        Refinement refinement = UserSession.getManager().refine(posExamples, negExamples);
        if (refinement != null) {
            resultHolderPanel.removeAllComponents();
            showAnswer(refinement.getRefinedAnswer());
        } else {
        // TODO show message that refinement failed
        }
    }

    @Override
    public void foundAnswer(boolean answerFound) {
        if (answerFound) {
            // wrongSolutionButton.setVisible(true);
            feedbackPanel.addComponent(wrongSolutionButton);
            feedbackPanel.setComponentAlignment(wrongSolutionButton, Alignment.MIDDLE_CENTER);
        }
    }

    private void showFeedback(boolean show) {
        feedbackPanel.setVisible(show);
    }

    private void resetFeedback() {
        feedbackLabel.setValue(" ");
        feedbackPanel.removeComponent(wrongSolutionButton);
    }
}

18 View Complete Implementation : SettingsWindow.java
Copyright Apache License 2.0
Author : cuba-platform
@Override
public void init(Map<String, Object> params) {
    Boolean changeThemeEnabledParam = (Boolean) params.get("changeThemeEnabled");
    if (changeThemeEnabledParam != null) {
        changeThemeEnabled = changeThemeEnabledParam;
    }
    AppWorkArea.Mode mode = userSettingsTools.loadAppWindowMode();
    msgTabbed = getMessage("modeTabbed");
    msgSingle = getMessage("modeSingle");
    modeOptions.setOptionsList(Arrays.asList(msgTabbed, msgSingle));
    if (mode == AppWorkArea.Mode.TABBED)
        modeOptions.setValue(msgTabbed);
    else
        modeOptions.setValue(msgSingle);
    ThemeConstantsRepository themeRepository = AppBeans.get(ThemeConstantsRepository.NAME);
    Set<String> supportedThemes = themeRepository.getAvailableThemes();
    appThemeField.setOptionsList(new ArrayList<>(supportedThemes));
    String userAppTheme = userSettingsTools.loadAppWindowTheme();
    appThemeField.setValue(userAppTheme);
    ComboBox vAppThemeField = (ComboBox) WebComponentsHelper.unwrap(appThemeField);
    vAppThemeField.setTextInputAllowed(false);
    appThemeField.setEditable(changeThemeEnabled);
    boolean langFieldVisible = !globalConfig.getLocaleSelectVisible();
    languageLabel.setVisible(langFieldVisible);
    appLangField.setVisible(langFieldVisible);
    initTimeZoneFields();
    User user = userSession.getUser();
    changePreplacedwordBtn.setAction(new BaseAction("changePreplacedw").withCaption(getMessage("changePreplacedw")).withHandler(event -> {
        Window preplacedwordDialog = openWindow("sec$User.changePreplacedword", OpenType.DIALOG, ParamsMap.of("currentPreplacedwordRequired", true));
        preplacedwordDialog.addCloseListener(actionId -> {
            // move focus back to window
            changePreplacedwordBtn.focus();
        });
    }));
    if (!user.equals(userSession.getCurrentOrSubsreplacedutedUser()) || ExternalUserCredentials.isLoggedInWithExternalAuth(userSession)) {
        changePreplacedwordBtn.setEnabled(false);
    }
    Map<String, Locale> locales = globalConfig.getAvailableLocales();
    TreeMap<String, String> options = new TreeMap<>();
    for (Map.Entry<String, Locale> entry : locales.entrySet()) {
        options.put(entry.getKey(), messages.getTools().localeToString(entry.getValue()));
    }
    appLangField.setOptionsMap(options);
    appLangField.setValue(userManagementService.loadOwnLocale());
    Action commitAction = new BaseAction("commit").withCaption(messages.getMainMessage("actions.Ok")).withShortcut(clientConfig.getCommitShortcut()).withPrimary(true).withHandler(event -> commit());
    addAction(commitAction);
    okBtn.setAction(commitAction);
    cancelBtn.setAction(new BaseAction("cancel").withCaption(messages.getMainMessage("actions.Cancel")).withHandler(event -> cancel()));
    resetScreenSettingsBtn.setAction(new BaseAction("resetScreenSettings").withCaption(getMessage("resetScreenSettings")).withHandler(buttonEvent -> showOptionDialog(getMessage("resetScreenSettings"), getMessage("resetScreenSettings.description"), MessageType.CONFIRMATION, new Action[] { new DialogAction(DialogAction.Type.YES).withHandler(event -> resetScreenSettings()), new DialogAction(DialogAction.Type.NO) })));
    initDefaultScreenField();
}

18 View Complete Implementation : TagAssignementComboBox.java
Copyright Eclipse Public License 1.0
Author : eclipse
/**
 * Combobox that lists all available Tags that can be replacedigned to a
 * {@link Target} or {@link DistributionSet}.
 */
public clreplaced TagreplacedignementComboBox extends HorizontalLayout {

    private static final long serialVersionUID = 1L;

    private static final String NAME_PROPERTY = "name";

    private static final String COLOR_PROPERTY = "color";

    private final IndexedContainer allreplacedignableTags;

    private final transient Set<TagreplacedignmentListener> listeners = Sets.newConcurrentHashSet();

    private final ComboBox replacedignableTagsComboBox;

    private final boolean readOnlyMode;

    /**
     * Constructor.
     *
     * @param i18n
     *            the i18n
     * @param readOnlyMode
     *            if true the combobox will be disabled so no replacedignment can be
     *            done.
     */
    TagreplacedignementComboBox(final VaadinMessageSource i18n, final boolean readOnlyMode) {
        this.readOnlyMode = readOnlyMode;
        setWidth("100%");
        allreplacedignableTags = new IndexedContainer();
        allreplacedignableTags.addContainerProperty(NAME_PROPERTY, String.clreplaced, "");
        allreplacedignableTags.addContainerProperty(COLOR_PROPERTY, String.clreplaced, "");
        replacedignableTagsComboBox = new ComboBoxBuilder().setId(UIComponentIdProvider.TAG_SELECTION_ID).setPrompt(i18n.getMessage(UIMessageIdProvider.TOOLTIP_SELECT_TAG)).setValueChangeListener(this::onSelectionChanged).buildCombBox();
        addComponent(replacedignableTagsComboBox);
        replacedignableTagsComboBox.setContainerDataSource(allreplacedignableTags);
        replacedignableTagsComboBox.setNullSelectionAllowed(true);
        replacedignableTagsComboBox.addStyleName(SPUIStyleDefinitions.DETAILS_LAYOUT_STYLE);
        replacedignableTagsComboBox.addStyleName(ValoTheme.COMBOBOX_TINY);
        replacedignableTagsComboBox.setEnabled(!readOnlyMode);
        replacedignableTagsComboBox.setWidth("100%");
        clearComboBoxSelection();
    }

    /**
     * Initializes the Combobox with all replacedignable tags.
     *
     * @param replacedignableTags
     *            replacedignable tags
     */
    void initializereplacedignableTags(final List<TagData> replacedignableTags) {
        replacedignableTags.forEach(this::addreplacedignableTag);
    }

    private void onSelectionChanged(final ValueChangeEvent event) {
        final Object selectedValue = event.getProperty().getValue();
        if (!isValidTagSelection(selectedValue) || readOnlyMode) {
            return;
        }
        replacedignTag((String) selectedValue);
    }

    private void replacedignTag(final String tagName) {
        allreplacedignableTags.removeItem(tagName);
        notifyListenersTagreplacedigned(tagName);
        clearComboBoxSelection();
    }

    private boolean isValidTagSelection(final Object selectedValue) {
        return selectedValue != null && selectedValue != replacedignableTagsComboBox.getNullSelectionItemId() && selectedValue instanceof String;
    }

    /**
     * Removes all Tags from Combobox.
     */
    void removeAllTags() {
        allreplacedignableTags.removeAllItems();
        clearComboBoxSelection();
    }

    /**
     * Adds an replacedignable Tag to the combobox.
     *
     * @param tagData
     *            the data of the Tag
     */
    void addreplacedignableTag(final TagData tagData) {
        final Item item = allreplacedignableTags.addItem(tagData.getName());
        if (item == null) {
            return;
        }
        item.gereplacedemProperty(NAME_PROPERTY).setValue(tagData.getName());
        item.gereplacedemProperty(COLOR_PROPERTY).setValue(tagData.getColor());
    }

    /**
     * Removes an replacedignable tag from the combobox.
     *
     * @param tagData
     *            the {@link TagData} of the Tag that should be removed.
     */
    void removereplacedignableTag(final TagData tagData) {
        allreplacedignableTags.removeItem(tagData.getName());
    }

    /**
     * Registers an {@link TagreplacedignmentListener} on the combobox.
     *
     * @param listener
     *            the listener to register
     */
    void addTagreplacedignmentListener(final TagreplacedignmentListener listener) {
        listeners.add(listener);
    }

    /**
     * Removes a {@link TagreplacedignmentListener} from the combobox,
     *
     * @param listener
     *            the listener that should be removed.
     */
    void removeTagreplacedignmentListener(final TagreplacedignmentListener listener) {
        listeners.remove(listener);
    }

    private void notifyListenersTagreplacedigned(final String tagName) {
        listeners.forEach(listener -> listener.replacedignTag(tagName));
    }

    private void clearComboBoxSelection() {
        replacedignableTagsComboBox.select(replacedignableTagsComboBox.getNullSelectionItemId());
    }
}

18 View Complete Implementation : BindSecurityGroupWindow.java
Copyright Apache License 2.0
Author : opensecuritycontroller
@SuppressWarnings({ "rawtypes" })
private void serviceTableClicked(long itemId) {
    ComboBox policyComboBox = (ComboBox) this.serviceTable.getContainerProperty(itemId, PROPERTY_ID_POLICY).getValue();
    ComboBox failurePolicyComboBox = (ComboBox) this.serviceTable.getContainerProperty(itemId, PROPERTY_ID_FAILURE_POLICY).getValue();
    Property itemProperty = this.serviceTable.getContainerProperty(itemId, PROPERTY_ID_ENABLED);
    boolean currentValue = (boolean) itemProperty.getValue();
    if (policyComboBox.getContainerDataSource().size() > 0) {
        if (isBindedWithMultiplePolicies(itemId)) {
            policyComboBox.setEnabled(false);
        } else {
            policyComboBox.setEnabled(currentValue);
        }
    }
    if (failurePolicyComboBox.getData() != null) {
        failurePolicyComboBox.setEnabled(currentValue);
    }
}

18 View Complete Implementation : BaseDAWindow.java
Copyright Apache License 2.0
Author : opensecuritycontroller
private ComboBox createEncapsulationTypeComboBox(VirtualizationType virtualizationType, List<TagEncapsulationType> types) {
    ComboBox encapsulationType = new ComboBox();
    encapsulationType.setTextInputAllowed(false);
    encapsulationType.setNullSelectionAllowed(true);
    BeanItemContainer<TagEncapsulationType> encapsulationTypeContainer = new BeanItemContainer<TagEncapsulationType>(TagEncapsulationType.clreplaced, types);
    encapsulationType.setContainerDataSource(encapsulationTypeContainer);
    ApplianceManagerConnectorDto currentMc = (ApplianceManagerConnectorDto) this.managerConnector.getValue();
    if (!virtualizationType.isOpenstack() || (currentMc != null && !currentMc.isPolicyMappingSupported())) {
        encapsulationType.setEnabled(false);
    }
    return encapsulationType;
}

18 View Complete Implementation : BaseDAWindow.java
Copyright Apache License 2.0
Author : opensecuritycontroller
protected void populateVirtualSystem() throws Exception {
    ApplianceModelSoftwareVersionDto currentAppliance = (ApplianceModelSoftwareVersionDto) this.applianceDefinition.getValue();
    // List VC Service
    ListVirtualizationConnectorBySwVersionRequest vcRequest = new ListVirtualizationConnectorBySwVersionRequest();
    if (currentAppliance != null) {
        vcRequest.setSwVersion(currentAppliance.getSwVersion());
    }
    ListResponse<VirtualizationConnectorDto> vcResponse = this.listVirtualizationConnectorBySwVersionService.dispatch(vcRequest);
    ApplianceManagerConnectorDto currentMC = (ApplianceManagerConnectorDto) this.managerConnector.getValue();
    // creating Virtual System Table
    this.vsTable.addContainerProperty("Enabled", Boolean.clreplaced, false);
    this.vsTable.addContainerProperty("Virtualization Connector", String.clreplaced, null);
    this.vsTable.addContainerProperty("Type", String.clreplaced, null);
    this.vsTable.addContainerProperty("Manager Domain", ComboBox.clreplaced, null);
    this.vsTable.addContainerProperty("Encapsulation Type", ComboBox.clreplaced, null);
    List<DomainDto> dl = getDomainList(currentMC);
    this.vsTable.removeAllItems();
    for (VirtualizationConnectorDto vc : vcResponse.getList()) {
        ComboBox domainComboBox = createDomainComboBox(dl);
        ComboBox encapsulationTypeComboBox = createEncapsulationTypeComboBox(vc.getType(), getEncapsulationType(currentAppliance, vc.getType()));
        // get Encapsulation Type for appliance
        // adding new row to vs table
        this.vsTable.addItem(new Object[] { vc.getName(), vc.getType().toString(), domainComboBox, encapsulationTypeComboBox }, vc.getId());
    }
}

18 View Complete Implementation : BaseDAWindow.java
Copyright Apache License 2.0
Author : opensecuritycontroller
private ComboBox createDomainComboBox(List<DomainDto> dl) {
    ComboBox domainComboBox = new ComboBox();
    BeanItemContainer<DomainDto> domainContainer = new BeanItemContainer<DomainDto>(DomainDto.clreplaced, dl);
    ApplianceManagerConnectorDto mc = (ApplianceManagerConnectorDto) this.managerConnector.getValue();
    domainComboBox.setContainerDataSource(domainContainer);
    domainComboBox.setTextInputAllowed(false);
    domainComboBox.setNullSelectionAllowed(false);
    domainComboBox.sereplacedemCaptionPropertyId("name");
    domainComboBox.setEnabled(mc.isPolicyMappingSupported());
    if (domainComboBox.gereplacedemIds().size() > 0) {
        domainComboBox.select(domainContainer.getIdByIndex(0));
    }
    return domainComboBox;
}

18 View Complete Implementation : FormHelper.java
Copyright GNU General Public License v3.0
Author : rlsutton1
/**
 * Deprecated - use EnreplacedyFieldBuilder instead
 *
 * @param field
 * @param form
 * @param fieldGroup
 * @param fieldLabel
 * @param fieldName
 * @param listClazz
 * @param listFieldName
 * @return
 */
@Deprecated
public <L extends CrudEnreplacedy> ComboBox bindEnreplacedyField(ComboBox field, AbstractLayout form, ValidatingFieldGroup<E> fieldGroup, String fieldLabel, String fieldName, Clreplaced<L> listClazz, String listFieldName) {
    return new EnreplacedyFieldBuilder<L>().setComponent(field).setForm(form).setLabel(fieldLabel).setField(fieldName).setListClreplaced(listClazz).setListFieldName(listFieldName).build();
}

18 View Complete Implementation : DependantComboBox.java
Copyright GNU General Public License v3.0
Author : rlsutton1
private void addParentHandler(final ComboBox parent, final EnreplacedyContainer<E> childContainer, final SingularAttribute<E, Parent> childForeignAttribute) {
    parent.addValueChangeListener(new ValueChangeListener() {

        private static final long serialVersionUID = 1L;

        @Override
        public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
            @SuppressWarnings("unchecked")
            Parent parentEnreplacedy = ((Parent) parent.getConvertedValue());
            childContainer.removeAllContainerFilters();
            childContainer.addContainerFilter(new Compare.Equal(childForeignAttribute.getName(), parentEnreplacedy));
            DependantComboBox.this.setContainerDataSource(childContainer);
            DependantComboBox.this.setValue(null);
        }
    });
}

18 View Complete Implementation : ReportParameterDateTimeRange.java
Copyright GNU General Public License v3.0
Author : rlsutton1
public clreplaced ReportParameterDateTimeRange extends ReportParameter<String> {

    protected DateField startfield;

    protected DateField endfield;

    protected String parameterFormat = "yyyy/MM/dd HH:mm:ss";

    protected String endParameterName;

    protected final String startParameterName;

    int endAdjustment = 0;

    protected ComboBox offsetType;

    /**
     * @param caption
     *            - shown on the UI
     * @param parameterName
     *            - parameter name preplaceded to ireport
     * @param resolution
     *            - Vaadin calendar control resolution
     * @param displayFormat
     *            - format to display to the user
     * @param parameterFormat
     *            - format of the value preplaceded to ireport
     */
    public ReportParameterDateTimeRange(String caption, String startParameterName, String endParameterName, Resolution resolution, String displayFormat, String parameterFormat, int endAdjustment) {
        super(caption, new String[] { startParameterName, endParameterName });
        Preconditions.checkNotNull(startParameterName);
        Preconditions.checkNotNull(endParameterName);
        this.startParameterName = startParameterName;
        this.endParameterName = endParameterName;
        startfield = new DateField(caption, new DateTime().withTimeAtStartOfDay().toDate());
        startfield.setResolution(resolution);
        startfield.setDateFormat(displayFormat);
        this.parameterFormat = parameterFormat;
        startfield.setImmediate(true);
        startfield.setValidationVisible(true);
        endfield = new DateField("To", new DateTime().toDate());
        endfield.setResolution(resolution);
        endfield.setDateFormat(displayFormat);
        this.parameterFormat = parameterFormat;
        endfield.setImmediate(true);
        endfield.setValidationVisible(true);
        createValidators();
        this.endAdjustment = endAdjustment;
    }

    public void addValueChangeListener(ValueChangeListener listener) {
        startfield.addValueChangeListener(listener);
        endfield.addValueChangeListener(listener);
    }

    public ReportParameterDateTimeRange(String caption, String startParameterName, String endParameterName) {
        super(caption, new String[] { startParameterName, endParameterName });
        Preconditions.checkNotNull(startParameterName);
        Preconditions.checkNotNull(endParameterName);
        this.startParameterName = startParameterName;
        this.endParameterName = endParameterName;
        startfield = new DateField(caption, new DateTime().withTimeAtStartOfDay().toDate());
        startfield.setResolution(Resolution.DAY);
        startfield.setDateFormat("yyyy/MM/dd");
        startfield.setValidationVisible(true);
        endfield = new DateField("To", new DateTime().withTimeAtStartOfDay().toDate());
        endfield.setResolution(Resolution.DAY);
        endfield.setDateFormat("yyyy/MM/dd");
        endfield.setValidationVisible(true);
        createValidators();
        endAdjustment = -1;
    }

    public void setMaxDateRange(final int maxDays) {
        Validator validator = new Validator() {

            private static final long serialVersionUID = 1L;

            @Override
            public void validate(Object value) throws InvalidValueException {
                if (endfield.getValue() != null && startfield.getValue() != null) {
                    DateTime end = new DateTime(endfield.getValue());
                    DateTime start = new DateTime(startfield.getValue());
                    Duration duration = new Duration(end, start);
                    if (Math.abs(duration.getStandardDays()) > maxDays) {
                        throw new InvalidValueException("A maximum of " + maxDays + " days is allowed");
                    }
                }
            }
        };
        startfield.addValidator(validator);
        endfield.addValidator(validator);
    }

    void createValidators() {
        startfield.addValidator(new Validator() {

            private static final long serialVersionUID = 1L;

            @Override
            public void validate(Object value) throws InvalidValueException {
                if (value == null) {
                    throw new InvalidValueException("Start date is invalid");
                }
                if (endfield.getValue() != null && ((Date) value).after(endfield.getValue())) {
                    throw new InvalidValueException("Start date must be before the end date");
                }
            }
        });
        endfield.addValidator(new Validator() {

            private static final long serialVersionUID = 1L;

            @Override
            public void validate(Object value) throws InvalidValueException {
                if (value == null) {
                    throw new InvalidValueException("End date is invalid");
                }
                if (startfield.getValue() != null && ((Date) value).before(startfield.getValue())) {
                    throw new InvalidValueException("Start date must be before the end date");
                }
            }
        });
    }

    @Override
    public String getValue(String parameterName) {
        SimpleDateFormat sdf = new SimpleDateFormat(parameterFormat);
        return sdf.format(getDate(parameterName));
    }

    public Date getDate(String parameterName) {
        DateParameterOffsetType type = (DateParameterOffsetType) offsetType.getValue();
        Date value;
        if (parameterName.equalsIgnoreCase(startParameterName)) {
            value = type.convertStartDate(startfield.getValue(), new Date(), getDateParameterType());
        } else if (parameterName.equalsIgnoreCase(endParameterName)) {
            value = new DateTime(endfield.getValue()).plusDays(endAdjustment).toDate();
            value = type.convertEndDate(value, new Date(), getDateParameterType());
        } else {
            throw new RuntimeException("Attempt to retrieve invalid date parameter name " + parameterName + " valid names are " + startParameterName + "," + endParameterName);
        }
        return value;
    }

    @Override
    public Component getComponent() {
        VerticalLayout layout = new VerticalLayout();
        List<DateParameterOffsetType> types = new LinkedList<>();
        for (DateParameterOffsetType type : DateParameterOffsetType.values()) {
            types.add(type);
        }
        offsetType = new ComboBox("Date Options", types);
        offsetType.setImmediate(true);
        offsetType.setNullSelectionAllowed(false);
        offsetType.setWidth("140");
        offsetType.setValue(DateParameterOffsetType.CONSTANT);
        offsetType.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 7081417825842355432L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                DateParameterOffsetType offsetTypeValue = (DateParameterOffsetType) event.getProperty().getValue();
                startfield.setVisible(offsetTypeValue == DateParameterOffsetType.CONSTANT);
                endfield.setVisible(offsetTypeValue == DateParameterOffsetType.CONSTANT);
            }
        });
        layout.addComponent(offsetType);
        VerticalLayout inset = new VerticalLayout();
        inset.setMargin(new MarginInfo(false, false, false, true));
        inset.addComponent(startfield);
        inset.addComponent(endfield);
        layout.addComponent(inset);
        return layout;
    }

    @Override
    public boolean shouldExpand() {
        return false;
    }

    @Override
    public void setDefaultValue(String defaultValue) {
    // this.field.setValue(defaultValue);
    }

    @Override
    public String getExpectedParameterClreplacedName() {
        return null;
    }

    @Override
    public String getDisplayValue(String parameterName) {
        Date date = getDate(parameterName);
        if ("ReportParameterEndDate".equalsIgnoreCase(parameterName)) {
            // actual end date will be 25/10/2017 00:00:00.0 but we want to
            // display 24/10/2017
            date = new DateTime(date).minusDays(endAdjustment).toDate();
        }
        return new SimpleDateFormat(startfield.getDateFormat()).format(date);
    }

    @Override
    public boolean validate() {
        boolean valid = false;
        try {
            startfield.validate();
            endfield.validate();
            valid = true;
        } catch (Exception e) {
        }
        return valid;
    }

    @Override
    public void setValuereplacedtring(String value, String parameterName) throws ReadOnlyException, ConversionException, ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(parameterFormat);
        DateField field;
        if (parameterName.equalsIgnoreCase(startParameterName)) {
            field = startfield;
        } else {
            field = endfield;
        }
        field.setValue(sdf.parse(value));
    }

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

    @Override
    public DateParameterType getDateParameterType() {
        return DateParameterType.DATE;
    }

    @Override
    public Date getStartDate() {
        return getDate(startParameterName);
    }

    @Override
    public Date getEndDate() {
        return getDate(endParameterName);
    }

    @Override
    public void setStartDate(Date date) {
        startfield.setValue(date);
    }

    @Override
    public void setEndDate(Date date) {
        endfield.setValue(date);
    }

    @Override
    public String getLabel(String parameterName) {
        if (parameterName.equalsIgnoreCase(endParameterName)) {
            return "To";
        }
        return "From";
    }

    @Override
    public String getSaveMetaData() {
        return ((DateParameterOffsetType) offsetType.getValue()).name();
    }

    @Override
    public void applySaveMetaData(String metaData) {
        offsetType.setValue(DateParameterOffsetType.valueOf(metaData));
    }

    @Override
    public String getMetaDataComment() {
        return ((DateParameterOffsetType) offsetType.getValue()).toString();
    }
}

18 View Complete Implementation : ReportParameterReportChooser.java
Copyright GNU General Public License v3.0
Author : rlsutton1
public clreplaced ReportParameterReportChooser<T extends Enum<T> & ReportChooser> extends ReportParameter<Enum<T>> implements ReportChooser {

    private ComboBox field;

    private Clreplaced<T> enumClreplaced;

    Logger logger = org.apache.logging.log4j.LogManager.getLogger();

    /**
     * @param caption
     * @param defaultValue
     * @param parameterName
     * @param enumClreplaced
     */
    public ReportParameterReportChooser(String caption, T defaultValue, String parameterName, Clreplaced<T> enumClreplaced) {
        super(caption, parameterName);
        field = new ComboBox(caption);
        this.enumClreplaced = enumClreplaced;
        field.setContainerDataSource(FormHelper.createContainerFromEnumClreplaced("value", enumClreplaced));
        field.setNewItemsAllowed(false);
        field.setNullSelectionAllowed(false);
        field.setTextInputAllowed(false);
        field.setValue(defaultValue);
    }

    @Override
    public String getValue(String parameterName) {
        return field.getValue().toString();
    }

    @Override
    public Component getComponent() {
        return field;
    }

    @Override
    public boolean shouldExpand() {
        return false;
    }

    @Override
    public void setDefaultValue(Enum<T> defaultValue) {
        field.setValue(defaultValue);
    }

    @Override
    public String getExpectedParameterClreplacedName() {
        return String.clreplaced.getCanonicalName();
    }

    @Override
    public JasperReportProperties getReportProperties(JasperReportProperties reportProperties) {
        @SuppressWarnings("unchecked")
        T e = (T) field.getValue();
        return e.getReportProperties(reportProperties);
    }

    @Override
    public String getDisplayValue(String parameterName) {
        return getValue(null);
    }

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

    @Override
    public void setValuereplacedtring(String value, String parameterName) {
        boolean set = false;
        try {
            field.setValue(Enum.valueOf(enumClreplaced, value));
            set = true;
        } catch (IllegalArgumentException e) {
            // we may have a toString method on the enum which will mean the
            // value that arrives here is the user friendly string
            for (T enumValue : enumClreplaced.getEnumConstants()) {
                if (enumValue.toString().equalsIgnoreCase(value)) {
                    field.setValue(enumValue);
                    set = true;
                    break;
                }
            }
            if (set == false) {
                logger.error(e, e);
            }
        }
    }

    @Override
    public boolean isDateField() {
        return false;
    }

    @Override
    public DateParameterType getDateParameterType() {
        throw new RuntimeException("Not implemented");
    }

    @Override
    public String getSaveMetaData() {
        return "";
    }

    @Override
    public void applySaveMetaData(String metaData) {
    // NO OP
    }

    @Override
    public String getMetaDataComment() {
        return "";
    }
}

17 View Complete Implementation : CmsSqlConsoleLayout.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Widget for the SQL console.<p>
 */
public clreplaced CmsSqlConsoleLayout extends VerticalLayout {

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

    /**
     * The button to execute the SQL.
     */
    protected Button m_ok;

    /**
     * Combo box for selecting the pool.
     */
    protected ComboBox<String> m_pool;

    /**
     * Text area containing the SQL statements.
     */
    protected TextArea m_script;

    /**
     * The executor.
     */
    private CmsSqlConsoleExecutor m_console;

    /**
     * Creates a new instance.<p>
     *
     * @param console the SQL executor
     */
    public CmsSqlConsoleLayout(CmsSqlConsoleExecutor console) {
        CmsVaadinUtils.readAndLocalizeDesign(this, CmsVaadinUtils.getWpMessagesForCurrentLocale(), null);
        m_console = console;
        m_ok.addClickListener(evt -> runQuery());
        m_pool.sereplacedems(OpenCms.getDbPoolNames());
        m_pool.setValue(CmsDbPoolV11.getDefaultDbPoolName());
        m_pool.setEmptySelectionAllowed(false);
    }

    /**
     * Runs the currently entered query and displays the results.
     */
    protected void runQuery() {
        String pool = m_pool.getValue();
        String stmt = m_script.getValue();
        if (stmt.trim().isEmpty()) {
            return;
        }
        CmsStringBufferReport report = new CmsStringBufferReport(Locale.ENGLISH);
        List<Throwable> errors = new ArrayList<>();
        CmsSqlConsoleResults result = m_console.execute(stmt, pool, report, errors);
        if (errors.size() > 0) {
            CmsErrorDialog.showErrorDialog(report.toString() + errors.get(0).getMessage(), errors.get(0));
        } else {
            Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);
            window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_SQLCONSOLE_QUERY_RESULTS_0));
            window.setContent(new CmsSqlConsoleResultsForm(result, report.toString()));
            A_CmsUI.get().addWindow(window);
            window.center();
        }
    }
}

17 View Complete Implementation : CmsImportExportUserDialog.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Get ComboBox for selecting roles.<p>
 *
 * @param ou name
 * @return ComboBox
 */
protected ComboBox<CmsRole> getRoleComboBox(String ou) {
    ComboBox<CmsRole> box = new ComboBox<CmsRole>();
    CmsUserEditDialog.iniRole(A_CmsUI.getCmsObject(), ou, box, null);
    box.setSelectedItem(CmsRole.EDITOR.forOrgUnit(ou));
    return box;
}

17 View Complete Implementation : CmsSetupStep03Database.java
Copyright GNU Lesser General Public License v2.1
Author : alkacon
/**
 * Setup step: Databbase settings.
 */
public clreplaced CmsSetupStep03Database extends A_CmsSetupStep {

    /**
     * Exception clreplaced for use during DB setup, where we get lists of strings as errors from CmsSetupDb instead of the original exceptions.
     */
    clreplaced DBException extends RuntimeException {

        /**
         * The list of original errors.
         */
        private List<String> m_errors;

        /**
         * The error message.
         */
        private String m_message;

        /**
         * Creates a new instance.<p>
         *
         * @param message the error message
         * @param errors the list of original errors
         */
        public DBException(String message, List<String> errors) {
            m_message = message;
            m_errors = new ArrayList<>(errors);
        }

        /**
         * Gets original errors, separated by newlines.
         *
         * @return the original errors
         */
        public String getDetails() {
            return CmsStringUtil.listreplacedtring(m_errors, "\n");
        }

        /**
         * @see java.lang.Throwable#getMessage()
         */
        @Override
        public String getMessage() {
            return m_message;
        }
    }

    /**
     * Back button.
     */
    private Button m_backButton;

    /**
     * DB selector.
     */
    private ComboBox m_dbSelect;

    /**
     * Forward button.
     */
    private Button m_forwardButton;

    /**
     * Main layout.
     */
    private VerticalLayout m_mainLayout;

    /**
     * Array for storing the DB settings panel (need to wrap it in array because it's not part of the declarative layout).
     */
    private CmsDbSettingsPanel[] m_panel = { null };

    /**
     * Setup bean.
     */
    private CmsSetupBean m_setupBean;

    /**
     * Creates a new instance.
     *
     * @param context the setup context
     */
    public CmsSetupStep03Database(I_SetupUiContext context) {
        super(context);
        CmsVaadinUtils.readAndLocalizeDesign(this, null, null);
        m_setupBean = context.getSetupBean();
        Map<String, Properties> propsForDbs = m_setupBean.getDatabaseProperties();
        List<String> dbList = new ArrayList<>();
        for (Map.Entry<String, Properties> entry : propsForDbs.entrySet()) {
            dbList.add(entry.getKey());
        }
        m_dbSelect.sereplacedems(dbList);
        m_dbSelect.sereplacedemCaptionGenerator(db -> propsForDbs.get(db).get(db + ".name").toString());
        String path = context.getSetupBean().getServletConfig().getServletContext().getContextPath();
        int lastSlash = path.lastIndexOf("/");
        String webapp = null;
        if (lastSlash != -1) {
            String lastSegment = path.substring(lastSlash + 1);
            if (!CmsStringUtil.isEmptyOrWhitespaceOnly(lastSegment)) {
                webapp = lastSegment;
            }
        }
        final String fWebapp = webapp;
        m_dbSelect.addValueChangeListener(evt -> {
            String value = (String) (evt.getValue());
            updateDb(value, fWebapp);
        });
        m_dbSelect.setNewItemProvider(null);
        m_dbSelect.setEmptySelectionAllowed(false);
        m_dbSelect.setValue("mysql");
        m_forwardButton.addClickListener(evt -> forward());
        m_backButton.addClickListener(evt -> m_context.stepBack());
    }

    /**
     * Creates DB and tables when necessary.<p>
     *
     * @throws Exception in case creating DB or tables fails
     */
    public void setupDb(boolean createDb, boolean createTables, boolean dropDb) throws Exception {
        boolean dbExists = false;
        if (m_setupBean.isInitialized()) {
            System.out.println("Setup-Bean initialized successfully.");
            CmsSetupDb db = new CmsSetupDb(m_setupBean.getWebAppRfsPath());
            try {
                // try to connect as the runtime user
                db.setConnection(m_setupBean.getDbDriver(), m_setupBean.getDbWorkConStr(), m_setupBean.getDbConStrParams(), m_setupBean.getDbWorkUser(), m_setupBean.getDbWorkPwd(), false);
                if (!db.noErrors()) {
                    // try to connect as the setup user
                    db.closeConnection();
                    db.clearErrors();
                    db.setConnection(m_setupBean.getDbDriver(), m_setupBean.getDbCreateConStr(), m_setupBean.getDbConStrParams(), m_setupBean.getDbCreateUser(), m_setupBean.getDbCreatePwd());
                } else {
                    dbExists = true;
                }
                if (!db.noErrors() || !m_setupBean.validateJdbc()) {
                    throw new DBException("DB connection test failed.", db.getErrors());
                }
            } finally {
                db.clearErrors();
                db.closeConnection();
            }
        }
        System.out.println("DB connection tested successfully.");
        CmsSetupDb db = null;
        if (m_setupBean.isInitialized()) {
            if (createDb || createTables) {
                db = new CmsSetupDb(m_setupBean.getWebAppRfsPath());
                // check if database exists
                if (m_setupBean.getDatabase().startsWith("oracle") || m_setupBean.getDatabase().startsWith("db2") || m_setupBean.getDatabase().startsWith("as400")) {
                    setWorkConnection(db);
                } else {
                    db.setConnection(m_setupBean.getDbDriver(), m_setupBean.getDbWorkConStr(), m_setupBean.getDbConStrParams(), m_setupBean.getDbCreateUser(), m_setupBean.getDbCreatePwd(), false);
                    dbExists = db.noErrors();
                    if (dbExists) {
                        db.closeConnection();
                    } else {
                        db.clearErrors();
                    }
                }
                if (!dbExists || dropDb) {
                    db.closeConnection();
                    if (!m_setupBean.getDatabase().startsWith("db2") && !m_setupBean.getDatabase().startsWith("as400")) {
                        db.setConnection(m_setupBean.getDbDriver(), m_setupBean.getDbCreateConStr(), m_setupBean.getDbConStrParams(), m_setupBean.getDbCreateUser(), m_setupBean.getDbCreatePwd());
                    }
                }
            }
        }
        if (!createDb && !createTables && !dbExists) {
            throw new Exception("You have not created the Alkacon OpenCms database.");
        }
        if (dbExists && createTables && !dropDb && (db != null)) {
            throw new Exception("You have selected to not drop existing DBs, but a DB with the given name exists.");
        }
        if (dbExists && createDb && dropDb && (db != null)) {
            // drop the DB
            db.closeConnection();
            db.setConnection(m_setupBean.getDbDriver(), m_setupBean.getDbCreateConStr(), m_setupBean.getDbConStrParams(), m_setupBean.getDbCreateUser(), m_setupBean.getDbCreatePwd());
            db.dropDatabase(m_setupBean.getDatabase(), m_setupBean.getReplacer());
            if (!db.noErrors()) {
                List<String> errors = new ArrayList<>(db.getErrors());
                db.clearErrors();
                throw new DBException("Error occurred while dropping the DB!", errors);
            }
            System.out.println("Database dropped successfully.");
        }
        if (createDb && (db != null)) {
            // Create Database
            db.createDatabase(m_setupBean.getDatabase(), m_setupBean.getReplacer());
            if (!db.noErrors()) {
                DBException ex = new DBException("Error occurred while creating the DB!", db.getErrors());
                db.clearErrors();
                throw ex;
            }
            db.closeConnection();
            System.out.println("Database created successfully.");
        }
        if (createTables && (db != null)) {
            setWorkConnection(db);
            // Drop Tables (intentionally quiet)
            db.dropTables(m_setupBean.getDatabase());
            db.clearErrors();
            db.closeConnection();
            // reopen the connection in order to display errors
            setWorkConnection(db);
            // Create Tables
            db.createTables(m_setupBean.getDatabase(), m_setupBean.getReplacer());
            if (!db.noErrors()) {
                DBException ex = new DBException("Error occurred while creating the DB!", db.getErrors());
                db.clearErrors();
                throw ex;
            }
            db.closeConnection();
            System.out.println("Tables created successfully.");
        }
        if (db != null) {
            db.closeConnection();
        }
        System.out.println("Database setup was successful.");
        m_context.stepForward();
    }

    /**
     * Set work connection.
     *
     * @param db the db setup bean
     */
    public void setWorkConnection(CmsSetupDb db) {
        db.setConnection(m_setupBean.getDbDriver(), m_setupBean.getDbWorkConStr(), m_setupBean.getDbConStrParams(), m_setupBean.getDbWorkUser(), m_setupBean.getDbWorkPwd());
    }

    /**
     * Proceed to next step.
     */
    private void forward() {
        try {
            CmsDbSettingsPanel panel = m_panel[0];
            panel.saveToSetupBean();
            boolean createDb = panel.getCreateDb();
            boolean dropDb = panel.getDropDb();
            boolean createTables = panel.getCreateTables();
            setupDb(createDb, createTables, dropDb);
        } catch (DBException e) {
            CmsSetupErrorDialog.showErrorDialog(e.getMessage(), e.getDetails());
        } catch (Exception e) {
            CmsSetupErrorDialog.showErrorDialog(e);
        }
    }

    /**
     * Switches DB type.
     *
     * @param dbName the database type
     * @param webapp the webapp name
     */
    private void updateDb(String dbName, String webapp) {
        m_mainLayout.removeAllComponents();
        m_setupBean.setDatabase(dbName);
        CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean);
        m_panel[0] = panel;
        panel.initFromSetupBean(webapp);
        m_mainLayout.addComponent(panel);
    }
}

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

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

    @AutoGenerated
    private Tree treeExpression;

    @AutoGenerated
    private ComboBox comboBox;

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

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     */
    public ExpressionEditorWindow() {
        buildMainLayout();
        // setCompositionRoot(mainLayout);
        setContent(mainLayout);
    // TODO add user code here
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("-1px");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // comboBox
        comboBox = new ComboBox();
        comboBox.setImmediate(false);
        comboBox.setWidth("-1px");
        comboBox.setHeight("-1px");
        mainLayout.addComponent(comboBox);
        // treeExpression
        treeExpression = new Tree();
        treeExpression.setImmediate(false);
        treeExpression.setWidth("100.0%");
        treeExpression.setHeight("-1px");
        mainLayout.addComponent(treeExpression);
        mainLayout.setExpandRatio(treeExpression, 1.0f);
        return mainLayout;
    }
}

17 View Complete Implementation : FormUtils.java
Copyright Apache License 2.0
Author : chelu
/**
 * Fill combo with a list of objeces.
 * @param data list to fill with.
 * @param clear true if clear all items before adding new ones.
 */
public static void fillCombo(ComboBox combo, List<?> data, boolean clear) {
    Object selected = combo.getValue();
    if (clear) {
        combo.removeAllItems();
    }
    for (Object o : data) {
        combo.addItem(o);
    }
    if (data.contains(selected))
        combo.setValue(selected);
}

17 View Complete Implementation : VaadinPaginator.java
Copyright Apache License 2.0
Author : chelu
/**
 * Paginator implementation for Vaadin framework
 *
 * @author Jose Luis Martin - ([email protected])
 */
@Configurable
public clreplaced VaadinPaginator<T> extends AbstractView<Page<T>> implements Paginator, Serializable {

    public static final String PAGINATOR = "paginator";

    private static final long serialVersionUID = 1L;

    /**
     * Label to show in pagination status.
     */
    private Label status = new Label("- / -");

    private Label resultCount = new Label("       ");

    /**
     * String array with available page sizes
     */
    private String[] pageSizes = { "10", "20", "30", "40", "50", "100", "ALL" };

    /**
     * goto next page button
     */
    private Button next;

    /**
     * goto previous page button
     */
    private Button previous;

    /**
     * goto first page button
     */
    private Button first;

    /**
     * goto last page button
     */
    private Button last;

    /**
     * select with page sizes
     */
    private ComboBox pgs = new ComboBox();

    /**
     * select with all pages for jump to page number
     */
    private ComboBox goTo = new ComboBox();

    /**
     * Listen buttons clicks
     */
    private ButtonClickListener buttonClickListener = new ButtonClickListener();

    private MessageSourceWrapper messageSource = new MessageSourceWrapper();

    private String nextIconUrl = "images/table/go-next.png";

    private String previousIconUrl = "images/table/go-previous.png";

    private String lastIconUrl = "images/table/go-last.png";

    private String firstIconUrl = "images/table/go-first.png";

    private boolean nativeButtons;

    /**
     * Creates a new paginator with default page size of 10 records
     */
    public VaadinPaginator() {
        this(new Page<T>(10));
    }

    /**
     * Creates a new paginator with current page
     * @param page current page
     */
    public VaadinPaginator(Page<T> page) {
        setModel(page);
        page.firstPage();
    }

    private Button createButton(String icon) {
        Button b = nativeButtons ? new NativeButton() : new Button();
        b.setIcon(new ThemeResource(icon));
        return b;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Component buildPanel() {
        // buttons
        if (next == null) {
            setNext(createButton(nextIconUrl));
        }
        if (this.last == null) {
            setLast(createButton(lastIconUrl));
        }
        if (this.previous == null) {
            setPrevious(createButton(previousIconUrl));
        }
        if (this.first == null) {
            setFirst(createButton(firstIconUrl));
        }
        // goto page select
        Label goToLabel = new Label(messageSource.getMessage("vaadinPaginator.goto"));
        goToLabel.setSizeUndefined();
        goToLabel.setStyleName(PAGINATOR);
        goTo.addValueChangeListener(new GoToValueChangeListener());
        goTo.setImmediate(true);
        // records by page select
        Label showRecords = new Label(messageSource.getMessage("vaadinPaginator.pageSize"));
        showRecords.setSizeUndefined();
        // page size combo
        for (String size : pageSizes) {
            pgs.addItem(size);
        }
        pgs.setNullSelectionAllowed(false);
        pgs.setValue(String.valueOf(getModel().getPageSize()));
        pgs.setWidth("6em");
        pgs.setImmediate(true);
        pgs.addValueChangeListener(new PgsValueChangeListener());
        BoxFormBuilder fb = new BoxFormBuilder();
        fb.setMargin(false);
        fb.setFixedHeight();
        fb.row();
        fb.add(resultCount);
        fb.addHorizontalGlue();
        fb.add(first);
        fb.add(previous);
        fb.add(status);
        fb.add(next);
        fb.add(last);
        fb.add(goToLabel);
        fb.add(goTo, 60);
        fb.addHorizontalGlue();
        fb.add(showRecords);
        fb.add(pgs, 60);
        return fb.getForm();
    }

    // Paginator Interface Implementation //
    /**
     * {@inheritDoc}
     */
    public boolean hasNext() {
        return getModel().hasNext();
    }

    /**
     * {@inheritDoc}
     */
    public boolean hasPrevious() {
        return getModel().hasPrevious();
    }

    /**
     * {@inheritDoc}
     */
    public boolean hasPage(int indexPage) {
        return getModel().hasPage(indexPage);
    }

    /**
     * {@inheritDoc}
     */
    public void setPage(int indexPage) {
        getModel().setPage(indexPage);
    }

    /**
     * {@inheritDoc}
     */
    public int getPage() {
        return getModel().getPage();
    }

    /**
     * {@inheritDoc}
     */
    public int getTotalPages() {
        return getModel().getTotalPages();
    }

    /**
     * {@inheritDoc}
     */
    public void nextPage() {
        getModel().nextPage();
    }

    /**
     * {@inheritDoc}
     */
    public void previousPage() {
        getModel().previousPage();
    }

    /**
     * {@inheritDoc}
     */
    public void lastPage() {
        setPage(getTotalPages());
    }

    /**
     * {@inheritDoc}
     */
    public void firstPage() {
        setPage(1);
    }

    /**
     * {@inheritDoc}
     */
    public int getStartIndex() {
        return getModel().getStartIndex();
    }

    /**
     * {@inheritDoc}
     */
    public int getPageSize() {
        return getModel().getPageSize();
    }

    /**
     * {@inheritDoc}
     */
    public void setPageSize(int pageSize) {
        getModel().setPageSize(pageSize);
    }

    /**
     * {@inheritDoc}
     */
    public void addPaginatorListener(PaginatorListener listener) {
        getModel().addPaginatorListener(listener);
    }

    /**
     * {@inheritDoc}
     */
    public void removePaginatorListener(PaginatorListener listener) {
        getModel().removePaginatorListener(listener);
    }

    /**
     * Parse string with page number
     * @param item
     * @return
     */
    private int parsePageSize(String item) {
        int pageSize = 20;
        if (item != null) {
            try {
                pageSize = Integer.parseInt(item.trim());
            } catch (NumberFormatException e) {
                pageSize = Integer.MAX_VALUE;
            }
        }
        return pageSize;
    }

    /**
     * {@inheritDoc}
     */
    public void doRefresh() {
        // update status
        int currentPage = getTotalPages() == 0 ? 0 : getPage();
        status.setValue(currentPage + " / " + getTotalPages());
        resultCount.setValue(messageSource.getMessage("vaadinPaginator.records") + getModel().getCount());
        // fill goto page select
        goTo.removeAllItems();
        for (int i = 1; i <= getModel().getTotalPages(); i++) {
            goTo.addItem(i);
        }
        if (next != null) {
            // Buttons
            next.setEnabled(hasNext());
            last.setEnabled(hasNext());
            previous.setEnabled(hasPrevious());
            first.setEnabled(hasPrevious());
        }
    }

    // Getters and Setters
    public String[] getPageSizes() {
        return pageSizes;
    }

    public void setPageSizes(String[] pageSizes) {
        this.pageSizes = pageSizes;
    }

    public Button getNext() {
        return next;
    }

    public void setNext(Button next) {
        this.next = next;
        next.addClickListener(buttonClickListener);
    }

    public Button getPrevious() {
        return previous;
    }

    public void setPrevious(Button previous) {
        this.previous = previous;
        previous.addClickListener(buttonClickListener);
    }

    public Button getFirst() {
        return first;
    }

    public void setFirst(Button first) {
        this.first = first;
        first.addClickListener(buttonClickListener);
    }

    public Button getLast() {
        return last;
    }

    public void setLast(Button last) {
        this.last = last;
        last.addClickListener(buttonClickListener);
    }

    // Listeners
    clreplaced PgsValueChangeListener implements ValueChangeListener {

        private static final long serialVersionUID = 1L;

        public void valueChange(ValueChangeEvent event) {
            int pageSize = parsePageSize((String) pgs.getValue());
            if (pageSize != getModel().getPageSize()) {
                setPageSize(pageSize);
            }
        }
    }

    clreplaced GoToValueChangeListener implements ValueChangeListener {

        private static final long serialVersionUID = 1L;

        public void valueChange(ValueChangeEvent event) {
            if (goTo.getValue() instanceof Integer) {
                if (!goTo.getValue().equals(getModel().getPage()))
                    setPage((Integer) goTo.getValue());
            }
        }
    }

    /**
     * Handle clicks on paginator buttons
     *
     * @author Jose Luis Martin - ([email protected])
     */
    clreplaced ButtonClickListener implements ClickListener {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {
            if (event.getComponent() == next) {
                nextPage();
            } else if (event.getComponent() == last) {
                lastPage();
            } else if (event.getComponent() == previous) {
                previousPage();
            } else if (event.getComponent() == first) {
                firstPage();
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public int getCount() {
        return getModel().getCount();
    }

    /**
     * {@inheritDoc}
     */
    public void setCount(int count) {
        getModel().setCount(count);
    }

    /**
     * @return the nextIconUrl
     */
    public String getNextIconUrl() {
        return nextIconUrl;
    }

    /**
     * @param nextIconUrl the nextIconUrl to set
     */
    public void setNextIconUrl(String nextIconUrl) {
        this.nextIconUrl = nextIconUrl;
    }

    /**
     * @return the previousIconUrl
     */
    public String getPreviousIconUrl() {
        return previousIconUrl;
    }

    /**
     * @param previousIconUrl the previousIconUrl to set
     */
    public void setPreviousIconUrl(String previousIconUrl) {
        this.previousIconUrl = previousIconUrl;
    }

    /**
     * @return the lastIconUrl
     */
    public String getLastIconUrl() {
        return lastIconUrl;
    }

    /**
     * @param lastIconUrl the lastIconUrl to set
     */
    public void setLastIconUrl(String lastIconUrl) {
        this.lastIconUrl = lastIconUrl;
    }

    /**
     * @return the firstIconUrl
     */
    public String getFirstIconUrl() {
        return firstIconUrl;
    }

    /**
     * @param firstIconUrl the firstIconUrl to set
     */
    public void setFirstIconUrl(String firstIconUrl) {
        this.firstIconUrl = firstIconUrl;
    }

    public MessageSource getMessageSource() {
        return messageSource.getMessageSource();
    }

    @Autowired
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource.setMessageSource(messageSource);
    }

    public boolean isNativeButtons() {
        return nativeButtons;
    }

    public void setNativeButtons(boolean nativeButtons) {
        this.nativeButtons = nativeButtons;
    }
}

17 View Complete Implementation : DefaultDistributionSetTypeLayout.java
Copyright Eclipse Public License 1.0
Author : eclipse
/**
 * Default DistributionSet Panel.
 */
public clreplaced DefaultDistributionSetTypeLayout extends BaseConfigurationView {

    private static final long serialVersionUID = 1L;

    private final transient SystemManagement systemManagement;

    private Long currentDefaultDisSetType;

    private Long selectedDefaultDisSetType;

    private TenantMetaData tenantMetaData;

    private final ComboBox combobox;

    private final Label changeIcon;

    DefaultDistributionSetTypeLayout(final SystemManagement systemManagement, final DistributionSetTypeManagement distributionSetTypeManagement, final VaadinMessageSource i18n, final SpPermissionChecker permChecker) {
        this.systemManagement = systemManagement;
        combobox = SPUIComponentProvider.getComboBox(null, "330", null, null, false, "", "label.combobox.tag");
        changeIcon = new Label();
        if (!permChecker.hasReadRepositoryPermission()) {
            return;
        }
        final Panel rootPanel = new Panel();
        rootPanel.setSizeFull();
        rootPanel.addStyleName("config-panel");
        final VerticalLayout vlayout = new VerticalLayout();
        vlayout.setMargin(true);
        vlayout.setSizeFull();
        final Label header = new Label(i18n.getMessage("configuration.defaultdistributionset.replacedle"));
        header.addStyleName("config-panel-header");
        vlayout.addComponent(header);
        final DistributionSetType currentDistributionSetType = getCurrentDistributionSetType();
        currentDefaultDisSetType = currentDistributionSetType.getId();
        final HorizontalLayout hlayout = new HorizontalLayout();
        hlayout.setSpacing(true);
        hlayout.setImmediate(true);
        final Label configurationLabel = new LabelBuilder().name(i18n.getMessage("configuration.defaultdistributionset.select.label")).buildLabel();
        hlayout.addComponent(configurationLabel);
        final Iterable<DistributionSetType> distributionSetTypeCollection = distributionSetTypeManagement.findAll(PageRequest.of(0, 100));
        combobox.setId(UIComponentIdProvider.SYSTEM_CONFIGURATION_DEFAULTDIS_COMBOBOX);
        combobox.setNullSelectionAllowed(false);
        for (final DistributionSetType distributionSetType : distributionSetTypeCollection) {
            combobox.addItem(distributionSetType.getId());
            combobox.sereplacedemCaption(distributionSetType.getId(), distributionSetType.getKey() + " (" + distributionSetType.getName() + ")");
            if (distributionSetType.getId().equals(currentDistributionSetType.getId())) {
                combobox.select(distributionSetType.getId());
            }
        }
        combobox.setImmediate(true);
        combobox.addValueChangeListener(event -> selectDistributionSetValue());
        hlayout.addComponent(combobox);
        changeIcon.setIcon(FontAwesome.CHECK);
        hlayout.addComponent(changeIcon);
        changeIcon.setVisible(false);
        vlayout.addComponent(hlayout);
        rootPanel.setContent(vlayout);
        setCompositionRoot(rootPanel);
    }

    private DistributionSetType getCurrentDistributionSetType() {
        tenantMetaData = systemManagement.getTenantMetadata();
        return tenantMetaData.getDefaultDsType();
    }

    @Override
    public void save() {
        if (!currentDefaultDisSetType.equals(selectedDefaultDisSetType) && selectedDefaultDisSetType != null) {
            tenantMetaData = systemManagement.updateTenantMetadata(selectedDefaultDisSetType);
            currentDefaultDisSetType = selectedDefaultDisSetType;
        }
        changeIcon.setVisible(false);
    }

    @Override
    public void undo() {
        combobox.select(currentDefaultDisSetType);
        selectedDefaultDisSetType = currentDefaultDisSetType;
        changeIcon.setVisible(false);
    }

    /**
     * Method that is called when combobox event is performed.
     */
    private void selectDistributionSetValue() {
        selectedDefaultDisSetType = (Long) combobox.getValue();
        if (!selectedDefaultDisSetType.equals(currentDefaultDisSetType)) {
            changeIcon.setVisible(true);
            notifyConfigurationChanged();
        } else {
            changeIcon.setVisible(false);
        }
    }
}

17 View Complete Implementation : BaseSecurityGroupInterfaceWindow.java
Copyright Apache License 2.0
Author : opensecuritycontroller
public abstract clreplaced BaseSecurityGroupInterfaceWindow extends CRUDBaseWindow<OkCancelButtonModel> {

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

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

    protected TextField name;

    protected ComboBox policy;

    protected TextField tag;

    protected Long vsId;

    private final ListVirtualSystemPolicyServiceApi listVirtualSystemPolicyService;

    public BaseSecurityGroupInterfaceWindow(Long vsId, ListVirtualSystemPolicyServiceApi listVirtualSystemPolicyService) {
        super();
        this.vsId = vsId;
        this.listVirtualSystemPolicyService = listVirtualSystemPolicyService;
    }

    protected TextField getName() {
        this.name = new TextField("Name");
        this.name.setImmediate(true);
        this.name.setRequired(true);
        this.name.setRequiredError("Name cannot be empty");
        return this.name;
    }

    protected TextField getTag() {
        this.tag = new TextField("Tag");
        this.tag.setImmediate(true);
        this.tag.setRequired(true);
        this.tag.setRequiredError("Tag cannot be empty");
        return this.tag;
    }

    protected Component getPolicy() {
        try {
            this.policy = new ComboBox("Select Policy");
            this.policy.setTextInputAllowed(false);
            this.policy.setNullSelectionAllowed(false);
            this.policy.setImmediate(true);
            this.policy.setRequired(true);
            this.policy.setRequiredError("Policy cannot be empty");
            populatePolicy();
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
            log.error("Error populating Policy List combobox", e);
        }
        return this.policy;
    }

    private void populatePolicy() {
        try {
            // Calling List Service
            BaseIdRequest req = new BaseIdRequest();
            req.setId(this.vsId);
            List<PolicyDto> vsPolicyDto = this.listVirtualSystemPolicyService.dispatch(req).getList();
            BeanItemContainer<PolicyDto> vsPolicyListContainer = new BeanItemContainer<PolicyDto>(PolicyDto.clreplaced, vsPolicyDto);
            this.policy.setContainerDataSource(vsPolicyListContainer);
            this.policy.sereplacedemCaptionPropertyId("policyName");
            if (vsPolicyListContainer.size() > 0) {
                this.policy.select(vsPolicyListContainer.getIdByIndex(0));
            }
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
            log.error("Error getting Virtual System Policy List", e);
        }
    }

    @Override
    public boolean validateForm() {
        this.name.validate();
        this.policy.validate();
        this.tag.validate();
        try {
            Long.parseLong(this.tag.getValue());
        } catch (NumberFormatException nfe) {
            log.error("Invalid tag value. Parse Excetion.", nfe);
            throw new InvalidValueException("Invalid tag value. Only Numbers are allowed.");
        }
        return true;
    }
}

16 View Complete Implementation : ApplyEditorWindow.java
Copyright Apache License 2.0
Author : apache
public clreplaced ApplyEditorWindow extends Window implements ApplyParametersChangedNotifier {

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

    @AutoGenerated
    private Button buttonSelect;

    @AutoGenerated
    private Table tableFunction;

    @AutoGenerated
    private HorizontalLayout horizontalLayout_1;

    @AutoGenerated
    private CheckBox checkBoxFilterIsBag;

    @AutoGenerated
    private ComboBox comboBoxDatatypeFilter;

    @AutoGenerated
    private TextField textFieldFilter;

    @AutoGenerated
    private TextArea textAreaDescription;

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

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

    private final ApplyEditorWindow self = this;

    private final ApplyParametersChangedNotifier notifier = new ApplyParametersChangedNotifier.BasicNotifier();

    private final BeanItemContainer<FunctionDefinition> container = new BeanItemContainer<FunctionDefinition>(FunctionDefinition.clreplaced);

    private final ApplyType apply;

    private final ApplyType applyParent;

    private final FunctionArgument argument;

    private final Object parent;

    private boolean isSaved = false;

    private FunctionDefinition function = null;

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     * @param parent
     * @param parentApply
     */
    public ApplyEditorWindow(ApplyType apply, ApplyType parentApply, FunctionArgument argument, Object parent) {
        buildMainLayout();
        // setCompositionRoot(mainLayout);
        setContent(mainLayout);
        // 
        // Save
        // 
        this.apply = apply;
        this.applyParent = parentApply;
        this.argument = argument;
        this.parent = parent;
        logger.info(this.apply + " " + this.applyParent + " " + this.argument + " " + this.parent);
        // 
        // Set our shortcuts
        // 
        this.setCloseShortcut(KeyCode.ESCAPE);
        // 
        // Initialize
        // 
        this.textAreaDescription.setValue(apply.getDescription());
        this.textAreaDescription.setNullRepresentation("");
        this.initializeButton();
        this.initializeTable();
        this.initializeFilters();
        // 
        // focus
        // 
        this.textFieldFilter.focus();
    }

    protected void initializeTable() {
        // 
        // Setup GUI properties
        // 
        this.tableFunction.setImmediate(true);
        this.tableFunction.setSelectable(true);
        this.tableFunction.setNullSelectionAllowed(false);
        this.tableFunction.setRequired(true);
        this.tableFunction.setRequiredError("You MUST select a function for the Apply");
        // 
        // Set its data source
        // 
        this.tableFunction.setContainerDataSource(this.container);
        this.tableFunction.setVisibleColumns(new Object[] { "xacmlid", "shortname", "datatypeBean", "isBagReturn" });
        this.tableFunction.setColumnHeaders(new String[] { "Function Xacml ID", "ID", "Return Data Type", "Return Bag?" });
        // 
        // Determine appropriate filters
        // 
        Datatype datatypeId = null;
        if (this.applyParent == null) {
            if (this.parent instanceof ConditionType) {
                // 
                // Only boolean functions allowed
                // 
                datatypeId = JPAUtils.findDatatype(XACML3.ID_DATATYPE_BOOLEAN);
            }
        } else {
            String parentFunction = this.applyParent.getFunctionId();
            this.function = JPAUtils.findFunction(parentFunction);
            if (this.function == null) {
                throw new IllegalArgumentException("applyParent's function is not found:" + parentFunction);
            }
            if (this.argument == null) {
                throw new IllegalArgumentException("Need to know what argument apply is ");
            }
            datatypeId = this.argument.getDatatypeBean();
        }
        Map<Datatype, List<FunctionDefinition>> functionMap = JPAUtils.getFunctionDatatypeMap();
        if (datatypeId == null) {
            // 
            // All functions are available
            // 
            for (Datatype id : functionMap.keySet()) {
                this.addTableEntries(functionMap.get(id));
            }
        } else {
            for (Datatype id : functionMap.keySet()) {
                if (id == null) {
                    if (datatypeId == null) {
                        this.addTableEntries(functionMap.get(id));
                        break;
                    }
                    continue;
                }
                if (id.getId() == datatypeId.getId()) {
                    this.addTableEntries(functionMap.get(id));
                    break;
                }
            }
        }
        // 
        // Setup double-click
        // 
        this.tableFunction.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    self.selected();
                }
            }
        });
        // 
        // Value change listener
        // 
        this.tableFunction.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                logger.info("valueChange " + self.tableFunction.getValue());
                if (self.tableFunction.getValue() != null) {
                    self.buttonSelect.setEnabled(true);
                } else {
                    self.buttonSelect.setEnabled(false);
                }
            }
        });
        // 
        // Select current value if possible
        // 
        if (this.apply != null && this.apply.getFunctionId() != null && this.apply.getFunctionId().isEmpty() == false) {
            FunctionDefinition current = JPAUtils.findFunction(this.apply.getFunctionId());
            if (current != null) {
                this.tableFunction.select(current);
                this.tableFunction.setCurrentPageFirsreplacedemId(current);
            } else {
                logger.warn("Could not find function in table for " + this.apply.getFunctionId());
            }
        } else {
            this.buttonSelect.setEnabled(false);
        }
    }

    protected void addTableEntries(List<FunctionDefinition> functions) {
        if (functions == null) {
            logger.warn("NULL list of functions, cannot add to table.");
            return;
        }
        for (FunctionDefinition function : functions) {
            // 
            // Just check if this function is available for this
            // apply.
            // 
            // if (XACMLFunctionValidator.isFunctionAvailable(function, this.apply, this.argument)) {
            this.container.addBean(function);
        // } else {
        // if (logger.isDebugEnabled()) {
        // logger.debug("Function not available: " + function);
        // }
        // }
        }
    }

    protected void initializeButton() {
        this.buttonSelect.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

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

    protected void initializeFilters() {
        this.textFieldFilter.setImmediate(true);
        this.textFieldFilter.addTextChangeListener(new TextChangeListener() {

            private static final long serialVersionUID = 1L;

            SimpleStringFilter currentFilter = null;

            @Override
            public void textChange(TextChangeEvent event) {
                // 
                // Remove current filter
                // 
                if (this.currentFilter != null) {
                    self.container.removeContainerFilter(this.currentFilter);
                    this.currentFilter = null;
                }
                // 
                // Get the text
                // 
                String value = event.getText();
                if (value != null && value.length() > 0) {
                    // 
                    // Add the new filter
                    // 
                    this.currentFilter = new SimpleStringFilter("shortname", value, true, false);
                    self.container.addContainerFilter(this.currentFilter);
                }
            }
        });
        this.comboBoxDatatypeFilter.setContainerDataSource(((XacmlAdminUI) UI.getCurrent()).getDatatypes());
        this.comboBoxDatatypeFilter.setImmediate(true);
        this.comboBoxDatatypeFilter.sereplacedemCaptionMode(ItemCaptionMode.PROPERTY);
        this.comboBoxDatatypeFilter.sereplacedemCaptionPropertyId("xacmlId");
        this.comboBoxDatatypeFilter.setNullSelectionAllowed(true);
        this.comboBoxDatatypeFilter.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            Container.Filter currentFilter = null;

            @Override
            public void valueChange(ValueChangeEvent event) {
                // 
                // Remove current filter
                // 
                if (this.currentFilter != null) {
                    self.container.removeContainerFilter(this.currentFilter);
                    this.currentFilter = null;
                }
                // 
                // Get the current selection
                // 
                Object id = self.comboBoxDatatypeFilter.getValue();
                if (id == null) {
                    return;
                }
                // 
                // Setup the filter
                // 
                final Datatype datatype = ((XacmlAdminUI) UI.getCurrent()).getDatatypes().gereplacedem(id).getEnreplacedy();
                this.currentFilter = new Container.Filter() {

                    private static final long serialVersionUID = 1L;

                    @Override
                    public boolean preplacedesFilter(Object itemId, Item item) throws UnsupportedOperationException {
                        if (itemId instanceof FunctionDefinition) {
                            Datatype dt = ((FunctionDefinition) itemId).getDatatypeBean();
                            if (dt == null) {
                                return false;
                            }
                            return dt.getXacmlId().equals(datatype.getXacmlId());
                        }
                        return false;
                    }

                    @Override
                    public boolean appliesToProperty(Object propertyId) {
                        if (propertyId != null && propertyId.toString().equals("datatypeBean")) {
                            return true;
                        }
                        return false;
                    }
                };
                self.container.addContainerFilter(this.currentFilter);
            }
        });
        this.checkBoxFilterIsBag.setImmediate(true);
        this.checkBoxFilterIsBag.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            Filter currentFilter = null;

            @Override
            public void valueChange(ValueChangeEvent event) {
                // 
                // Remove current filter
                // 
                if (this.currentFilter != null) {
                    self.container.removeContainerFilter(this.currentFilter);
                    this.currentFilter = null;
                }
                // 
                // Is it checked?
                // 
                if (self.checkBoxFilterIsBag.getValue() == false) {
                    // 
                    // Nope, get out of here
                    // 
                    return;
                }
                // 
                // Add the filter
                // 
                this.currentFilter = new Compare.Equal("isBagReturn", true);
                self.container.addContainerFilter(this.currentFilter);
            }
        });
    }

    protected void selected() {
        // 
        // Is there a selected function?
        // 
        try {
            // 
            // Run the commit
            // 
            this.textAreaDescription.commit();
            this.tableFunction.commit();
            // 
            // Commit worked, get the selected function
            // 
            Object id = this.tableFunction.getValue();
            // 
            // Sanity check, it *should* never be null
            // unless someone changed the initialization code.
            // 
            if (id == null || !(id instanceof FunctionDefinition)) {
                throw new InvalidValueException(this.tableFunction.getRequiredError());
            }
            // 
            // Get the actual function and save it into the apply
            // 
            this.function = (FunctionDefinition) id;
            this.apply.setDescription(this.textAreaDescription.getValue());
            this.apply.setFunctionId(function.getXacmlid());
        } catch (SourceException | InvalidValueException e) {
            // 
            // Vaadin GUI will display message
            // 
            return;
        }
        /**
         * 		//
         * 		// Make sure the arguments are good
         * 		//
         * 		final ApplyType copyApply = XACMLObjectCopy.copy(this.apply);
         * 		final ApplyArgumentsEditorWindow window = new ApplyArgumentsEditorWindow(copyApply, this.function);
         * 		window.setCaption("Define Arguments for " + this.function.getShortname());
         * 		window.setModal(true);
         * 		window.addCloseListener(new CloseListener() {
         * 			private static final long serialVersionUID = 1L;
         *
         * 			@Override
         * 			public void windowClose(CloseEvent e) {
         * 				//
         * 				// Did the user click save?
         * 				//
         * 				if (window.isSaved() == false) {
         * 					return;
         * 				}
         * 				//
         * 				// Save our arguments
         * 				//
         * 				self.apply.getExpression().clear();
         * 				self.apply.getExpression().addAll(copyApply.getExpression());
         * 				//
         * 				// We are saved
         * 				//
         * 				self.isSaved = true;
         * 				//
         * 				// Fire
         * 				//
         * 				self.fireEvent(self.apply, self.applyParent, self.argument, self.parent);
         * 				//
         * 				// Close the apply editor window
         * 				//
         * 				self.close();
         * 			}
         * 		});
         * 		window.center();
         * 		UI.getCurrent().addWindow(window);
         */
        // 
        // We are saved
        // 
        self.isSaved = true;
        // 
        // Fire
        // 
        self.fireEvent(self.apply, self.applyParent, self.argument, self.parent);
        // 
        // Close the apply editor window
        // 
        self.close();
    }

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

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

    @Override
    public void fireEvent(ApplyType apply, ApplyType parent, FunctionArgument argument, Object container) {
        this.notifier.fireEvent(apply, parent, argument, container);
    }

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

    public FunctionDefinition getSelectedFunction() {
        return this.function;
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("-1px");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // horizontalLayout_1
        horizontalLayout_1 = buildHorizontalLayout_1();
        mainLayout.addComponent(horizontalLayout_1);
        // tableFunction
        tableFunction = new Table();
        tableFunction.setCaption("Select A Function");
        tableFunction.setImmediate(false);
        tableFunction.setWidth("100.0%");
        tableFunction.setHeight("-1px");
        tableFunction.setInvalidAllowed(false);
        tableFunction.setRequired(true);
        mainLayout.addComponent(tableFunction);
        mainLayout.setExpandRatio(tableFunction, 1.0f);
        // buttonSelect
        buttonSelect = new Button();
        buttonSelect.setCaption("Select and Continue");
        buttonSelect.setImmediate(true);
        buttonSelect.setWidth("-1px");
        buttonSelect.setHeight("-1px");
        mainLayout.addComponent(buttonSelect);
        mainLayout.setComponentAlignment(buttonSelect, new Alignment(48));
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayout_1() {
        // common part: create layout
        horizontalLayout_1 = new HorizontalLayout();
        horizontalLayout_1.setImmediate(false);
        horizontalLayout_1.setWidth("-1px");
        horizontalLayout_1.setHeight("-1px");
        horizontalLayout_1.setMargin(false);
        horizontalLayout_1.setSpacing(true);
        // textAreaDescription
        textAreaDescription = new TextArea();
        textAreaDescription.setCaption("Enter A Description");
        textAreaDescription.setImmediate(false);
        textAreaDescription.setWidth("50.0%");
        textAreaDescription.setHeight("-1px");
        horizontalLayout_1.addComponent(textAreaDescription);
        // textFieldFilter
        textFieldFilter = new TextField();
        textFieldFilter.setCaption("Filter Function By ID");
        textFieldFilter.setImmediate(false);
        textFieldFilter.setWidth("-1px");
        textFieldFilter.setHeight("-1px");
        horizontalLayout_1.addComponent(textFieldFilter);
        horizontalLayout_1.setComponentAlignment(textFieldFilter, new Alignment(9));
        // comboBoxDatatypeFilter
        comboBoxDatatypeFilter = new ComboBox();
        comboBoxDatatypeFilter.setCaption("Filter By Data Type");
        comboBoxDatatypeFilter.setImmediate(false);
        comboBoxDatatypeFilter.setWidth("-1px");
        comboBoxDatatypeFilter.setHeight("-1px");
        horizontalLayout_1.addComponent(comboBoxDatatypeFilter);
        horizontalLayout_1.setComponentAlignment(comboBoxDatatypeFilter, new Alignment(9));
        // checkBoxFilterIsBag
        checkBoxFilterIsBag = new CheckBox();
        checkBoxFilterIsBag.setCaption("Is Bag Filter");
        checkBoxFilterIsBag.setImmediate(false);
        checkBoxFilterIsBag.setWidth("-1px");
        checkBoxFilterIsBag.setHeight("-1px");
        horizontalLayout_1.addComponent(checkBoxFilterIsBag);
        horizontalLayout_1.setComponentAlignment(checkBoxFilterIsBag, new Alignment(9));
        return horizontalLayout_1;
    }
}

16 View Complete Implementation : ApplyEditorWindow.java
Copyright MIT License
Author : att
public clreplaced ApplyEditorWindow extends Window implements ApplyParametersChangedNotifier {

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

    @AutoGenerated
    private Button buttonSelect;

    @AutoGenerated
    private Table tableFunction;

    @AutoGenerated
    private HorizontalLayout horizontalLayout_1;

    @AutoGenerated
    private CheckBox checkBoxFilterIsBag;

    @AutoGenerated
    private ComboBox comboBoxDatatypeFilter;

    @AutoGenerated
    private TextField textFieldFilter;

    @AutoGenerated
    private TextArea textAreaDescription;

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

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

    private final ApplyEditorWindow self = this;

    private final ApplyParametersChangedNotifier notifier = new ApplyParametersChangedNotifier.BasicNotifier();

    private final BeanItemContainer<FunctionDefinition> container = new BeanItemContainer<FunctionDefinition>(FunctionDefinition.clreplaced);

    private final ApplyType apply;

    private final ApplyType applyParent;

    private final FunctionArgument argument;

    private final Object parent;

    private boolean isSaved = false;

    private FunctionDefinition function = null;

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     * @param apply
     * @param parent
     * @param parentApply
     * @param argument
     */
    public ApplyEditorWindow(ApplyType apply, ApplyType parentApply, FunctionArgument argument, Object parent) {
        buildMainLayout();
        // setCompositionRoot(mainLayout);
        setContent(mainLayout);
        // 
        // Save
        // 
        this.apply = apply;
        this.applyParent = parentApply;
        this.argument = argument;
        this.parent = parent;
        logger.info(this.apply + " " + this.applyParent + " " + this.argument + " " + this.parent);
        // 
        // Set our shortcuts
        // 
        this.setCloseShortcut(KeyCode.ESCAPE);
        // 
        // Initialize
        // 
        this.textAreaDescription.setValue(apply.getDescription());
        this.textAreaDescription.setNullRepresentation("");
        this.initializeButton();
        this.initializeTable();
        this.initializeFilters();
        // 
        // focus
        // 
        this.textFieldFilter.focus();
    }

    protected void initializeTable() {
        // 
        // Setup GUI properties
        // 
        this.tableFunction.setImmediate(true);
        this.tableFunction.setSelectable(true);
        this.tableFunction.setNullSelectionAllowed(false);
        this.tableFunction.setRequired(true);
        this.tableFunction.setRequiredError("You MUST select a function for the Apply");
        // 
        // Set its data source
        // 
        this.tableFunction.setContainerDataSource(this.container);
        this.tableFunction.setVisibleColumns(new Object[] { "xacmlid", "shortname", "datatypeBean", "isBagReturn" });
        this.tableFunction.setColumnHeaders(new String[] { "Function Xacml ID", "ID", "Return Data Type", "Return Bag?" });
        // 
        // Determine appropriate filters
        // 
        Datatype datatypeId = null;
        if (this.applyParent == null) {
            if (this.parent instanceof ConditionType) {
                // 
                // Only boolean functions allowed
                // 
                datatypeId = JPAUtils.findDatatype(XACML3.ID_DATATYPE_BOOLEAN);
            }
        } else {
            String parentFunction = this.applyParent.getFunctionId();
            this.function = JPAUtils.findFunction(parentFunction);
            if (this.function == null) {
                throw new IllegalArgumentException("applyParent's function is not found:" + parentFunction);
            }
            if (this.argument == null) {
                throw new IllegalArgumentException("Need to know what argument apply is ");
            }
            datatypeId = this.argument.getDatatypeBean();
        }
        Map<Datatype, List<FunctionDefinition>> functionMap = JPAUtils.getFunctionDatatypeMap();
        if (datatypeId == null) {
            // 
            // All functions are available
            // 
            for (Datatype id : functionMap.keySet()) {
                this.addTableEntries(functionMap.get(id));
            }
        } else {
            for (Datatype id : functionMap.keySet()) {
                if (id == null) {
                    if (datatypeId == null) {
                        this.addTableEntries(functionMap.get(id));
                        break;
                    }
                    continue;
                }
                if (id.getId() == datatypeId.getId()) {
                    this.addTableEntries(functionMap.get(id));
                    break;
                }
            }
        }
        // 
        // Setup double-click
        // 
        this.tableFunction.addItemClickListener(new ItemClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void itemClick(ItemClickEvent event) {
                if (event.isDoubleClick()) {
                    self.selected();
                }
            }
        });
        // 
        // Value change listener
        // 
        this.tableFunction.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                logger.info("valueChange " + self.tableFunction.getValue());
                if (self.tableFunction.getValue() != null) {
                    self.buttonSelect.setEnabled(true);
                } else {
                    self.buttonSelect.setEnabled(false);
                }
            }
        });
        // 
        // Select current value if possible
        // 
        if (this.apply != null && this.apply.getFunctionId() != null && this.apply.getFunctionId().isEmpty() == false) {
            FunctionDefinition current = JPAUtils.findFunction(this.apply.getFunctionId());
            if (current != null) {
                this.tableFunction.select(current);
                this.tableFunction.setCurrentPageFirsreplacedemId(current);
            } else {
                logger.warn("Could not find function in table for " + this.apply.getFunctionId());
            }
        } else {
            this.buttonSelect.setEnabled(false);
        }
    }

    protected void addTableEntries(List<FunctionDefinition> functions) {
        if (functions == null) {
            logger.warn("NULL list of functions, cannot add to table.");
            return;
        }
        for (FunctionDefinition function : functions) {
            // 
            // Just check if this function is available for this
            // apply.
            // 
            // if (XACMLFunctionValidator.isFunctionAvailable(function, this.apply, this.argument)) {
            this.container.addBean(function);
        // } else {
        // if (logger.isDebugEnabled()) {
        // logger.debug("Function not available: " + function);
        // }
        // }
        }
    }

    protected void initializeButton() {
        this.buttonSelect.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

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

    protected void initializeFilters() {
        this.textFieldFilter.setImmediate(true);
        this.textFieldFilter.addTextChangeListener(new TextChangeListener() {

            private static final long serialVersionUID = 1L;

            SimpleStringFilter currentFilter = null;

            @Override
            public void textChange(TextChangeEvent event) {
                // 
                // Remove current filter
                // 
                if (this.currentFilter != null) {
                    self.container.removeContainerFilter(this.currentFilter);
                    this.currentFilter = null;
                }
                // 
                // Get the text
                // 
                String value = event.getText();
                if (value != null && value.length() > 0) {
                    // 
                    // Add the new filter
                    // 
                    this.currentFilter = new SimpleStringFilter("shortname", value, true, false);
                    self.container.addContainerFilter(this.currentFilter);
                }
            }
        });
        this.comboBoxDatatypeFilter.setContainerDataSource(((XacmlAdminUI) UI.getCurrent()).getDatatypes());
        this.comboBoxDatatypeFilter.setImmediate(true);
        this.comboBoxDatatypeFilter.sereplacedemCaptionMode(ItemCaptionMode.PROPERTY);
        this.comboBoxDatatypeFilter.sereplacedemCaptionPropertyId("xacmlId");
        this.comboBoxDatatypeFilter.setNullSelectionAllowed(true);
        this.comboBoxDatatypeFilter.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            Container.Filter currentFilter = null;

            @Override
            public void valueChange(ValueChangeEvent event) {
                // 
                // Remove current filter
                // 
                if (this.currentFilter != null) {
                    self.container.removeContainerFilter(this.currentFilter);
                    this.currentFilter = null;
                }
                // 
                // Get the current selection
                // 
                Object id = self.comboBoxDatatypeFilter.getValue();
                if (id == null) {
                    return;
                }
                // 
                // Setup the filter
                // 
                final Datatype datatype = ((XacmlAdminUI) UI.getCurrent()).getDatatypes().gereplacedem(id).getEnreplacedy();
                this.currentFilter = new Container.Filter() {

                    private static final long serialVersionUID = 1L;

                    @Override
                    public boolean preplacedesFilter(Object itemId, Item item) throws UnsupportedOperationException {
                        if (itemId instanceof FunctionDefinition) {
                            Datatype dt = ((FunctionDefinition) itemId).getDatatypeBean();
                            if (dt == null) {
                                return false;
                            }
                            return (dt.getXacmlId().equals(datatype.getXacmlId()));
                        }
                        return false;
                    }

                    @Override
                    public boolean appliesToProperty(Object propertyId) {
                        if (propertyId != null && propertyId.toString().equals("datatypeBean")) {
                            return true;
                        }
                        return false;
                    }
                };
                self.container.addContainerFilter(this.currentFilter);
            }
        });
        this.checkBoxFilterIsBag.setImmediate(true);
        this.checkBoxFilterIsBag.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            Filter currentFilter = null;

            @Override
            public void valueChange(ValueChangeEvent event) {
                // 
                // Remove current filter
                // 
                if (this.currentFilter != null) {
                    self.container.removeContainerFilter(this.currentFilter);
                    this.currentFilter = null;
                }
                // 
                // Is it checked?
                // 
                if (self.checkBoxFilterIsBag.getValue() == false) {
                    // 
                    // Nope, get out of here
                    // 
                    return;
                }
                // 
                // Add the filter
                // 
                this.currentFilter = new Compare.Equal("isBagReturn", true);
                self.container.addContainerFilter(this.currentFilter);
            }
        });
    }

    protected void selected() {
        // 
        // Is there a selected function?
        // 
        try {
            // 
            // Run the commit
            // 
            this.textAreaDescription.commit();
            this.tableFunction.commit();
            // 
            // Commit worked, get the selected function
            // 
            Object id = this.tableFunction.getValue();
            // 
            // Sanity check, it *should* never be null
            // unless someone changed the initialization code.
            // 
            if (id == null || !(id instanceof FunctionDefinition)) {
                throw new InvalidValueException(this.tableFunction.getRequiredError());
            }
            // 
            // Get the actual function and save it into the apply
            // 
            this.function = (FunctionDefinition) id;
            this.apply.setDescription(this.textAreaDescription.getValue());
            this.apply.setFunctionId(function.getXacmlid());
        } catch (SourceException | InvalidValueException e) {
            // 
            // Vaadin GUI will display message
            // 
            return;
        }
        /**
         * 		//
         * 		// Make sure the arguments are good
         * 		//
         * 		final ApplyType copyApply = XACMLObjectCopy.copy(this.apply);
         * 		final ApplyArgumentsEditorWindow window = new ApplyArgumentsEditorWindow(copyApply, this.function);
         * 		window.setCaption("Define Arguments for " + this.function.getShortname());
         * 		window.setModal(true);
         * 		window.addCloseListener(new CloseListener() {
         * 			private static final long serialVersionUID = 1L;
         *
         * 			@Override
         * 			public void windowClose(CloseEvent e) {
         * 				//
         * 				// Did the user click save?
         * 				//
         * 				if (window.isSaved() == false) {
         * 					return;
         * 				}
         * 				//
         * 				// Save our arguments
         * 				//
         * 				self.apply.getExpression().clear();
         * 				self.apply.getExpression().addAll(copyApply.getExpression());
         * 				//
         * 				// We are saved
         * 				//
         * 				self.isSaved = true;
         * 				//
         * 				// Fire
         * 				//
         * 				self.fireEvent(self.apply, self.applyParent, self.argument, self.parent);
         * 				//
         * 				// Close the apply editor window
         * 				//
         * 				self.close();
         * 			}
         * 		});
         * 		window.center();
         * 		UI.getCurrent().addWindow(window);
         */
        // 
        // We are saved
        // 
        self.isSaved = true;
        // 
        // Fire
        // 
        self.fireEvent(self.apply, self.applyParent, self.argument, self.parent);
        // 
        // Close the apply editor window
        // 
        self.close();
    }

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

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

    @Override
    public void fireEvent(ApplyType apply, ApplyType parent, FunctionArgument argument, Object container) {
        this.notifier.fireEvent(apply, parent, argument, container);
    }

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

    public FunctionDefinition getSelectedFunction() {
        return this.function;
    }

    @AutoGenerated
    private VerticalLayout buildMainLayout() {
        // common part: create layout
        mainLayout = new VerticalLayout();
        mainLayout.setImmediate(false);
        mainLayout.setWidth("-1px");
        mainLayout.setHeight("-1px");
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);
        // top-level component properties
        setWidth("-1px");
        setHeight("-1px");
        // horizontalLayout_1
        horizontalLayout_1 = buildHorizontalLayout_1();
        mainLayout.addComponent(horizontalLayout_1);
        // tableFunction
        tableFunction = new Table();
        tableFunction.setCaption("Select A Function");
        tableFunction.setImmediate(false);
        tableFunction.setWidth("100.0%");
        tableFunction.setHeight("-1px");
        tableFunction.setInvalidAllowed(false);
        tableFunction.setRequired(true);
        mainLayout.addComponent(tableFunction);
        mainLayout.setExpandRatio(tableFunction, 1.0f);
        // buttonSelect
        buttonSelect = new Button();
        buttonSelect.setCaption("Select and Continue");
        buttonSelect.setImmediate(true);
        buttonSelect.setWidth("-1px");
        buttonSelect.setHeight("-1px");
        mainLayout.addComponent(buttonSelect);
        mainLayout.setComponentAlignment(buttonSelect, new Alignment(48));
        return mainLayout;
    }

    @AutoGenerated
    private HorizontalLayout buildHorizontalLayout_1() {
        // common part: create layout
        horizontalLayout_1 = new HorizontalLayout();
        horizontalLayout_1.setImmediate(false);
        horizontalLayout_1.setWidth("-1px");
        horizontalLayout_1.setHeight("-1px");
        horizontalLayout_1.setMargin(false);
        horizontalLayout_1.setSpacing(true);
        // textAreaDescription
        textAreaDescription = new TextArea();
        textAreaDescription.setCaption("Enter A Description");
        textAreaDescription.setImmediate(false);
        textAreaDescription.setWidth("50.0%");
        textAreaDescription.setHeight("-1px");
        horizontalLayout_1.addComponent(textAreaDescription);
        // textFieldFilter
        textFieldFilter = new TextField();
        textFieldFilter.setCaption("Filter Function By ID");
        textFieldFilter.setImmediate(false);
        textFieldFilter.setWidth("-1px");
        textFieldFilter.setHeight("-1px");
        horizontalLayout_1.addComponent(textFieldFilter);
        horizontalLayout_1.setComponentAlignment(textFieldFilter, new Alignment(9));
        // comboBoxDatatypeFilter
        comboBoxDatatypeFilter = new ComboBox();
        comboBoxDatatypeFilter.setCaption("Filter By Data Type");
        comboBoxDatatypeFilter.setImmediate(false);
        comboBoxDatatypeFilter.setWidth("-1px");
        comboBoxDatatypeFilter.setHeight("-1px");
        horizontalLayout_1.addComponent(comboBoxDatatypeFilter);
        horizontalLayout_1.setComponentAlignment(comboBoxDatatypeFilter, new Alignment(9));
        // checkBoxFilterIsBag
        checkBoxFilterIsBag = new CheckBox();
        checkBoxFilterIsBag.setCaption("Is Bag Filter");
        checkBoxFilterIsBag.setImmediate(false);
        checkBoxFilterIsBag.setWidth("-1px");
        checkBoxFilterIsBag.setHeight("-1px");
        horizontalLayout_1.addComponent(checkBoxFilterIsBag);
        horizontalLayout_1.setComponentAlignment(checkBoxFilterIsBag, new Alignment(9));
        return horizontalLayout_1;
    }
}

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

    private static final long serialVersionUID = 1L;

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

    private AttributeEditorWindow self = this;

    private boolean isSaved = false;

    private Attribute attribute;

    private FormLayout mainLayout = new FormLayout();

    @PropertyId("isDesignator")
    DesignatorSelectorField selectDesignator;

    @PropertyId("selectorPath")
    TextField selectorPath = new TextField("Attribute Selector Path");

    @PropertyId("xacmlId")
    TextField xacmlID = new TextField("XACML ID");

    @PropertyId("categoryBean")
    ComboBox category = new ComboBox("Category");

    @PropertyId("description")
    TextArea descriptionField = new TextArea("Description");

    @PropertyId("datatypeBean")
    ComboBox datatype = new ComboBox("DataType");

    @PropertyId("constraintType")
    ComboBox constraintTypes = new ComboBox("Constraint Type");

    @PropertyId("constraintValues")
    ConstraintField constraintValues;

    Button saveButton = new Button("Save");

    FieldGroup fieldGroup = null;

    /**
     * The constructor should first build the main layout, set the
     * composition root and then do any custom initialization.
     *
     * The constructor will not be automatically regenerated by the
     * visual editor.
     * @param enreplacedyItem
     */
    public AttributeEditorWindow(EnreplacedyItem<Attribute> enreplacedyItem) {
        // 
        // Save our attribute
        // 
        this.attribute = enreplacedyItem.getEnreplacedy();
        if (logger.isDebugEnabled()) {
            logger.debug("Editing attribute: " + enreplacedyItem.getEnreplacedy().toString());
        }
        // 
        // Set our shortcuts
        // 
        this.setCloseShortcut(KeyCode.ESCAPE);
        // 
        // Create our main layout
        // 
        this.setContent(mainLayout);
        // 
        // Finish setting up the main layout
        // 
        this.mainLayout.setSpacing(true);
        this.mainLayout.setMargin(true);
        // 
        // Setup option group, binding the
        // field group doesn't seem to work.
        // 
        this.selectDesignator = new DesignatorSelectorField(enreplacedyItem);
        this.selectDesignator.setCaption("Select the Attribute Type");
        this.selectDesignator.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                Object value = self.selectDesignator.getValue();
                if (value == null || !(value instanceof Character)) {
                    self.selectorPath.setVisible(false);
                }
                if (((Character) value) == '1') {
                    self.selectorPath.setVisible(false);
                } else {
                    self.selectorPath.setVisible(true);
                }
            }
        });
        // 
        // Setup selector path
        // 
        this.selectorPath.setImmediate(true);
        this.selectorPath.setNullRepresentation("");
        this.selectorPath.setWidth("100%");
        // 
        // Setup the Category combo
        // 
        this.category.setContainerDataSource(((XacmlAdminUI) UI.getCurrent()).getCategories());
        this.category.sereplacedemCaptionMode(ItemCaptionMode.PROPERTY);
        this.category.sereplacedemCaptionPropertyId("xacmlId");
        this.category.setFilteringMode(FilteringMode.CONTAINS);
        this.category.setImmediate(true);
        this.category.setNullSelectionAllowed(false);
        this.category.setConverter(new SingleSelectConverter<Object>(this.category));
        // 
        // Setup the Datatype combo
        // 
        this.datatype.setContainerDataSource(((XacmlAdminUI) UI.getCurrent()).getDatatypes());
        this.datatype.sereplacedemCaptionMode(ItemCaptionMode.PROPERTY);
        this.datatype.sereplacedemCaptionPropertyId("xacmlId");
        this.datatype.setFilteringMode(FilteringMode.CONTAINS);
        this.datatype.setImmediate(true);
        this.datatype.setNullSelectionAllowed(false);
        this.datatype.setConverter(new SingleSelectConverter<Object>(this.datatype));
        // 
        // Setup the constraint type combo
        // 
        this.constraintTypes.setContainerDataSource(((XacmlAdminUI) UI.getCurrent()).getConstraintTypes());
        this.constraintTypes.sereplacedemCaptionMode(ItemCaptionMode.PROPERTY);
        this.constraintTypes.sereplacedemCaptionPropertyId("constraintType");
        this.constraintTypes.setFilteringMode(FilteringMode.CONTAINS);
        this.constraintTypes.setImmediate(true);
        this.constraintTypes.setNullSelectionAllowed(true);
        this.constraintTypes.setConverter(new SingleSelectConverter<Object>(this.constraintTypes));
        // 
        // Setup the constraint value custom field
        // 
        this.constraintValues = new ConstraintField(enreplacedyItem);
        // 
        // Finish laying out the main layout
        // 
        this.mainLayout.addComponent(this.selectDesignator);
        this.mainLayout.addComponent(this.selectorPath);
        this.mainLayout.addComponent(this.xacmlID);
        this.mainLayout.addComponent(this.category);
        this.mainLayout.addComponent(this.descriptionField);
        this.mainLayout.addComponent(this.datatype);
        this.mainLayout.addComponent(this.constraintTypes);
        this.mainLayout.addComponent(this.constraintValues);
        // 
        // Now create our field group and bind our bean items
        // This will populate the components with the attribute's
        // current value.
        // 
        this.fieldGroup = new FieldGroup(enreplacedyItem);
        this.fieldGroup.bindMemberFields(this);
        // 
        // Finishing setting up after the bind. There are some components
        // where initializing the bind causes some properties to be reset.
        // 
        this.xacmlID.setWidth("100%");
        this.descriptionField.setNullRepresentation("");
        this.descriptionField.setWidth("100%");
        this.setupDatatype(this.attribute.getDatatypeBean().getIdentifer());
        this.datatype.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                Identifier id = self.getCurrentDatatype();
                if (id != null) {
                    self.setupDatatype(id);
                }
            }
        });
        // 
        // Listen to when constraint type changes
        // 
        this.constraintTypes.addValueChangeListener(new ValueChangeListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                Object value = self.constraintTypes.getValue();
                if (value == null) {
                    self.constraintValues.resetContent(null, self.getCurrentDatatype());
                } else {
                    ConstraintType newValue = ((XacmlAdminUI) UI.getCurrent()).getConstraintTypes().gereplacedem(value).getEnreplacedy();
                    self.constraintValues.resetContent(newValue, self.getCurrentDatatype());
                }
            }
        });
        // 
        // Setup our "SAVE" button to commit the fields
        // 
        this.mainLayout.addComponent(this.saveButton);
        this.mainLayout.setComponentAlignment(this.saveButton, Alignment.MIDDLE_CENTER);
        this.saveButton.addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void buttonClick(ClickEvent event) {
                try {
                    // 
                    // SAVE the latest values
                    // 
                    fieldGroup.commit();
                    // 
                    // Set that we did save the attribute
                    // 
                    self.isSaved = true;
                    // 
                    // Close the window
                    // 
                    self.close();
                } catch (CommitException e) {
                    logger.error("Failed to commit fields", e);
                }
            }
        });
        // 
        // Add our close listener so we can discard anything that was changed.
        // 
        this.addCloseListener(new CloseListener() {

            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                if (self.isSaved == false) {
                    logger.info("discarding");
                    // 
                    // Discard any changes to the existing JPA container enreplacedy
                    // 
                    self.fieldGroup.discard();
                    // 
                    // Make sure there are no filters on the container
                    // 
                    ((XacmlAdminUI) UI.getCurrent()).getConstraintTypes().removeAllContainerFilters();
                }
            }
        });
        // 
        // Set focus
        // 
        this.xacmlID.focus();
    }

    private void setupDatatype(Identifier datatype) {
        if (datatype.equals(XACML3.ID_DATATYPE_INTEGER) || datatype.equals(XACML3.ID_DATATYPE_DOUBLE)) {
            ((XacmlAdminUI) UI.getCurrent()).getConstraintTypes().removeAllContainerFilters();
            this.constraintTypes.setEnabled(true);
            this.constraintValues.resetDatatype(datatype);
            return;
        }
        if (datatype.equals(XACML3.ID_DATATYPE_STRING)) {
            ((XacmlAdminUI) UI.getCurrent()).getConstraintTypes().addContainerFilter(new Not(new Compare.Equal("constraintType", ConstraintType.RANGE_TYPE)));
            if (this.attribute.getConstraintType() != null && this.attribute.getConstraintType().getConstraintType() != null && this.attribute.getConstraintType().getConstraintType().equals(ConstraintType.RANGE_TYPE)) {
                this.attribute.setConstraintType(null);
            }
            this.constraintValues.resetDatatype(datatype);
            return;
        }
        // 
        // No constraint for all other datatypes
        // 
        this.attribute.setConstraintType(null);
        this.constraintTypes.select(null);
        this.constraintTypes.setEnabled(false);
    }

    private Identifier getCurrentDatatype() {
        Object id = self.datatype.getValue();
        if (id != null) {
            EnreplacedyItem<Datatype> dt = ((XacmlAdminUI) UI.getCurrent()).getDatatypes().gereplacedem(id);
            if (dt != null) {
                return dt.getEnreplacedy().getIdentifer();
            }
        }
        return null;
    }

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

16 View Complete Implementation : DemoUI.java
Copyright Apache License 2.0
Author : blackbluegl
@Override
protected void init(VaadinRequest request) {
    UI.getCurrent().setLocale(Locale.ENGLISH);
    // Initialize our new UI component
    MeetingCalendar meetings = new MeetingCalendar();
    meetings.setSizeFull();
    ComboBox<Locale> localeBox = new ComboBox<>();
    localeBox.sereplacedems(Locale.getAvailableLocales());
    localeBox.setEmptySelectionAllowed(false);
    localeBox.setValue(UI.getCurrent().getLocale());
    localeBox.addValueChangeListener(e -> meetings.getCalendar().setLocale(e.getValue()));
    ComboBox<String> zoneBox = new ComboBox<>();
    zoneBox.sereplacedems(ZoneId.getAvailableZoneIds());
    zoneBox.setEmptySelectionAllowed(false);
    zoneBox.setValue(meetings.getCalendar().getZoneId().getId());
    zoneBox.addValueChangeListener(e -> meetings.getCalendar().setZoneId(ZoneId.of(e.getValue())));
    CalStyle initial = new CalStyle("Day 1 - 7", () -> meetings.getCalendar().withVisibleDays(1, 7));
    ComboBox<CalStyle> calActionComboBox = new ComboBox<>();
    calActionComboBox.sereplacedems(initial, new CalStyle("Day 1 - 5", () -> meetings.getCalendar().withVisibleDays(1, 5)), new CalStyle("Day 2 - 5", () -> meetings.getCalendar().withVisibleDays(2, 5)), new CalStyle("Day 6 - 7", () -> meetings.getCalendar().withVisibleDays(6, 7)));
    calActionComboBox.addValueChangeListener(e -> e.getValue().act());
    calActionComboBox.setEmptySelectionAllowed(false);
    Button fixedSize = new Button("fixed Size", (Button.ClickEvent clickEvent) -> meetings.panel.setHeightUndefined());
    fixedSize.setIcon(VaadinIcons.LINK);
    Button fullSize = new Button("full Size", (Button.ClickEvent clickEvent) -> meetings.panel.setHeight(100, Unit.PERCENTAGE));
    fullSize.setIcon(VaadinIcons.UNLINK);
    ComboBox<Month> months = new ComboBox<>();
    months.sereplacedems(Month.values());
    months.sereplacedemCaptionGenerator(month -> month.getDisplayName(TextStyle.FULL, meetings.getCalendar().getLocale()));
    months.setEmptySelectionAllowed(false);
    months.addValueChangeListener(me -> meetings.switchToMonth(me.getValue()));
    Button today = new Button("today", (Button.ClickEvent clickEvent) -> meetings.getCalendar().withDay(LocalDate.now()));
    Button week = new Button("week", (Button.ClickEvent clickEvent) -> meetings.getCalendar().withWeek(LocalDate.now()));
    HorizontalLayout nav = new HorizontalLayout(localeBox, zoneBox, fixedSize, fullSize, months, today, week, calActionComboBox);
    // nav.setWidth("100%");
    // Show it in the middle of the screen
    final VerticalLayout layout = new VerticalLayout();
    layout.setStyleName("demoContentLayout");
    layout.setSizeFull();
    layout.setMargin(true);
    layout.setSpacing(true);
    layout.addComponent(nav);
    layout.addComponentsAndExpand(meetings);
    setContent(layout);
    calActionComboBox.setSelectedItem(initial);
}

16 View Complete Implementation : MaintenanceWindowLayout.java
Copyright Eclipse Public License 1.0
Author : eclipse
/**
 * {@link MaintenanceWindowLayout} defines UI layout that is used to specify the
 * maintenance schedule while replacedigning distribution set(s) to the target(s).
 */
public clreplaced MaintenanceWindowLayout extends VerticalLayout {

    private static final long serialVersionUID = 1L;

    private final VaadinMessageSource i18n;

    private static final String CRON_VALIDATION_ERROR = "message.maintenancewindow.schedule.validation.error";

    private TextField schedule;

    private TextField duration;

    private ComboBox timeZone;

    private Label scheduleTranslator;

    /**
     * Constructor for the control to specify the maintenance schedule.
     *
     * @param i18n
     *            (@link VaadinMessageSource} to get the localized resource
     *            strings.
     */
    public MaintenanceWindowLayout(final VaadinMessageSource i18n) {
        this.i18n = i18n;
        createMaintenanceScheduleControl();
        createMaintenanceDurationControl();
        createMaintenanceTimeZoneControl();
        createMaintenanceScheduleTranslatorControl();
        final HorizontalLayout controlContainer = new HorizontalLayout();
        controlContainer.addComponent(schedule);
        controlContainer.addComponent(duration);
        controlContainer.addComponent(timeZone);
        addComponent(controlContainer);
        addComponent(scheduleTranslator);
        setStyleName("dist-window-maintenance-window-layout");
        setId(UIComponentIdProvider.MAINTENANCE_WINDOW_LAYOUT_ID);
    }

    /**
     * Text field to specify the schedule.
     */
    private void createMaintenanceScheduleControl() {
        schedule = new TextFieldBuilder(Action.MAINTENANCE_WINDOW_SCHEDULE_LENGTH).id(UIComponentIdProvider.MAINTENANCE_WINDOW_SCHEDULE_ID).caption(i18n.getMessage("caption.maintenancewindow.schedule")).validator(new CronValidator()).prompt("0 0 3 ? * 6").required(true, i18n).buildTextComponent();
        schedule.addTextChangeListener(new CronTranslationListener());
    }

    /**
     * Validates if the maintenance schedule is a valid cron expression.
     */
    private clreplaced CronValidator implements Validator {

        private static final long serialVersionUID = 1L;

        // Exception squid:S1166 - Vaadin validation clreplaced,
        // InvalidValueException,
        // doesn't have the constructor to preplaced throwable, but shows the
        // validation
        // errors to the user
        @SuppressWarnings("squid:S1166")
        @Override
        public void validate(final Object value) {
            try {
                MaintenanceScheduleHelper.validateCronSchedule((String) value);
            } catch (final InvalidMaintenanceScheduleException e) {
                throw new InvalidValueException(i18n.getMessage(CRON_VALIDATION_ERROR) + ": " + e.getMessage());
            }
        }
    }

    /**
     * Used for cron expression translation.
     */
    private clreplaced CronTranslationListener implements TextChangeListener {

        private static final long serialVersionUID = 1L;

        private final transient CronDescriptor cronDescriptor;

        public CronTranslationListener() {
            cronDescriptor = CronDescriptor.instance(getClientsLocale());
        }

        @Override
        public void textChange(final TextChangeEvent event) {
            scheduleTranslator.setValue(translateCron(event.getText()));
        }

        // Exception squid:S1166 - when the format of the cron expression is not
        // valid, the hint is shown to provide the valid one
        @SuppressWarnings("squid:S1166")
        private String translateCron(final String cronExpression) {
            try {
                return cronDescriptor.describe(MaintenanceScheduleHelper.getCronFromExpression(cronExpression));
            } catch (final IllegalArgumentException ex) {
                return i18n.getMessage(CRON_VALIDATION_ERROR);
            }
        }

        private Locale getClientsLocale() {
            return Page.getCurrent().getWebBrowser().getLocale();
        }
    }

    /**
     * Text field to specify the duration.
     */
    private void createMaintenanceDurationControl() {
        duration = new TextFieldBuilder(Action.MAINTENANCE_WINDOW_DURATION_LENGTH).id(UIComponentIdProvider.MAINTENANCE_WINDOW_DURATION_ID).caption(i18n.getMessage("caption.maintenancewindow.duration")).validator(new DurationValidator()).prompt("hh:mm:ss").required(true, i18n).buildTextComponent();
    }

    /**
     * Validates if the duration is specified in expected format.
     */
    private clreplaced DurationValidator implements Validator {

        private static final long serialVersionUID = 1L;

        // Exception squid:S1166 - Vaadin validation clreplaced,
        // InvalidValueException,
        // doesn't have the constructor to preplaced throwable, but shows the
        // validation
        // errors to the user
        @SuppressWarnings("squid:S1166")
        @Override
        public void validate(final Object value) {
            try {
                MaintenanceScheduleHelper.validateDuration((String) value);
            } catch (final InvalidMaintenanceScheduleException e) {
                throw new InvalidValueException(i18n.getMessage("message.maintenancewindow.duration.validation.error", e.getDurationErrorIndex()));
            }
        }
    }

    /**
     * Combo box to pick the time zone offset.
     */
    private void createMaintenanceTimeZoneControl() {
        // ComboBoxBuilder cannot be used here, because Builder do
        // 'comboBox.sereplacedemCaptionPropertyId(SPUILabelDefinitions.VAR_NAME);'
        // which interferes our code: 'timeZone.addItems(getAllTimeZones());'
        timeZone = new ComboBox();
        timeZone.setId(UIComponentIdProvider.MAINTENANCE_WINDOW_TIME_ZONE_ID);
        timeZone.setCaption(i18n.getMessage("caption.maintenancewindow.timezone"));
        timeZone.addItems(getAllTimeZones());
        timeZone.setValue(getClientTimeZone());
        timeZone.addStyleName(ValoTheme.COMBOBOX_SMALL);
        timeZone.setTextInputAllowed(false);
        timeZone.setNullSelectionAllowed(false);
    }

    /**
     * Get list of all time zone offsets supported.
     */
    private static List<String> getAllTimeZones() {
        return ZoneId.getAvailableZoneIds().stream().map(id -> ZonedDateTime.now(ZoneId.of(id)).getOffset().getId().replace("Z", "+00:00")).distinct().sorted().collect(Collectors.toList());
    }

    /**
     * Get time zone of the browser client to be used as default.
     */
    private static String getClientTimeZone() {
        return ZonedDateTime.now(SPDateTimeUtil.getTimeZoneId(SPDateTimeUtil.getBrowserTimeZone())).getOffset().getId().replaceAll("Z", "+00:00");
    }

    /**
     * Label to translate the cron schedule to human readable format.
     */
    private void createMaintenanceScheduleTranslatorControl() {
        scheduleTranslator = new LabelBuilder().id(UIComponentIdProvider.MAINTENANCE_WINDOW_SCHEDULE_TRANSLATOR_ID).name(i18n.getMessage(CRON_VALIDATION_ERROR)).buildLabel();
        scheduleTranslator.addStyleName(ValoTheme.LABEL_TINY);
    }

    /**
     * Get the cron expression for maintenance schedule.
     *
     * @return {@link String}.
     */
    public String getMaintenanceSchedule() {
        return schedule.getValue();
    }

    /**
     * Get the maintenance window duration.
     *
     * @return {@link String}.
     */
    public String getMaintenanceDuration() {
        return duration.getValue();
    }

    /**
     * Get the timezone for maintenance window.
     *
     * @return {@link String}.
     */
    public String getMaintenanceTimeZone() {
        return timeZone.getValue().toString();
    }

    /**
     * Set all the controls to their default values.
     */
    public void clearAllControls() {
        schedule.setValue("");
        duration.setValue("");
        timeZone.setValue(getClientTimeZone());
        scheduleTranslator.setValue(i18n.getMessage(CRON_VALIDATION_ERROR));
    }

    /**
     * Method, used for validity check, when schedule text is changed.
     *
     * @param event
     *            (@link TextChangeEvent} the event object after schedule text
     *            change.
     * @return validity of maintenance window controls.
     */
    public boolean onScheduleChange(final TextChangeEvent event) {
        schedule.setValue(event.getText());
        return isScheduleAndDurationValid();
    }

    /**
     * Method, used for validity check, when duration text is changed.
     *
     * @param event
     *            (@link TextChangeEvent} the event object after duration text
     *            change.
     * @return validity of maintenance window controls.
     */
    public boolean onDurationChange(final TextChangeEvent event) {
        duration.setValue(event.getText());
        return isScheduleAndDurationValid();
    }

    private boolean isScheduleAndDurationValid() {
        if (schedule.isEmpty() || duration.isEmpty()) {
            return false;
        }
        return schedule.isValid() && duration.isValid();
    }

    public TextField getScheduleControl() {
        return schedule;
    }

    public TextField getDurationControl() {
        return duration;
    }
}

16 View Complete Implementation : BaseSecurityGroupWindow.java
Copyright Apache License 2.0
Author : opensecuritycontroller
public abstract clreplaced BaseSecurityGroupWindow extends LoadingIndicatorCRUDBaseWindow {

    private static final int TEXT_CHANGE_FILTER_DELAY = 500;

    private static final int SELECTOR_TABLE_HEIGHT = 200;

    private static final int SELECTOR_TABLE_WIDTH = 400;

    private static final int ITEMS_NAME_COLUMN_WIDTH = SELECTOR_TABLE_WIDTH - 3;

    private static final int SELECTED_TABLE_WIDTH = SELECTOR_TABLE_WIDTH + 250;

    private static final int SELECTED_ITEMS_NAME_COLUMN_WIDTH = ITEMS_NAME_COLUMN_WIDTH - 130;

    private static final int SELECTED_ITEMS_REGION_COLUMN_WIDTH = SELECTED_TABLE_WIDTH - ITEMS_NAME_COLUMN_WIDTH - 150;

    private static final int SELECTED_ITEMS_TYPE_COLUMN_WIDTH = SELECTED_TABLE_WIDTH - SELECTED_ITEMS_NAME_COLUMN_WIDTH - SELECTED_ITEMS_REGION_COLUMN_WIDTH - 165;

    private static final String PROTECT_EXTERNAL = "protectExternal";

    private static final String SECURITY_GROUP_MEMBER_VM = "VM";

    private static final String SECURITY_GROUP_MEMBER_NETWORK = "NETWORK";

    private static final String SECURITY_GROUP_MEMBER_SUBNET = "SUBNET";

    private final clreplaced ImmediateTextFilterDecorator implements FilterDecorator {

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

        @Override
        public boolean usePopupForNumericProperty(Object propertyId) {
            return false;
        }

        @Override
        public boolean isTextFilterImmediate(Object propertyId) {
            return true;
        }

        @Override
        public String getToCaption() {
            return null;
        }

        @Override
        public int getTextChangeTimeout(Object propertyId) {
            return TEXT_CHANGE_FILTER_DELAY;
        }

        @Override
        public String getSetCaption() {
            return null;
        }

        @Override
        public NumberFilterPopupConfig getNumberFilterPopupConfig() {
            return null;
        }

        @Override
        public Locale getLocale() {
            return null;
        }

        @Override
        public String getFromCaption() {
            return null;
        }

        @Override
        public Resource getEnumFilterIcon(Object propertyId, Object value) {
            return null;
        }

        @Override
        public String getEnumFilterDisplayName(Object propertyId, Object value) {
            return null;
        }

        @Override
        public String getDateFormatPattern(Object propertyId) {
            return null;
        }

        @Override
        public Resolution getDateFieldResolution(Object propertyId) {
            return null;
        }

        @Override
        public String getClearCaption() {
            return null;
        }

        @Override
        public Resource getBooleanFilterIcon(Object propertyId, boolean value) {
            return null;
        }

        @Override
        public String getBooleanFilterDisplayName(Object propertyId, boolean value) {
            return null;
        }

        @Override
        public String getAllItemsVisibleString() {
            return null;
        }
    }

    private static final long serialVersionUID = 1L;

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

    protected SecurityGroupDto currentSecurityGroup = null;

    private ValueChangeListener projectChangedListener;

    private ValueChangeListener triggerPopulateFromListListener;

    /**
     * Indicates whether the from list is being loaded for the first time or not. After the first time
     * the from list is loaded, this is set to false.
     */
    private boolean isInitialFromListLoad = true;

    protected static final String TYPE_SELECTION = "By Type";

    protected static final String TYPE_ALL = "All Servers belonging to Project";

    // form fields
    protected TextField name;

    protected ComboBox project;

    protected ComboBox region;

    protected OptionGroup protectionTypeOption;

    protected ComboBox protectionEnreplacedyType;

    protected VerticalLayout selector;

    protected FilterTable itemsTable;

    protected FilterTable selectedItemsTable;

    protected BeanContainer<String, SecurityGroupMemberItemDto> itemsContainer;

    protected BeanContainer<String, SecurityGroupMemberItemDto> selectedItemsContainer;

    private ListOpenstackMembersServiceApi listOpenstackMembersService;

    private ListRegionByVcIdServiceApi listRegionByVcIdService;

    private ListProjectByVcIdServiceApi listProjectByVcIdServiceApi;

    private ListSecurityGroupMembersBySgServiceApi listSecurityGroupMembersBySgService;

    public BaseSecurityGroupWindow(ListOpenstackMembersServiceApi listOpenstackMembersService, ListRegionByVcIdServiceApi listRegionByVcIdService, ListProjectByVcIdServiceApi listProjectByVcIdServiceApi, ListSecurityGroupMembersBySgServiceApi listSecurityGroupMembersBySgService) {
        super();
        this.listOpenstackMembersService = listOpenstackMembersService;
        this.listRegionByVcIdService = listRegionByVcIdService;
        this.listProjectByVcIdServiceApi = listProjectByVcIdServiceApi;
        this.listSecurityGroupMembersBySgService = listSecurityGroupMembersBySgService;
        initListeners();
    }

    @SuppressWarnings("serial")
    private Component getType() {
        this.protectionTypeOption = new OptionGroup("Selection Type:");
        this.protectionTypeOption.addItem(TYPE_ALL);
        this.protectionTypeOption.addItem(TYPE_SELECTION);
        this.protectionTypeOption.select(TYPE_ALL);
        this.protectionTypeOption.addValueChangeListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                if (BaseSecurityGroupWindow.this.protectionTypeOption.getValue() == TYPE_ALL) {
                    enableSelection(false);
                } else if (BaseSecurityGroupWindow.this.protectionTypeOption.getValue() == TYPE_SELECTION) {
                    enableSelection(true);
                }
                // Populate to list first and then the from list since we use the 'to' list items to exclude them from
                // the 'from' list
                populateToList();
                populateFromList();
            }
        });
        return this.protectionTypeOption;
    }

    private Component getProtectionEnreplacedyType() {
        this.protectionEnreplacedyType = new ComboBox();
        this.protectionEnreplacedyType.setTextInputAllowed(false);
        this.protectionEnreplacedyType.setNullSelectionAllowed(false);
        this.protectionEnreplacedyType.addItem(SECURITY_GROUP_MEMBER_VM);
        this.protectionEnreplacedyType.addItem(SECURITY_GROUP_MEMBER_NETWORK);
        this.protectionEnreplacedyType.addItem(SECURITY_GROUP_MEMBER_SUBNET);
        this.protectionEnreplacedyType.select(SECURITY_GROUP_MEMBER_VM);
        this.protectionEnreplacedyType.addValueChangeListener(this.triggerPopulateFromListListener);
        return this.protectionEnreplacedyType;
    }

    protected void enableSelection(boolean enable) {
        this.protectionEnreplacedyType.setEnabled(enable);
        this.selector.setEnabled(enable);
        this.selectedItemsTable.setEnabled(enable);
        this.itemsTable.setEnabled(enable);
    }

    @Override
    public void initForm() {
        try {
            this.form.addComponent(getName());
            this.form.addComponent(getProject());
            this.form.addComponent(getRegion());
            this.form.addComponent(getType());
            this.form.addComponent(getProtectionEnreplacedyType());
            this.content.addComponent(getSelectionWidget());
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
        }
    }

    @Override
    public void makeServiceCalls(ProgressIndicatorWindow progressIndicatorWindow) {
        progressIndicatorWindow.updateStatus("Populating Project Information");
        // Dont auto select project in case of update, since update sets the project automatically once the load completes.
        populateProjects(!isUpdateWindow());
        progressIndicatorWindow.updateStatus("Populating Region Information");
        populateRegion();
    }

    @Override
    public boolean validateForm() {
        try {
            this.name.validate();
            this.project.validate();
            return true;
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage() + ".", Notification.Type.ERROR_MESSAGE);
        }
        return false;
    }

    protected TextField getName() {
        this.name = new TextField("Name");
        this.name.setImmediate(true);
        this.name.setRequired(true);
        this.name.setRequiredError("Name cannot be empty");
        return this.name;
    }

    protected ComboBox getProject() {
        try {
            this.project = new ComboBox("Select Project");
            this.project.setTextInputAllowed(true);
            this.project.setNullSelectionAllowed(false);
            this.project.setImmediate(true);
            this.project.setRequired(true);
            this.project.setRequiredError("Project cannot be empty");
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
            log.error("Error populating Project List combobox", e);
        }
        return this.project;
    }

    protected ComboBox getRegion() {
        this.region = new ComboBox("Select Region");
        this.region.setTextInputAllowed(false);
        this.region.setNullSelectionAllowed(true);
        this.region.setImmediate(true);
        return this.region;
    }

    @SuppressWarnings("serial")
    protected Component getSelectionWidget() {
        this.selector = new VerticalLayout();
        this.selector.addStyleName(StyleConstants.VMIDC_WINDOW_CONTENT_WRAPPER);
        this.selector.setSizeFull();
        this.itemsTable = createSelectorTable();
        this.itemsTable.setCaption(VmidcMessages.getString(VmidcMessages_.SELECTOR_replacedLE));
        this.itemsTable.setColumnWidth("name", ITEMS_NAME_COLUMN_WIDTH);
        this.itemsContainer = createItemContainer();
        this.itemsTable.setContainerDataSource(this.itemsContainer);
        this.itemsTable.setVisibleColumns("name");
        this.selectedItemsTable = createSelectorTable();
        this.selectedItemsTable.setCaption(VmidcMessages.getString(VmidcMessages_.SELECTED_replacedLE));
        this.selectedItemsTable.setWidth(SELECTED_TABLE_WIDTH + "px");
        this.selectedItemsTable.setColumnWidth("name", SELECTED_ITEMS_NAME_COLUMN_WIDTH);
        this.selectedItemsTable.setColumnWidth("region", SELECTED_ITEMS_REGION_COLUMN_WIDTH);
        this.selectedItemsTable.setColumnWidth("type", SELECTED_ITEMS_TYPE_COLUMN_WIDTH);
        this.selectedItemsContainer = createItemContainer();
        this.selectedItemsTable.setContainerDataSource(this.selectedItemsContainer);
        this.selectedItemsTable.setVisibleColumns("name", "region", "type", PROTECT_EXTERNAL);
        this.selectedItemsTable.setColumnHeader(PROTECT_EXTERNAL, "Protect External");
        VerticalLayout selectorButtonLayout = new VerticalLayout();
        selectorButtonLayout.addStyleName(StyleConstants.SELECTOR_BUTTON_LAYOUT);
        Button addButton = new Button(VmidcMessages.getString(VmidcMessages_.SELECTOR_TO_BUTTON));
        addButton.addStyleName(StyleConstants.SELECTOR_BUTTON);
        addButton.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                moveItems(BaseSecurityGroupWindow.this.itemsTable, BaseSecurityGroupWindow.this.selectedItemsTable);
            }
        });
        Button removeButton = new Button(VmidcMessages.getString(VmidcMessages_.SELECTOR_FROM_BUTTON));
        removeButton.addStyleName(StyleConstants.SELECTOR_BUTTON);
        removeButton.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                moveItems(BaseSecurityGroupWindow.this.selectedItemsTable, BaseSecurityGroupWindow.this.itemsTable);
            }
        });
        selectorButtonLayout.addComponent(addButton);
        selectorButtonLayout.addComponent(removeButton);
        HorizontalLayout selectorLayout = new HorizontalLayout();
        selectorLayout.addComponent(createSelectorTableLayout(this.itemsTable, this.itemsContainer));
        selectorLayout.addComponent(selectorButtonLayout);
        selectorLayout.addComponent(createSelectorTableLayout(this.selectedItemsTable, this.selectedItemsContainer));
        this.selector.addComponent(selectorLayout);
        return this.selector;
    }

    protected void updateCountFooter(CustomTable table, int count) {
        table.setColumnFooter("name", VmidcMessages.getString(VmidcMessages_.SELECTOR_COUNT, count));
    }

    protected void populateToList() {
        this.selectedItemsContainer.removeAllItems();
        this.selectedItemsTable.removeAllItems();
        if (this.protectionTypeOption.getValue() != TYPE_ALL && this.currentSecurityGroup.getId() != null) {
            try {
                SetResponse<SecurityGroupMemberItemDto> response = this.listSecurityGroupMembersBySgService.dispatch(new BaseIdRequest(this.currentSecurityGroup.getId()));
                CustomTable toTable = this.selectedItemsTable;
                for (SecurityGroupMemberItemDto memberItem : response.getSet()) {
                    this.selectedItemsContainer.addBean(memberItem);
                    handleProtectExternal(toTable, memberItem.getOpenstackId(), memberItem);
                }
                updateCountFooter(this.selectedItemsTable, this.selectedItemsTable.gereplacedemIds().size());
            } catch (Exception e) {
                ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
                log.error("Error getting to Servers List", e);
            }
        }
    }

    private void populateProjects(boolean autoSelect) {
        try {
            Long vcId = this.currentSecurityGroup.getParentId();
            if (vcId != null) {
                // Calling List Service
                BaseIdRequest req = new BaseIdRequest();
                req.setId(vcId);
                List<OsProjectDto> projectList = this.listProjectByVcIdServiceApi.dispatch(req).getList();
                this.project.removeValueChangeListener(this.projectChangedListener);
                this.project.removeAllItems();
                BeanItemContainer<OsProjectDto> projectListContainer = new BeanItemContainer<>(OsProjectDto.clreplaced, projectList);
                this.project.setContainerDataSource(projectListContainer);
                this.project.sereplacedemCaptionPropertyId("name");
                this.project.addValueChangeListener(this.projectChangedListener);
                if (autoSelect && projectList.get(0) != null) {
                    this.project.select(projectList.get(0));
                }
            } else {
                this.project.removeAllItems();
            }
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
            log.error("Error getting project List", e);
        }
    }

    private void populateRegion() {
        try {
            OsProjectDto projectDto = (OsProjectDto) this.project.getValue();
            if (projectDto != null) {
                this.region.removeValueChangeListener(this.triggerPopulateFromListListener);
                this.region.removeAllItems();
                BaseOpenStackRequest req = new BaseOpenStackRequest();
                req.setProjectName(projectDto.getName());
                req.setProjectId(projectDto.getId());
                req.setId(this.currentSecurityGroup.getParentId());
                ListResponse<String> response = this.listRegionByVcIdService.dispatch(req);
                this.region.addItems(response.getList());
                this.region.addValueChangeListener(this.triggerPopulateFromListListener);
                if (response.getList().get(0) != null) {
                    this.region.select(response.getList().get(0));
                }
            } else {
                this.region.removeAllItems();
            }
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
            log.error("Error getting Region List", e);
        }
    }

    private void populateFromList() {
        try {
            OsProjectDto projectDto = (OsProjectDto) this.project.getValue();
            String region = (String) this.region.getValue();
            String memberType = (String) this.protectionEnreplacedyType.getValue();
            boolean isProtectAll = this.protectionTypeOption.getValue() == TYPE_ALL;
            this.itemsContainer.removeAllItems();
            this.itemsTable.removeAllItems();
            if (projectDto != null && StringUtils.isNotEmpty(region) && !isProtectAll) {
                ListOpenstackMembersRequest req = new ListOpenstackMembersRequest();
                if (this.currentSecurityGroup.getId() != null) {
                    req.setId(this.currentSecurityGroup.getId());
                }
                req.setParentId(this.currentSecurityGroup.getParentId());
                req.setProjectName(projectDto.getName());
                req.setProjectId(projectDto.getId());
                req.setRegion(region);
                req.setType(memberType.toString());
                if (this.isInitialFromListLoad) {
                    req.setCurrentSelectedMembers(null);
                } else {
                    req.setCurrentSelectedMembers(getSelectedMembers());
                }
                ListResponse<SecurityGroupMemberItemDto> response = this.listOpenstackMembersService.dispatch(req);
                this.isInitialFromListLoad = false;
                this.itemsContainer.addAll(response.getList());
                updateCountFooter(this.itemsTable, this.itemsContainer.size());
                this.itemsContainer.sort(new Object[] { "name" }, new boolean[] { true });
            }
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
            log.error("Error getting Servers List", e);
        }
    }

    @SuppressWarnings("serial")
    private void initListeners() {
        this.projectChangedListener = new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                if (BaseSecurityGroupWindow.this.selectedItemsContainer != null) {
                    BaseSecurityGroupWindow.this.selectedItemsContainer.removeAllItems();
                }
                if (BaseSecurityGroupWindow.this.itemsContainer != null) {
                    BaseSecurityGroupWindow.this.itemsContainer.removeAllItems();
                }
                if (BaseSecurityGroupWindow.this.region != null) {
                    populateRegion();
                }
            }
        };
        this.triggerPopulateFromListListener = new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                if (BaseSecurityGroupWindow.this.itemsTable != null) {
                    populateFromList();
                }
            }
        };
        // We don't want enter to close the dialog
        getComponentModel().getOkButton().removeClickShortcut();
    }

    private Button getTableItemsSelectionButton(String text) {
        Button itemsSelectionButton = new Button(text);
        itemsSelectionButton.addStyleName(ValoTheme.BUTTON_LINK);
        itemsSelectionButton.addStyleName(StyleConstants.LINK_BUTTON);
        return itemsSelectionButton;
    }

    @SuppressWarnings("serial")
    private FilterTable createSelectorTable() {
        final FilterTable table = new FilterTable();
        table.setStyleName(ValoTheme.TABLE_COMPACT);
        table.setSizeFull();
        table.setSelectable(true);
        table.setColumnCollapsingAllowed(false);
        table.setColumnReorderingAllowed(false);
        table.setImmediate(true);
        table.setNullSelectionAllowed(false);
        table.setFilterBarVisible(true);
        table.setPageLength(3);
        updateCountFooter(table, 0);
        table.setMultiSelect(true);
        table.setHeight(SELECTOR_TABLE_HEIGHT + "px");
        table.setWidth(SELECTOR_TABLE_WIDTH + "px");
        table.setFooterVisible(true);
        table.setColumnHeader("name", VmidcMessages.getString(VmidcMessages_.NAME));
        table.setColumnHeader("region", VmidcMessages.getString(VmidcMessages_.OS_REGION));
        table.setColumnHeader("type", VmidcMessages.getString(VmidcMessages_.OS_MEMBER_TYPE));
        table.addGeneratedColumn(PROTECT_EXTERNAL, new CheckBoxGenerator());
        table.sort(new Object[] { "name" }, new boolean[] { true });
        table.setFilterDecorator(new ImmediateTextFilterDecorator());
        // Enable Drag drop
        table.setDragMode(TableDragMode.MULTIROW);
        table.setDropHandler(new DropHandler() {

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

            @SuppressWarnings("unchecked")
            @Override
            public void drop(DragAndDropEvent event) {
                CustomTable fromTable = ((TableTransferable) event.getTransferable()).getSourceComponent();
                CustomTable toTable = (CustomTable) event.getTargetDetails().getTarget();
                Set<String> itemIdsSelected = (Set<String>) fromTable.getValue();
                // If drag started on an unselected row, select it in the from table before we move
                if (itemIdsSelected == null || itemIdsSelected.size() == 0) {
                    fromTable.select(((TableTransferable) event.getTransferable()).gereplacedemId());
                }
                moveItems(fromTable, toTable);
            }
        });
        table.addItemSetChangeListener(new ItemSetChangeListener() {

            @Override
            public void containerItemSetChange(ItemSetChangeEvent event) {
                updateCountFooter(table, table.gereplacedemIds().size());
            }
        });
        return table;
    }

    @SuppressWarnings("unchecked")
    protected Set<SecurityGroupMemberItemDto> getSelectedMembers() {
        this.selectedItemsTable.getFilterable().removeAllContainerFilters();
        Collection<String> itemIdSelected = (Collection<String>) this.selectedItemsTable.gereplacedemIds();
        Set<SecurityGroupMemberItemDto> selectedMembers = new HashSet<>();
        for (String itemId : itemIdSelected) {
            selectedMembers.add(this.selectedItemsContainer.gereplacedem(itemId).getBean());
        }
        return selectedMembers;
    }

    @SuppressWarnings("unchecked")
    private void moveItems(CustomTable fromTable, CustomTable toTable) {
        if (fromTable.equals(toTable)) {
            return;
        }
        BeanContainer<String, SecurityGroupMemberItemDto> fromContainer = (BeanContainer<String, SecurityGroupMemberItemDto>) fromTable.getContainerDataSource();
        BeanContainer<String, SecurityGroupMemberItemDto> toContainer = (BeanContainer<String, SecurityGroupMemberItemDto>) toTable.getContainerDataSource();
        boolean isMovingToSelectedItemList = toTable == this.selectedItemsTable;
        String memberType = (String) this.protectionEnreplacedyType.getValue();
        Set<String> itemIdsSelected = (Set<String>) fromTable.getValue();
        for (String itemId : itemIdsSelected) {
            if (fromContainer.gereplacedem(itemId) != null) {
                SecurityGroupMemberItemDto memberItem = fromContainer.gereplacedem(itemId).getBean();
                // Add the item to the 'to' container, if the 'to' container is the selected items table
                if (isMovingToSelectedItemList) {
                    toContainer.addBean(memberItem);
                    handleProtectExternal(toTable, itemId, memberItem);
                } else if (memberItem.getType().equals(memberType)) {
                    // If the 'to' container is not the selected list, we need to check the current selected type
                    // from the UI and add the member only if it matches the selected type
                    toContainer.addBean(memberItem);
                }
            }
            fromContainer.removeItem(itemId);
            fromTable.removeItem(itemId);
        }
        toTable.setValue(itemIdsSelected);
        updateCountFooter(fromTable, fromTable.gereplacedemIds().size());
        updateCountFooter(toTable, toTable.gereplacedemIds().size());
        toTable.sort(new Object[] { toTable.getSortContainerPropertyId() }, new boolean[] { toTable.isSortAscending() });
    }

    private void handleProtectExternal(CustomTable toTable, String itemId, SecurityGroupMemberItemDto memberItem) {
        boolean enableProtectExternalFlag = !SECURITY_GROUP_MEMBER_SUBNET.equals(memberItem.getType());
        toTable.getContainerProperty(itemId, PROTECT_EXTERNAL).setReadOnly(enableProtectExternalFlag);
    }

    private BeanContainer<String, SecurityGroupMemberItemDto> createItemContainer() {
        BeanContainer<String, SecurityGroupMemberItemDto> container = new BeanContainer<String, SecurityGroupMemberItemDto>(SecurityGroupMemberItemDto.clreplaced);
        container.setBeanIdProperty("openstackId");
        container.sereplacedemSorter(ViewUtil.getCaseInsensitiveItemSorter());
        return container;
    }

    @SuppressWarnings("serial")
    private Component createSelectorTableLayout(final FilterTable table, final BeanContainer<String, SecurityGroupMemberItemDto> tableContainer) {
        VerticalLayout layout = new VerticalLayout();
        Button allButton = getTableItemsSelectionButton(VmidcMessages.getString(VmidcMessages_.SELECTOR_ALL));
        allButton.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                table.setValue(tableContainer.gereplacedemIds());
            }
        });
        Button noneButton = getTableItemsSelectionButton(VmidcMessages.getString(VmidcMessages_.SELECTOR_NONE));
        noneButton.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                table.setValue(null);
            }
        });
        Button invertButton = getTableItemsSelectionButton(VmidcMessages.getString(VmidcMessages_.SELECTOR_INVERT));
        invertButton.addClickListener(new ClickListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void buttonClick(ClickEvent event) {
                Set<String> itemIdsSelected = (Set<String>) table.getValue();
                Collection<String> allItems = (Collection<String>) table.gereplacedemIds();
                table.setValue(allItems.stream().filter(s -> !itemIdsSelected.contains(s)).collect(Collectors.toSet()));
            }
        });
        HorizontalLayout buttonLayout = new HorizontalLayout(allButton, noneButton, invertButton);
        layout.addComponent(table);
        layout.addComponent(buttonLayout);
        return layout;
    }

    private boolean isUpdateWindow() {
        return this.currentSecurityGroup.getId() != null;
    }

    @SuppressWarnings("serial")
    private clreplaced CheckBoxGenerator implements ColumnGenerator {

        @Override
        public Object generateCell(CustomTable source, Object itemId, Object columnId) {
            Property<?> prop = source.gereplacedem(itemId).gereplacedemProperty(columnId);
            return new CheckBox(null, prop);
        }
    }
}

16 View Complete Implementation : BindSecurityGroupWindow.java
Copyright Apache License 2.0
Author : opensecuritycontroller
private ComboBox getFailurePolicyComboBox() {
    ComboBox failurePolicy = new ComboBox("Select Failure Policy");
    failurePolicy.setTextInputAllowed(false);
    failurePolicy.setNullSelectionAllowed(false);
    failurePolicy.setImmediate(true);
    failurePolicy.setRequired(true);
    failurePolicy.setRequiredError("Failure Policy cannot be empty");
    failurePolicy.addItems(FailurePolicyType.FAIL_OPEN, FailurePolicyType.FAIL_CLOSE);
    failurePolicy.select(FailurePolicyType.FAIL_OPEN);
    failurePolicy.setEnabled(false);
    return failurePolicy;
}

16 View Complete Implementation : AddUserWindow.java
Copyright Apache License 2.0
Author : opensecuritycontroller
public clreplaced AddUserWindow extends CRUDBaseWindow<OkCancelButtonModel> {

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

    final String CAPTION = "Add User";

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

    // form fields
    private TextField firstName = null;

    private TextField lastName = null;

    private TextField loginName = null;

    private PreplacedwordField preplacedword = null;

    private TextField email = null;

    private ComboBox role = null;

    private final AddUserServiceApi addUserService;

    public AddUserWindow(UserView userView, AddUserServiceApi addUserService) throws Exception {
        this.addUserService = addUserService;
        createWindow(this.CAPTION);
    }

    @Override
    public void populateForm() {
        this.loginName = new TextField("User Name");
        this.loginName.setImmediate(true);
        this.firstName = new TextField("First Name");
        this.lastName = new TextField("Last Name");
        this.preplacedword = new PreplacedwordField("Preplacedword");
        this.preplacedword.setImmediate(true);
        this.email = new TextField("Email");
        this.email.addValidator(new EmailValidator("Please enter a valid email address"));
        this.role = new ComboBox("Role");
        this.role.setTextInputAllowed(false);
        this.role.setNullSelectionAllowed(false);
        this.role.addItem(UpdateUserWindow.ROLE_ADMIN);
        this.role.select(UpdateUserWindow.ROLE_ADMIN);
        // adding not null constraint
        this.loginName.setRequired(true);
        this.loginName.setRequiredError("User Name cannot be empty");
        this.preplacedword.setRequired(true);
        this.preplacedword.setRequiredError("Preplacedword cannot be empty");
        this.role.setRequired(true);
        this.form.setMargin(true);
        this.form.setSizeUndefined();
        this.form.addComponent(this.loginName);
        this.form.addComponent(this.firstName);
        this.form.addComponent(this.lastName);
        this.form.addComponent(this.preplacedword);
        this.form.addComponent(this.email);
        this.form.addComponent(this.role);
        this.loginName.focus();
    }

    @Override
    public boolean validateForm() {
        try {
            this.loginName.validate();
            this.preplacedword.validate();
            this.email.validate();
            this.role.validate();
            return true;
        } catch (Exception e) {
            log.debug("Validation Error");
            ViewUtil.iscNotification(e.getMessage() + ".", Notification.Type.ERROR_MESSAGE);
        }
        return false;
    }

    @Override
    public void submitForm() {
        try {
            if (validateForm()) {
                // creating add request with user entered data
                AddUserRequest addRequest = new AddUserRequest();
                addRequest.setFirstName(this.firstName.getValue().trim());
                addRequest.setLastName(this.lastName.getValue().trim());
                addRequest.setLoginName(this.loginName.getValue().trim());
                addRequest.setEmail(this.email.getValue().trim());
                addRequest.setPreplacedword(this.preplacedword.getValue());
                addRequest.setRole(this.role.getValue().toString());
                // calling add service
                AddUserResponse addResponse;
                log.info("adding new user - " + this.loginName.getValue());
                addResponse = this.addUserService.dispatch(addRequest);
                // adding returned ID to the request DTO object
                addRequest.setId(addResponse.getId());
                close();
            }
        } catch (Exception e) {
            log.info(e.getMessage());
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
        }
    }
}

16 View Complete Implementation : BaseDAWindow.java
Copyright Apache License 2.0
Author : opensecuritycontroller
@SuppressWarnings("unchecked")
protected void updateDomains(ApplianceManagerConnectorDto mcDto) {
    List<DomainDto> dl = getDomainList(mcDto);
    for (Object itemId : this.vsTable.gereplacedemIds()) {
        ComboBox domainComboBox = createDomainComboBox(dl);
        Item item = this.vsTable.gereplacedem(itemId);
        item.gereplacedemProperty("Manager Domain").setValue(domainComboBox);
    }
}

16 View Complete Implementation : EmailTargetLayout.java
Copyright GNU General Public License v3.0
Author : rlsutton1
@SuppressWarnings("unchecked")
private void getValidEmailContacts(ComboBox targetAddress) {
    JpaBaseDao<ReportEmailRecipient, Long> reportEmailRecipient = JpaBaseDao.getGenericDao(ReportEmailRecipient.clreplaced);
    targetAddress.addContainerProperty("id", String.clreplaced, null);
    targetAddress.addContainerProperty("email", String.clreplaced, null);
    targetAddress.addContainerProperty("namedemail", String.clreplaced, null);
    for (final ReportEmailRecipient contact : reportEmailRecipient.findAll()) {
        if (contact.getEmail() != null) {
            Item item = targetAddress.addItem(contact.getEmail());
            if (item != null) {
                item.gereplacedemProperty("email").setValue(contact.getEmail());
                item.gereplacedemProperty("id").setValue(contact.getEmail());
                item.gereplacedemProperty("namedemail").setValue(contact.getEmail());
            }
        }
    }
}