com.vaadin.ui.Table

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

19 Examples 7

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

public clreplaced SslConfigurationLayout extends FormLayout implements TruststoreChangedListener {

    private static final long serialVersionUID = 1L;

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

    private final int CERT_MONTHLY_THRESHOLD = 3;

    private Table sslConfigTable;

    private VmidcWindow<OkCancelButtonModel> deleteWindow;

    private DeleteSslCertificateServiceApi deleteSslCertificateService;

    private ListSslCertificatesServiceApi listSslCertificateService;

    private ServiceRegistration<TruststoreChangedListener> registration;

    public SslConfigurationLayout(DeleteSslCertificateServiceApi deleteSslCertificate, ListSslCertificatesServiceApi listSslCertificateService, X509TrustManagerApi trustManager, BundleContext ctx) {
        super();
        this.deleteSslCertificateService = deleteSslCertificate;
        this.listSslCertificateService = listSslCertificateService;
        SslCertificateUploader certificateUploader = new SslCertificateUploader(trustManager);
        VerticalLayout sslUploadContainer = makeSslUploadContainer(certificateUploader, getString(CERTIFICATE_UPLOAD_replacedLE));
        InternalCertReplacementUploader internalCertReplacementUploader = new InternalCertReplacementUploader(trustManager);
        VerticalLayout sslReplaceInternalContainer = makeSslUploadContainer(internalCertReplacementUploader, getString(KEYPAIR_UPLOAD_replacedLE));
        VerticalLayout sslListContainer = new VerticalLayout();
        sslListContainer.addComponent(createHeaderForSslList());
        this.sslConfigTable = new Table();
        this.sslConfigTable.setSizeFull();
        this.sslConfigTable.setImmediate(true);
        this.sslConfigTable.addContainerProperty("Alias", String.clreplaced, null);
        this.sslConfigTable.addContainerProperty("SHA1 fingerprint", String.clreplaced, null);
        this.sslConfigTable.addContainerProperty("Issuer", String.clreplaced, null);
        this.sslConfigTable.addContainerProperty("Valid from", Date.clreplaced, null);
        this.sslConfigTable.addContainerProperty("Valid until", Date.clreplaced, null);
        this.sslConfigTable.addContainerProperty("Algorithm type", String.clreplaced, null);
        this.sslConfigTable.addContainerProperty("Delete", Button.clreplaced, null);
        this.sslConfigTable.setColumnWidth("Issuer", 200);
        buildSslConfigurationTable();
        Panel sslConfigTablePanel = new Panel();
        sslConfigTablePanel.setContent(this.sslConfigTable);
        sslListContainer.addComponent(sslConfigTablePanel);
        addComponent(sslReplaceInternalContainer);
        addComponent(sslUploadContainer);
        addComponent(sslListContainer);
        this.registration = ctx.registerService(TruststoreChangedListener.clreplaced, this, null);
    }

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

    private HorizontalLayout createHeaderForSslList() {
        HorizontalLayout header = ViewUtil.createSubHeader("List of available certificates", null);
        Button refresh = new Button();
        refresh.setStyleName(Reindeer.BUTTON_LINK);
        refresh.setDescription("Refresh");
        refresh.setIcon(new ThemeResource("img/Refresh.png"));
        refresh.addClickListener((Button.ClickListener) event -> buildSslConfigurationTable());
        header.addComponent(refresh);
        return header;
    }

    private List<CertificateBasicInfoModel> getPersistenceSslData() {
        List<CertificateBasicInfoModel> basicInfoModels = new ArrayList<>();
        BaseRequest<BaseDto> listRequest = new BaseRequest<>();
        ListResponse<CertificateBasicInfoModel> res;
        try {
            res = this.listSslCertificateService.dispatch(listRequest);
            basicInfoModels = res.getList();
        } catch (Exception e) {
            log.error("Failed to get information from SSL attributes table", e);
            ViewUtil.iscNotification("Failed to get information from SSL attributes table (" + e.getMessage() + ")", Notification.Type.ERROR_MESSAGE);
        }
        return basicInfoModels;
    }

    private void colorizeValidUntilRows() {
        final Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, this.CERT_MONTHLY_THRESHOLD);
        this.sslConfigTable.setCellStyleGenerator((Table.CellStyleGenerator) (table, itemId, propertyId) -> {
            if (propertyId != null) {
                return null;
            }
            Item item = this.sslConfigTable.gereplacedem(itemId);
            Date validUntil = (Date) item.gereplacedemProperty("Valid until").getValue();
            if (validUntil.before(calendar.getTime())) {
                return "highlight-warning";
            } else {
                return null;
            }
        });
    }

    private void buildSslConfigurationTable() {
        List<CertificateBasicInfoModel> persistenceSslData = getPersistenceSslData();
        this.sslConfigTable.removeAllItems();
        try {
            for (CertificateBasicInfoModel info : persistenceSslData) {
                this.sslConfigTable.addItem(new Object[] { info.getAlias(), info.getSha1Fingerprint(), info.getIssuer(), info.getValidFrom(), info.getValidTo(), info.getAlgorithmType(), createDeleteEntry(info) }, info.getAlias().toLowerCase());
            }
        } catch (Exception e) {
            log.error("Cannot build SSL configuration table", e);
            ViewUtil.iscNotification("Fail to get information from SSL attributes table (" + e.getMessage() + ")", Notification.Type.ERROR_MESSAGE);
        }
        // Additional +1 is added for handling vaadin problem with resizing to content table
        this.sslConfigTable.setPageLength(this.sslConfigTable.size() + 1);
        this.sslConfigTable.sort(new Object[] { "Alias" }, new boolean[] { false });
        colorizeValidUntilRows();
    }

    private Button createDeleteEntry(CertificateBasicInfoModel certificateModel) {
        String removeBtnLabel = (certificateModel.isConnected()) ? "Force delete" : "Delete";
        final Button deleteArchiveButton = new Button(removeBtnLabel);
        deleteArchiveButton.setData(certificateModel);
        deleteArchiveButton.addClickListener(this.removeButtonListener);
        if (certificateModel.getAlias().contains(getString(KEYPAIR_INTERNAL_DISPLAY_ALIAS))) {
            deleteArchiveButton.setEnabled(false);
        }
        return deleteArchiveButton;
    }

    private Button.ClickListener removeButtonListener = new Button.ClickListener() {

        private static final long serialVersionUID = 5173505013809394877L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            final CertificateBasicInfoModel certificateModel = (CertificateBasicInfoModel) event.getButton().getData();
            if (certificateModel.isConnected()) {
                SslConfigurationLayout.this.deleteWindow = WindowUtil.createAlertWindow(getString(MAINTENANCE_SSLCONFIGURATION_FORCE_REMOVE_DIALOG_replacedLE), getString(MAINTENANCE_SSLCONFIGURATION_FORCE_REMOVE_DIALOG_CONTENT, certificateModel.getAlias()));
            } else {
                SslConfigurationLayout.this.deleteWindow = WindowUtil.createAlertWindow(getString(MAINTENANCE_SSLCONFIGURATION_REMOVE_DIALOG_replacedLE), getString(MAINTENANCE_SSLCONFIGURATION_REMOVE_DIALOG_CONTENT, certificateModel.getAlias()));
            }
            SslConfigurationLayout.this.deleteWindow.getComponentModel().getOkButton().setData(certificateModel.getAlias());
            SslConfigurationLayout.this.deleteWindow.getComponentModel().setOkClickedListener(SslConfigurationLayout.this.acceptRemoveButtonListener);
            ViewUtil.addWindow(SslConfigurationLayout.this.deleteWindow);
        }
    };

    private Button.ClickListener acceptRemoveButtonListener = new Button.ClickListener() {

        private static final long serialVersionUID = 2512910250970666944L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            final String alias = (String) event.getButton().getData();
            log.info("Removing ssl entry with alias: " + alias);
            boolean succeed;
            DeleteSslEntryRequest deleteRequest = new DeleteSslEntryRequest(alias);
            try {
                SslConfigurationLayout.this.deleteSslCertificateService.dispatch(deleteRequest);
                succeed = true;
            } catch (Exception e) {
                succeed = false;
                log.error("Failed to remove SSL alias from truststore", e);
            }
            SslConfigurationLayout.this.buildSslConfigurationTable();
            SslConfigurationLayout.this.deleteWindow.close();
            String outputMessage = (succeed) ? MAINTENANCE_SSLCONFIGURATION_REMOVED : MAINTENANCE_SSLCONFIGURATION_REMOVE_FAILURE;
            ViewUtil.iscNotification(getString(outputMessage, new Date()), null, Notification.Type.TRAY_NOTIFICATION);
        }
    };

    @Override
    public void truststoreChanged() {
        buildSslConfigurationTable();
    }

    @Override
    public void detach() {
        super.detach();
        try {
            this.registration.unregister();
        } catch (IllegalStateException ise) {
        // This is not a problem, it just means
        // that the UI bundle stopped before this
        // detach call occurred.
        }
    }
}

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

public clreplaced ArchiveLayout extends FormLayout {

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

    Logger log = LoggerFactory.getLogger(ArchiveLayout.clreplaced);

    private Table archiveTable;

    public ArchiveLayout(ArchiveServiceApi archiveService, GetJobsArchiveServiceApi getJobsArchiveService, UpdateJobsArchiveServiceApi updateJobsArchiveService) {
        super();
        VerticalLayout downloadContainer = new VerticalLayout();
        VerticalLayout archiveContainer = new VerticalLayout();
        // Component to Archive Jobs
        JobsArchiverPanel archiveConfigurator = new JobsArchiverPanel(this, archiveService, getJobsArchiveService, updateJobsArchiveService);
        archiveConfigurator.setSizeFull();
        archiveContainer.addComponent(ViewUtil.createSubHeader("Archive Jobs/Alerts", null));
        archiveContainer.addComponent(archiveConfigurator);
        downloadContainer.addComponent(ViewUtil.createSubHeader("Download Archive", null));
        // Component to download archive
        this.archiveTable = new Table();
        this.archiveTable.setSizeFull();
        this.archiveTable.setPageLength(5);
        this.archiveTable.setImmediate(true);
        this.archiveTable.addContainerProperty("Name", String.clreplaced, null);
        this.archiveTable.addContainerProperty("Date", Date.clreplaced, null);
        this.archiveTable.addContainerProperty("Size", Long.clreplaced, null);
        this.archiveTable.addContainerProperty("Download", Link.clreplaced, null);
        this.archiveTable.addContainerProperty("Delete", Button.clreplaced, null);
        buildArchivesTable();
        Panel archiveTablePanel = new Panel();
        archiveTablePanel.setContent(this.archiveTable);
        addComponent(archiveContainer);
        addComponent(archiveTablePanel);
    }

    public void buildArchivesTable() {
        this.archiveTable.removeAllItems();
        File[] fileList = new File("archive").listFiles();
        if (fileList == null) {
            fileList = new File[0];
        }
        for (File archiveFile : fileList) {
            this.archiveTable.addItem(new Object[] { archiveFile.getName(), new Date(archiveFile.lastModified()), archiveFile.length(), createDownloadLink(archiveFile), createDeleteArchive(archiveFile) }, archiveFile.getName());
        }
        this.archiveTable.sort(new Object[] { "Date" }, new boolean[] { false });
    }

    @SuppressWarnings("serial")
    private Button createDeleteArchive(File archiveFile) {
        final Button deleteArchiveButton = new Button("Delete");
        deleteArchiveButton.setData(archiveFile);
        deleteArchiveButton.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                final File archiveFile = (File) deleteArchiveButton.getData();
                final VmidcWindow<OkCancelButtonModel> deleteWindow = WindowUtil.createAlertWindow("Delete Archive File", "Delete Archive File - " + archiveFile);
                deleteWindow.getComponentModel().setOkClickedListener(new ClickListener() {

                    @Override
                    public void buttonClick(ClickEvent event) {
                        archiveFile.delete();
                        buildArchivesTable();
                        deleteWindow.close();
                    }
                });
                ViewUtil.addWindow(deleteWindow);
            }
        });
        return deleteArchiveButton;
    }

    private Link createDownloadLink(File archiveFile) {
        return new Link("Download " + archiveFile, new FileResource(archiveFile));
    }
}

19 Source : MultiSelectTable.java
with Apache License 2.0
from ijazfx

/**
 * A Table that can be used as a field to modify List>YourDomainObject< or
 * Set>YourDomainObject< typed fields in your domain model.
 * <p>
 * The field supports only non buffered mode. Also, the field tries to keep the
 * original collection and just modify its content. This helps e.g. some ORM
 * libraries to create more efficient updates to the database.
 * <p>
 * If the field value is null (and users selects rows) the field tries to add a
 * value with no-arg constructor or with ArrayList/HashMap if interface is used.
 *
 * @author Matti Tahvonen
 * @param <ET> The type in the enreplacedy collection
 */
public clreplaced MultiSelectTable<ET> extends CustomField<Collection> {

    private static final long serialVersionUID = -3245403481676039947L;

    private String[] visProps;

    private String[] pendingHeaders;

    Table table = new Table() {

        private static final long serialVersionUID = -770469825702542170L;

        {
            setSelectable(true);
            setMultiSelect(true);
            setSizeFull();
            setImmediate(true);
        }

        private boolean clientSideChange;

        @Override
        public void changeVariables(Object source, Map<String, Object> variables) {
            clientSideChange = true;
            super.changeVariables(source, variables);
            clientSideChange = false;
        }

        @Override
        protected void setValue(Object newValue, boolean repaintIsNotNeeded) throws ReadOnlyException {
            Set<ET> oldvalue = (Set<ET>) getValue();
            super.setValue(newValue, repaintIsNotNeeded);
            if (clientSideChange) {
                // TODO add strategies for maintaining the order in case of List
                // e.g. same as listing, selection order ...
                Set newvalue = (Set) getValue();
                Set<ET> orphaned = new HashSet<>(oldvalue);
                orphaned.removeAll(newvalue);
                removeRelation(orphaned);
                allRemovedRelations.addAll(orphaned);
                allAddedRelations.removeAll(orphaned);
                Set<ET> newValues = new LinkedHashSet<>(newvalue);
                newValues.removeAll(oldvalue);
                addRelation(newValues);
                allAddedRelations.addAll(newValues);
                allRemovedRelations.removeAll(newValues);
                MultiSelectTable.this.fireValueChange(true);
            }
        }
    };

    private Clreplaced<ET> optionType;

    private Set<ET> allAddedRelations = new HashSet<>();

    private Set<ET> allRemovedRelations = new HashSet<>();

    public MultiSelectTable(Clreplaced<ET> optionType) {
        this();
        table.setContainerDataSource(new ListContainer(optionType));
        this.optionType = optionType;
    }

    public MultiSelectTable(String caption) {
        this();
        setCaption(caption);
    }

    /**
     * Adds given options to the modified collection. The default implementation
     * simply uses java.util.Collection APIs to maintain the edited collection.
     * If the underlying data model needs some some custom maintenance, e.g. a
     * bi-directional many-to-many relation in JPA, you can add your own logic
     * by overriding this method.
     *
     * @param newValues the new objects to be added to the collection.
     */
    protected void addRelation(Set<ET> newValues) {
        getEditedCollection().addAll(newValues);
    }

    /**
     * Removes given options from the modified collection. The default
     * implementation simply uses java.util.Collection APIs to maintain the
     * edited collection. If the underlying data model needs some some custom
     * maintenance, e.g. a bi-directional many-to-many relation in JPA, you can
     * add your own logic by overriding this method.
     *
     * @param orphaned the new objects to be removed from the collection.
     */
    protected void removeRelation(Set<ET> orphaned) {
        getEditedCollection().removeAll(orphaned);
    }

    /**
     * @return all objects that are added to the edited collection. The added
     * relations are calculated since last call to setPropertyDataSource method
     * (when the modified property/collection is set by e.g. FieldGroup) or
     * explicit call to clearModifiedRelations().
     */
    public Set<ET> getAllAddedRelations() {
        return allAddedRelations;
    }

    /**
     * @return all objects that are removed from the edited collection. The
     * deleted relations are calculated since last call to setPropertyDataSource
     * method (when the modified property/collection is set by e.g. FieldGroup)
     * or explicit call to clearModifiedRelations().
     */
    public Set<ET> getAllRemovedRelations() {
        return allRemovedRelations;
    }

    /**
     * @return all objects that are either added or removed to/from the edited
     * collection. The objects are calculated since last call to
     * setPropertyDataSource method (when the modified property/collection is
     * set by e.g. FieldGroup) or explicit call to clearModifiedRelations().
     */
    public Set<ET> getAllModifiedRelations() {
        HashSet<ET> all = new HashSet<>(allAddedRelations);
        all.addAll(allRemovedRelations);
        return all;
    }

    @Override
    public void setPropertyDataSource(Property newDataSource) {
        clearModifiedRelations();
        super.setPropertyDataSource(newDataSource);
    }

    /**
     * Clears the fields that track the elements that are added or removed to
     * the modified collection. This method is automatically called when a new
     * property is replacedigned to this field.
     */
    public void clearModifiedRelations() {
        allAddedRelations.clear();
        allRemovedRelations.clear();
    }

    /**
     * @return the collection being edited by this field.
     */
    protected Collection<ET> getEditedCollection() {
        Collection c = getValue();
        if (c == null) {
            if (getPropertyDataSource() == null) {
                // this should never happen :-)
                return new HashSet();
            }
            Clreplaced fieldType = getPropertyDataSource().getType();
            if (fieldType.isInterface()) {
                if (fieldType == List.clreplaced) {
                    c = new ArrayList();
                } else {
                    // Set
                    c = new HashSet();
                }
            } else {
                try {
                    c = (Collection) fieldType.newInstance();
                } catch (IllegalAccessException | InstantiationException ex) {
                    throw new RuntimeException("Could not instantiate the used colleciton type", ex);
                }
            }
        }
        return c;
    }

    public MultiSelectTable<ET> withProperties(String... visibleProperties) {
        visProps = visibleProperties;
        if (isContainerInitialized()) {
            table.setVisibleColumns((Object[]) visibleProperties);
        } else {
            for (String string : visibleProperties) {
                table.addContainerProperty(string, String.clreplaced, "");
            }
        }
        return this;
    }

    private boolean isContainerInitialized() {
        return table.getContainerDataSource() instanceof ListContainer;
    }

    public MultiSelectTable<ET> withColumnHeaders(String... columnNamesForVisibleProperties) {
        if (isContainerInitialized()) {
            table.setColumnHeaders(columnNamesForVisibleProperties);
        } else {
            pendingHeaders = columnNamesForVisibleProperties;
            // Add headers to temporary indexed container, in case table is initially
            // empty
            for (String prop : columnNamesForVisibleProperties) {
                table.addContainerProperty(prop, String.clreplaced, "");
            }
        }
        return this;
    }

    @Override
    protected Component initContent() {
        return table;
    }

    @Override
    public Clreplaced<? extends Collection> getType() {
        return Collection.clreplaced;
    }

    @Override
    protected void setInternalValue(Collection newValue) {
        super.setInternalValue(newValue);
        table.setValue(newValue);
    }

    /**
     * Sets the list of options available.
     *
     * @param list the list of available options
     * @return this for fluent configuration
     */
    public MultiSelectTable<ET> setOptions(List<ET> list) {
        if (visProps == null) {
            table.setContainerDataSource(new ListContainer(optionType, list));
        } else {
            table.setContainerDataSource(new ListContainer(optionType, list), Arrays.asList(visProps));
        }
        if (pendingHeaders != null) {
            table.setColumnHeaders(pendingHeaders);
        }
        return this;
    }

    /**
     * Sets the list of options available.
     *
     * @param list the list of available options
     * @return this for fluent configuration
     */
    public MultiSelectTable<ET> setOptions(ET... list) {
        if (visProps == null) {
            table.setContainerDataSource(new ListContainer(optionType, Arrays.asList(list)));
        } else {
            table.setContainerDataSource(new ListContainer(optionType, Arrays.asList(list)), Arrays.asList(visProps));
        }
        if (pendingHeaders != null) {
            table.setColumnHeaders(pendingHeaders);
        }
        return this;
    }

    public MultiSelectTable() {
        setHeight("230px");
        // TODO verify if this is needed in real usage, but at least to preplaced the test
        setConverter(new Converter<Collection, Collection>() {

            private static final long serialVersionUID = -20358585168853508L;

            @Override
            public Collection convertToModel(Collection value, Clreplaced<? extends Collection> targetType, Locale locale) throws Converter.ConversionException {
                return value;
            }

            @Override
            public Collection convertToPresentation(Collection value, Clreplaced<? extends Collection> targetType, Locale locale) throws Converter.ConversionException {
                return value;
            }

            @Override
            public Clreplaced<Collection> getModelType() {
                return (Clreplaced<Collection>) getEditedCollection().getClreplaced();
            }

            @Override
            public Clreplaced<Collection> getPresentationType() {
                return Collection.clreplaced;
            }
        });
    }

    public void select(ET objectToSelect) {
        if (!table.isSelected(objectToSelect)) {
            table.select(objectToSelect);
            getEditedCollection().add(objectToSelect);
        }
    }

    public void unSelect(ET objectToDeselect) {
        if (table.isSelected(objectToDeselect)) {
            table.unselect(objectToDeselect);
            getEditedCollection().remove(objectToDeselect);
        }
    }

    /**
     * @return the underlaying Table
     * @deprecated use getTable() instead.
     */
    @Deprecated
    protected Table getUnderlayingTable() {
        return table;
    }

    /**
     * @return the underlaying table implementation. Note that the component
     * heavily relies on some features so changing some of the configuration
     * options in Table is unsafe.
     */
    public Table getTable() {
        return table;
    }

    public MultiSelectTable<ET> withColumnHeaderMode(Table.ColumnHeaderMode mode) {
        getUnderlayingTable().setColumnHeaderMode(mode);
        return this;
    }

    public MultiSelectTable<ET> withFullWidth() {
        setWidth(100, Unit.PERCENTAGE);
        return this;
    }

    public MultiSelectTable<ET> withHeight(String height) {
        setHeight(height);
        return this;
    }

    public MultiSelectTable<ET> withFullHeight() {
        return withHeight("100%");
    }

    public MultiSelectTable<ET> withWidth(String width) {
        setWidth(width);
        return this;
    }

    public MultiSelectTable withSize(MSize mSize) {
        setWidth(mSize.getWidth(), mSize.getWidthUnit());
        setHeight(mSize.getHeight(), mSize.getHeightUnit());
        return this;
    }

    public MultiSelectTable<ET> withCaption(String caption) {
        setCaption(caption);
        return this;
    }

    public MultiSelectTable<ET> withStyleName(String... styleNames) {
        for (String styleName : styleNames) {
            addStyleName(styleName);
        }
        return this;
    }

    public MultiSelectTable<ET> withIcon(Resource icon) {
        setIcon(icon);
        return this;
    }

    public MultiSelectTable<ET> withId(String id) {
        table.setId(id);
        return this;
    }

    public MultiSelectTable<ET> expand(String... propertiesToExpand) {
        for (String property : propertiesToExpand) {
            table.setColumnExpandRatio(property, 1);
        }
        return this;
    }

    public void withRowHeaderMode(Table.RowHeaderMode rowHeaderMode) {
        getUnderlayingTable().setRowHeaderMode(rowHeaderMode);
    }

    public MultiSelectTable<ET> setMultiSelectMode(MultiSelectMode mode) {
        getTable().setMultiSelectMode(mode);
        return this;
    }
}

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

public clreplaced BindSecurityGroupWindow extends CRUDBaseWindow<OkCancelButtonModel> {

    private static final String PROPERTY_ID_POLICY = "Inspection Policy";

    private static final String PROPERTY_ID_DA = "Distributed Appliance";

    private static final String PROPERTY_ID_ENABLED = "Enabled";

    private static final String PROPERTY_ID_FAILURE_POLICY = "Chaining Failure Policy";

    private static final String PROPERTY_ID_CHAIN_ORDER = "Order";

    private static final long serialVersionUID = 1L;

    final String CAPTION = "Bind Policy to Security Group";

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

    private final SecurityGroupDto currentSecurityGroup;

    private Table serviceTable = null;

    private Long vcId;

    private final BindSecurityGroupServiceApi bindSecurityGroupService;

    private final ListSecurityGroupBindingsBySgServiceApi listSecurityGroupBindingsBySgService;

    private final ServerApi server;

    private List<VirtualSystemPolicyBindingDto> allBindings;

    public BindSecurityGroupWindow(SecurityGroupDto sgDto, BindSecurityGroupServiceApi bindSecurityGroupService, ListSecurityGroupBindingsBySgServiceApi listSecurityGroupBindingsBySgService, ServerApi server, Long vcId) throws Exception {
        this.currentSecurityGroup = sgDto;
        this.bindSecurityGroupService = bindSecurityGroupService;
        this.listSecurityGroupBindingsBySgService = listSecurityGroupBindingsBySgService;
        this.server = server;
        this.vcId = vcId;
        createWindow(this.CAPTION + " - " + this.currentSecurityGroup.getName());
    }

    @Override
    public void populateForm() throws ActionNotSupportedException {
        this.content.addStyleName(StyleConstants.VMIDC_WINDOW_CONTENT_WRAPPER);
        this.content.addComponent(getServicePanel());
    }

    public List<Long> getSelectedServicesId() {
        List<Long> selectedServices = new ArrayList<>();
        for (Object id : this.serviceTable.gereplacedemIds()) {
            if (this.serviceTable.getContainerProperty(id, PROPERTY_ID_ENABLED).getValue().equals(true)) {
                selectedServices.add((Long) id);
            }
        }
        return selectedServices;
    }

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

    @Override
    public void submitForm() {
        try {
            if (validateForm()) {
                BindSecurityGroupRequest bindRequest = new BindSecurityGroupRequest();
                bindRequest.setVcId(this.vcId);
                bindRequest.setSecurityGroupId(this.currentSecurityGroup.getId());
                bindRequest.setSfcId(this.currentSecurityGroup.getServiceFunctionChainId());
                /*From UI to differentiate if it is a SFC  or non-SFC bind, we have to preplaced a value from
                VirtualizationConnectorView file because binding window for sfc and non-sfc cases is going to be different.
                A condition needs to be added when we support SFC bind
                through UI(or shall we add it now?).For now we do not allow SFC bind from UI hence it is false*/
                bindRequest.setBindSfc(false);
                this.allBindings = this.listSecurityGroupBindingsBySgService.dispatch(new BaseIdRequest(this.currentSecurityGroup.getId())).getMemberList();
                for (Long selectedVsId : getSelectedServicesId()) {
                    VirtualSystemPolicyBindingDto previousBinding = null;
                    for (VirtualSystemPolicyBindingDto binding : this.allBindings) {
                        if (binding.getVirtualSystemId().equals(selectedVsId)) {
                            previousBinding = binding;
                            break;
                        }
                    }
                    Item selectedService = this.serviceTable.gereplacedem(selectedVsId);
                    // TODO Larkins: Fix UI to receive the set of policies from the User
                    // Do not update the policy binding from the UI.
                    // Policy mapping for manager supporting multiple policies is not supported through UI.
                    Set<Long> policyIdSet = null;
                    if (isBindedWithMultiplePolicies(previousBinding)) {
                        policyIdSet = previousBinding.getPolicyIds();
                    } else {
                        Object selectedPolicy = ((ComboBox) selectedService.gereplacedemProperty(PROPERTY_ID_POLICY).getValue()).getValue();
                        policyIdSet = selectedPolicy == null ? null : new HashSet<>(Arrays.asList(((PolicyDto) selectedPolicy).getId()));
                    }
                    String serviceName = (String) selectedService.gereplacedemProperty(PROPERTY_ID_DA).getValue();
                    ComboBox failurePolicyComboBox = (ComboBox) selectedService.gereplacedemProperty(PROPERTY_ID_FAILURE_POLICY).getValue();
                    FailurePolicyType failurePolicyType = FailurePolicyType.NA;
                    if (failurePolicyComboBox.getData() != null) {
                        // If failure policy is supported, the data is not null
                        // and we need to use the failure policy
                        // specified in the combobox
                        failurePolicyType = (FailurePolicyType) failurePolicyComboBox.getValue();
                    }
                    Long order = null;
                    if (!bindRequest.isBindSfc()) {
                        order = (Long) selectedService.gereplacedemProperty(PROPERTY_ID_CHAIN_ORDER).getValue();
                    }
                    // send null if user did not modify this set
                    bindRequest.addServiceToBindTo(new VirtualSystemPolicyBindingDto(selectedVsId, serviceName, policyIdSet, failurePolicyType, order));
                }
                BaseJobResponse response = this.bindSecurityGroupService.dispatch(bindRequest);
                close();
                ViewUtil.showJobNotification(response.getJobId(), this.server);
            }
        } catch (Exception e) {
            log.error("Fail to Bind Security Group", e);
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
        }
    }

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

    @SuppressWarnings("unchecked")
    protected void moveItem(boolean moveUp) {
        if (this.serviceTable.getValue() != null) {
            long selectedItemId = (long) this.serviceTable.getValue();
            Property<Long> selectedItemChainProperty = this.serviceTable.getContainerProperty(selectedItemId, PROPERTY_ID_CHAIN_ORDER);
            Long currentOrderValue = selectedItemChainProperty.getValue();
            Object nexreplacedemIdObj = this.serviceTable.nexreplacedemId(selectedItemId);
            Object previousItemIdObj = this.serviceTable.prevItemId(selectedItemId);
            if (moveUp && previousItemIdObj != null) {
                Property<Long> previousItemChainProperty = this.serviceTable.getContainerProperty(previousItemIdObj, PROPERTY_ID_CHAIN_ORDER);
                Long previousItemOrderValue = previousItemChainProperty.getValue();
                selectedItemChainProperty.setValue(previousItemOrderValue);
                previousItemChainProperty.setValue(currentOrderValue);
                sortByChainOrder();
            } else if (!moveUp && nexreplacedemIdObj != null) {
                Property<Long> nexreplacedemChainProperty = this.serviceTable.getContainerProperty(nexreplacedemIdObj, PROPERTY_ID_CHAIN_ORDER);
                Long nexreplacedemOrderValue = nexreplacedemChainProperty.getValue();
                selectedItemChainProperty.setValue(nexreplacedemOrderValue);
                nexreplacedemChainProperty.setValue(currentOrderValue);
                sortByChainOrder();
            }
        }
    }

    private void sortByChainOrder() {
        this.serviceTable.sort(new Object[] { PROPERTY_ID_CHAIN_ORDER }, new boolean[] { true });
    }

    @SuppressWarnings("unchecked")
    private void populateServiceTable() throws Exception {
        // TODO: Future. Convert this table into Bean container and add DTOs in
        // it.
        // creating Virtual System Table
        this.serviceTable.addContainerProperty(PROPERTY_ID_CHAIN_ORDER, Long.clreplaced, null);
        this.serviceTable.addContainerProperty(PROPERTY_ID_ENABLED, Boolean.clreplaced, false);
        this.serviceTable.addContainerProperty(PROPERTY_ID_DA, String.clreplaced, null);
        this.serviceTable.addContainerProperty(PROPERTY_ID_POLICY, ComboBox.clreplaced, null);
        this.serviceTable.addContainerProperty(PROPERTY_ID_FAILURE_POLICY, ComboBox.clreplaced, null);
        this.serviceTable.removeAllItems();
        this.allBindings = this.listSecurityGroupBindingsBySgService.dispatch(new BaseIdRequest(this.currentSecurityGroup.getId())).getMemberList();
        for (VirtualSystemPolicyBindingDto binding : this.allBindings) {
            List<PolicyDto> policies = binding.getPolicies();
            ComboBox policyComboBox = getPolicyComboBox(policies);
            policyComboBox.setRequired(policies != null && policies.size() > 0);
            ComboBox failurePolicyComboBox = getFailurePolicyComboBox();
            this.serviceTable.addItem(new Object[] { binding.getOrder(), binding.getName(), policyComboBox, failurePolicyComboBox }, binding.getVirtualSystemId());
            if (binding.isBinded() && !binding.getPolicyIds().isEmpty()) {
                // For any existing bindings, set enabled and set the order
                // value
                this.serviceTable.getContainerProperty(binding.getVirtualSystemId(), PROPERTY_ID_ENABLED).setValue(true);
                ComboBox comboBoxPolicy = (ComboBox) this.serviceTable.getContainerProperty(binding.getVirtualSystemId(), PROPERTY_ID_POLICY).getValue();
                comboBoxPolicy.setEnabled(policies != null && !isBindedWithMultiplePolicies(binding));
                for (Object comboBoxItemId : comboBoxPolicy.getContainerDataSource().gereplacedemIds()) {
                    if (comboBoxPolicy.gereplacedem(comboBoxItemId).gereplacedemProperty("id").getValue().equals(binding.getPolicyIds().iterator().next())) {
                        comboBoxPolicy.select(comboBoxItemId);
                        break;
                    }
                }
            }
            ComboBox comboBoxFailurePolicy = (ComboBox) this.serviceTable.getContainerProperty(binding.getVirtualSystemId(), PROPERTY_ID_FAILURE_POLICY).getValue();
            if (binding.getFailurePolicyType() != FailurePolicyType.NA) {
                if (binding.isBinded()) {
                    comboBoxFailurePolicy.setEnabled(true);
                }
                comboBoxFailurePolicy.setData(binding.getFailurePolicyType());
                comboBoxFailurePolicy.select(binding.getFailurePolicyType());
            } else {
                comboBoxFailurePolicy.setData(null);
                comboBoxFailurePolicy.setEnabled(false);
            }
        }
        sortByChainOrder();
        if (this.serviceTable.gereplacedemIds().size() > 0) {
            this.serviceTable.select(this.serviceTable.gereplacedemIds().iterator().next());
        }
    }

    private ComboBox getPolicyComboBox(List<PolicyDto> policyDtoList) {
        ComboBox policy = new ComboBox("Select Policy");
        policy.setTextInputAllowed(false);
        policy.setNullSelectionAllowed(false);
        policy.setImmediate(true);
        policy.setRequired(true);
        policy.setRequiredError("Policy cannot be empty");
        BeanItemContainer<PolicyDto> policyListContainer = new BeanItemContainer<>(PolicyDto.clreplaced, policyDtoList);
        policy.setContainerDataSource(policyListContainer);
        policy.sereplacedemCaptionPropertyId("policyName");
        if (policyListContainer.size() > 0) {
            policy.select(policyListContainer.getIdByIndex(0));
        }
        policy.setEnabled(false);
        return policy;
    }

    private ComboBox getFailurePolicyComboBox() {
        ComboBox failurePolicy = new ComboBox("Select Failure Policy");
        failurePolicy.setTextInputAllowed(false);
        failurePolicy.setNullSelectionAllowed(false);
        failurePolicy.setImmediate(true);
        failurePolicy.setRequired(true);
        failurePolicy.setRequiredError("Failure Policy cannot be empty");
        failurePolicy.addItems(FailurePolicyType.FAIL_OPEN, FailurePolicyType.FAIL_CLOSE);
        failurePolicy.select(FailurePolicyType.FAIL_OPEN);
        failurePolicy.setEnabled(false);
        return failurePolicy;
    }

    @SuppressWarnings({ "rawtypes" })
    private void serviceTableClicked(long itemId) {
        ComboBox policyComboBox = (ComboBox) this.serviceTable.getContainerProperty(itemId, PROPERTY_ID_POLICY).getValue();
        ComboBox failurePolicyComboBox = (ComboBox) this.serviceTable.getContainerProperty(itemId, PROPERTY_ID_FAILURE_POLICY).getValue();
        Property itemProperty = this.serviceTable.getContainerProperty(itemId, PROPERTY_ID_ENABLED);
        boolean currentValue = (boolean) itemProperty.getValue();
        if (policyComboBox.getContainerDataSource().size() > 0) {
            if (isBindedWithMultiplePolicies(itemId)) {
                policyComboBox.setEnabled(false);
            } else {
                policyComboBox.setEnabled(currentValue);
            }
        }
        if (failurePolicyComboBox.getData() != null) {
            failurePolicyComboBox.setEnabled(currentValue);
        }
    }

    private boolean isBindedWithMultiplePolicies(Long vsId) {
        for (VirtualSystemPolicyBindingDto binding : this.allBindings) {
            if (binding.getVirtualSystemId().equals(vsId) && isBindedWithMultiplePolicies(binding)) {
                return true;
            }
        }
        return false;
    }

    private boolean isBindedWithMultiplePolicies(VirtualSystemPolicyBindingDto binding) {
        return binding.isMultiplePoliciesSupported() && binding.isBinded() && binding.getPolicyIds().size() > 1;
    }

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

        @Override
        public Object generateCell(Table source, final Object itemId, Object columnId) {
            Property<?> prop = source.gereplacedem(itemId).gereplacedemProperty(columnId);
            CheckBox checkBox = new CheckBox(null, prop);
            checkBox.addValueChangeListener(new ValueChangeListener() {

                @Override
                public void valueChange(ValueChangeEvent event) {
                    serviceTableClicked((long) itemId);
                }
            });
            return checkBox;
        }
    }
}

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

@SuppressWarnings("serial")
public clreplaced AddSSLCertificateWindow extends CRUDBaseApproveWindow {

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

    final String CAPTION = "Add SSL certificate";

    private Table sslConfigTable;

    private final ArrayList<CertificateResolverModel> certificateResolverModels;

    private final SSLCertificateWindowInterface sslCertificateWindowInterface;

    private final X509TrustManagerApi trustManager;

    public interface SSLCertificateWindowInterface {

        void submitFormAction(ArrayList<CertificateResolverModel> certificateResolverModels);

        void cancelFormAction();
    }

    public AddSSLCertificateWindow(ArrayList<CertificateResolverModel> certificateResolverModels, SSLCertificateWindowInterface sslCertificateWindowInterface, X509TrustManagerApi trustManager) throws Exception {
        super(new ApproveCancelButtonModel());
        this.certificateResolverModels = certificateResolverModels;
        this.sslCertificateWindowInterface = sslCertificateWindowInterface;
        this.trustManager = trustManager;
        createWindow(this.CAPTION);
    }

    @Override
    public void populateForm() throws Exception {
        this.sslConfigTable = new Table();
        this.sslConfigTable.setSizeFull();
        this.sslConfigTable.setImmediate(true);
        this.sslConfigTable.addContainerProperty("Alias", String.clreplaced, null);
        this.sslConfigTable.addContainerProperty("SHA1 fingerprint", String.clreplaced, null);
        this.sslConfigTable.addContainerProperty("Issuer", String.clreplaced, null);
        this.sslConfigTable.addContainerProperty("Valid from", Date.clreplaced, null);
        this.sslConfigTable.addContainerProperty("Valid until", Date.clreplaced, null);
        this.sslConfigTable.addContainerProperty("Algorithm type", String.clreplaced, null);
        this.sslConfigTable.setColumnWidth("Issuer", 200);
        populateSSLConfigTable();
        this.form.addComponent(this.sslConfigTable);
    }

    private void populateSSLConfigTable() {
        this.sslConfigTable.removeAllItems();
        try {
            java.util.List<CertificateBasicInfoModel> certificateInfoList = getCertificateBasicInfoModelList();
            for (CertificateBasicInfoModel info : certificateInfoList) {
                this.sslConfigTable.addItem(new Object[] { info.getAlias(), info.getSha1Fingerprint(), info.getIssuer(), info.getValidFrom(), info.getValidTo(), info.getAlgorithmType() }, info.getSha1Fingerprint());
            }
        } catch (Exception e) {
            log.error("Cannot populate SSL configuration table", e);
        }
        // Additional +1 is added for handling vaadin problem with resizing to content table
        this.sslConfigTable.setPageLength(this.sslConfigTable.size() + 1);
    }

    private ArrayList<CertificateBasicInfoModel> getCertificateBasicInfoModelList() {
        ArrayList<CertificateBasicInfoModel> certificateBasicInfoModels = new ArrayList<>();
        for (CertificateResolverModel basicInfoModel : this.certificateResolverModels) {
            try {
                certificateBasicInfoModels.add(new CertificateBasicInfoModel(basicInfoModel.getAlias(), this.trustManager.getSha1Fingerprint(basicInfoModel.getCertificate()), basicInfoModel.getCertificate().getIssuerDN().getName(), basicInfoModel.getCertificate().getNotBefore(), basicInfoModel.getCertificate().getNotAfter(), basicInfoModel.getCertificate().getSigAlgName(), this.trustManager.certificateToString(basicInfoModel.getCertificate())));
            } catch (NoSuchAlgorithmException | CertificateEncodingException e) {
                log.error("Cannot create certificate basic information model", e);
            }
        }
        return certificateBasicInfoModels;
    }

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

    @Override
    public void submitForm() {
        String caption = VmidcMessages.getString(VmidcMessages_.MAINTENANCE_SSLCONFIGURATION_ADDED, new Date());
        for (CertificateResolverModel certObj : this.certificateResolverModels) {
            try {
                this.trustManager.addEntry(certObj.getCertificate(), certObj.getAlias());
            } catch (Exception e) {
                caption = VmidcMessages.getString(VmidcMessages_.MAINTENANCE_SSLCONFIGURATION_FAILED_ADD, new Date());
                log.error("Cannot add new entry in truststore", e);
            }
        }
        ViewUtil.iscNotification(caption, null, Notification.Type.TRAY_NOTIFICATION);
        this.sslCertificateWindowInterface.submitFormAction(this.certificateResolverModels);
        close();
    }

    @Override
    public void cancelForm() {
        this.sslCertificateWindowInterface.cancelFormAction();
        close();
    }
}

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

public clreplaced SummaryLayout extends FormLayout {

    private static final String LOGDIR_PATH = "data/log";

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

    private Table summarytable = null;

    private CheckBox checkbox = null;

    private Button download = null;

    private ServerApi server;

    private BackupServiceApi backupService;

    private ArchiveApi archiver;

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

    public SummaryLayout(ServerApi server, BackupServiceApi backupService, ArchiveApi archiver) {
        super();
        this.server = server;
        this.backupService = backupService;
        this.archiver = archiver;
        this.summarytable = createTable();
        // creating Server table
        this.summarytable.addItem(new Object[] { "DNS Name: ", getHostName() }, new Integer(1));
        this.summarytable.addItem(new Object[] { "IP Address: ", getIpAddress() }, new Integer(2));
        this.summarytable.addItem(new Object[] { "Version: ", getVersion() }, new Integer(3));
        this.summarytable.addItem(new Object[] { "Uptime: ", server.uptimeToString() }, new Integer(4));
        this.summarytable.addItem(new Object[] { "Current Server Time: ", new Date().toString() }, new Integer(5));
        VerticalLayout tableContainer = new VerticalLayout();
        tableContainer.addComponent(this.summarytable);
        addComponent(tableContainer);
        addComponent(createCheckBox());
        HorizontalLayout actionContainer = new HorizontalLayout();
        actionContainer.addComponent(createDownloadButton());
        addComponent(actionContainer);
    }

    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.addContainerProperty("Name", String.clreplaced, null);
        table.addContainerProperty("Status", String.clreplaced, null);
        table.setColumnHeaderMode(Table.ColumnHeaderMode.HIDDEN);
        return table;
    }

    @SuppressWarnings("serial")
    private Button createDownloadButton() {
        this.download = new Button(VmidcMessages.getString(VmidcMessages_.SUMMARY_DOWNLOAD_LOG)) {

            @Override
            public void setEnabled(boolean enabled) {
                if (enabled) {
                    // because setEnabled(false) calls are ignored and button is disabled
                    // on client because of setDisableOnClick(true), by doing this we
                    // make sure that the button is actually disabled so that setEnabled(true)
                    // has effect
                    getUI().getConnectorTracker().getDiffState(this).put("enabled", false);
                    super.setEnabled(enabled);
                }
            }
        };
        SummaryLayout.this.download.setDisableOnClick(true);
        if (this.checkbox != null && this.checkbox.getValue()) {
            this.download.setCaption(VmidcMessages.getString(VmidcMessages_.SUMMARY_DOWNLOAD_BUNDLE));
        }
        StreamResource zipStream = getZipStream();
        FileDownloader fileDownloader = new FileDownloader(zipStream);
        fileDownloader.extend(this.download);
        return this.download;
    }

    @SuppressWarnings("serial")
    private CheckBox createCheckBox() {
        this.checkbox = new CheckBox(VmidcMessages.getString(VmidcMessages_.SUMMARY_DOWNLOAD_INCLUDE_DB));
        this.checkbox.setImmediate(true);
        this.checkbox.setValue(false);
        this.checkbox.addValueChangeListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                if (SummaryLayout.this.checkbox.getValue()) {
                    SummaryLayout.this.download.setCaption(VmidcMessages.getString(VmidcMessages_.SUMMARY_DOWNLOAD_BUNDLE));
                } else {
                    SummaryLayout.this.download.setCaption(VmidcMessages.getString(VmidcMessages_.SUMMARY_DOWNLOAD_LOG));
                }
            }
        });
        return this.checkbox;
    }

    @SuppressWarnings("serial")
    private StreamResource getZipStream() {
        StreamResource.StreamSource source = new StreamResource.StreamSource() {

            @Override
            public InputStream getStream() {
                InputStream fin = null;
                try {
                    if (SummaryLayout.this.checkbox.getValue()) {
                        getDBBackup();
                    }
                    // creating a zip file resource to download
                    fin = new FileInputStream(SummaryLayout.this.archiver.archive(LOGDIR_PATH, "ServerSupportBundle.zip"));
                } catch (Exception exception) {
                    log.error("Failed! to receive zip file from Archieve Util", exception);
                } finally {
                    SummaryLayout.this.backupService.deleteBackupFilesFrom(LOGDIR_PATH);
                    SummaryLayout.this.download.setEnabled(true);
                }
                return fin;
            }
        };
        StreamResource resource = new StreamResource(source, "ServerSupportBundle.zip");
        return resource;
    }

    private void getDBBackup() {
        try {
            BackupResponse res = this.backupService.dispatch(new BackupRequest());
            if (res.isSuccess()) {
                // move backup to log directory
                FileUtils.copyFileToDirectory(this.backupService.getEncryptedBackupFile(), new File("log" + File.separator));
                this.backupService.deleteBackupFiles();
                log.info("Backup Successful! adding backup file to Support Bundle");
            }
        } catch (Exception e) {
            log.error("Failed to add DB backup in support bundle", e);
        }
    }

    private String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (Exception e) {
            log.error("Error while reading Host Name ", e);
        }
        return "";
    }

    public String getIpAddress() {
        try {
            return this.server.getHostIpAddress();
        } catch (Exception e) {
            log.error("Error while Host IP address ", e);
        }
        return "";
    }

    private String getVersion() {
        return this.server.getVersionStr();
    }
}

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

public clreplaced PluginsLayout extends FormLayout {

    private static final String PROP_PLUGIN_INFO = "Info";

    private static final int PLUGIN_INFO_COLUMN_WIDTH = 350;

    private static final String PROP_PLUGIN_STATE = "State";

    private static final String PROP_PLUGIN_NAME = "Name";

    private static final String PROP_PLUGIN_SERVICES = "Services";

    private static final String PROP_PLUGIN_VERSION = "Version";

    private static final String PROP_PLUGIN_DELETE = "";

    private static final long serialVersionUID = 1L;

    Logger log = LoggerFactory.getLogger(PluginsLayout.clreplaced);

    private Table plugins;

    private Panel pluginsPanel;

    PluginUploader uploader;

    private ImportPluginServiceApi importPluginService;

    private ServiceRegistration<PluginListener> registration;

    public PluginsLayout(BundleContext ctx, ImportPluginServiceApi importPluginService, ServerApi server) throws Exception {
        super();
        this.importPluginService = importPluginService;
        this.uploader = new PluginUploader(server);
        VerticalLayout uploadContainer = new VerticalLayout();
        VerticalLayout pluginsContainer = new VerticalLayout();
        VerticalLayout sdkContainer = new VerticalLayout();
        this.uploader.setSizeFull();
        this.uploader.addSucceededListener(getUploadSucceededListener());
        uploadContainer.addComponent(ViewUtil.createSubHeader("Upload", null));
        uploadContainer.addComponent(this.uploader);
        this.plugins = new Table();
        this.plugins.setPageLength(5);
        this.plugins.setImmediate(true);
        this.plugins.addContainerProperty(PROP_PLUGIN_STATE, String.clreplaced, null);
        this.plugins.addContainerProperty(PROP_PLUGIN_NAME, String.clreplaced, null);
        this.plugins.addContainerProperty(PROP_PLUGIN_SERVICES, Integer.clreplaced, null);
        this.plugins.addContainerProperty(PROP_PLUGIN_VERSION, String.clreplaced, null);
        this.plugins.addContainerProperty(PROP_PLUGIN_INFO, String.clreplaced, null);
        this.plugins.addContainerProperty(PROP_PLUGIN_DELETE, Button.clreplaced, null);
        this.plugins.setColumnWidth(PROP_PLUGIN_INFO, PLUGIN_INFO_COLUMN_WIDTH);
        // Add a tooltip to the error column so the user is able to see the
        // complete error message
        this.plugins.sereplacedemDescriptionGenerator((Component source, Object itemId, Object propertyId) -> {
            Object errorMessage = PluginsLayout.this.plugins.getContainerProperty(itemId, PROP_PLUGIN_INFO).getValue();
            if (errorMessage != null && errorMessage instanceof String) {
                return StringEscapeUtils.escapeHtml(errorMessage.toString());
            } else {
                return null;
            }
        });
        this.pluginsPanel = new Panel();
        this.pluginsPanel.setContent(this.plugins);
        pluginsContainer.addComponent(ViewUtil.createSubHeader("Plugins", null));
        pluginsContainer.addComponent(this.pluginsPanel);
        Button downloadSdkSdn = getDownloadSdkButtonForSdnController();
        Button downloadSdkManager = getDownloadSdkButtonForManager();
        sdkContainer.addComponent(ViewUtil.createSubHeader("SDK", null));
        sdkContainer.addComponent(new HorizontalLayout(downloadSdkSdn, downloadSdkManager));
        addComponent(uploadContainer);
        addComponent(pluginsContainer);
        addComponent(sdkContainer);
        // Subscribe to Plugin Notifications
        this.registration = ctx.registerService(PluginListener.clreplaced, this::updateTable, null);
    }

    private void updateTable(PluginEvent event) {
        PluginApi plugin = event.getPlugin();
        switch(event.getType()) {
            case ADDING:
                Item addingItem = this.plugins.addItem(plugin);
                if (addingItem != null) {
                    updateItem(addingItem, plugin);
                }
                break;
            case MODIFIED:
                Item modifyingItem = this.plugins.gereplacedem(plugin);
                if (modifyingItem == null) {
                    modifyingItem = this.plugins.addItem(plugin);
                }
                if (modifyingItem != null) {
                    updateItem(modifyingItem, plugin);
                }
                break;
            case REMOVED:
                this.plugins.removeItem(plugin);
                break;
            default:
                this.log.error("Unknown plugin event type: " + event.getType());
                break;
        }
    }

    private Button getDownloadSdkButtonForSdnController() throws URISyntaxException, MalformedURLException {
        SdkUtil sdkUtil = new SdkUtil();
        Button downloadSdk = new Button(VmidcMessages.getString(VmidcMessages_.MAINTENANCE_SDNPLUGIN_DOWNLOAD_SDK));
        URI currentLocation = UI.getCurrent().getPage().getLocation();
        URI downloadLocation = new URI(currentLocation.getScheme(), null, currentLocation.getHost(), currentLocation.getPort(), sdkUtil.getSdk(SdkUtil.sdkType.SDN_CONTROLLER), null, null);
        FileDownloader downloader = new FileDownloader(new ExternalResource(downloadLocation.toURL().toString()));
        downloader.extend(downloadSdk);
        return downloadSdk;
    }

    private Button getDownloadSdkButtonForManager() throws URISyntaxException, MalformedURLException {
        SdkUtil sdkUtil = new SdkUtil();
        Button downloadSdk = new Button(VmidcMessages.getString(VmidcMessages_.MAINTENANCE_MANAGERPLUGIN_DOWNLOAD_SDK));
        URI currentLocation = UI.getCurrent().getPage().getLocation();
        URI downloadLocation = new URI(currentLocation.getScheme(), null, currentLocation.getHost(), currentLocation.getPort(), sdkUtil.getSdk(SdkUtil.sdkType.MANAGER), null, null);
        FileDownloader downloader = new FileDownloader(new ExternalResource(downloadLocation.toURL().toString()));
        downloader.extend(downloadSdk);
        return downloadSdk;
    }

    @SuppressWarnings("unchecked")
    private void updateItem(Item item, PluginApi plugin) {
        item.gereplacedemProperty(PROP_PLUGIN_STATE).setValue(plugin.getState().toString());
        item.gereplacedemProperty(PROP_PLUGIN_NAME).setValue(plugin.getSymbolicName());
        item.gereplacedemProperty(PROP_PLUGIN_VERSION).setValue(plugin.getVersion());
        item.gereplacedemProperty(PROP_PLUGIN_SERVICES).setValue(plugin.getServiceCount());
        String info;
        if (plugin.getState() == State.ERROR) {
            info = plugin.getError();
        } else {
            info = "";
        }
        item.gereplacedemProperty(PROP_PLUGIN_INFO).setValue(info);
        Button deleteButton = new Button("Delete");
        deleteButton.addClickListener(event -> deletePlugin(plugin));
        item.gereplacedemProperty(PROP_PLUGIN_DELETE).setValue(deleteButton);
    }

    private void deletePlugin(PluginApi plugin) {
        final VmidcWindow<OkCancelButtonModel> deleteWindow = WindowUtil.createAlertWindow("Delete Plugin", "Delete Plugin - " + plugin.getSymbolicName());
        deleteWindow.getComponentModel().setOkClickedListener(event -> {
            if (this.importPluginService.isControllerTypeUsed(plugin.getName())) {
                ViewUtil.iscNotification("SDN Controller Plugin '" + plugin.getName() + "' is used.", Notification.Type.ERROR_MESSAGE);
            } else {
                try {
                    File origin = plugin.getOrigin();
                    if (origin == null) {
                        throw new IllegalStateException(String.format("Install unit %s has no origin file.", plugin.getSymbolicName()));
                    }
                    // Use Java 7 Files.delete(), as it throws an informative exception when deletion fails
                    Files.delete(origin.toPath());
                } catch (Exception e) {
                    ViewUtil.showError("Fail to remove Plugin '" + plugin.getSymbolicName() + "'", e);
                }
            }
            deleteWindow.close();
        });
        ViewUtil.addWindow(deleteWindow);
    }

    private UploadSucceededListener getUploadSucceededListener() {
        return new UploadSucceededListener() {

            @Override
            public void uploadComplete(String uploadPath) {
                try {
                    ImportFileRequest importRequest = new ImportFileRequest(uploadPath);
                    PluginsLayout.this.importPluginService.dispatch(importRequest);
                    ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_PLUGIN_SUCCESSFUL), null, Notification.Type.TRAY_NOTIFICATION);
                } catch (Exception e) {
                    PluginsLayout.this.log.info(e.getMessage());
                    ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
                }
            }
        };
    }

    @Override
    public void detach() {
        this.registration.unregister();
        super.detach();
    }
}

18 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);
        }
    }
}

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

public clreplaced NetworkLayout extends FormLayout {

    private static final long serialVersionUID = 1L;

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

    public Table networkTable = null;

    private Button editNATSettings = null;

    public Table natTable;

    private GetNetworkSettingsServiceApi getNetworkSettingsService;

    private CheckNetworkSettingsServiceApi checkNetworkSettingsService;

    private GetNATSettingsServiceApi getNATSettingsService;

    private SetNATSettingsServiceApi setNATSettingsService;

    private ValidationApi validator;

    private ServerApi server;

    public NetworkLayout(GetNetworkSettingsServiceApi getNetworkSettingsService, CheckNetworkSettingsServiceApi checkNetworkSettingsService, SetNetworkSettingsServiceApi setNetworkSettingsService, GetNATSettingsServiceApi getNATSettingsService, SetNATSettingsServiceApi setNATSettingsService, ValidationApi validator, ServerApi server) {
        super();
        this.getNetworkSettingsService = getNetworkSettingsService;
        this.checkNetworkSettingsService = checkNetworkSettingsService;
        this.getNATSettingsService = getNATSettingsService;
        this.setNATSettingsService = setNATSettingsService;
        this.server = server;
        this.validator = validator;
        try {
            // creating layout to hold option group and edit button
            HorizontalLayout optionLayout = new HorizontalLayout();
            optionLayout.addStyleName(StyleConstants.COMPONENT_SPACING_TOP_BOTTOM);
            Panel networkPanel = new Panel("IP Details");
            VerticalLayout networkLayout = new VerticalLayout();
            Panel networkPanelDHCP = new Panel("DHCP");
            networkTable = createNetworkTable();
            networkLayout.addComponent(networkTable);
            networkPanelDHCP.setContent(networkLayout);
            networkPanel.setContent(networkPanelDHCP);
            Panel natPanel = new Panel("NAT Details");
            VerticalLayout natLayout = new VerticalLayout();
            HorizontalLayout editNatLayout = new HorizontalLayout();
            HorizontalLayout dhcpLayout = new HorizontalLayout();
            dhcpLayout.addStyleName("network-options");
            dhcpLayout.setEnabled(false);
            dhcpLayout.setImmediate(true);
            optionLayout.addComponent(dhcpLayout);
            editNatLayout.addStyleName(StyleConstants.COMPONENT_SPACING_TOP_BOTTOM);
            editNatLayout.addComponent(createNATEditButton());
            natLayout.addComponent(editNatLayout);
            this.natTable = createNATTable();
            natLayout.addComponent(this.natTable);
            natLayout.addStyleName(StyleConstants.COMPONENT_SPACING_TOP_BOTTOM);
            natPanel.setContent(natLayout);
            // populating Network Information in the Table
            populateNetworkTable();
            // populating NAT information in the Table
            populateNATTable();
            addComponent(networkPanel);
            addComponent(natPanel);
        } catch (Exception ex) {
            log.error("Failed to get network settings", ex);
        }
    }

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

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

    @SuppressWarnings("serial")
    private void editNATSettingsClicked() throws Exception {
        try {
            if (!hasDeployedInstances()) {
                ViewUtil.addWindow(new SetNATSettingsWindow(this, this.setNATSettingsService, this.validator, this.server));
            } else {
                final VmidcWindow<OkCancelButtonModel> alertWindow = WindowUtil.createAlertWindow(VmidcMessages.getString(VmidcMessages_.NW_CHANGE_WARNING_replacedLE), VmidcMessages.getString(VmidcMessages_.NW_CHANGE_WARNING));
                alertWindow.getComponentModel().setOkClickedListener(new ClickListener() {

                    @Override
                    public void buttonClick(ClickEvent event) {
                        alertWindow.close();
                        try {
                            ViewUtil.addWindow(new SetNATSettingsWindow(NetworkLayout.this, NetworkLayout.this.setNATSettingsService, NetworkLayout.this.validator, NetworkLayout.this.server));
                        } catch (Exception e) {
                            ViewUtil.showError("Error displaying NAT setting window", e);
                        }
                    }
                });
                ViewUtil.addWindow(alertWindow);
            }
        } catch (Exception e) {
            log.error("Failed to check if NAT settings can be changed. Launching edit settings window", e);
            ViewUtil.addWindow(new SetNATSettingsWindow(this, this.setNATSettingsService, this.validator, this.server));
        }
    }

    private boolean hasDeployedInstances() throws Exception {
        CheckNetworkSettingResponse response = this.checkNetworkSettingsService.dispatch(new Request() {
        });
        return response.hasDeployedInstances();
    }

    private Table createNetworkTable() {
        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 network table with empty values
        table.addItem(new Object[] { "IPv4 Address: ", "" }, new Integer(1));
        table.addItem(new Object[] { "Netmask:", "" }, new Integer(2));
        table.addItem(new Object[] { "Default Gateway: ", "" }, new Integer(3));
        table.addItem(new Object[] { "Primary DNS Server: ", "" }, new Integer(4));
        table.addItem(new Object[] { "Secondary DNS Server: ", "" }, new Integer(5));
        return table;
    }

    private Table createNATTable() {
        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 network table with empty values
        table.addItem(new Object[] { "Public IPv4 Address: ", "" }, new Integer(1));
        return table;
    }

    @SuppressWarnings("unchecked")
    public void populateNetworkTable() {
        try {
            GetNetworkSettingsRequest getNetworkSettingsRequest = new GetNetworkSettingsRequest();
            GetNetworkSettingsResponse getNetworkSettingsResponse = this.getNetworkSettingsService.dispatch(getNetworkSettingsRequest);
            this.networkTable.gereplacedem(1).gereplacedemProperty("Value").setValue(getNetworkSettingsResponse.getHostIpAddress());
            this.networkTable.gereplacedem(2).gereplacedemProperty("Value").setValue(getNetworkSettingsResponse.getHostSubnetMask());
            this.networkTable.gereplacedem(3).gereplacedemProperty("Value").setValue(getNetworkSettingsResponse.getHostDefaultGateway());
            this.networkTable.gereplacedem(4).gereplacedemProperty("Value").setValue(getNetworkSettingsResponse.getHostDnsServer1());
            this.networkTable.gereplacedem(5).gereplacedemProperty("Value").setValue(getNetworkSettingsResponse.getHostDnsServer2());
        } catch (Exception ex) {
            log.error("Failed to get network settings", ex);
        }
    }

    @SuppressWarnings("unchecked")
    public void populateNATTable() {
        try {
            BaseDtoResponse<NATSettingsDto> response = this.getNATSettingsService.dispatch(new Request() {
            });
            this.natTable.gereplacedem(1).gereplacedemProperty("Value").setValue(response.getDto().getPublicIPAddress());
        } catch (Exception ex) {
            log.error("Failed to get NAT settings", ex);
        }
    }
}

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

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

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

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

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

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.addContainerProperty("Name", String.clreplaced, null);
    table.addContainerProperty("Status", String.clreplaced, null);
    table.setColumnHeaderMode(Table.ColumnHeaderMode.HIDDEN);
    return table;
}

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

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

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

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

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

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

11 Source : NetworkLayout.java
with Apache License 2.0
from opensecuritycontroller

private Table createNATTable() {
    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 network table with empty values
    table.addItem(new Object[] { "Public IPv4 Address: ", "" }, new Integer(1));
    return table;
}

11 Source : NetworkLayout.java
with Apache License 2.0
from opensecuritycontroller

private Table createNetworkTable() {
    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 network table with empty values
    table.addItem(new Object[] { "IPv4 Address: ", "" }, new Integer(1));
    table.addItem(new Object[] { "Netmask:", "" }, new Integer(2));
    table.addItem(new Object[] { "Default Gateway: ", "" }, new Integer(3));
    table.addItem(new Object[] { "Primary DNS Server: ", "" }, new Integer(4));
    table.addItem(new Object[] { "Secondary DNS Server: ", "" }, new Integer(5));
    return table;
}

10 Source : BaseDAWindow.java
with Apache License 2.0
from opensecuritycontroller

public abstract clreplaced BaseDAWindow extends CRUDBaseWindow<OkCancelButtonModel> {

    private static final long serialVersionUID = 1L;

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

    // form fields
    protected TextField name = null;

    protected ComboBox managerConnector = null;

    protected ComboBox applianceDefinition = null;

    protected Panel attributePanel = null;

    protected Table attributes = null;

    protected PreplacedwordField sharedKey;

    protected Table vsTable = null;

    protected DistributedApplianceDto currentDAObject = null;

    private final ListApplianceModelSwVersionComboServiceApi listApplianceModelSwVersionComboService;

    private final ListDomainsByMcIdServiceApi listDomainsByMcIdService;

    private final ListEncapsulationTypeByVersionTypeAndModelApi listEncapsulationTypeByVersionTypeAndModel;

    private final ListApplianceManagerConnectorServiceApi listApplianceManagerConnectorService;

    private final ListVirtualizationConnectorBySwVersionServiceApi listVirtualizationConnectorBySwVersionService;

    private final ValidationApi validator;

    public BaseDAWindow(ListApplianceModelSwVersionComboServiceApi listApplianceModelSwVersionComboService, ListDomainsByMcIdServiceApi listDomainsByMcIdService, ListEncapsulationTypeByVersionTypeAndModelApi listEncapsulationTypeByVersionTypeAndModel, ListApplianceManagerConnectorServiceApi listApplianceManagerConnectorService, ListVirtualizationConnectorBySwVersionServiceApi listVirtualizationConnectorBySwVersionService, ValidationApi validator) {
        super();
        this.listApplianceModelSwVersionComboService = listApplianceModelSwVersionComboService;
        this.listDomainsByMcIdService = listDomainsByMcIdService;
        this.listEncapsulationTypeByVersionTypeAndModel = listEncapsulationTypeByVersionTypeAndModel;
        this.listApplianceManagerConnectorService = listApplianceManagerConnectorService;
        this.listVirtualizationConnectorBySwVersionService = listVirtualizationConnectorBySwVersionService;
        this.validator = validator;
    }

    protected Panel getAttributesPanel() {
        this.sharedKey = new PreplacedwordField();
        this.sharedKey.setRequiredError("shared secret key cannot be empty");
        this.sharedKey.setRequired(true);
        // best show/hide this conditionally based on Manager type.
        this.sharedKey.setValue("dummy1234");
        this.attributes = new Table();
        this.attributes.setPageLength(0);
        this.attributes.setSelectable(true);
        this.attributes.setSizeFull();
        this.attributes.setImmediate(true);
        this.attributes.addContainerProperty("Attribute Name", String.clreplaced, null);
        this.attributes.addContainerProperty("Value", PreplacedwordField.clreplaced, null);
        this.attributes.addItem(new Object[] { "Shared Secret key", this.sharedKey }, new Integer(1));
        // creating panel to store attributes table
        this.attributePanel = new Panel("Common Appliance Configuration Attributes:");
        this.attributePanel.addStyleName("form_Panel");
        this.attributePanel.setWidth(100, Sizeable.Unit.PERCENTAGE);
        this.attributePanel.setContent(this.attributes);
        return this.attributePanel;
    }

    /**
     * @return AZ Panel
     */
    @SuppressWarnings("serial")
    protected Panel getVirtualSystemPanel() {
        try {
            this.vsTable = new Table();
            this.vsTable.setPageLength(5);
            this.vsTable.setImmediate(true);
            this.vsTable.addGeneratedColumn("Enabled", new CheckBoxGenerator());
            this.vsTable.addItemClickListener(new ItemClickListener() {

                @Override
                public void itemClick(ItemClickEvent event) {
                    vsTableClicked((Long) event.gereplacedemId());
                }
            });
            // populating VS table
            populateVirtualSystem();
            Panel vsPanel = new Panel("Virtualization System:");
            vsPanel.addStyleName("form_Panel");
            vsPanel.setWidth(100, Sizeable.Unit.PERCENTAGE);
            vsPanel.setContent(this.vsTable);
            return vsPanel;
        } catch (Exception e) {
            log.error("Error while creating DA's VS panel", e);
        }
        return null;
    }

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

    private List<TagEncapsulationType> getEncapsulationType(ApplianceModelSoftwareVersionDto currentAppliance, VirtualizationType type) throws Exception {
        ListEncapsulationTypeByVersionTypeAndModelRequest req = new ListEncapsulationTypeByVersionTypeAndModelRequest(currentAppliance.getSwVersion(), currentAppliance.getApplianceModel(), type);
        return this.listEncapsulationTypeByVersionTypeAndModel.dispatch(req).getList();
    }

    protected ComboBox getDomainComboBox(Object id) {
        return (ComboBox) this.vsTable.gereplacedem(id).gereplacedemProperty("Manager Domain").getValue();
    }

    protected ComboBox getEncapsulationTypeComboBox(Object id) {
        return (ComboBox) this.vsTable.gereplacedem(id).gereplacedemProperty("Encapsulation Type").getValue();
    }

    @SuppressWarnings("unchecked")
    private void vsTableClicked(long itemId) {
        if (this.vsTable.getContainerProperty(itemId, "Enabled").getValue().equals(true)) {
            this.vsTable.getContainerProperty(itemId, "Enabled").setValue(false);
        } else {
            this.vsTable.getContainerProperty(itemId, "Enabled").setValue(true);
        }
    }

    /**
     * @return MC ComboBox
     */
    @SuppressWarnings("serial")
    protected ComboBox getManagerConnector() {
        try {
            ListResponse<ApplianceManagerConnectorDto> res = this.listApplianceManagerConnectorService.dispatch(new BaseRequest<>());
            BeanItemContainer<ApplianceManagerConnectorDto> mcList = new BeanItemContainer<ApplianceManagerConnectorDto>(ApplianceManagerConnectorDto.clreplaced, res.getList());
            this.managerConnector = new ComboBox("Manager Connector");
            this.managerConnector.setTextInputAllowed(false);
            this.managerConnector.setNullSelectionAllowed(false);
            this.managerConnector.setContainerDataSource(mcList);
            this.managerConnector.sereplacedemCaptionPropertyId("name");
            if (mcList.size() > 0) {
                this.managerConnector.select(mcList.getIdByIndex(0));
            }
            this.managerConnector.setImmediate(true);
            this.managerConnector.setRequired(true);
            this.managerConnector.setRequiredError("Manager Connector cannot be empty");
            this.managerConnector.addValueChangeListener(new ValueChangeListener() {

                @Override
                public void valueChange(ValueChangeEvent event) {
                    ApplianceManagerConnectorDto mcDto = (ApplianceManagerConnectorDto) BaseDAWindow.this.managerConnector.getValue();
                    updateAppliances();
                    updateDomains(mcDto);
                }
            });
        } catch (Exception e) {
            log.error("Error populating MC combobox", e);
        }
        return this.managerConnector;
    }

    @SuppressWarnings("serial")
    protected void updateAppliances() {
        ApplianceManagerConnectorDto currentMC = (ApplianceManagerConnectorDto) this.managerConnector.getValue();
        if (currentMC != null) {
            ListApplianceModelSwVersionComboRequest adRequest = new ListApplianceModelSwVersionComboRequest();
            adRequest.setType(currentMC.getManagerType());
            ListResponse<ApplianceModelSoftwareVersionDto> adResponse = null;
            try {
                adResponse = this.listApplianceModelSwVersionComboService.dispatch(adRequest);
                BeanItemContainer<ApplianceModelSoftwareVersionDto> adList = new BeanItemContainer<ApplianceModelSoftwareVersionDto>(ApplianceModelSoftwareVersionDto.clreplaced, adResponse.getList());
                this.applianceDefinition.setContainerDataSource(adList);
                this.applianceDefinition.sereplacedemCaptionPropertyId("name");
                if (adList.size() > 0) {
                    this.applianceDefinition.select(adList.getIdByIndex(0));
                }
                this.applianceDefinition.addValueChangeListener(new ValueChangeListener() {

                    @Override
                    public void valueChange(ValueChangeEvent event) {
                        try {
                            populateVirtualSystem();
                        } catch (Exception e) {
                            log.error("Error while populating Virtual System Table ", e);
                        }
                    }
                });
            } catch (Exception e) {
                log.error("Error retrieving appliance list", e);
            }
        }
    }

    @SuppressWarnings("unchecked")
    protected void updateDomains(ApplianceManagerConnectorDto mcDto) {
        List<DomainDto> dl = getDomainList(mcDto);
        for (Object itemId : this.vsTable.gereplacedemIds()) {
            ComboBox domainComboBox = createDomainComboBox(dl);
            Item item = this.vsTable.gereplacedem(itemId);
            item.gereplacedemProperty("Manager Domain").setValue(domainComboBox);
        }
    }

    private ComboBox createDomainComboBox(List<DomainDto> dl) {
        ComboBox domainComboBox = new ComboBox();
        BeanItemContainer<DomainDto> domainContainer = new BeanItemContainer<DomainDto>(DomainDto.clreplaced, dl);
        ApplianceManagerConnectorDto mc = (ApplianceManagerConnectorDto) this.managerConnector.getValue();
        domainComboBox.setContainerDataSource(domainContainer);
        domainComboBox.setTextInputAllowed(false);
        domainComboBox.setNullSelectionAllowed(false);
        domainComboBox.sereplacedemCaptionPropertyId("name");
        domainComboBox.setEnabled(mc.isPolicyMappingSupported());
        if (domainComboBox.gereplacedemIds().size() > 0) {
            domainComboBox.select(domainContainer.getIdByIndex(0));
        }
        return domainComboBox;
    }

    private ComboBox createEncapsulationTypeComboBox(VirtualizationType virtualizationType, List<TagEncapsulationType> types) {
        ComboBox encapsulationType = new ComboBox();
        encapsulationType.setTextInputAllowed(false);
        encapsulationType.setNullSelectionAllowed(true);
        BeanItemContainer<TagEncapsulationType> encapsulationTypeContainer = new BeanItemContainer<TagEncapsulationType>(TagEncapsulationType.clreplaced, types);
        encapsulationType.setContainerDataSource(encapsulationTypeContainer);
        ApplianceManagerConnectorDto currentMc = (ApplianceManagerConnectorDto) this.managerConnector.getValue();
        if (!virtualizationType.isOpenstack() || (currentMc != null && !currentMc.isPolicyMappingSupported())) {
            encapsulationType.setEnabled(false);
        }
        return encapsulationType;
    }

    /**
     * @return AD ComboBox
     */
    protected ComboBox getApplianceDefinition() {
        try {
            this.applianceDefinition = new ComboBox("Service Function Definition");
            this.applianceDefinition.setTextInputAllowed(false);
            this.applianceDefinition.setNullSelectionAllowed(false);
            this.applianceDefinition.setRequired(true);
            this.applianceDefinition.setRequiredError("Service Function Definition cannot be Empty");
            this.applianceDefinition.setWidth(100, Unit.PERCENTAGE);
            updateAppliances();
        } catch (Exception e) {
            log.error("Error populating appliance list combobox", e);
        }
        return this.applianceDefinition;
    }

    protected List<DomainDto> getDomainList(ApplianceManagerConnectorDto mc) {
        if (mc != null) {
            ListResponse<DomainDto> response = new ListResponse<DomainDto>();
            try {
                // List Domains Service
                BaseIdRequest agRequest = new BaseIdRequest();
                agRequest.setId(mc.getId());
                response = this.listDomainsByMcIdService.dispatch(agRequest);
            } catch (Exception e) {
                log.error("Error populating domain combobox", e);
            }
            return response.getList();
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public boolean validateForm() {
        try {
            this.name.validate();
            if (!this.validator.isValidDaName(this.name.getValue().toString())) {
                ViewUtil.iscNotification("DA name must not exceed 13 characters, must start with a letter,  and can only contain numbers, letters and dash(-).", Notification.Type.ERROR_MESSAGE);
                return false;
            }
            this.managerConnector.validate();
            this.applianceDefinition.validate();
            this.sharedKey.validate();
            int rowCount = 0;
            ApplianceManagerConnectorDto mcDto = (ApplianceManagerConnectorDto) this.managerConnector.getValue();
            for (Object id : this.vsTable.gereplacedemIds()) {
                if (this.vsTable.getContainerProperty(id, "Enabled").getValue().equals(true)) {
                    rowCount++;
                    DomainDto domainDto = (DomainDto) getDomainComboBox(id).getValue();
                    if (domainDto == null && mcDto.isPolicyMappingSupported()) {
                        ViewUtil.iscNotification("Please ensure domain is selected.", Notification.Type.ERROR_MESSAGE);
                        return false;
                    }
                    VirtualizationType vsType = VirtualizationType.fromText((String) this.vsTable.getContainerProperty(id, "Type").getValue());
                    TagEncapsulationType tag = (TagEncapsulationType) getEncapsulationTypeComboBox(id).getValue();
                    if (vsType.isOpenstack() && mcDto.isPolicyMappingSupported()) {
                        if (tag == null) {
                            ViewUtil.iscNotification("Please ensure Encapsulation type is selected.", Notification.Type.ERROR_MESSAGE);
                            return false;
                        }
                    } else {
                        if (tag != null) {
                            ViewUtil.iscNotification("Please ensure Encapsulation type is selected only for Openstack Virtual Systems.", Notification.Type.ERROR_MESSAGE);
                            return false;
                        }
                    }
                }
            }
            if (rowCount <= 0) {
                ViewUtil.iscNotification("Please select one or more Virtualization System for creating this DA.", Notification.Type.ERROR_MESSAGE);
                return false;
            }
            return true;
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage() + ".", Notification.Type.ERROR_MESSAGE);
        }
        return false;
    }

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

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

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

public abstract clreplaced BaseDeploymentSpecWindow extends LoadingIndicatorCRUDBaseWindow {

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

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

    protected static final String AVAILABILITY_ZONES = "By Availability Zone";

    protected static final String HOSTS = "By Host";

    protected static final String HOST_AGGREGATES = "By Host Aggregates";

    protected static final String NONE = "All (Hosts in selected Region)";

    protected DeploymentSpecDto deploymentSpecDto;

    private ValueChangeListener projectChangedListener;

    private ValueChangeListener regionChangedListener;

    protected TextField name;

    protected IntStepper count;

    protected CheckBox shared;

    protected ComboBox region;

    protected ComboBox floatingIpPool;

    protected ComboBox project;

    protected OptionGroup userOption;

    protected Table optionTable;

    protected ComboBox managementNetwork;

    protected ComboBox inspectionNetwork;

    protected Long vsId;

    protected Panel optionPanel;

    private final ListAvailabilityZonesServiceApi listAvailabilityZonesService;

    private final ListFloatingIpPoolsServiceApi listFloatingIpPoolsService;

    private final ListHostAggregateServiceApi listHostAggregateService;

    private final ListHostServiceApi listHostService;

    private final ListNetworkServiceApi listNetworkService;

    private final ListRegionServiceApi listRegionService;

    private final ListProjectServiceApi listProjectService;

    public BaseDeploymentSpecWindow(DeploymentSpecDto deploymentSpecDto, ListAvailabilityZonesServiceApi listAvailabilityZonesService, ListFloatingIpPoolsServiceApi listFloatingIpPoolsService, ListHostServiceApi listHostService, ListHostAggregateServiceApi listHostAggregateService, ListNetworkServiceApi listNetworkService, ListRegionServiceApi listRegionService, ListProjectServiceApi listProjectService) {
        this.deploymentSpecDto = deploymentSpecDto;
        this.listAvailabilityZonesService = listAvailabilityZonesService;
        this.listFloatingIpPoolsService = listFloatingIpPoolsService;
        this.listNetworkService = listNetworkService;
        this.listRegionService = listRegionService;
        this.listProjectService = listProjectService;
        this.listHostService = listHostService;
        this.listHostAggregateService = listHostAggregateService;
        this.vsId = deploymentSpecDto.getParentId();
        initListeners();
    }

    @Override
    public void initForm() {
        this.form.addComponent(getName());
        this.form.addComponent(getProjects());
        this.form.addComponent(getRegion());
        this.form.addComponent(getUserOptions());
        this.form.addComponent(getOptionTable());
        List<ComboBox> networks = getNetworkComboBoxes();
        for (ComboBox combobox : networks) {
            this.form.addComponent(combobox);
        }
        this.form.addComponent(getIPPool());
        this.form.addComponent(getCount());
        this.form.addComponent(getSharedCheckBox());
        this.name.focus();
        getCount().setEnabled(false);
    }

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

    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 Component getProjects() {
        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;
    }

    @SuppressWarnings("serial")
    protected OptionGroup getUserOptions() {
        this.userOption = new OptionGroup("Selection Criterion:");
        this.userOption.addItem(NONE);
        this.userOption.addItem(AVAILABILITY_ZONES);
        this.userOption.addItem(HOST_AGGREGATES);
        this.userOption.addItem(HOSTS);
        this.userOption.select(NONE);
        this.userOption.addValueChangeListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                populateOptionTable();
            }
        });
        return this.userOption;
    }

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

    protected ComboBox getIPPool() {
        this.floatingIpPool = new ComboBox("Select Floating IP Pool");
        this.floatingIpPool.setTextInputAllowed(false);
        this.floatingIpPool.setNullSelectionAllowed(true);
        this.floatingIpPool.setImmediate(true);
        this.floatingIpPool.setRequired(false);
        return this.floatingIpPool;
    }

    protected List<ComboBox> getNetworkComboBoxes() {
        List<ComboBox> networkComboBox = new ArrayList<>();
        this.managementNetwork = new ComboBox("Select Management Network");
        this.managementNetwork.setTextInputAllowed(false);
        this.managementNetwork.setNullSelectionAllowed(false);
        this.managementNetwork.setImmediate(true);
        this.managementNetwork.setRequired(true);
        this.managementNetwork.setRequiredError("Management Network cannot be empty");
        networkComboBox.add(this.managementNetwork);
        this.inspectionNetwork = new ComboBox("Select Inspection Network");
        this.inspectionNetwork.setTextInputAllowed(false);
        this.inspectionNetwork.setNullSelectionAllowed(false);
        this.inspectionNetwork.setImmediate(true);
        this.inspectionNetwork.setRequired(true);
        this.inspectionNetwork.setRequiredError("Inspection Network cannot be empty");
        networkComboBox.add(this.inspectionNetwork);
        return networkComboBox;
    }

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

    private List<OsNetworkDto> getNetworks() {
        try {
            OsProjectDto selectedProject = (OsProjectDto) this.project.getValue();
            if (selectedProject != null && this.region.getValue() != null) {
                // Calling List Network Service
                BaseOpenStackRequest req = new BaseOpenStackRequest();
                req.setId(this.vsId);
                req.setRegion((String) this.region.getValue());
                req.setProjectName(selectedProject.getName());
                req.setProjectId(selectedProject.getId());
                List<OsNetworkDto> res = this.listNetworkService.dispatch(req).getList();
                return res;
            }
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
            log.error("Error getting Network List", e);
        }
        return null;
    }

    @SuppressWarnings("serial")
    protected Panel getOptionTable() {
        this.optionTable = new Table();
        this.optionTable.setPageLength(3);
        this.optionTable.setSizeFull();
        this.optionTable.setImmediate(true);
        this.optionTable.addGeneratedColumn("Enabled", new CheckBoxGenerator());
        this.optionTable.addContainerProperty("Name", String.clreplaced, null);
        this.optionTable.addItemClickListener(new ItemClickListener() {

            @Override
            public void itemClick(ItemClickEvent event) {
                optionTableClicked(event);
            }
        });
        this.optionPanel = new Panel();
        this.optionPanel.addStyleName(StyleConstants.FORM_PANEL);
        this.optionPanel.setWidth(100, Sizeable.Unit.PERCENTAGE);
        this.optionPanel.setContent(this.optionTable);
        return this.optionPanel;
    }

    protected IntStepper getCount() {
        if (this.count == null) {
            this.count = new IntStepper("Deployment Count");
            this.count.setImmediate(true);
            this.count.setValue(1);
            this.count.setStepAmount(1);
            this.count.setMinValue(1);
            this.count.setRequiredError("Instance Count cannot be empty");
        }
        return this.count;
    }

    protected CheckBox getSharedCheckBox() {
        this.shared = new CheckBox("Shared");
        this.shared.setValue(true);
        this.shared.setImmediate(true);
        return this.shared;
    }

    private void populateProjects(boolean autoSelect) {
        try {
            // Calling List Service
            BaseIdRequest req = new BaseIdRequest();
            req.setId(this.vsId);
            List<OsProjectDto> projectList = this.listProjectService.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 && projectListContainer.size() > 0) {
                this.project.select(projectListContainer.getIdByIndex(0));
            }
        } 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.regionChangedListener);
                this.region.removeAllItems();
                BaseOpenStackRequest req = new BaseOpenStackRequest();
                req.setProjectName(projectDto.getName());
                req.setId(this.vsId);
                ListResponse<String> response = this.listRegionService.dispatch(req);
                this.region.addItems(response.getList());
                this.region.addValueChangeListener(this.regionChangedListener);
                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 populateOptionTable() {
        try {
            this.form.replaceComponent(this.optionPanel, getOptionTable());
            OsProjectDto selectedProject = (OsProjectDto) this.project.getValue();
            if (selectedProject != null && this.region.getValue() != null) {
                BaseOpenStackRequest req = new BaseOpenStackRequest();
                req.setId(this.vsId);
                req.setProjectName(selectedProject.getName());
                req.setProjectId(selectedProject.getId());
                req.setRegion((String) this.region.getValue());
                // creating Option Table
                this.optionTable.addContainerProperty("Enabled", Boolean.clreplaced, false);
                // remove previous columns
                this.optionTable.removeAllItems();
                if (this.userOption.getValue() == AVAILABILITY_ZONES) {
                    getCount().setValue(1);
                    getCount().setEnabled(false);
                    ListResponse<AvailabilityZoneDto> res = this.listAvailabilityZonesService.dispatch(req);
                    for (AvailabilityZoneDto az : res.getList()) {
                        this.optionTable.addItem(new Object[] { az.getZone() }, az);
                    }
                } else if (this.userOption.getValue() == HOSTS) {
                    getCount().setEnabled(true);
                    ListResponse<HostDto> res = this.listHostService.dispatch(req);
                    for (HostDto host : res.getList()) {
                        this.optionTable.addItem(new Object[] { host.getName() }, host);
                    }
                } else if (this.userOption.getValue() == HOST_AGGREGATES) {
                    getCount().setValue(1);
                    getCount().setEnabled(false);
                    ListResponse<HostAggregateDto> res = this.listHostAggregateService.dispatch(req);
                    for (HostAggregateDto hostAggr : res.getList()) {
                        this.optionTable.addItem(new Object[] { hostAggr.getName() }, hostAggr);
                    }
                } else {
                    getCount().setValue(1);
                    getCount().setEnabled(false);
                }
                this.optionTable.sort(new Object[] { "Name" }, new boolean[] { true });
            } else {
                this.optionTable.removeAllItems();
            }
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
            log.error("Failed to get Option Table", e);
        }
    }

    private void populateFloatingPool() {
        this.floatingIpPool.removeAllItems();
        try {
            OsProjectDto selectedProject = (OsProjectDto) this.project.getValue();
            if (selectedProject != null && this.region.getValue() != null) {
                BaseOpenStackRequest req = new BaseOpenStackRequest();
                req.setId(this.vsId);
                req.setProjectName(selectedProject.getName());
                req.setProjectId(selectedProject.getId());
                req.setRegion((String) this.region.getValue());
                List<String> floatingIpPoolList = this.listFloatingIpPoolsService.dispatch(req).getList();
                if (floatingIpPoolList.size() > 0) {
                    this.floatingIpPool.addItems(floatingIpPoolList);
                }
            }
        } catch (ExtensionNotPresentException notPresentException) {
            ViewUtil.iscNotification(notPresentException.getMessage(), Notification.Type.WARNING_MESSAGE);
            log.warn("Failed to get IP Pool", notPresentException);
        } catch (Exception e) {
            ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
            log.error("Failed to get IP Pool", e);
        }
    }

    @Override
    public boolean validateForm() {
        this.name.validate();
        // UI validation empty Selection while using AZ/Host deployment mode
        if (this.userOption.getValue().equals(AVAILABILITY_ZONES) || this.userOption.getValue().equals(HOSTS) || this.userOption.getValue().equals(HOST_AGGREGATES)) {
            int count = 0;
            for (Object id : this.optionTable.gereplacedemIds()) {
                if (this.optionTable.getContainerProperty(id, "Enabled").getValue().equals(true)) {
                    count++;
                }
            }
            if (count == 0) {
                ViewUtil.iscNotification("Atleast one selection is Required!", Notification.Type.ERROR_MESSAGE);
                return false;
            }
        }
        this.project.validate();
        this.region.validate();
        this.managementNetwork.validate();
        this.inspectionNetwork.validate();
        this.floatingIpPool.validate();
        return true;
    }

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

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

    @SuppressWarnings("unchecked")
    private void optionTableClicked(ItemClickEvent event) {
        if (this.userOption.getValue() == NONE) {
            return;
        }
        Object itemId = 0L;
        if (this.userOption.getValue() == AVAILABILITY_ZONES) {
            itemId = event.gereplacedemId();
        } else if (this.userOption.getValue() == HOSTS) {
            itemId = event.gereplacedemId();
        } else if (this.userOption.getValue() == HOST_AGGREGATES) {
            itemId = event.gereplacedemId();
        }
        if (this.optionTable.getContainerProperty(itemId, "Enabled").getValue().equals(true)) {
            this.optionTable.getContainerProperty(itemId, "Enabled").setValue(false);
        } else {
            this.optionTable.getContainerProperty(itemId, "Enabled").setValue(true);
        }
    }

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

            @Override
            public void valueChange(ValueChangeEvent event) {
                if (BaseDeploymentSpecWindow.this.region != null) {
                    populateRegion();
                }
                if (BaseDeploymentSpecWindow.this.managementNetwork != null && BaseDeploymentSpecWindow.this.inspectionNetwork != null) {
                    List<OsNetworkDto> networks = getNetworks();
                    populateNetworks(BaseDeploymentSpecWindow.this.managementNetwork, networks);
                    populateNetworks(BaseDeploymentSpecWindow.this.inspectionNetwork, networks);
                }
                if (BaseDeploymentSpecWindow.this.floatingIpPool != null) {
                    populateFloatingPool();
                }
            }
        };
        this.regionChangedListener = new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                if (BaseDeploymentSpecWindow.this.optionTable != null) {
                    populateOptionTable();
                }
            }
        };
    }

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