com.vaadin.ui.VerticalLayout

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

34 Examples 7

19 Source : PluginView.java
with Apache License 2.0
from opensecuritycontroller

@Activate
void start(BundleContext ctx) throws Exception {
    setSizeFull();
    addStyleName(StyleConstants.BASE_CONTAINER);
    VerticalLayout component = createComponent("Plugins", "Plugins", new PluginsLayout(ctx, this.importPluginService, this.server), HELP_PLUGIN_GUID);
    addComponent(component);
    setExpandRatio(component, 1L);
}

19 Source : MainUI.java
with Apache License 2.0
from opensecuritycontroller

private void buildMainLayout() {
    this.mainLayout.setWidth("100%");
    this.mainLayout.setHeight("100%");
    this.mainLayout.addStyleName("view-content");
    VerticalLayout sidebar = buildSidebar();
    this.mainLayout.addComponent(sidebar);
    // Content
    this.mainLayout.addComponent(this.content);
    this.content.setSizeFull();
    this.mainLayout.setExpandRatio(this.content, 1);
    this.root.addComponent(this.mainLayout);
}

19 Source : CRUDBaseSubView.java
with Apache License 2.0
from opensecuritycontroller

private void createSubView(String replacedle, ToolbarButtons[] buttons) {
    setSizeFull();
    final VerticalLayout layout = new VerticalLayout();
    layout.addStyleName(StyleConstants.BASE_CONTAINER);
    layout.setSizeFull();
    final VerticalLayout panel = new VerticalLayout();
    panel.addStyleName("panel");
    panel.setSizeFull();
    layout.addComponent(createHeader(replacedle));
    layout.addComponent(panel);
    if (buttons != null) {
        panel.addComponent(createToolbar(buttons));
    }
    panel.addComponent(createTable());
    panel.setExpandRatio(this.table, 1L);
    layout.setExpandRatio(panel, 1L);
    addComponent(layout);
}

18 Source : VmidcWindow.java
with Apache License 2.0
from opensecuritycontroller

/**
 * Create a Modal window with the given parameters.
 *
 * @param content
 *            the content to be placed within the window
 */
@Override
public void setContent(Component content) {
    if (content == null) {
        super.setContent(content);
    } else {
        VerticalLayout panelContent = new VerticalLayout();
        panelContent.addComponent(content);
        panelContent.addComponent(submitLayout());
        super.setContent(panelContent);
    }
}

18 Source : AddDistributedApplianceWindow.java
with Apache License 2.0
from opensecuritycontroller

@Override
public void populateForm() {
    try {
        this.name = new TextField("Name");
        this.name.focus();
        this.name.setImmediate(true);
        this.name.setRequired(true);
        this.name.setRequiredError("Name cannot be empty");
        FormLayout innerForm = new FormLayout();
        innerForm.addComponent(this.name);
        innerForm.addComponent(getManagerConnector());
        innerForm.addComponent(getApplianceDefinition());
        innerForm.setWidth(100, Unit.PERCENTAGE);
        VerticalLayout layout = new VerticalLayout();
        layout.addComponent(innerForm);
        // TODO: Future. Need to dynamically show/hide attributes based on manager type
        getAttributesPanel();
        layout.addComponent(getVirtualSystemPanel());
        this.form.setMargin(true);
        this.form.setWidth(689, Unit.PIXELS);
        this.form.addComponent(layout);
    } catch (Exception e) {
        log.error("Fail to populate Distributed Appliance form", e);
        ViewUtil.iscNotification("Fail to populate Distributed Appliance form (" + e.getMessage() + ")", Notification.Type.ERROR_MESSAGE);
    }
}

18 Source : SslConfigurationLayout.java
with Apache License 2.0
from opensecuritycontroller

private VerticalLayout makeSslUploadContainer(SslCertificateUploader certificateUploader, String replacedle) {
    VerticalLayout sslUploadContainer = new VerticalLayout();
    try {
        certificateUploader.setSizeFull();
        certificateUploader.setUploadNotifier(uploadStatus -> {
            if (uploadStatus) {
                buildSslConfigurationTable();
            }
        });
        sslUploadContainer.addComponent(ViewUtil.createSubHeader(replacedle, null));
        sslUploadContainer.addComponent(certificateUploader);
    } catch (Exception e) {
        log.error("Cannot add upload component. Trust manager factory failed to initialize", e);
        ViewUtil.iscNotification(getString(MAINTENANCE_SSLCONFIGURATION_UPLOAD_INIT_FAILED, new Date()), null, Notification.Type.TRAY_NOTIFICATION);
    }
    return sslUploadContainer;
}

18 Source : ManageLayout.java
with Apache License 2.0
from opensecuritycontroller

@SuppressWarnings("serial")
public VerticalLayout createBackup() {
    final VerticalLayout bkpLayout = new VerticalLayout();
    bkpLayout.addStyleName("componentSpacing");
    this.backupButton = new Button("Create Backup");
    this.backupButton.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                PreplacedwordWindow preplacedwordWindow = new PreplacedwordWindow(ManageLayout.this.validator);
                preplacedwordWindow.setSubmitFormListener(preplacedword -> {
                    try {
                        BackupRequest req = new BackupRequest();
                        req.setBackupPreplacedword(preplacedword);
                        BackupResponse res = ManageLayout.this.backupService.dispatch(req);
                        if (res.isSuccess()) {
                            ViewUtil.iscNotification("Backup Successful!", null, Notification.Type.TRAY_NOTIFICATION);
                            ManageLayout.this.linkContainer.removeAllComponents();
                            createDownloadLink(ManageLayout.this.backupService.getEncryptedBackupFile());
                        }
                    } catch (Exception e) {
                        ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
                        log.error("Failed to backup vmiDCServer Database ", e);
                    }
                });
                ViewUtil.addWindow(preplacedwordWindow);
            } catch (Exception e) {
                ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
                log.error("Failed to backup vmiDCServer Database ", e);
            }
        }
    });
    bkpLayout.addComponent(this.backupButton);
    this.linkContainer = new HorizontalLayout();
    File backupFile = this.backupService.getEncryptedBackupFile();
    if (backupFile.exists()) {
        createDownloadLink(backupFile);
    }
    bkpLayout.addComponent(this.linkContainer);
    return bkpLayout;
}

17 Source : HelloVaadin.java
with BSD 3-Clause "New" or "Revised" License
from piranhacloud

/**
 * Init the UI.
 *
 * @param request the request.
 */
@Override
protected void init(VaadinRequest request) {
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    layout.setSpacing(true);
    setContent(layout);
    layout.addComponent(new Label("Hello Vaadin"));
}

17 Source : SecurityGroupMembershipInfoWindow.java
with Apache License 2.0
from opensecuritycontroller

public Component getTreeTable() throws Exception {
    VerticalLayout content = new VerticalLayout();
    content.setMargin(new MarginInfo(true, true, false, true));
    this.treeTable = new TreeTable();
    this.treeTable.setPageLength(10);
    this.treeTable.setSelectable(false);
    this.treeTable.setSizeFull();
    this.treeTable.addContainerProperty(PROPERTY_ID_MEMBER_NAME, String.clreplaced, "");
    this.treeTable.addContainerProperty(PROPERTY_ID_MEMBER_TYPE, String.clreplaced, "");
    this.treeTable.addContainerProperty(PROPERTY_ID_MEMBER_IP, String.clreplaced, "");
    this.treeTable.addContainerProperty(PROPERTY_ID_MEMBER_MAC, String.clreplaced, "");
    this.treeTable.setColumnHeader(PROPERTY_ID_MEMBER_NAME, VmidcMessages.getString(VmidcMessages_.NAME));
    this.treeTable.setColumnHeader(PROPERTY_ID_MEMBER_TYPE, VmidcMessages.getString(VmidcMessages_.OS_MEMBER_TYPE));
    this.treeTable.setColumnHeader(PROPERTY_ID_MEMBER_MAC, VmidcMessages.getString(VmidcMessages_.GENERAL_MACADDR));
    this.treeTable.setColumnHeader(PROPERTY_ID_MEMBER_IP, VmidcMessages.getString(VmidcMessages_.GENERAL_IPADDR));
    this.treeTable.setColumnWidth(PROPERTY_ID_MEMBER_NAME, NAME_COLUMN_WIDTH);
    this.treeTable.setColumnWidth(PROPERTY_ID_MEMBER_TYPE, TYPE_COLUMN_WIDTH);
    this.treeTable.setColumnWidth(PROPERTY_ID_MEMBER_MAC, MAC_COLUMN_WIDTH);
    this.treeTable.setColumnWidth(PROPERTY_ID_MEMBER_IP, IP_COLUMN_WIDTH);
    populateData();
    content.addComponent(this.treeTable);
    return content;
}

17 Source : BaseSecurityGroupWindow.java
with Apache License 2.0
from 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);
        }
    }
}

17 Source : BaseSecurityGroupWindow.java
with Apache License 2.0
from opensecuritycontroller

@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;
}

17 Source : MainUI.java
with Apache License 2.0
from opensecuritycontroller

private VerticalLayout buildSidebar() {
    VerticalLayout sideBar = new VerticalLayout();
    sideBar.addStyleName("sidebar");
    sideBar.addComponent(buildMainMenu());
    sideBar.setExpandRatio(this.menu, 1);
    sideBar.setWidth(null);
    sideBar.setHeight("100%");
    return sideBar;
}

17 Source : DemoUI.java
with Apache License 2.0
from 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);
}

17 Source : GiftcardUI.java
with Apache License 2.0
from AxonIQ

@Override
protected void init(VaadinRequest vaadinRequest) {
    HorizontalLayout commandBar = new HorizontalLayout();
    commandBar.setWidth("100%");
    commandBar.addComponents(issuePanel(), bulkIssuePanel(), redeemPanel());
    Grid summary = summaryGrid();
    HorizontalLayout statusBar = new HorizontalLayout();
    Label statusLabel = new Label("Status");
    statusBar.setDefaultComponentAlignment(Alignment.MIDDLE_RIGHT);
    statusBar.addComponent(statusLabel);
    statusBar.setWidth("100%");
    VerticalLayout layout = new VerticalLayout();
    layout.addComponents(commandBar, summary, statusBar);
    layout.setExpandRatio(summary, 1f);
    layout.setSizeFull();
    setContent(layout);
    UI.getCurrent().setErrorHandler(new DefaultErrorHandler() {

        @Override
        public void error(com.vaadin.server.ErrorEvent event) {
            Throwable cause = event.getThrowable();
            logger.error("an error occured", cause);
            while (cause.getCause() != null) {
                cause = cause.getCause();
            }
            Notification.show("Error", cause.getMessage(), Notification.Type.ERROR_MESSAGE);
        }
    });
    setPollInterval(1000);
    int offset = Page.getCurrent().getWebBrowser().getTimezoneOffset();
    // offset is in milliseconds
    ZoneOffset instantOffset = ZoneOffset.ofTotalSeconds(offset / 1000);
    StatusUpdater statusUpdater = new StatusUpdater(statusLabel, instantOffset);
    updaterThread = Executors.newScheduledThreadPool(1).scheduleAtFixedRate(statusUpdater, 1000, 5000, TimeUnit.MILLISECONDS);
    setPollInterval(1000);
    getSession().getSession().setMaxInactiveInterval(30);
    addDetachListener((DetachListener) detachEvent -> {
        logger.warn("Closing UI");
        updaterThread.cancel(true);
    });
}

16 Source : ChatUI.java
with Apache License 2.0
from saturnism

/**
 * Created by rayt on 6/25/17.
 */
@Push
@PreserveOnRefresh
public clreplaced ChatUI extends UI {

    private static final Logger logger = Logger.getLogger(ChatUI.clreplaced.getName());

    private static final ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9090).usePlaintext().build();

    private static final ChatServiceGrpc.ChatServiceStub stub = ChatServiceGrpc.newStub(channel);

    private final VerticalLayout layout = new VerticalLayout();

    private final TextField name = new TextField();

    private final TextField message = new TextField();

    private final Button button = new Button("Send");

    public ChatUI() {
        name.setId("tf.name");
        name.setCaption("Type your name here:");
        message.setId("tf.message");
        message.setCaption("Type your message here:");
        layout.addComponents(name, message, button);
        setContent(layout);
    }

    @Override
    protected void init(VaadinRequest vaadinRequest) {
        final UI currentUI = getCurrent();
        final StreamObserver<Chat.ChatMessage> observer = stub.chat(new StreamObserver<Chat.ChatMessageFromServer>() {

            @Override
            public void onNext(Chat.ChatMessageFromServer chatMessageFromServer) {
                currentUI.access(() -> layout.addComponent(new Label(String.format("%s: %s", chatMessageFromServer.getMessage().getFrom(), chatMessageFromServer.getMessage().getMessage()))));
            }

            @Override
            public void onError(Throwable throwable) {
                logger.log(Level.SEVERE, "gRPC Error", throwable);
            }

            @Override
            public void onCompleted() {
                logger.info("gRPC Call Completed");
            }
        });
        button.addClickListener(e -> {
            final String nameValue = name.getValue();
            final String messageValue = message.getValue();
            observer.onNext(Chat.ChatMessage.newBuilder().setFrom(nameValue).setMessage(messageValue).build());
        });
    }
}

16 Source : UpdateDistributedApplianceWindow.java
with Apache License 2.0
from opensecuritycontroller

@SuppressWarnings("unchecked")
@Override
public void populateForm() {
    try {
        this.name = new TextField("Name");
        this.name.setImmediate(true);
        this.name.focus();
        this.name.setRequired(true);
        this.name.setEnabled(false);
        this.name.setRequiredError("Name cannot be empty");
        FormLayout innerForm = new FormLayout();
        innerForm.addComponent(this.name);
        innerForm.addComponent(getManagerConnector());
        innerForm.addComponent(getApplianceDefinition());
        innerForm.setWidth(100, Unit.PERCENTAGE);
        VerticalLayout layout = new VerticalLayout();
        layout.addComponent(innerForm);
        // TODO: Future. Need to dynamically show/hide attributes based on manager type
        getAttributesPanel();
        layout.addComponent(getVirtualSystemPanel());
        this.name.setValue(this.currentDAObject.getName());
        // this.sharedKey.setValue(this.currentDAObject.getSecretKey());
        // manager connecter drop down with the existing value
        BeanItemContainer<ApplianceManagerConnectorDto> mcContainer = (BeanItemContainer<ApplianceManagerConnectorDto>) this.managerConnector.getContainerDataSource();
        for (ApplianceManagerConnectorDto mc : mcContainer.gereplacedemIds()) {
            if (mc.getId().equals(this.currentDAObject.getMcId())) {
                this.managerConnector.select(mc);
            }
        }
        this.managerConnector.setEnabled(false);
        // appliance definition drop down with existing value
        setApplianceDefinitionToCurrent();
        // select existing virtual systems for this DA
        selectExistingVistualSytems();
        this.form.setMargin(true);
        this.form.setWidth(689, Unit.PIXELS);
        this.form.addComponent(layout);
        this.applianceDefinition.addValueChangeListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                selectExistingVistualSytems();
            }
        });
    } catch (Exception e) {
        log.error("Fail to load DA Form", e);
        ViewUtil.iscNotification("Fail load Distributed Appliance Form (" + e.getMessage() + ")", Notification.Type.ERROR_MESSAGE);
    }
}

16 Source : AgentStatusWindow.java
with Apache License 2.0
from opensecuritycontroller

public clreplaced AgentStatusWindow extends Window {

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

    private final List<DistributedApplianceInstanceDto> daiList;

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

    protected FormLayout form;

    private VerticalLayout statusPane;

    private final GetAgentStatusServiceApi getAgentStatusService;

    @SuppressWarnings("serial")
    public AgentStatusWindow(List<DistributedApplianceInstanceDto> daiList, GetAgentStatusServiceApi getAgentStatusService) {
        super();
        this.daiList = daiList;
        this.getAgentStatusService = getAgentStatusService;
        setModal(true);
        setClosable(true);
        setResizable(true);
        setHeight("500px");
        setWidth("475px");
        setCaption("Appliance Instance Status");
        // creating top level layout for every window
        VerticalLayout content = new VerticalLayout();
        content.setWidthUndefined();
        // creating form layout shared by all derived clreplacedes
        this.form = new FormLayout();
        this.form.setMargin(true);
        HorizontalLayout windowToolbar = new HorizontalLayout();
        windowToolbar.setSpacing(true);
        windowToolbar.addStyleName("buttonToolbar");
        Button close = new Button("Close");
        close.setClickShortcut(KeyCode.ESCAPE, null);
        close.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                close();
            }
        });
        close.focus();
        Button refresh = new Button("Refresh");
        refresh.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                refreshTable();
            }
        });
        windowToolbar.addComponents(refresh, close);
        this.form.addComponent(windowToolbar);
        this.form.setComponentAlignment(windowToolbar, Alignment.TOP_RIGHT);
        this.statusPane = new VerticalLayout();
        this.form.addComponent(this.statusPane);
        refreshTable();
        content.addComponent(this.form);
        setContent(content);
    }

    private void refreshTable() {
        this.statusPane.removeAllComponents();
        DistributedApplianceInstancesRequest req = new DistributedApplianceInstancesRequest(this.daiList);
        try {
            GetAgentStatusResponse response = this.getAgentStatusService.dispatch(req);
            for (AgentStatusResponse status : response.getAgentStatusList()) {
                // TODO emanoel: For now replaceduming that if the dpa info is null the status is not supported by the manager.
                // may change the status response for an enum: DISCOVERED, INSPECTION_READY, NOT_PROVIDED, etc.
                if (status.getAgentDpaInfo() != null) {
                    this.statusPane.addComponent(createTableStatusProvided(status));
                } else {
                    this.statusPane.addComponent(createTableStatusNotProvided(status));
                }
            }
        } catch (Exception e) {
            log.error("Fail to get DAI status", e);
            ViewUtil.iscNotification("Fail to get Appliance Instance status (" + e.getMessage() + ")", Notification.Type.ERROR_MESSAGE);
        }
    }

    @SuppressWarnings("unchecked")
    private Table createTableStatusNotProvided(AgentStatusResponse res) {
        Table statusTable = new Table();
        // initializing network table with empty values
        addCommonTableItems(statusTable);
        addCommonTableItemValues(res, statusTable);
        statusTable.addItem(new Object[] { "Status: ", "" }, new Integer(6));
        statusTable.gereplacedem(6).gereplacedemProperty("Value").setValue(res.getStatusLines().get(0));
        return statusTable;
    }

    private void addCommonTableItems(Table statusTable) {
        statusTable.setImmediate(true);
        statusTable.setStyleName(ValoTheme.TABLE_COMPACT);
        statusTable.addContainerProperty("Property", String.clreplaced, "");
        statusTable.addContainerProperty("Value", String.clreplaced, "");
        statusTable.setColumnHeaderMode(Table.ColumnHeaderMode.HIDDEN);
        statusTable.setPageLength(0);
        statusTable.setReadOnly(true);
        statusTable.addItem(new Object[] { "Name: ", "" }, new Integer(1));
        statusTable.addItem(new Object[] { "Local IP: ", "" }, new Integer(2));
        statusTable.addItem(new Object[] { "Public IP: ", "" }, new Integer(3));
        statusTable.addItem(new Object[] { "V.Server: ", "" }, new Integer(4));
        statusTable.addItem(new Object[] { "Manager IP: ", "" }, new Integer(5));
    }

    @SuppressWarnings("unchecked")
    private Table createTableStatusProvided(AgentStatusResponse res) {
        Table statusTable = new Table();
        // initializing network table with empty values
        addCommonTableItems(statusTable);
        statusTable.addItem(new Object[] { "Uptime: ", "" }, new Integer(6));
        statusTable.addItem(new Object[] { "DPA PID: ", "" }, new Integer(7));
        statusTable.addItem(new Object[] { "DPA Info: ", "" }, new Integer(8));
        statusTable.addItem(new Object[] { "DPA Stats: ", "" }, new Integer(9));
        statusTable.addItem(new Object[] { "Discovered: ", "" }, new Integer(10));
        statusTable.addItem(new Object[] { "Inspection Ready: ", "" }, new Integer(11));
        if (null != res.getVersion()) {
            statusTable.gereplacedem(6).gereplacedemProperty("Value").setValue(res.getCurrentServerTime().toString());
        } else {
            statusTable.gereplacedem(6).gereplacedemProperty("Value").setValue("Not Available due to communication error.");
        }
        try {
            addCommonTableItemValues(res, statusTable);
            if (null != res.getVersion()) {
                statusTable.gereplacedem(7).gereplacedemProperty("Value").setValue(res.getAgentDpaInfo().netXDpaRuntimeInfo.dpaPid);
                statusTable.gereplacedem(8).gereplacedemProperty("Value").setValue("IPC Ver:" + res.getAgentDpaInfo().dpaStaticInfo.ipcVersion + ", Name:" + res.getAgentDpaInfo().dpaStaticInfo.dpaName + ", Version:" + res.getAgentDpaInfo().dpaStaticInfo.dpaVersion);
                Long dropped = 0L;
                if (res.getAgentDpaInfo().netXDpaRuntimeInfo.dropResource != null) {
                    dropped += res.getAgentDpaInfo().netXDpaRuntimeInfo.dropResource;
                }
                if (res.getAgentDpaInfo().netXDpaRuntimeInfo.dropSva != null) {
                    dropped += res.getAgentDpaInfo().netXDpaRuntimeInfo.dropSva;
                }
                if (res.getAgentDpaInfo().netXDpaRuntimeInfo.dropError != null) {
                    dropped += res.getAgentDpaInfo().netXDpaRuntimeInfo.dropError;
                }
                statusTable.gereplacedem(9).gereplacedemProperty("Value").setValue("Rx:" + res.getAgentDpaInfo().netXDpaRuntimeInfo.rx + ", Tx:" + res.getAgentDpaInfo().netXDpaRuntimeInfo.txSva + ", Dropped:" + dropped + ", Insp-If:" + res.getAgentDpaInfo().netXDpaRuntimeInfo.workloadInterfaces);
                statusTable.gereplacedem(10).gereplacedemProperty("Value").setValue(Boolean.valueOf(res.isDiscovered()).toString());
                statusTable.gereplacedem(11).gereplacedemProperty("Value").setValue(Boolean.valueOf(res.isInspectionReady()).toString());
            }
        } catch (Exception e) {
            log.error("Fail to retrieve agent info", e);
            statusTable.gereplacedem(6).gereplacedemProperty("Value").setValue("Not Available due to communication error.");
        }
        return statusTable;
    }

    @SuppressWarnings("unchecked")
    private void addCommonTableItemValues(AgentStatusResponse res, Table statusTable) {
        statusTable.gereplacedem(1).gereplacedemProperty("Value").setValue(res.getApplianceName());
        statusTable.gereplacedem(2).gereplacedemProperty("Value").setValue(res.getApplianceIp());
        statusTable.gereplacedem(3).gereplacedemProperty("Value").setValue(res.getPublicIp());
        statusTable.gereplacedem(4).gereplacedemProperty("Value").setValue(res.getVirtualServer());
        statusTable.gereplacedem(5).gereplacedemProperty("Value").setValue(res.getManagerIp());
    }
}

16 Source : CRUDBaseWindow.java
with Apache License 2.0
from opensecuritycontroller

/**
 * Base Windows which provides default functionality for child clreplaced to extend
 */
@SuppressWarnings("serial")
public abstract clreplaced CRUDBaseWindow<T extends OkCancelButtonModel> extends VmidcWindow<T> {

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

    protected FormLayout form = null;

    protected VerticalLayout content;

    private PageInformationComponent infoText;

    @SuppressWarnings("unchecked")
    public CRUDBaseWindow() {
        super((T) new OkCancelButtonModel());
    }

    public CRUDBaseWindow(T componentModel) {
        super(componentModel);
    }

    // returns an empty form layout to derived clreplacedes with OK and submit in it.
    public void createWindow(String caption) throws Exception {
        setCaption(caption);
        // creating top level layout for every window
        this.content = new VerticalLayout();
        // creating form layout shared by all derived clreplacedes
        this.form = new FormLayout();
        this.form.setMargin(true);
        this.form.setSizeUndefined();
        this.infoText = new PageInformationComponent();
        this.infoText.addStyleName(StyleConstants.PAGE_INFO_COMPONENT_WINDOW);
        this.content.addComponent(this.infoText);
        this.content.addComponent(this.form);
        getComponentModel().setOkClickedListener((ClickListener) event -> submitForm());
        getComponentModel().setCancelClickedListener((ClickListener) event -> {
            cancelForm();
            close();
        });
        // calling populateForm to create window specific content
        populateForm();
        // adding content to this window
        setContent(this.content);
    }

    /**
     * @see PageInformationComponent#setInfoText(String, String)
     */
    public void setInfoText(String replacedle, String content) {
        this.infoText.setInfoText(replacedle, content);
    }

    protected void handleCatchAllException(Throwable e) {
        log.error(e.getMessage(), e);
        ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
    }

    public void cancelForm() {
    }

    // creating window specific forms
    public abstract void populateForm() throws Exception;

    public abstract boolean validateForm();

    // window specific implementation for submitting a form
    public abstract void submitForm();
}

16 Source : MaintenanceView.java
with Apache License 2.0
from opensecuritycontroller

private VerticalLayout createTab(String caption, String replacedle, FormLayout content, String guid) {
    VerticalLayout tabSheet = new VerticalLayout();
    tabSheet.setCaption(caption);
    tabSheet.setStyleName(StyleConstants.TAB_SHEET);
    Panel panel = new Panel();
    // creating subHeader inside panel
    panel.setContent(content);
    panel.setSizeFull();
    tabSheet.addComponent(ViewUtil.createSubHeader(replacedle, guid));
    tabSheet.addComponent(panel);
    return tabSheet;
}

16 Source : SslCertificateUploader.java
with Apache License 2.0
from opensecuritycontroller

public clreplaced SslCertificateUploader extends CustomComponent implements Receiver, FailedListener, SucceededListener {

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

    private static final long serialVersionUID = 1L;

    private UploadNotifier uploadNotifier;

    protected File file;

    protected Upload upload;

    protected final VerticalLayout verLayout = new VerticalLayout();

    protected X509TrustManagerApi x509TrustManager;

    public SslCertificateUploader(X509TrustManagerApi x509TrustManager) {
        this.x509TrustManager = x509TrustManager;
        Panel panel = new Panel();
        layout(panel);
        setCompositionRoot(panel);
    }

    protected void layout(Panel panel) {
        createUpload();
        this.verLayout.setSpacing(true);
        panel.setWidth("100%");
        panel.setContent(this.verLayout);
        this.verLayout.addComponent(this.upload);
        this.verLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
    }

    public void setUploadNotifier(UploadNotifier uploadNotifier) {
        this.uploadNotifier = uploadNotifier;
    }

    @Override
    public OutputStream receiveUpload(String filename, String mimeType) {
        if (filename != null && !filename.isEmpty()) {
            log.info("Start uploading certificate: " + filename);
            try {
                this.file = File.createTempFile("tmp", filename);
                return new FileOutputStream(this.file);
            } catch (final java.io.IOException e) {
                log.error("Error opening certificate: " + filename, e);
                ViewUtil.iscNotification(getString(UPLOAD_COMMON_ERROR) + filename, Notification.Type.ERROR_MESSAGE);
            }
        }
        return null;
    }

    protected void createUpload() {
        this.upload = new Upload();
        this.upload.setButtonCaption(getString(MAINTENANCE_SSLCONFIGURATION_UPLOAD));
        this.upload.setReceiver(this);
        this.upload.addFailedListener(this);
        this.upload.addSucceededListener(this);
        this.upload.setImmediate(false);
        final UploadInfoWindow uploadInfoWindow = new UploadInfoWindow(this.upload);
        this.upload.addStartedListener((StartedListener) event -> {
            if (uploadInfoWindow.getParent() == null) {
                ViewUtil.addWindow(uploadInfoWindow);
            }
        });
    }

    private void repaintUpload() {
        boolean enabled = this.upload.isEnabled();
        this.verLayout.removeComponent(this.upload);
        createUpload();
        this.upload.setEnabled(enabled);
        this.verLayout.addComponent(this.upload);
    }

    @Override
    public void uploadSucceeded(SucceededEvent event) {
        boolean succeeded = true;
        try {
            processCertificateFile();
            log.info("=============== Upload certificate succeeded");
            repaintUpload();
        } catch (Exception ex) {
            succeeded = false;
            log.error("=============== Failed to upload certificate", ex);
            ViewUtil.iscNotification("SSL certificate upload failed. " + ex.getMessage() + " Please use a valid certificate file", Notification.Type.ERROR_MESSAGE);
            repaintUpload();
        }
        if (this.uploadNotifier != null) {
            this.uploadNotifier.finishedUpload(succeeded);
        }
    }

    protected void processCertificateFile() throws Exception {
        log.info("================ SSL certificate upload completed");
        log.info("================ Adding new entry to truststore...");
        ViewUtil.iscNotification(getString(MAINTENANCE_SSLCONFIGURATION_SUCCESSFUL, new Date()), null, Notification.Type.TRAY_NOTIFICATION);
        this.x509TrustManager.addEntry(this.file);
        removeUploadedFile();
    }

    @Override
    public void uploadFailed(FailedEvent event) {
        log.error(new Label(new Date() + ": SSL certificate upload failed.").getValue());
        if (event.getFilename() == null || event.getFilename().isEmpty()) {
            log.warn("No upload certificate file specified");
            ViewUtil.iscNotification(getString(MAINTENANCE_SSLCONFIGURATION_NOFILE), Notification.Type.ERROR_MESSAGE);
            repaintUpload();
        } else if (event.getReason() instanceof UploadInterruptedException) {
            log.warn("SSL certificate upload is cancelled by the user");
        } else {
            log.warn("SSL certificate upload failed");
            ViewUtil.iscNotification(getString(MAINTENANCE_SSLCONFIGURATION_FAILED), Notification.Type.ERROR_MESSAGE);
            repaintUpload();
        }
        removeUploadedFile();
    }

    protected void removeUploadedFile() {
        if (this.file != null && this.file.exists()) {
            try {
                FileUtils.forceDelete(this.file);
            } catch (IOException e) {
                log.error("Deleting ssl certificate file: " + this.file + " failed when upload was cancelled by user.", e);
            }
        }
    }

    public interface UploadNotifier {

        void finishedUpload(boolean uploadStatus);
    }
}

16 Source : ApplianceUploader.java
with Apache License 2.0
from opensecuritycontroller

@SuppressWarnings("serial")
public clreplaced ApplianceUploader extends CustomComponent implements Receiver, FailedListener {

    static final String OVF_UPLOAD_PATH = "data" + File.separator + "ovf" + File.separator;

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

    private static int TEMP_FOLDER_COUNTER = 0;

    private final Upload upload;

    private File file;

    private final Panel panel = new Panel();

    private final VerticalLayout verLayout = new VerticalLayout();

    private String uploadPath;

    public ApplianceUploader() {
        this.upload = new Upload();
        this.upload.setButtonCaption(null);
        this.upload.setReceiver(this);
        this.upload.addFailedListener(this);
        this.upload.setImmediate(false);
        final UploadInfoWindow uploadInfoWindow = new UploadInfoWindow(this.upload);
        this.upload.addStartedListener(new StartedListener() {

            @Override
            public void uploadStarted(final StartedEvent event) {
                if (uploadInfoWindow.getParent() == null) {
                    ViewUtil.addWindow(uploadInfoWindow);
                }
            }
        });
        this.verLayout.setSpacing(true);
        this.verLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
        this.verLayout.addComponent(this.upload);
        this.panel.setWidth("100%");
        this.panel.setContent(this.verLayout);
        setCompositionRoot(this.panel);
    }

    public Upload getUpload() {
        return this.upload;
    }

    @Override
    public OutputStream receiveUpload(String filename, String mimeType) {
        if (filename == null || filename.isEmpty()) {
            return null;
        }
        log.info("Start uploading file: " + filename);
        try {
            if (validateZipFile(filename)) {
                this.uploadPath = getUploadPath(true);
                File uploadDirectory = new File(this.uploadPath);
                if (!uploadDirectory.exists()) {
                    FileUtils.forceMkdir(uploadDirectory);
                }
                this.file = new File(this.uploadPath + filename);
                return new FileOutputStream(this.file);
            }
        } catch (Exception e) {
            log.error("Error opening file: " + filename, e);
            ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_COMMON_ERROR) + e.getMessage(), Notification.Type.ERROR_MESSAGE);
        }
        return null;
    }

    public static String getImageFolderPath() {
        return getUploadPath(false);
    }

    public String getUploadPath() {
        return this.uploadPath;
    }

    /**
     * Gets the upload path for the file. If isTmpFolder is set to true, returns a unique temporary upload file path.
     * If it is set to false it returns the actual image upload folder.
     *
     * @param isTmpFolder
     *            the temporary path the file is uploaded before being moved to the actual image path
     *
     * @return the temporary path when isTmpFolder is set to true
     *         the image path when isTmpFolder is set to false
     */
    public static String getUploadPath(boolean isTmpFolder) {
        String uploadPath = "";
        uploadPath += OVF_UPLOAD_PATH;
        if (isTmpFolder) {
            uploadPath += "tmp" + TEMP_FOLDER_COUNTER++ + File.separator;
        }
        return uploadPath;
    }

    @Override
    public void uploadFailed(FailedEvent event) {
        if (event.getFilename() == null || event.getFilename().isEmpty()) {
            ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_APPLIANCE_NOFILE), Notification.Type.ERROR_MESSAGE);
        } else if (event.getReason() instanceof UploadInterruptedException) {
            log.warn("Appliance Image upload is cancelled by the user");
        } else {
            ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_APPLIANCE_FAILED), Notification.Type.ERROR_MESSAGE);
        }
        if (this.uploadPath != null) {
            File uploadDirectory = new File(this.uploadPath);
            if (uploadDirectory.exists()) {
                try {
                    FileUtils.deleteDirectory(uploadDirectory);
                } catch (IOException e) {
                    log.error("Deleting upload directory: " + this.uploadPath + " failed when upload was cancelled by user.", e);
                }
            }
        }
    }

    private boolean validateZipFile(String fileName) {
        return FilenameUtils.getExtension(fileName).equals("zip");
    }
}

16 Source : CRUDBaseView.java
with Apache License 2.0
from opensecuritycontroller

/**
 * returns an empty View layout containing CRUD ToolBar, CSS layout, Table
 * with columnList and replacedle of the view
 *
 * @param parentreplacedle
 *            replacedle of the parent panel
 * @param parentCRUDButtons
 *            Array Toolbar buttons to diaplay parent panel
 * @param parentMultiSelect
 *            multi select parent table
 * @param childreplacedle
 *            replacedle of child panel
 * @param childCRUDButtons
 *            Array of toolbar buttons to display in child panel
 * @param parentSubViewList
 *            Map of CRUDBaseSubViews with their respective Button captions for Parent Table
 * @param childSubViewList
 *            Map of CRUDBaseSubViews with their respective Button captions for Child Table
 */
public void createView(String parentreplacedle, List<ToolbarButtons> parentCRUDButtons, boolean parentMultiSelect, String childreplacedle, List<ToolbarButtons> childCRUDButtons, Map<String, CRUDBaseSubView<?, ?>> parentSubViewList, Map<String, CRUDBaseSubView<?, ?>> childSubViewMap) {
    boolean addChildTable = childreplacedle != null;
    setSizeFull();
    this.parentSubViewMap = parentSubViewList;
    this.childSubViewMap = childSubViewMap;
    // parent container with header
    this.parentContainerLayout = new VerticalLayout();
    this.parentContainerLayout.addStyleName(StyleConstants.BASE_CONTAINER);
    this.parentContainerLayout.setSizeFull();
    // parent panel with table and CRUD buttons
    final VerticalLayout parentPanel = new VerticalLayout();
    parentPanel.addStyleName("panel");
    parentPanel.setSizeFull();
    this.parentContainerLayout.addComponent(createHeader(parentreplacedle, false));
    this.parentContainerLayout.addComponent(parentPanel);
    this.infoText = new PageInformationComponent();
    this.infoText.addStyleName(StyleConstants.PAGE_INFO_COMPONENT);
    parentPanel.addComponent(this.infoText);
    if (parentCRUDButtons != null) {
        parentPanel.addComponent(createParentToolbar(parentCRUDButtons));
    }
    parentPanel.addComponent(createParentTable(parentMultiSelect));
    // expand parentTable with parentPanel
    parentPanel.setExpandRatio(this.parentTable, 1L);
    // expand parentPanel with parentContainer
    this.parentContainerLayout.setExpandRatio(parentPanel, 1L);
    if (addChildTable) {
        // child container with header
        this.childContainerLayout = new VerticalLayout();
        this.childContainerLayout.addStyleName(StyleConstants.BASE_CONTAINER);
        this.childContainerLayout.setSizeFull();
        // child panel with table and CRUD buttons
        final VerticalLayout childPanel = new VerticalLayout();
        childPanel.addStyleName("panel");
        childPanel.setSizeFull();
        this.childContainerLayout.addComponent(createHeader(childreplacedle, true));
        this.childContainerLayout.addComponent(childPanel);
        if (childCRUDButtons != null) {
            childPanel.addComponent(createChildToolBar(childCRUDButtons));
        }
        // adding table to panel layout
        childPanel.addComponent(createChildTable());
        // expand childTable with childPanel
        childPanel.setExpandRatio(this.childTable, 1L);
        // expand childPanel with childContainer
        this.childContainerLayout.setExpandRatio(childPanel, 1L);
        this.viewSplitter = new VerticalSplitPanel();
        this.viewSplitter.addStyleName(ValoTheme.SPLITPANEL_LARGE);
        this.viewSplitter.addComponent(this.parentContainerLayout);
        this.viewSplitter.addComponent(this.childContainerLayout);
        this.viewSplitter.setImmediate(true);
        this.viewSplitter.setMaxSplitPosition(75, Unit.PERCENTAGE);
        this.viewSplitter.setMinSplitPosition(25, Unit.PERCENTAGE);
        // adding split panel to the main view
        addComponent(this.viewSplitter);
    } else {
        addComponent(this.parentContainerLayout);
    }
}

15 Source : DemoUI.java
with Apache License 2.0
from TatuLund

@Override
protected void init(VaadinRequest vaadinRequest) {
    final VerticalLayout layout = new VerticalLayout();
    layout.setSizeFull();
    MessageGrid messageGrid = new MessageGrid();
    DemoFastGrid demoGrid = new DemoFastGrid(messageGrid);
    Button clearButton = new Button("Clear");
    clearButton.addClickListener(e -> {
        messageGrid.clear();
    });
    Button addButton = new Button();
    // Add Row
    addButton.setIcon(VaadinIcons.PLUS_CIRCLE);
    addButton.addClickListener(e -> {
        demoGrid.addBlankRow();
    });
    addButton.setDescription("Add a new row");
    Button rowValidationButton = new Button();
    rowValidationButton.setIcon(VaadinIcons.CHECK_CIRCLE_O);
    rowValidationButton.setStyleName(ValoTheme.BUTTON_QUIET);
    rowValidationButton.addClickListener(e -> {
        demoGrid.getNavigation().setRowValidation(!demoGrid.getNavigation().getRowValidation());
        if (!demoGrid.getNavigation().getRowValidation())
            rowValidationButton.setStyleName(ValoTheme.BUTTON_QUIET);
        else
            rowValidationButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);
    });
    rowValidationButton.setDescription("Toggle rowValidation");
    Button rowOpenClickButton = new Button();
    rowOpenClickButton.setIcon(VaadinIcons.FOLDER_OPEN_O);
    rowOpenClickButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);
    rowOpenClickButton.addClickListener(e -> {
        demoGrid.getNavigation().setOpenEditorWithSingleClick(!demoGrid.getNavigation().getOpenEditorWithSingleClick());
        if (!demoGrid.getNavigation().getOpenEditorWithSingleClick())
            rowOpenClickButton.setStyleName(ValoTheme.BUTTON_QUIET);
        else
            rowOpenClickButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);
    });
    rowOpenClickButton.setDescription("Toggle openEditorWithSingleClick");
    Button rowOpenByTypingButton = new Button();
    rowOpenByTypingButton.setIcon(VaadinIcons.KEYBOARD_O);
    rowOpenByTypingButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);
    rowOpenByTypingButton.addClickListener(e -> {
        demoGrid.getNavigation().setOpenEditorOnTyping(!demoGrid.getNavigation().getOpenEditorOnTyping());
        if (!demoGrid.getNavigation().getOpenEditorOnTyping())
            rowOpenByTypingButton.setStyleName(ValoTheme.BUTTON_QUIET);
        else
            rowOpenByTypingButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);
    });
    rowOpenByTypingButton.setDescription("Toggle openEditorOnTyping");
    Button openEditorButton = new Button();
    openEditorButton.setIcon(VaadinIcons.INPUT);
    openEditorButton.setDescription("Open editor at 1,3");
    openEditorButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);
    openEditorButton.addClickListener(e -> {
        demoGrid.openEditor();
    });
    Button disableGridEditButton = new Button();
    disableGridEditButton.setIcon(VaadinIcons.PENCIL);
    disableGridEditButton.setDescription("Toggle Grid Editing");
    disableGridEditButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);
    disableGridEditButton.addClickListener(e -> {
        if (demoGrid.getEditor().isEnabled()) {
            if (demoGrid.getEditor().isOpen()) {
                demoGrid.getEditor().cancel();
            }
            demoGrid.getEditor().setEnabled(false);
            openEditorButton.setEnabled(false);
            disableGridEditButton.setStyleName(ValoTheme.BUTTON_QUIET);
        } else {
            demoGrid.getEditor().setEnabled(true);
            openEditorButton.setEnabled(true);
            disableGridEditButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);
        }
    });
    Button moveSelectionButton = new Button();
    moveSelectionButton.setIcon(VaadinIcons.BULLSEYE);
    moveSelectionButton.setDescription("Toggle select follow");
    moveSelectionButton.setStyleName(ValoTheme.BUTTON_QUIET);
    moveSelectionButton.addClickListener(e -> {
        if (demoGrid.moveSelection) {
            demoGrid.moveSelection = false;
            demoGrid.deselectAll();
            demoGrid.setSelectionMode(SelectionMode.NONE);
            moveSelectionButton.setStyleName(ValoTheme.BUTTON_QUIET);
        } else {
            demoGrid.moveSelection = true;
            demoGrid.setSelectionMode(SelectionMode.SINGLE);
            moveSelectionButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);
        }
    });
    Button resetFocusButton = new Button();
    resetFocusButton.setIcon(VaadinIcons.CORNER_UPPER_LEFT);
    resetFocusButton.setDescription("Reset focust to 0,1");
    resetFocusButton.setStyleName(ValoTheme.BUTTON_FRIENDLY);
    resetFocusButton.addClickListener(e -> {
        demoGrid.resetFocus();
    });
    HorizontalLayout buttons = new HorizontalLayout();
    buttons.addComponents(addButton, rowValidationButton, rowOpenClickButton, rowOpenByTypingButton, disableGridEditButton, moveSelectionButton, resetFocusButton, openEditorButton);
    layout.setMargin(true);
    layout.setSpacing(true);
    layout.addComponent(demoGrid);
    layout.addComponent(buttons);
    layout.addComponent(messageGrid);
    layout.addComponent(clearButton);
    layout.setSizeFull();
    layout.setExpandRatio(demoGrid, 10);
    layout.setExpandRatio(buttons, 1);
    layout.setExpandRatio(clearButton, 1);
    layout.setExpandRatio(messageGrid, 6);
    setContent(layout);
}

15 Source : PluginUploader.java
with Apache License 2.0
from opensecuritycontroller

@SuppressWarnings("serial")
public clreplaced PluginUploader extends CustomComponent implements Receiver, FailedListener, SucceededListener {

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

    private static int TEMP_FOLDER_COUNTER = 0;

    private final Upload upload;

    private File file;

    private final Panel panel = new Panel();

    private final VerticalLayout verLayout = new VerticalLayout();

    private String uploadPath;

    private final ServerApi server;

    public interface UploadSucceededListener {

        void uploadComplete(String uploadPath);
    }

    private UploadSucceededListener uploadSucceededListener;

    public PluginUploader(ServerApi server) {
        this.server = server;
        this.upload = new Upload();
        this.upload.setButtonCaption("Upload");
        this.upload.setReceiver(this);
        this.upload.addFailedListener(this);
        this.upload.addSucceededListener(this);
        this.upload.setImmediate(false);
        final UploadInfoWindow uploadInfoWindow = new UploadInfoWindow(this.upload);
        this.upload.addStartedListener(new StartedListener() {

            @Override
            public void uploadStarted(final StartedEvent event) {
                if (uploadInfoWindow.getParent() == null) {
                    ViewUtil.addWindow(uploadInfoWindow);
                }
            }
        });
        this.verLayout.setSpacing(true);
        this.verLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
        this.verLayout.addComponent(this.upload);
        this.panel.setWidth("100%");
        this.panel.setContent(this.verLayout);
        setCompositionRoot(this.panel);
    }

    @Override
    public OutputStream receiveUpload(String filename, String mimeType) {
        if (filename == null || filename.isEmpty()) {
            return null;
        }
        log.info("Start uploading file: " + filename);
        try {
            if (validateFileExtension(filename)) {
                this.uploadPath = getTemporaryUploadPath();
                File uploadDirectory = new File(this.uploadPath);
                if (!uploadDirectory.exists()) {
                    FileUtils.forceMkdir(uploadDirectory);
                }
                this.file = new File(this.uploadPath + filename);
                return new FileOutputStream(this.file);
            }
        } catch (Exception e) {
            log.error("Error opening file: " + filename, e);
            ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_COMMON_ERROR) + e.getMessage(), Notification.Type.ERROR_MESSAGE);
        }
        return null;
    }

    /**
     * Gets the upload path for the file. If isTmpFolder is set to true, returns a unique temporary upload file path.
     * If it is set to false it returns the actual image upload folder.
     *
     * @param isTmpFolder
     *            the temporary path the file is uploaded before being moved to the actual image path
     *
     * @return the temporary path when isTmpFolder is set to true
     *         the image path when isTmpFolder is set to false
     */
    private static String getTemporaryUploadPath() {
        String uploadPath = "tmp" + TEMP_FOLDER_COUNTER++ + File.separator;
        return uploadPath;
    }

    @Override
    public void uploadSucceeded(SucceededEvent event) {
        log.info("Upload Successful! replacedyzing Uploaded Image.....");
        try {
            // Do the unzip only if there is enough disc space
            if (!this.server.isEnoughSpace()) {
                String message = VmidcMessages.getString(VmidcMessages_.UPLOAD_PLUGIN_NOSPACE);
                throw new VmidcException(message);
            }
            if (!validateFileExtension(this.file.getName())) {
                String message = VmidcMessages.getString(VmidcMessages_.UPLOAD_PLUGIN_FAILED);
                throw new VmidcException(message);
            }
            if (this.uploadSucceededListener != null) {
                this.uploadSucceededListener.uploadComplete(this.uploadPath);
            }
        } catch (Exception e) {
            log.error("Failed to unzip uploaded zip file", e);
            try {
                FileUtils.deleteDirectory(new File(this.uploadPath));
            } catch (IOException ex) {
                log.error("Failed to cleanup the tmp directory", ex);
            }
            this.uploadPath = null;
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
        }
    }

    @Override
    public void uploadFailed(FailedEvent event) {
        if (event.getFilename() == null || event.getFilename().isEmpty()) {
            String message = VmidcMessages.getString(VmidcMessages_.UPLOAD_PLUGIN_NOFILE);
            ViewUtil.iscNotification(message, Notification.Type.ERROR_MESSAGE);
        } else if (event.getReason() instanceof UploadInterruptedException) {
            log.warn(event.getFilename().toString() + " Plugin upload is cancelled by the user");
        } else {
            String message = VmidcMessages.getString(VmidcMessages_.UPLOAD_PLUGIN_FAILED);
            ViewUtil.iscNotification(message, Notification.Type.WARNING_MESSAGE);
        }
        if (this.uploadPath != null) {
            File uploadDirectory = new File(this.uploadPath);
            if (uploadDirectory.exists()) {
                try {
                    FileUtils.deleteDirectory(uploadDirectory);
                } catch (IOException e) {
                    log.error("Deleting upload directory: " + this.uploadPath + " failed when upload was cancelled by user.", e);
                }
            }
        }
    }

    private boolean validateFileExtension(String fileName) {
        String extension = FilenameUtils.getExtension(fileName);
        return extension.equals("bar");
    }

    public void addSucceededListener(UploadSucceededListener uploadSucceededListener) {
        this.uploadSucceededListener = uploadSucceededListener;
    }

    public String getUploadPath() {
        return this.uploadPath;
    }
}

15 Source : DbRestorer.java
with Apache License 2.0
from opensecuritycontroller

@SuppressWarnings("serial")
public clreplaced DbRestorer extends CustomComponent implements Receiver, FailedListener, SucceededListener {

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

    private final Upload upload;

    private File file;

    private final Panel panel = new Panel();

    private final VerticalLayout verLayout = new VerticalLayout();

    private final RestoreServiceApi restoreService;

    private final ServerApi server;

    private final ValidationApi validator;

    public DbRestorer(RestoreServiceApi restoreService, ServerApi server, ValidationApi validator) {
        this.restoreService = restoreService;
        this.server = server;
        this.validator = validator;
        this.upload = new Upload();
        this.upload.setButtonCaption(VmidcMessages.getString(VmidcMessages_.UPLOAD_RESTORE));
        this.upload.setReceiver(this);
        this.upload.addFailedListener(this);
        this.upload.addSucceededListener(this);
        this.upload.setImmediate(false);
        final UploadInfoWindow uploadInfoWindow = new UploadInfoWindow(this.upload);
        this.upload.addStartedListener(new StartedListener() {

            @Override
            public void uploadStarted(final StartedEvent event) {
                if (uploadInfoWindow.getParent() == null) {
                    ViewUtil.addWindow(uploadInfoWindow);
                }
            }
        });
        this.verLayout.setSpacing(true);
        this.panel.setWidth("100%");
        this.panel.setContent(this.verLayout);
        this.verLayout.addComponent(this.upload);
        this.verLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
        setCompositionRoot(this.panel);
    }

    @Override
    public OutputStream receiveUpload(String filename, String mimeType) {
        if (filename == null || filename.isEmpty()) {
            return null;
        }
        // validate uploaded file is a zip file or encrypted backup file
        if (!this.restoreService.isValidBackupFilename(filename)) {
            ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_RESTORE_INVALID_BACKUP, this.server.getProductName()), Notification.Type.WARNING_MESSAGE);
            return null;
        }
        log.info("Start uploading file: " + filename);
        try {
            this.file = new File(filename);
            return new FileOutputStream(this.file);
        } catch (final java.io.FileNotFoundException e) {
            log.error("Error opening file: " + filename, e);
            ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_COMMON_ERROR) + e.getMessage(), Notification.Type.ERROR_MESSAGE);
        }
        return null;
    }

    @Override
    public void uploadSucceeded(SucceededEvent event) {
        log.info("Upload Successful! Restoring Database ......");
        try {
            PreplacedwordWindow.SubmitFormListener restoreAction = preplacedword -> {
                RestoreRequest req = new RestoreRequest();
                req.setBkpFile(this.file);
                req.setPreplacedword(preplacedword);
                try {
                    this.restoreService.dispatch(req);
                    ViewUtil.iscNotification("Upload", VmidcMessages.getString(VmidcMessages_.UPLOAD_RESTORE_UPLOAD_STARTED, this.server.getProductName()), Notification.Type.WARNING_MESSAGE);
                } catch (Exception e) {
                    log.error("Restore Service Failed.", e);
                    ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
                } finally {
                    // We can delete the uploaded file now since it has been extracted.
                    this.file.delete();
                }
            };
            if (this.restoreService.isValidEncryptedBackupFilename(event.getFilename())) {
                // ask user for decryption preplacedword first
                PreplacedwordWindow preplacedwordWindow = new PreplacedwordWindow(this.validator);
                preplacedwordWindow.setSubmitFormListener(restoreAction);
                ViewUtil.addWindow(preplacedwordWindow);
            } else if (this.restoreService.isValidZipBackupFilename(event.getFilename())) {
                // perform restore without decryption
                restoreAction.submit(null);
            }
        } catch (Exception e) {
            log.error("Restore Service Failed.", e);
            // ensure that uploaded file is deleted
            this.file.delete();
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
        }
    }

    @Override
    public void uploadFailed(FailedEvent event) {
        if (event.getFilename() == null || event.getFilename().isEmpty()) {
            ViewUtil.iscNotification(VmidcMessages.getString("upload.restore.nofile"), Notification.Type.ERROR_MESSAGE);
        } else if (event.getReason() instanceof UploadInterruptedException) {
            log.warn("Database backup Upload is cancelled by the user");
        } else {
            ViewUtil.iscNotification(VmidcMessages.getString("upload.restore.invalid.backup"), Notification.Type.WARNING_MESSAGE);
        }
    }
}

14 Source : BaseSecurityGroupWindow.java
with Apache License 2.0
from opensecuritycontroller

@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;
}

14 Source : MainUI.java
with Apache License 2.0
from opensecuritycontroller

@Theme("vmidc")
@SuppressWarnings("serial")
@PreserveOnRefresh
@Push(value = PushMode.AUTOMATIC, transport = Transport.WEBSOCKET)
@org.osgi.service.component.annotations.Component(service = MainUI.clreplaced, scope = ServiceScope.PROTOTYPE)
public clreplaced MainUI extends UI implements BroadcastListener {

    private static final int SESSION_EXPIRE_TIME_OUT_IN_SECS = 1800;

    // Status View
    public static final String VIEW_FRAGMENT_APPLIANCE_INSTANCES = "Appliance Instances";

    public static final String VIEW_FRAGMENT_JOBS = "Jobs";

    public static final String VIEW_FRAGMENT_ALERTS = "Alerts";

    // Setup Views
    public static final String VIEW_FRAGMENT_VIRTUALIZATION_CONNECTORS = "Virtualization Connectors";

    public static final String VIEW_FRAGMENT_SECURITY_MANAGER_CONNECTORS = "Manager Connectors";

    public static final String VIEW_FRAGMENT_SECURITY_FUNCTION_CATALOG = "Service Function Catalog";

    public static final String VIEW_FRAGMENT_DISTRIBUTED_APPLIANCES = "Distributed Appliances";

    // Manage Views
    public static final String VIEW_FRAGMENT_SERVER = "Server";

    public static final String VIEW_FRAGMENT_PLUGIN = "Plugins";

    public static final String VIEW_FRAGMENT_USERS = "Users";

    public static final String VIEW_FRAGMENT_ALARMS = "Alarms";

    private static final long serialVersionUID = 1L;

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

    private CRUDBaseView<?, ?> currentView;

    // accordion used as side navigation
    private final Accordion accordion = new Accordion();

    // accordion tabs
    private final CssLayout status = new CssLayout();

    private final CssLayout setup = new CssLayout();

    private final CssLayout options = new CssLayout();

    VerticalLayout root = new VerticalLayout();

    VerticalLayout loginLayout;

    HorizontalLayout header = new HorizontalLayout();

    HorizontalLayout mainLayout = new HorizontalLayout();

    CssLayout menu = new CssLayout();

    CssLayout content = new CssLayout();

    @Reference
    ServerApi server;

    @Reference
    LoginServiceApi loginService;

    @Reference
    ComponentServiceObjects<AlertView> alertViewFactory;

    @Reference
    ComponentServiceObjects<ApplianceInstanceView> applianceInstanceViewFactory;

    @Reference
    ComponentServiceObjects<JobView> jobViewFactory;

    @Reference
    ComponentServiceObjects<VirtualizationConnectorView> virtualizationConnectorViewFactory;

    @Reference
    ComponentServiceObjects<ManagerConnectorView> managerConnectorViewFactory;

    @Reference
    ComponentServiceObjects<ApplianceView> applicanceViewFactory;

    @Reference
    ComponentServiceObjects<DistributedApplianceView> distributedApplicanceViewFactory;

    @Reference
    ComponentServiceObjects<UserView> userViewFactory;

    @Reference
    ComponentServiceObjects<AlarmView> alarmViewFactory;

    @Reference
    ComponentServiceObjects<PluginView> pluginViewFactory;

    @Reference
    ComponentServiceObjects<MaintenanceView> maintenanceViewFactory;

    @Reference
    GetDtoFromEnreplacedyServiceFactoryApi getDtoFromEnreplacedyServiceFactory;

    Set<OSCViewProvider<?>> statusViews = new LinkedHashSet<>();

    Set<OSCViewProvider<?>> setupViews = new LinkedHashSet<>();

    Set<OSCViewProvider<?>> manageViews = new LinkedHashSet<>();

    private Navigator nav;

    private ServiceRegistration<BroadcastListener> registration;

    private BundleContext ctx;

    private AlertView alertView;

    public void setCurrentView(CRUDBaseView<?, ?> view) {
        this.currentView = view;
    }

    @Activate
    private void start(BundleContext ctx) {
        this.ctx = ctx;
        this.statusViews.add(new OSCViewProvider<>(VIEW_FRAGMENT_ALERTS, AlertView.clreplaced, this.alertViewFactory));
        this.statusViews.add(new OSCViewProvider<>(VIEW_FRAGMENT_APPLIANCE_INSTANCES, ApplianceInstanceView.clreplaced, this.applianceInstanceViewFactory));
        this.statusViews.add(new OSCViewProvider<>(VIEW_FRAGMENT_JOBS, JobView.clreplaced, this.jobViewFactory));
        this.setupViews.add(new OSCViewProvider<>(VIEW_FRAGMENT_VIRTUALIZATION_CONNECTORS, VirtualizationConnectorView.clreplaced, this.virtualizationConnectorViewFactory));
        this.setupViews.add(new OSCViewProvider<>(VIEW_FRAGMENT_SECURITY_MANAGER_CONNECTORS, ManagerConnectorView.clreplaced, this.managerConnectorViewFactory));
        this.setupViews.add(new OSCViewProvider<>(VIEW_FRAGMENT_SECURITY_FUNCTION_CATALOG, ApplianceView.clreplaced, this.applicanceViewFactory));
        this.setupViews.add(new OSCViewProvider<>(VIEW_FRAGMENT_DISTRIBUTED_APPLIANCES, DistributedApplianceView.clreplaced, this.distributedApplicanceViewFactory));
        this.manageViews.add(new OSCViewProvider<>(VIEW_FRAGMENT_USERS, UserView.clreplaced, this.userViewFactory));
        this.manageViews.add(new OSCViewProvider<>(VIEW_FRAGMENT_ALARMS, AlarmView.clreplaced, this.alarmViewFactory));
        this.manageViews.add(new OSCViewProvider<>(VIEW_FRAGMENT_PLUGIN, PluginView.clreplaced, this.pluginViewFactory));
        this.manageViews.add(new OSCViewProvider<>(VIEW_FRAGMENT_SERVER, MaintenanceView.clreplaced, this.maintenanceViewFactory));
    }

    @Override
    protected void init(VaadinRequest request) {
        Page.getCurrent().setreplacedle(this.server.getProductName());
        setLocale(Locale.US);
        setContent(this.root);
        this.root.addStyleName("root");
        this.root.setSizeFull();
        this.nav = new Navigator(this, this.content);
        this.alertView = this.alertViewFactory.getService();
        this.nav.addView("", this.alertView);
        this.nav.setErrorView(this.alertView);
        for (ViewProvider page : this.statusViews) {
            this.nav.addProvider(page);
        }
        for (ViewProvider page : this.setupViews) {
            this.nav.addProvider(page);
        }
        for (ViewProvider page : this.manageViews) {
            this.nav.addProvider(page);
        }
        // setting idle timeout to 30 minutes here instead of web.xml
        request.getWrappedSession().setMaxInactiveInterval(SESSION_EXPIRE_TIME_OUT_IN_SECS);
        if (getSession().getAttribute("user") != null) {
            // session exists go to Main View
            buildMainView();
        } else {
            // no session exists go to login page
            buildLoginForm();
        }
        // override vaadin default error messages
        VaadinService.getCurrent().setSystemMessagesProvider(new SystemMessagesProvider() {

            @Override
            public SystemMessages getSystemMessages(SystemMessagesInfo systemMessagesInfo) {
                CustomizedSystemMessages messages = new CustomizedSystemMessages();
                // disable communication errorS
                messages.setCommunicationErrorCaption(null);
                messages.setCommunicationErrorMessage(null);
                messages.setCommunicationErrorNotificationEnabled(false);
                messages.setSessionExpiredCaption(null);
                messages.setSessionExpiredMessage(MainUI.this.server.getProductName() + " session timeout. Please <u>click here</u> to Login again.");
                messages.setSessionExpiredNotificationEnabled(true);
                messages.setSessionExpiredURL(getLogoutUrl());
                return messages;
            }
        });
        // generic error handler for any UI exceptions
        UI.getCurrent().setErrorHandler(new ErrorHandler() {

            @Override
            public void error(com.vaadin.server.ErrorEvent event) {
                if (!(event.getThrowable() instanceof UploadException)) {
                    // show error as an error notification to the user
                    ViewUtil.iscNotification(event.getThrowable().getMessage(), Notification.Type.ERROR_MESSAGE);
                    log.error("Unhandled error", event.getThrowable());
                }
            }
        });
    }

    private void buildLoginForm() {
        addStyleName("login");
        this.loginLayout = new VerticalLayout();
        this.loginLayout.setSizeFull();
        this.loginLayout.addStyleName("login-layout");
        this.root.addComponent(this.loginLayout);
        final CssLayout loginPanel = new CssLayout();
        loginPanel.addStyleName("login-panel");
        HorizontalLayout labels = new HorizontalLayout();
        labels.setWidth("100%");
        labels.setMargin(true);
        labels.addStyleName("labels");
        loginPanel.addComponent(labels);
        Label product = new Label(this.server.getProductName());
        product.addStyleName("product-label-login");
        labels.addComponent(new Image(null, new ThemeResource("img/logo.png")));
        labels.addComponent(product);
        labels.setComponentAlignment(product, Alignment.MIDDLE_LEFT);
        labels.setExpandRatio(product, 1);
        HorizontalLayout fields = new HorizontalLayout();
        fields.setSpacing(true);
        fields.setMargin(true);
        fields.addStyleName("fields");
        final TextField username = new TextField("Login ID");
        username.focus();
        username.setImmediate(true);
        username.setRequired(true);
        username.setRequiredError("Login ID or Preplacedword cannot be empty");
        fields.addComponent(username);
        final PreplacedwordField preplacedword = new PreplacedwordField("Preplacedword");
        preplacedword.setRequired(true);
        preplacedword.setImmediate(true);
        preplacedword.setRequiredError("Login ID or Preplacedword cannot be empty");
        fields.addComponent(preplacedword);
        final Button login = new Button("Log In");
        login.addStyleName("default");
        fields.addComponent(login);
        fields.setComponentAlignment(login, Alignment.BOTTOM_LEFT);
        final ShortcutListener enter = new ShortcutListener("Login", KeyCode.ENTER, null) {

            @Override
            public void handleAction(Object sender, Object target) {
                login.click();
            }
        };
        login.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                try {
                    username.validate();
                    preplacedword.validate();
                    LoginRequest request = new LoginRequest();
                    request.setLoginName(username.getValue().trim());
                    request.setPreplacedword(preplacedword.getValue());
                    LoginResponse response = MainUI.this.loginService.dispatch(request);
                    if (response != null) {
                        login.removeShortcutListener(enter);
                        if (getSession() != null) {
                            getSession().setAttribute("user", username.getValue());
                        }
                        MainUI.this.root.removeComponent(MainUI.this.loginLayout);
                        buildMainView();
                    }
                } catch (EmptyValueException e) {
                    ViewUtil.iscNotification(e.getMessage() + ".", Notification.Type.ERROR_MESSAGE);
                    username.focus();
                } catch (Exception e) {
                    username.focus();
                    ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
                }
            }
        });
        login.addShortcutListener(enter);
        loginPanel.addComponent(fields);
        this.loginLayout.addComponent(loginPanel);
        this.loginLayout.setComponentAlignment(loginPanel, Alignment.MIDDLE_CENTER);
    }

    private void buildMainView() {
        buildHeader();
        buildMainLayout();
        this.root.setExpandRatio(this.mainLayout, 1);
        this.registration = this.ctx.registerService(BroadcastListener.clreplaced, this, null);
        // adding view change listener to navigator
        addViewChangeListener();
        String uriFragment = Page.getCurrent().getUriFragment();
        if (StringUtils.isBlank(uriFragment)) {
            uriFragment = VIEW_FRAGMENT_ALERTS;
        }
        String sanitizedFragment = StringUtils.remove(uriFragment, '!').replace('+', ' ');
        this.nav.navigateTo(sanitizedFragment);
    }

    private void buildMainLayout() {
        this.mainLayout.setWidth("100%");
        this.mainLayout.setHeight("100%");
        this.mainLayout.addStyleName("view-content");
        VerticalLayout sidebar = buildSidebar();
        this.mainLayout.addComponent(sidebar);
        // Content
        this.mainLayout.addComponent(this.content);
        this.content.setSizeFull();
        this.mainLayout.setExpandRatio(this.content, 1);
        this.root.addComponent(this.mainLayout);
    }

    private VerticalLayout buildSidebar() {
        VerticalLayout sideBar = new VerticalLayout();
        sideBar.addStyleName("sidebar");
        sideBar.addComponent(buildMainMenu());
        sideBar.setExpandRatio(this.menu, 1);
        sideBar.setWidth(null);
        sideBar.setHeight("100%");
        return sideBar;
    }

    private void buildHeader() {
        this.header.addStyleName("branding");
        this.header.addStyleName("header");
        // product name and information
        Label product = new Label(this.server.getProductName() + "<br> <span clreplaced='product-version'> Version: " + this.server.getVersionStr() + "</span>", ContentMode.HTML);
        product.addStyleName("product-label");
        product.setSizeUndefined();
        HorizontalLayout brandingLayout = new HorizontalLayout();
        brandingLayout.addStyleName("header-content");
        brandingLayout.addComponent(new Image(null, new ThemeResource("img/logo.png")));
        brandingLayout.addComponent(product);
        // creating home help button
        Button mainHelpButton = new Button();
        mainHelpButton.setImmediate(true);
        mainHelpButton.setStyleName(Reindeer.BUTTON_LINK);
        mainHelpButton.setDescription("Help");
        mainHelpButton.setIcon(new ThemeResource("img/headerHelp.png"));
        mainHelpButton.addClickListener(new ClickListener() {

            private String guid = "";

            @Override
            public void buttonClick(ClickEvent event) {
                ViewUtil.showHelpBrowserWindow(this.guid);
            }
        });
        HorizontalLayout helpLayout = new HorizontalLayout();
        helpLayout.addComponent(mainHelpButton);
        helpLayout.addStyleName("homeHelpButton");
        // Adding current user to header
        Label user = new Label("User: " + getCurrent().getSession().getAttribute("user").toString());
        // header banner
        HorizontalLayout userlayout = new HorizontalLayout();
        userlayout.addStyleName("user");
        userlayout.addComponent(user);
        // create Logout button next to user
        userlayout.addComponent(buildLogout());
        // Adding help button to the user layout next to logout button
        userlayout.addComponent(helpLayout);
        this.header.setWidth("100%");
        this.header.setHeight("65px");
        this.header.addComponent(brandingLayout);
        this.header.addComponent(userlayout);
        this.header.setExpandRatio(brandingLayout, 1);
        this.root.addComponent(this.header);
    }

    private CssLayout buildMainMenu() {
        buildSubmenu(this.status, this.statusViews);
        buildSubmenu(this.setup, this.setupViews);
        buildSubmenu(this.options, this.manageViews);
        this.accordion.addTab(this.status, "Status", new ThemeResource("img/status_header.png"));
        this.accordion.addTab(this.setup, "Setup", new ThemeResource("img/setup_header.png"));
        this.accordion.addTab(this.options, "Manage", new ThemeResource("img/manage_header.png"));
        this.menu.addComponent(this.accordion);
        this.menu.addStyleName("menu");
        this.menu.setHeight("100%");
        return this.menu;
    }

    private void buildSubmenu(CssLayout submenu, Set<OSCViewProvider<?>> views) {
        for (final OSCViewProvider<?> view : views) {
            String viewName = view.getName();
            NativeButton b = new NativeButton(viewName);
            // selecting default menu button
            if (view.getName().equals(VIEW_FRAGMENT_ALERTS)) {
                b.addStyleName("selected");
            }
            b.addClickListener(new ClickListener() {

                @Override
                public void buttonClick(ClickEvent event) {
                    clearMenuSelection();
                    event.getButton().addStyleName("selected");
                    if (!MainUI.this.nav.getState().equals(viewName)) {
                        MainUI.this.nav.navigateTo(viewName);
                    }
                }
            });
            submenu.setSizeFull();
            submenu.addComponent(b);
        }
    }

    private Button buildLogout() {
        Button exit = new Button("Logout");
        exit.setDescription("Logout");
        exit.setWidth("100%");
        exit.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                getSession().setAttribute("user", null);
                for (UI ui : getSession().getUIs()) {
                    ui.close();
                }
            }
        });
        return exit;
    }

    private void clearMenuSelection() {
        for (Component next : this.menu) {
            if (next instanceof Accordion) {
                clearAccordionSubMenu((Accordion) next);
            }
        }
    }

    private void clearAccordionSubMenu(Accordion subMenu) {
        for (Component next : subMenu) {
            if (next instanceof CssLayout) {
                clearSubmenuSelection((CssLayout) next);
            }
        }
    }

    private void clearSubmenuSelection(CssLayout subMenu) {
        for (Component next : subMenu) {
            if (next instanceof NativeButton) {
                next.removeStyleName("selected");
            }
        }
    }

    @Override
    public void receiveBroadcast(final BroadcastMessage msg) {
        access(new Runnable() {

            @Override
            public void run() {
                try {
                    if (MainUI.this.currentView == null) {
                        return;
                    }
                    if (msg.getEnreplacedyId() == Long.MIN_VALUE) {
                        return;
                    }
                    String dto = msg.getReceiver() + "Dto";
                    if (MainUI.this.currentView.isDtoChangeRelevantToParentView(dto)) {
                        MainUI.this.currentView.syncTables(msg, false, MainUI.this.getDtoFromEnreplacedyServiceFactory);
                    } else if (MainUI.this.currentView.isDtoChangeRelevantToChildView(dto)) {
                        MainUI.this.currentView.syncTables(msg, true, MainUI.this.getDtoFromEnreplacedyServiceFactory);
                    } else if (MainUI.this.currentView.isDtoRelevantToParentSubView(dto)) {
                        MainUI.this.currentView.delegateBroadcastMessagetoSubView(msg, false, MainUI.this.getDtoFromEnreplacedyServiceFactory);
                    } else if (MainUI.this.currentView.isDtoRelevantToChildSubView(dto)) {
                        MainUI.this.currentView.delegateBroadcastMessagetoSubView(msg, true, MainUI.this.getDtoFromEnreplacedyServiceFactory);
                    }
                } catch (Exception e) {
                    log.error("Fail to receive DTO broadcast", e);
                }
            }
        });
    }

    @Override
    public void detach() {
        try {
            // unregister before closing
            if (this.registration != null) {
                try {
                    this.registration.unregister();
                } catch (IllegalStateException ise) {
                // The listener was already unregistered,
                // so no problems here.
                }
            }
            log.info("MainUI.detach() called");
            super.detach();
        } catch (Exception e) {
            log.error("Detach Exception " + e.getMessage());
        }
    }

    private String getLogoutUrl() {
        if (VaadinServletService.getCurrentRequest() != null) {
            return VaadinServletService.getCurrentRequest().getContextPath();
        } else {
            return "https://" + this.server.getServerIpAddress() + "/";
        }
    }

    @Override
    public void close() {
        try {
            log.info("MainUI.close() called");
            if (this.alertView != null) {
                this.alertViewFactory.ungetService(this.alertView);
            }
            if (UI.getCurrent() != null && UI.getCurrent().getPage() != null) {
                UI.getCurrent().getPage().setLocation(getLogoutUrl());
            }
            super.close();
        } catch (Exception e) {
            log.error("Destroy Exception " + e.getMessage());
        }
    }

    private void addViewChangeListener() {
        this.nav.addViewChangeListener(new ViewChangeListener() {

            @Override
            public boolean beforeViewChange(ViewChangeEvent event) {
                return true;
            }

            @Override
            public void afterViewChange(ViewChangeEvent event) {
                if (updateAccordion(event, MainUI.this.statusViews, MainUI.this.status)) {
                    return;
                } else if (updateAccordion(event, MainUI.this.setupViews, MainUI.this.setup)) {
                    return;
                } else {
                    updateAccordion(event, MainUI.this.manageViews, MainUI.this.options);
                }
            }

            private boolean updateAccordion(ViewChangeEvent event, Set<OSCViewProvider<?>> views, CssLayout subMenu) {
                int i = 0;
                for (OSCViewProvider<?> view : views) {
                    if (event.getNewView().getClreplaced().equals(view.getType())) {
                        clearMenuSelection();
                        MainUI.this.accordion.setSelectedTab(subMenu);
                        if (subMenu.getComponent(i) != null) {
                            subMenu.getComponent(i).addStyleName("selected");
                        }
                        return true;
                    }
                    i++;
                }
                return false;
            }
        });
    }
}

14 Source : EmailLayout.java
with Apache License 2.0
from opensecuritycontroller

public clreplaced EmailLayout extends FormLayout {

    private static final long serialVersionUID = 1L;

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

    public Table emailTable = null;

    private VerticalLayout container = null;

    private Button edit = null;

    private GetEmailSettingsServiceApi getEmailSettingsService;

    private SetEmailSettingsServiceApi setEmailSettingsService;

    public EmailLayout(GetEmailSettingsServiceApi getEmailSettingsService, SetEmailSettingsServiceApi setEmailSettingsService) {
        super();
        this.getEmailSettingsService = getEmailSettingsService;
        this.setEmailSettingsService = setEmailSettingsService;
        try {
            this.emailTable = createTable();
            // creating layout to hold edit button
            HorizontalLayout optionLayout = new HorizontalLayout();
            optionLayout.addComponent(createEditButton());
            // populating Email Settings in the Table
            populateEmailtable();
            // adding all components to Container
            this.container = new VerticalLayout();
            this.container.addComponent(optionLayout);
            this.container.addComponent(this.emailTable);
            // adding container to the root Layout
            addComponent(this.container);
        } catch (Exception ex) {
            log.error("Failed to get email settings", ex);
        }
    }

    @SuppressWarnings("serial")
    private Button createEditButton() {
        // creating edit button
        this.edit = new Button("Edit");
        this.edit.setEnabled(true);
        this.edit.addStyleName(StyleConstants.BUTTON_TOOLBAR);
        this.edit.addStyleName(StyleConstants.EDIT_BUTTON);
        this.edit.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                try {
                    editClicked();
                } catch (Exception e) {
                    ViewUtil.showError("Error editing email settings", e);
                }
            }
        });
        return this.edit;
    }

    private void editClicked() throws Exception {
        try {
            ViewUtil.addWindow(new SetEmailSettingsWindow(this, this.getEmailSettingsService, this.setEmailSettingsService));
        } catch (Exception ex) {
            log.error("Error: " + ex);
        }
    }

    private Table createTable() {
        Table table = new Table();
        table.setSizeFull();
        table.setPageLength(0);
        table.setSelectable(false);
        table.setColumnCollapsingAllowed(true);
        table.setColumnReorderingAllowed(true);
        table.setImmediate(true);
        table.setNullSelectionAllowed(false);
        table.setColumnHeaderMode(Table.ColumnHeaderMode.HIDDEN);
        table.addContainerProperty("Name", String.clreplaced, null);
        table.addContainerProperty("Value", String.clreplaced, null);
        // initializing email table with empty values
        table.addItem(new Object[] { "Outgoing Mail Server (SMTP): ", "" }, new Integer(1));
        table.addItem(new Object[] { "Port: ", "" }, new Integer(2));
        table.addItem(new Object[] { "Email Id: ", "" }, new Integer(3));
        return table;
    }

    @SuppressWarnings("unchecked")
    public void populateEmailtable() {
        try {
            BaseDtoResponse<EmailSettingsDto> emailSettingsResponse = this.getEmailSettingsService.dispatch(new Request() {
            });
            if (emailSettingsResponse.getDto() != null) {
                this.emailTable.gereplacedem(1).gereplacedemProperty("Value").setValue(emailSettingsResponse.getDto().getMailServer());
                this.emailTable.gereplacedem(2).gereplacedemProperty("Value").setValue(emailSettingsResponse.getDto().getPort());
                this.emailTable.gereplacedem(3).gereplacedemProperty("Value").setValue(emailSettingsResponse.getDto().getEmailId());
            }
        } catch (Exception ex) {
            log.error("Failed to get email settings", ex);
        }
    }
}

14 Source : CRUDBaseView.java
with Apache License 2.0
from opensecuritycontroller

/**
 * @param
 *            <P>
 *            Parent DTO clreplaced
 * @param <C>
 *            Child DTO clreplaced
 */
public abstract clreplaced CRUDBaseView<P extends BaseDto, C extends BaseDto> extends VerticalLayout implements View {

    public static final long NULL_SELECTION_ITEM_ID = -1L;

    private static final long serialVersionUID = 1L;

    private long parenreplacedemId;

    private long childItemId;

    protected FilterTable parentTable;

    protected FilterTable childTable;

    protected VerticalLayout parentContainerLayout;

    public VerticalLayout childContainerLayout;

    protected HorizontalLayout parentToolbar;

    protected HorizontalLayout childToolbar;

    protected BeanContainer<Long, P> parentContainer;

    protected BeanContainer<Long, C> childContainer;

    protected List<P> itemList;

    public VerticalSplitPanel viewSplitter;

    protected Map<String, CRUDBaseSubView<?, ?>> parentSubViewMap;

    public Map<String, CRUDBaseSubView<?, ?>> childSubViewMap;

    private PageInformationComponent infoText;

    @SuppressWarnings("serial")
    private final ClickListener buttonClickListener = new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                buttonClicked(event);
            } catch (Exception e) {
                ViewUtil.showError("Error invoking action in view", e);
            }
        }
    };

    public BeanItem<P> getParenreplacedem() {
        return this.parentContainer.gereplacedem(getParenreplacedemId());
    }

    public BeanItem<C> getChildItem() {
        return this.childContainer.gereplacedem(getChildItemId());
    }

    public void createView(String parentreplacedle, List<ToolbarButtons> parentCRUDButtons) {
        createView(parentreplacedle, parentCRUDButtons, false, null, null);
    }

    public void createView(String parentreplacedle, List<ToolbarButtons> parentCRUDButtons, boolean multiSelect) {
        createView(parentreplacedle, parentCRUDButtons, multiSelect, null, null);
    }

    public void createView(String parentreplacedle, List<ToolbarButtons> parentCRUDButtons, String childreplacedle, List<ToolbarButtons> childCRUDButtons) {
        createView(parentreplacedle, parentCRUDButtons, false, childreplacedle, childCRUDButtons);
    }

    public void createView(String parentreplacedle, List<ToolbarButtons> parentCRUDButtons, boolean parentMultiSelect, String childreplacedle, List<ToolbarButtons> childCRUDButtons) {
        createView(parentreplacedle, parentCRUDButtons, parentMultiSelect, childreplacedle, childCRUDButtons, null, null);
    }

    /**
     * returns an empty View layout containing CRUD ToolBar, CSS layout, Table
     * with columnList and replacedle of the view
     *
     * @param parentreplacedle
     *            replacedle of the parent panel
     * @param parentCRUDButtons
     *            Array Toolbar buttons to diaplay parent panel
     * @param parentMultiSelect
     *            multi select parent table
     * @param childreplacedle
     *            replacedle of child panel
     * @param childCRUDButtons
     *            Array of toolbar buttons to display in child panel
     * @param parentSubViewList
     *            Map of CRUDBaseSubViews with their respective Button captions for Parent Table
     * @param childSubViewList
     *            Map of CRUDBaseSubViews with their respective Button captions for Child Table
     */
    public void createView(String parentreplacedle, List<ToolbarButtons> parentCRUDButtons, boolean parentMultiSelect, String childreplacedle, List<ToolbarButtons> childCRUDButtons, Map<String, CRUDBaseSubView<?, ?>> parentSubViewList, Map<String, CRUDBaseSubView<?, ?>> childSubViewMap) {
        boolean addChildTable = childreplacedle != null;
        setSizeFull();
        this.parentSubViewMap = parentSubViewList;
        this.childSubViewMap = childSubViewMap;
        // parent container with header
        this.parentContainerLayout = new VerticalLayout();
        this.parentContainerLayout.addStyleName(StyleConstants.BASE_CONTAINER);
        this.parentContainerLayout.setSizeFull();
        // parent panel with table and CRUD buttons
        final VerticalLayout parentPanel = new VerticalLayout();
        parentPanel.addStyleName("panel");
        parentPanel.setSizeFull();
        this.parentContainerLayout.addComponent(createHeader(parentreplacedle, false));
        this.parentContainerLayout.addComponent(parentPanel);
        this.infoText = new PageInformationComponent();
        this.infoText.addStyleName(StyleConstants.PAGE_INFO_COMPONENT);
        parentPanel.addComponent(this.infoText);
        if (parentCRUDButtons != null) {
            parentPanel.addComponent(createParentToolbar(parentCRUDButtons));
        }
        parentPanel.addComponent(createParentTable(parentMultiSelect));
        // expand parentTable with parentPanel
        parentPanel.setExpandRatio(this.parentTable, 1L);
        // expand parentPanel with parentContainer
        this.parentContainerLayout.setExpandRatio(parentPanel, 1L);
        if (addChildTable) {
            // child container with header
            this.childContainerLayout = new VerticalLayout();
            this.childContainerLayout.addStyleName(StyleConstants.BASE_CONTAINER);
            this.childContainerLayout.setSizeFull();
            // child panel with table and CRUD buttons
            final VerticalLayout childPanel = new VerticalLayout();
            childPanel.addStyleName("panel");
            childPanel.setSizeFull();
            this.childContainerLayout.addComponent(createHeader(childreplacedle, true));
            this.childContainerLayout.addComponent(childPanel);
            if (childCRUDButtons != null) {
                childPanel.addComponent(createChildToolBar(childCRUDButtons));
            }
            // adding table to panel layout
            childPanel.addComponent(createChildTable());
            // expand childTable with childPanel
            childPanel.setExpandRatio(this.childTable, 1L);
            // expand childPanel with childContainer
            this.childContainerLayout.setExpandRatio(childPanel, 1L);
            this.viewSplitter = new VerticalSplitPanel();
            this.viewSplitter.addStyleName(ValoTheme.SPLITPANEL_LARGE);
            this.viewSplitter.addComponent(this.parentContainerLayout);
            this.viewSplitter.addComponent(this.childContainerLayout);
            this.viewSplitter.setImmediate(true);
            this.viewSplitter.setMaxSplitPosition(75, Unit.PERCENTAGE);
            this.viewSplitter.setMinSplitPosition(25, Unit.PERCENTAGE);
            // adding split panel to the main view
            addComponent(this.viewSplitter);
        } else {
            addComponent(this.parentContainerLayout);
        }
    }

    /**
     * @see PageInformationComponent#setInfoText(String)
     */
    public void setInfoText(String replacedle, String content) {
        this.infoText.setInfoText(replacedle, content);
    }

    // returns Table containing columns from the columnList and entries provided
    // by populateTable method.
    @SuppressWarnings({ "serial", "unchecked" })
    private FilterTable createParentTable(final boolean multiSelect) {
        this.parentTable = new FilterTable();
        this.parentTable.setStyleName(ValoTheme.TABLE_COMPACT);
        this.parentTable.setSizeFull();
        this.parentTable.setSelectable(true);
        this.parentTable.setColumnCollapsingAllowed(true);
        this.parentTable.setColumnReorderingAllowed(true);
        this.parentTable.setImmediate(true);
        this.parentTable.setNullSelectionAllowed(false);
        if (!multiSelect) {
            this.parentTable.setNullSelectionItemId(NULL_SELECTION_ITEM_ID);
        }
        this.parentTable.setFilterBarVisible(true);
        this.parentTable.setMultiSelect(multiSelect);
        this.parentTable.setFilterGenerator(ViewUtil.getFilterGenerator());
        initParentTable();
        this.parentContainer.sereplacedemSorter(ViewUtil.getCaseInsensitiveItemSorter());
        // populate table with view specific values
        populateParentTable();
        // Setting parenreplacedemID to the first value row in the parent table
        // by default (if exist).
        selectFirstParenreplacedemIfExists(multiSelect);
        // Handle Selection when filtering changes the items
        this.parentTable.addItemSetChangeListener(new ItemSetChangeListener() {

            @Override
            public void containerItemSetChange(ItemSetChangeEvent event) {
                // If the table is empty, reset the selection so the child table updates itself
                if (CRUDBaseView.this.parentTable.gereplacedemIds().size() == 0) {
                    CRUDBaseView.this.parentTable.setValue(null);
                } else if (CRUDBaseView.this.parentTable.getValue() == null || CRUDBaseView.this.parentTable.getValue() instanceof Set && ((Set<?>) CRUDBaseView.this.parentTable.getValue()).isEmpty()) {
                    // If the table does not have a selection but has items, select the first item
                    selectFirstParenreplacedemIfExists(multiSelect);
                }
            }
        });
        // Handle selection changes
        this.parentTable.addValueChangeListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                Object value = event.getProperty().getValue();
                if (value != null) {
                    if (multiSelect) {
                        parentTableClicked((Set<Long>) value);
                    } else {
                        parentTableClicked((Long) value);
                    }
                } else {
                    parentTableClicked(NULL_SELECTION_ITEM_ID);
                }
                if (CRUDBaseView.this.childContainerLayout != null && !CRUDBaseView.this.viewSplitter.getSecondComponent().equals(CRUDBaseView.this.childContainerLayout)) {
                    CRUDBaseView.this.viewSplitter.removeComponent(CRUDBaseView.this.viewSplitter.getSecondComponent());
                    CRUDBaseView.this.viewSplitter.addComponent(CRUDBaseView.this.childContainerLayout);
                }
            }
        });
        return this.parentTable;
    }

    // returns Table containing columns from the columnList and entries provided
    // by populateTable method.
    @SuppressWarnings("serial")
    private FilterTable createChildTable() {
        this.childTable = new FilterTable();
        this.childTable.setStyleName(ValoTheme.TABLE_COMPACT);
        this.childTable.setSizeFull();
        this.childTable.setSelectable(true);
        this.childTable.setColumnCollapsingAllowed(true);
        this.childTable.setColumnReorderingAllowed(true);
        this.childTable.setFilterBarVisible(true);
        this.childTable.setImmediate(true);
        this.childTable.setNullSelectionAllowed(false);
        this.childTable.setNullSelectionItemId(NULL_SELECTION_ITEM_ID);
        this.childTable.setFilterGenerator(ViewUtil.getFilterGenerator());
        initChildTable();
        this.childContainer.sereplacedemSorter(ViewUtil.getCaseInsensitiveItemSorter());
        if (getParenreplacedem() != null) {
            populateChildTable(getParenreplacedem());
        }
        // Setting childItemID to the first value row in the child table
        // by default (if exist).
        if (this.childTable.firsreplacedemId() != null) {
            childTableClicked((Long) this.childTable.firsreplacedemId());
            this.childTable.setValue(this.childTable.firsreplacedemId());
        }
        // Handle Selection when filtering changes the items
        this.childTable.addItemSetChangeListener(new ItemSetChangeListener() {

            @Override
            public void containerItemSetChange(ItemSetChangeEvent event) {
                // If the table is empty, reset the selection so the table updates itself
                if (CRUDBaseView.this.childTable.gereplacedemIds().size() == 0) {
                    CRUDBaseView.this.childTable.setValue(null);
                } else if (CRUDBaseView.this.childTable.getValue() == null) {
                    // If the table does not have a selection but has items, select the first item
                    childTableClicked((Long) CRUDBaseView.this.childTable.firsreplacedemId());
                }
            }
        });
        // Handle selection changes
        this.childTable.addValueChangeListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                Object value = event.getProperty().getValue();
                if (value != null) {
                    childTableClicked((Long) value);
                } else {
                    childTableClicked(NULL_SELECTION_ITEM_ID);
                }
            }
        });
        return this.childTable;
    }

    // returns Header layout with view replacedle
    @SuppressWarnings("serial")
    private HorizontalLayout createHeader(String replacedle, final boolean isChildTable) {
        HorizontalLayout header = null;
        if (isChildTable) {
            header = ViewUtil.createSubHeader(replacedle, getChildHelpGuid());
        } else {
            header = ViewUtil.createSubHeader(replacedle, getParentHelpGuid());
        }
        Button refresh = new Button();
        refresh.setStyleName(Reindeer.BUTTON_LINK);
        refresh.setDescription("Refresh");
        refresh.setIcon(new ThemeResource("img/Refresh.png"));
        refresh.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                if (isChildTable) {
                    populateChildTable(getParenreplacedem());
                } else {
                    populateParentTable();
                }
            }
        });
        header.addComponent(refresh);
        return header;
    }

    // Returns ToolBar UI
    private HorizontalLayout createParentToolbar(List<ToolbarButtons> parentCRUDButtons) {
        this.parentToolbar = new HorizontalLayout();
        this.parentToolbar.addStyleName("buttonToolbar");
        this.parentToolbar.setWidth("100%");
        Label filler = new Label();
        for (ToolbarButtons button : parentCRUDButtons) {
            if (button == null) {
                continue;
            }
            if (button.getAlignment() == HorizontalAlignment.RIGHT && this.parentToolbar.getComponentIndex(filler) == -1) {
                this.parentToolbar.addComponent(filler);
                this.parentToolbar.setExpandRatio(filler, 1.0f);
            }
            Button buttonComponent = ViewUtil.buildToolbarButton(this.parentToolbar, button, this.buttonClickListener);
            if (button == ToolbarButtons.ADD || button == ToolbarButtons.SHOW_PENDING_ACKNOWLEDGE_ALERTS || button == ToolbarButtons.SHOW_ALL_ALERTS) {
                buttonComponent.setEnabled(true);
            }
        // TODO: Future. Later use the following code to support Parent Table drill down
        }
        if (this.parentToolbar.getComponentIndex(filler) == -1) {
            this.parentToolbar.addComponent(filler);
            this.parentToolbar.setExpandRatio(filler, 1.0f);
        }
        return this.parentToolbar;
    }

    private HorizontalLayout createChildToolBar(List<ToolbarButtons> buttonList) {
        this.childToolbar = new HorizontalLayout();
        this.childToolbar.addStyleName("buttonToolbar");
        for (ToolbarButtons button : buttonList) {
            if (button == null) {
                continue;
            }
            ViewUtil.buildToolbarButton(this.childToolbar, button, this.buttonClickListener);
        }
        return this.childToolbar;
    }

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
        MainUI main = (MainUI) UI.getCurrent();
        main.setCurrentView(this);
    }

    private void setParenreplacedem(BeanItem<P> parenreplacedem) {
    }

    private void setChildItem(Item childItem) {
    }

    public long getParenreplacedemId() {
        return this.parenreplacedemId;
    }

    public long getChildItemId() {
        return this.childItemId;
    }

    public BeanContainer<Long, P> getParentContainer() {
        return this.parentContainer;
    }

    public BeanContainer<Long, C> getChildContainer() {
        return this.childContainer;
    }

    @SuppressWarnings("unchecked")
    public /*
     * If you override this method make sure you check for NULL_SELECTION_ITEM_ID in the child.
     */
    void parentTableClicked(long parenreplacedemId) {
        this.parenreplacedemId = parenreplacedemId;
        if (parenreplacedemId != NULL_SELECTION_ITEM_ID) {
            ViewUtil.setButtonsEnabled(true, this.parentToolbar);
            setParenreplacedem((BeanItem<P>) this.parentTable.gereplacedem(parenreplacedemId));
            this.parentTable.setValue(parenreplacedemId);
            ViewUtil.enableToolBarButtons(true, this.childToolbar, Arrays.asList(ToolbarButtons.ADD_CHILD.getId()));
        } else {
            ViewUtil.setButtonsEnabled(false, this.parentToolbar);
            setParenreplacedem(null);
        }
        if (this.childTable != null) {
            // populating child table according to the item selected in the parent table
            populateChildTable(getParenreplacedem());
            if (this.childTable.firsreplacedemId() != null) {
                childTableClicked((Long) this.childTable.firsreplacedemId());
                this.childTable.setValue(this.childTable.firsreplacedemId());
            } else {
                ViewUtil.setButtonsEnabled(false, this.childToolbar, Arrays.asList(ToolbarButtons.ADD_CHILD.getId()));
            }
        }
    }

    private void parentTableClicked(Set<Long> selectedItems) {
        ViewUtil.setButtonsEnabled(true, this.parentToolbar);
        ViewUtil.enableToolBarButtons(true, this.childToolbar, Arrays.asList(ToolbarButtons.ADD_CHILD.getId()));
        this.itemList = new ArrayList<P>();
        Object[] itemIds = selectedItems.toArray();
        for (Object itemId : itemIds) {
            this.itemList.add(this.parentContainer.gereplacedem(itemId).getBean());
        }
        if (this.itemList.size() == 1) {
            this.parenreplacedemId = (long) itemIds[0];
            setParenreplacedem(this.parentContainer.gereplacedem(this.parenreplacedemId));
            this.parentTable.setValue(this.parenreplacedemId);
        }
    }

    protected void childTableClicked(long childItemId) {
        if (childItemId != NULL_SELECTION_ITEM_ID) {
            ViewUtil.setButtonsEnabled(true, this.childToolbar);
            this.childItemId = childItemId;
            setChildItem(this.childTable.gereplacedem(childItemId));
            this.childTable.setValue(childItemId);
        } else {
            ViewUtil.setButtonsEnabled(false, this.childToolbar, Arrays.asList(ToolbarButtons.ADD_CHILD.getId()));
        }
    }

    public void syncTables(BroadcastMessage msg, boolean child, GetDtoFromEnreplacedyServiceFactoryApi getDtoFactory) throws Exception {
        ParameterizedType parameterizedType = (ParameterizedType) getClreplaced().getGenericSuperclreplaced();
        if (child) {
            @SuppressWarnings("unchecked")
            Clreplaced<C> childClreplaced = (Clreplaced<C>) parameterizedType.getActualTypeArguments()[1];
            syncChildTable(msg, getDtoFactory.getService(childClreplaced));
        } else {
            @SuppressWarnings("unchecked")
            Clreplaced<P> parentClreplaced = (Clreplaced<P>) parameterizedType.getActualTypeArguments()[0];
            syncParentTable(msg, getDtoFactory.getService(parentClreplaced));
        }
    }

    @SuppressWarnings("unchecked")
    protected void syncParentTable(BroadcastMessage msg, GetDtoFromEnreplacedyServiceApi<P> getDtoService) throws Exception {
        if (msg.getEventType().equals(EventType.DELETED)) {
            // delete item from parent container
            getParentContainer().removeItem(msg.getEnreplacedyId());
            // if no parent element exists we should remove all the child
            // elements
            if (this.parentContainer.gereplacedemIds().size() == 0) {
                ViewUtil.setButtonsEnabled(false, this.parentToolbar, Arrays.asList(ToolbarButtons.ADD.getId(), ToolbarButtons.SHOW_ALL_ALERTS.getId()));
                ViewUtil.enableToolBarButtons(true, this.parentToolbar, Arrays.asList(ToolbarButtons.ADD.getId(), ToolbarButtons.SHOW_ALL_ALERTS.getId()));
                if (this.childContainer != null) {
                    this.childContainer.removeAllItems();
                    ViewUtil.setButtonsEnabled(false, this.childToolbar);
                }
            } else {
                selectFirstParenreplacedemIfExists(this.parentTable.isMultiSelect());
            }
        } else {
            P dto = null;
            if (msg.getDto() == null) {
                GetDtoFromEnreplacedyRequest req = new GetDtoFromEnreplacedyRequest();
                req.setEnreplacedyId(msg.getEnreplacedyId());
                req.setEnreplacedyName(msg.getReceiver());
                BaseDtoResponse<P> res = getDtoService.dispatch(req);
                dto = res.getDto();
            } else {
                dto = (P) msg.getDto();
            }
            if (msg.getEventType().equals(EventType.UPDATED) && getParentContainer().gereplacedem(msg.getEnreplacedyId()) != null) {
                updateParentContainer(dto);
            } else {
                // add new item to the container
                getParentContainer().addItemAt(0, msg.getEnreplacedyId(), dto);
            }
        }
    }

    @SuppressWarnings("unchecked")
    private void syncChildTable(BroadcastMessage msg, GetDtoFromEnreplacedyServiceApi<C> getDtoService) throws Exception {
        if (msg.getEventType().equals(EventType.DELETED)) {
            // delete item from child container
            getChildContainer().removeItem(msg.getEnreplacedyId());
            if (this.childTable.firsreplacedemId() != null) {
                // select first element from the table
                childTableClicked((Long) this.childTable.firsreplacedemId());
            } else {
                ViewUtil.setButtonsEnabled(false, this.childToolbar, Arrays.asList(ToolbarButtons.ADD_CHILD.getId()));
            }
        } else {
            C dto = null;
            if (msg.getDto() == null) {
                GetDtoFromEnreplacedyRequest req = new GetDtoFromEnreplacedyRequest();
                req.setEnreplacedyId(msg.getEnreplacedyId());
                req.setEnreplacedyName(msg.getReceiver());
                BaseDtoResponse<C> res = getDtoService.dispatch(req);
                dto = res.getDto();
            } else {
                dto = (C) msg.getDto();
            }
            if (dto != null && dto.getParentId() != null && dto.getParentId().equals(getParenreplacedemId())) {
                if (msg.getEventType().equals(EventType.UPDATED) && getChildContainer().gereplacedem(msg.getEnreplacedyId()) != null) {
                    updateChildContainer(dto);
                } else {
                    getChildContainer().addItem(msg.getEnreplacedyId(), dto);
                }
            }
        }
    }

    public void delegateBroadcastMessagetoSubView(BroadcastMessage msg, boolean child, GetDtoFromEnreplacedyServiceFactoryApi getDtoFromEnreplacedyServiceFactory) throws Exception {
        if (!child) {
            for (Entry<String, CRUDBaseSubView<?, ?>> parentSubView : this.parentSubViewMap.entrySet()) {
                if (parentSubView.getValue().getTableContainer().getBeanType().getSimpleName().equals(msg.getReceiver() + "Dto")) {
                    parentSubView.getValue().syncTable(msg, getDtoFromEnreplacedyServiceFactory);
                }
            }
        } else {
            for (Entry<String, CRUDBaseSubView<?, ?>> childSubView : this.childSubViewMap.entrySet()) {
                if (childSubView.getValue() != null && childSubView.getValue().getTableContainer().getBeanType().getSimpleName().equals(msg.getReceiver() + "Dto")) {
                    childSubView.getValue().syncTable(msg, getDtoFromEnreplacedyServiceFactory);
                }
            }
        }
    }

    protected void updateParentContainer(P dto) {
        ViewUtil.updateTableContainer(getParentContainer(), dto, this.parentTable);
    }

    private void updateChildContainer(C dto) {
        ViewUtil.updateTableContainer(getChildContainer(), dto, this.childTable);
    }

    private void selectFirstParenreplacedemIfExists(boolean multiSelect) {
        if (this.parentTable.firsreplacedemId() != null) {
            if (multiSelect) {
                HashSet<Long> temp = new HashSet<Long>();
                temp.add((Long) this.parentTable.firsreplacedemId());
                parentTableClicked(temp);
                this.parentTable.setValue(temp);
            } else {
                parentTableClicked((Long) this.parentTable.firsreplacedemId());
                this.parentTable.setValue(this.parentTable.firsreplacedemId());
            }
        }
    }

    /**
     * Gets the help id for the parent view
     *
     * @return
     */
    protected String getParentHelpGuid() {
        return null;
    }

    protected String getChildHelpGuid() {
        return null;
    }

    public boolean isDtoChangeRelevantToParentView(String dto) {
        return this.parentTable != null && getParentContainer() != null && getParentContainer().getBeanType() != null && getParentContainer().getBeanType().getSimpleName().equals(dto);
    }

    public boolean isDtoChangeRelevantToChildView(String dto) {
        return this.childTable != null && getChildContainer() != null && getChildContainer().getBeanType() != null && getChildContainer().getBeanType().getSimpleName().equals(dto);
    }

    public boolean isDtoRelevantToParentSubView(String dto) {
        if (this.parentSubViewMap != null) {
            for (Entry<String, CRUDBaseSubView<?, ?>> parentSubViewEntry : this.parentSubViewMap.entrySet()) {
                if (parentSubViewEntry.getValue() != null && parentSubViewEntry.getValue().table != null && parentSubViewEntry.getValue().getTableContainer() != null && parentSubViewEntry.getValue().getTableContainer().getBeanType() != null && parentSubViewEntry.getValue().getTableContainer().getBeanType().getSimpleName().equals(dto)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean isDtoRelevantToChildSubView(String dto) {
        if (this.childSubViewMap != null) {
            for (Entry<String, CRUDBaseSubView<?, ?>> childSubViewEntry : this.childSubViewMap.entrySet()) {
                if (childSubViewEntry.getValue() != null && childSubViewEntry.getValue().table != null && childSubViewEntry.getValue().getTableContainer() != null && childSubViewEntry.getValue().getTableContainer().getBeanType() != null && childSubViewEntry.getValue().getTableContainer().getBeanType().getSimpleName().equals(dto)) {
                    return true;
                }
            }
        }
        return false;
    }

    public String getKeyforChildSubView(int index) {
        int i = 0;
        for (String key : this.childSubViewMap.keySet()) {
            if (i == index) {
                return key;
            }
        }
        return null;
    }

    public abstract void buttonClicked(ClickEvent event) throws Exception;

    public abstract void initParentTable();

    public abstract void populateParentTable();

    public abstract void initChildTable();

    public abstract void populateChildTable(BeanItem<P> parenreplacedem);
}

13 Source : PluginView.java
with Apache License 2.0
from opensecuritycontroller

private VerticalLayout createComponent(String caption, String replacedle, FormLayout content, String guid) {
    VerticalLayout tabSheet = new VerticalLayout();
    Panel panel = new Panel();
    // creating subHeader inside panel
    panel.setContent(content);
    panel.setSizeFull();
    tabSheet.addComponent(ViewUtil.createSubHeader(replacedle, guid));
    tabSheet.addComponent(panel);
    return tabSheet;
}

13 Source : PageInformationComponent.java
with Apache License 2.0
from opensecuritycontroller

private Component buildMainLayout() {
    // top-level component properties
    setWidth("100.0%");
    setHeight("-1px");
    setStyleName(StyleConstants.PAGE_INFO_COMPONENT_COMMON);
    // infoLabel
    this.replacedleLabel = new Label();
    initializeLabel(this.replacedleLabel);
    final Button collapseButton = new Button();
    collapseButton.setStyleName(Reindeer.BUTTON_LINK);
    collapseButton.setIcon(new ThemeResource(StyleConstants.EXPAND_IMAGE));
    collapseButton.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            PageInformationComponent.this.contentLabel.setVisible(!PageInformationComponent.this.contentLabel.isVisible());
            if (PageInformationComponent.this.contentLabel.isVisible()) {
                collapseButton.setIcon(new ThemeResource(StyleConstants.COLLAPSE_IMAGE));
            } else {
                collapseButton.setIcon(new ThemeResource(StyleConstants.EXPAND_IMAGE));
            }
        }
    });
    HorizontalLayout replacedleLayout = new HorizontalLayout();
    initializeLayout(replacedleLayout);
    replacedleLayout.setStyleName(StyleConstants.PAGE_INFO_replacedLE_LAYOUT);
    replacedleLayout.addComponent(this.replacedleLabel);
    replacedleLayout.addComponent(collapseButton);
    replacedleLayout.setExpandRatio(this.replacedleLabel, 1.0f);
    this.contentLabel = new Label();
    initializeLabel(this.contentLabel);
    this.contentLabel.setVisible(false);
    this.contentLabel.setStyleName(StyleConstants.PAGE_INFO_CONTENT_LABEL);
    this.contentLabel.setContentMode(ContentMode.HTML);
    VerticalLayout mainLayout = new VerticalLayout();
    initializeLayout(mainLayout);
    mainLayout.addComponent(replacedleLayout);
    mainLayout.addComponent(this.contentLabel);
    return mainLayout;
}

13 Source : JobsArchiverPanel.java
with Apache License 2.0
from opensecuritycontroller

public clreplaced JobsArchiverPanel extends CustomComponent {

    private static final long serialVersionUID = 1L;

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

    private VerticalLayout container = null;

    private Label triggerLabel = new Label("Triggering:");

    private String lastTriggerLabelText = "Last Triggered Timestamp: ";

    private Label lastTriggerTimestampLabel = null;

    private OptionGroup freqOpt = null;

    private CheckBox autoSchedChkBox = null;

    private Label thresholdLabel = new Label("Archive Jobs/Alerts older than the last: ");

    private OptionGroup thresOpt = null;

    private IntStepper archiveThreshold = null;

    private Panel panel = new Panel();

    private Button updateButton = null;

    private Button onDemandButton = null;

    private final String TEXT_FREQ_OPT_WEEKLY = "Weekly";

    private final String ID_FREQ_OPT_WEEKLY = "WEEKLY";

    private final String TEXT_FREQ_OPT_MONTHLY = "Monthly";

    private final String ID_FREQ_OPT_MONTHLY = "MONTHLY";

    private final String TEXT_THRES_OPT_MONTHS = "Months";

    private final String ID_THRES_OPT_MONTHS = "MONTHS";

    private final String TEXT_THRES_OPT_YEARS = "Years";

    private final String ID_THRES_OPT_YEARS = "YEARS";

    private final String UPDATE_SCHED_BUTTON_LABEL = "Update Schedule";

    private final String ON_DEMAND_BUTTON_LABEL = "On Demand";

    private String ARCHIVE_STYLE = "archive-options";

    private JobsArchiveDto dto;

    private final ArchiveLayout parentLayout;

    private final ArchiveServiceApi archiveService;

    private final GetJobsArchiveServiceApi getJobsArchiveService;

    private final UpdateJobsArchiveServiceApi updateJobsArchiveService;

    public JobsArchiverPanel(ArchiveLayout parentLayout, ArchiveServiceApi archiveService, GetJobsArchiveServiceApi getJobsArchiveService, UpdateJobsArchiveServiceApi updateJobsArchiveService) {
        super();
        this.parentLayout = parentLayout;
        this.archiveService = archiveService;
        this.getJobsArchiveService = getJobsArchiveService;
        this.updateJobsArchiveService = updateJobsArchiveService;
        try {
            this.dto = populateJobsArchiveDto().getDto();
            // create frequency layout component
            VerticalLayout freqLayout = new VerticalLayout();
            freqLayout.addComponent(createLastTriggerLabel());
            freqLayout.addComponent(createAutoSchedCheckBox());
            freqLayout.addComponent(createFrequencyOptionGroup());
            freqLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
            freqLayout.setSpacing(true);
            // create triggering panel component
            Panel triggerPanel = new Panel();
            triggerPanel.setWidth("50%");
            triggerPanel.setContent(freqLayout);
            // create threshold layout component
            HorizontalLayout thresLayout = new HorizontalLayout();
            thresLayout.addComponent(this.thresholdLabel);
            thresLayout.addComponent(createArchiveThreshold());
            thresLayout.addComponent(createThresholdOptionGroup());
            thresLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
            thresLayout.setSpacing(true);
            // add all components to container
            this.container = new VerticalLayout();
            this.container.addStyleName(StyleConstants.COMPONENT_SPACING);
            this.container.addComponent(this.triggerLabel);
            this.container.addComponent(triggerPanel);
            this.container.addComponent(thresLayout);
            // add buttons component to container
            HorizontalLayout buttonLayout = new HorizontalLayout();
            buttonLayout.addComponent(createOnDemandScheduleButton());
            buttonLayout.addComponent(createUpdateScheduleButton());
            buttonLayout.setSpacing(true);
            this.container.addComponent(buttonLayout);
            // add container to root panel
            this.container.setSpacing(true);
            this.panel.setWidth("100%");
            this.panel.setContent(this.container);
            setCompositionRoot(this.panel);
        } catch (Exception ex) {
            log.error("Failed to init archiver panel", ex);
        }
    }

    private BaseDtoResponse<JobsArchiveDto> populateJobsArchiveDto() throws Exception {
        BaseDtoResponse<JobsArchiveDto> res = this.getJobsArchiveService.dispatch(new Request() {
        });
        return res;
    }

    Integer convertToPositiveIntegerOrNull(String strVal) {
        Integer val = null;
        try {
            val = Integer.parseInt(strVal);
        } catch (Exception ex) {
            return null;
        }
        if (val < 0) {
            return null;
        }
        return val;
    }

    private Label createLastTriggerLabel() {
        String lastTriggerTimestamp = "None";
        this.lastTriggerTimestampLabel = new Label();
        if (this.dto != null && this.dto.getLastTriggerTimestamp() != null) {
            lastTriggerTimestamp = this.dto.getLastTriggerTimestamp().toString();
        }
        this.lastTriggerTimestampLabel.setCaption(this.lastTriggerLabelText + lastTriggerTimestamp);
        return this.lastTriggerTimestampLabel;
    }

    private CheckBox createAutoSchedCheckBox() {
        this.autoSchedChkBox = new CheckBox("Auto Schedule");
        this.autoSchedChkBox.setImmediate(true);
        if (this.dto == null) {
            this.autoSchedChkBox.setValue(false);
        } else {
            boolean isAuto = this.dto.getAutoSchedule();
            this.autoSchedChkBox.setValue(isAuto);
        }
        return this.autoSchedChkBox;
    }

    private OptionGroup createFrequencyOptionGroup() {
        this.freqOpt = new OptionGroup();
        this.freqOpt.addItem(this.ID_FREQ_OPT_WEEKLY);
        this.freqOpt.sereplacedemCaption(this.ID_FREQ_OPT_WEEKLY, this.TEXT_FREQ_OPT_WEEKLY);
        this.freqOpt.addItem(this.ID_FREQ_OPT_MONTHLY);
        this.freqOpt.sereplacedemCaption(this.ID_FREQ_OPT_MONTHLY, this.TEXT_FREQ_OPT_MONTHLY);
        this.freqOpt.addStyleName(this.ARCHIVE_STYLE);
        this.freqOpt.setImmediate(true);
        if (this.dto == null) {
            this.freqOpt.select(this.ID_FREQ_OPT_MONTHLY);
        } else {
            this.freqOpt.select(this.dto.getFrequency());
        }
        return this.freqOpt;
    }

    private IntStepper createArchiveThreshold() {
        this.archiveThreshold = new IntStepper();
        if (this.dto == null) {
            this.archiveThreshold.setValue(3);
        } else {
            this.archiveThreshold.setValue(this.dto.getThresholdValue());
        }
        this.archiveThreshold.setStepAmount(1);
        this.archiveThreshold.setMinValue(1);
        this.archiveThreshold.setRequiredError("Archive threshold cannot be empty");
        return this.archiveThreshold;
    }

    private OptionGroup createThresholdOptionGroup() {
        this.thresOpt = new OptionGroup();
        this.thresOpt.addItem(this.ID_THRES_OPT_MONTHS);
        this.thresOpt.sereplacedemCaption(this.ID_THRES_OPT_MONTHS, this.TEXT_THRES_OPT_MONTHS);
        this.thresOpt.addItem(this.ID_THRES_OPT_YEARS);
        this.thresOpt.sereplacedemCaption(this.ID_THRES_OPT_YEARS, this.TEXT_THRES_OPT_YEARS);
        this.thresOpt.addStyleName(this.ARCHIVE_STYLE);
        this.thresOpt.setImmediate(true);
        if (this.dto == null) {
            this.thresOpt.select(this.ID_THRES_OPT_MONTHS);
        } else {
            this.thresOpt.select(this.dto.getThresholdUnit());
        }
        return this.thresOpt;
    }

    @SuppressWarnings("serial")
    private Button createUpdateScheduleButton() {
        this.updateButton = new Button(this.UPDATE_SCHED_BUTTON_LABEL);
        this.updateButton.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                try {
                    BaseRequest<JobsArchiveDto> request = new BaseRequest<JobsArchiveDto>();
                    request.setDto(new JobsArchiveDto());
                    request.getDto().setId(JobsArchiverPanel.this.dto.getId());
                    request.getDto().setAutoSchedule(JobsArchiverPanel.this.autoSchedChkBox.getValue());
                    request.getDto().setFrequency(JobsArchiverPanel.this.freqOpt.getValue().toString());
                    request.getDto().setThresholdUnit(JobsArchiverPanel.this.thresOpt.getValue().toString());
                    request.getDto().setThresholdValue(JobsArchiverPanel.this.archiveThreshold.getValue());
                    JobsArchiverPanel.this.updateJobsArchiveService.dispatch(request);
                    JobsArchiverPanel.this.archiveService.maybeScheduleArchiveJob();
                    ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.MAINTENANCE_JOBSARCHIVE_SUBMIT_SUCCESSFUL), null, Notification.Type.TRAY_NOTIFICATION);
                } catch (Exception e) {
                    log.error("Fail to update archive schedule", e);
                    ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.MAINTENANCE_JOBSARCHIVE_SUBMIT_FAILED), Notification.Type.ERROR_MESSAGE);
                }
            }
        });
        return this.updateButton;
    }

    @SuppressWarnings("serial")
    private Button createOnDemandScheduleButton() {
        this.onDemandButton = new Button(this.ON_DEMAND_BUTTON_LABEL);
        this.onDemandButton.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                JobsArchiverPanel.this.onDemandButton.setEnabled(false);
                ViewUtil.iscNotification("On demand archiving started in the background", null, Notification.Type.TRAY_NOTIFICATION);
                Thread thread = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        BaseRequest<JobsArchiveDto> request = new BaseRequest<JobsArchiveDto>();
                        request.setDto(new JobsArchiveDto());
                        request.getDto().setFrequency(JobsArchiverPanel.this.freqOpt.getValue().toString());
                        request.getDto().setThresholdUnit(JobsArchiverPanel.this.thresOpt.getValue().toString());
                        request.getDto().setThresholdValue(JobsArchiverPanel.this.archiveThreshold.getValue());
                        try {
                            JobsArchiverPanel.this.archiveService.dispatch(request);
                            ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.MAINTENANCE_JOBSARCHIVE_ONDEMAND_SUCCESSFUL), null, Notification.Type.TRAY_NOTIFICATION);
                            JobsArchiverPanel.this.parentLayout.buildArchivesTable();
                            JobsArchiverPanel.this.onDemandButton.setEnabled(true);
                        } catch (Exception e) {
                            ViewUtil.showError("Error starting on demand archiving", e);
                        }
                    }
                });
                thread.start();
            }
        });
        return this.onDemandButton;
    }
}

9 Source : BindSecurityGroupWindow.java
with Apache License 2.0
from opensecuritycontroller

@SuppressWarnings("serial")
private Component getServicePanel() throws ActionNotSupportedException {
    try {
        this.serviceTable = new Table();
        this.serviceTable.setCaption("Services:");
        this.serviceTable.setPageLength(5);
        this.serviceTable.setImmediate(true);
        this.serviceTable.setSelectable(true);
        this.serviceTable.setMultiSelect(false);
        this.serviceTable.setNullSelectionAllowed(false);
        this.serviceTable.setNullSelectionItemId(CRUDBaseView.NULL_SELECTION_ITEM_ID);
        this.serviceTable.addGeneratedColumn(PROPERTY_ID_ENABLED, new CheckBoxGenerator());
        populateServiceTable();
        VerticalLayout selectorButtonLayout = new VerticalLayout();
        selectorButtonLayout.addStyleName(StyleConstants.SELECTOR_BUTTON_LAYOUT);
        Button moveUpButton = new Button(VmidcMessages.getString(VmidcMessages_.ORDER_MOVE_UP_TEXT));
        moveUpButton.setHtmlContentAllowed(true);
        moveUpButton.setDescription(VmidcMessages.getString(VmidcMessages_.ORDER_MOVE_UP_DESC));
        moveUpButton.addStyleName(StyleConstants.SELECTOR_BUTTON);
        moveUpButton.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                moveItem(true);
            }
        });
        Button moveDownButton = new Button(VmidcMessages.getString(VmidcMessages_.ORDER_MOVE_DOWN_TEXT));
        moveDownButton.setHtmlContentAllowed(true);
        moveDownButton.setDescription(VmidcMessages.getString(VmidcMessages_.ORDER_MOVE_DOWN_DESC));
        moveDownButton.addStyleName(StyleConstants.SELECTOR_BUTTON);
        moveDownButton.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                moveItem(false);
            }
        });
        selectorButtonLayout.addComponent(moveUpButton);
        selectorButtonLayout.addComponent(moveDownButton);
        HorizontalLayout selectorLayout = new HorizontalLayout();
        selectorLayout.addComponent(selectorButtonLayout);
        selectorLayout.addComponent(this.serviceTable);
        return selectorLayout;
    } catch (ActionNotSupportedException actionNotSupportedException) {
        throw actionNotSupportedException;
    } catch (Exception e) {
        ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
        log.error("Error while creating Services panel", e);
    }
    return null;
}

5 Source : JobView.java
with Apache License 2.0
from opensecuritycontroller

@SuppressWarnings("serial")
private void buildGraph() {
    try {
        this.embeddedImage = new Embedded();
        this.embeddedImage.setSizeFull();
        refreshGraph();
        Button refresh = new Button("Refresh");
        refresh.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                try {
                    refreshGraph();
                } catch (Exception e) {
                    ViewUtil.showError("Error while building task graph DOT file.", e);
                }
            }
        });
        final HorizontalLayout toolbarLayout = new HorizontalLayout();
        toolbarLayout.addComponent(refresh);
        toolbarLayout.setSizeFull();
        toolbarLayout.setMargin(true);
        final VerticalLayout imageLayout = new VerticalLayout();
        imageLayout.addComponent(this.embeddedImage);
        imageLayout.setComponentAlignment(this.embeddedImage, Alignment.MIDDLE_CENTER);
        imageLayout.setSizeUndefined();
        final VerticalLayout layout = new VerticalLayout();
        layout.addComponent(refresh);
        layout.setComponentAlignment(refresh, Alignment.TOP_LEFT);
        layout.addComponent(imageLayout);
        layout.setSizeUndefined();
        final Window window = new Window();
        window.setContent(layout);
        window.setModal(true);
        window.setHeight("80%");
        window.setWidth("80%");
        window.setClosable(true);
        window.setResizable(true);
        window.setCaption("Task Graph for Job " + getParenreplacedemId());
        window.center();
        window.setWindowMode(WindowMode.MAXIMIZED);
        window.addCloseShortcut(ShortcutAction.KeyCode.ESCAPE, null);
        ViewUtil.addWindow(window);
        window.focus();
    } catch (Exception e) {
        ViewUtil.showError("Error while building task graph DOT file.", e);
    }
}