Here are the examples of the java api com.vaadin.ui.Panel taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
19 Examples
19
Source : BaseDAWindow.java
with Apache License 2.0
from opensecuritycontroller
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);
}
}
}
19
Source : BaseDAWindow.java
with Apache License 2.0
from opensecuritycontroller
with Apache License 2.0
from opensecuritycontroller
/**
* @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;
}
19
Source : BaseVCWindow.java
with Apache License 2.0
from opensecuritycontroller
with Apache License 2.0
from opensecuritycontroller
public abstract clreplaced BaseVCWindow extends CRUDBaseWindow<OkCancelButtonModel> {
private static final String OPENSTACK_ICEHOUSE = "Icehouse";
private static final String KUBERNETES_1_6 = "v1.6";
/**
*/
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(BaseVCWindow.clreplaced);
public static final String DEFAULT_HTTPS = "false";
public static final String DEFAULT_RABBITMQ_USER = "guest";
public static final String DEFAULT_RABBITMQ_USER_PreplacedWORD = "guest";
public static final String DEFAULT_RABBITMQ_PORT = "5672";
protected static final String SHOW_ADVANCED_SETTINGS_CAPTION = VmidcMessages.getString(VmidcMessages_.SHOW_ADVANCED);
protected static final String KEYSTONE_CAPTION = VmidcMessages.getString(VmidcMessages_.KEYSTONE);
protected static final String SDN_CONTROLLER_CAPTION = "SDN Controller";
protected static final String OPENSTACK_CAPTION = VmidcMessages.getString(VmidcMessages_.KEYSTONE);
protected Map<String, String> providerAttributes = new HashMap<>();
protected List<ErrorType> errorTypesToIgnore = new ArrayList<>();
private HashSet<SslCertificateAttrDto> sslCertificateAttrs = new HashSet<>();
// current view referencecurrentVCObject
protected VirtualizationConnectorView vcView = null;
protected BeanItem<VirtualizationConnectorDto> currentVCObject = null;
// form fields
protected TextField name = null;
protected ComboBox virtualizationType = null;
// Controller input fields
protected TextField controllerIP = null;
protected TextField controllerUser = null;
protected PreplacedwordField controllerPW = null;
// Provider input fields
protected TextField providerIP = null;
protected TextField adminDomainId = null;
protected TextField adminProjectName = null;
protected TextField providerUser = null;
protected PreplacedwordField providerPW = null;
// Open stack Input Fields
protected ComboBox controllerType = null;
// All Panels
protected Panel controllerPanel = null;
protected Panel providerPanel = null;
protected Button advancedSettings = null;
private final PluginService pluginService;
private final ValidationApi validator;
private final X509TrustManagerApi trustManager;
public BaseVCWindow(PluginService pluginService, ValidationApi validator, X509TrustManagerApi trustManager) {
super();
this.pluginService = pluginService;
this.validator = validator;
this.trustManager = trustManager;
}
@Override
public boolean validateForm() {
try {
this.name.validate();
this.virtualizationType.validate();
if (this.virtualizationType.getValue().toString().equals(VirtualizationType.OPENSTACK.toString())) {
String controllerType = (String) BaseVCWindow.this.controllerType.getValue();
if (!NO_CONTROLLER_TYPE.equals(controllerType) && !this.pluginService.usesProviderCreds(controllerType)) {
this.controllerIP.validate();
this.validator.checkValidIpAddress(this.controllerIP.getValue());
this.controllerUser.validate();
this.controllerPW.validate();
}
}
this.providerIP.validate();
this.validator.checkValidIpAddress(this.providerIP.getValue());
if (this.adminDomainId.isVisible()) {
this.adminDomainId.validate();
}
if (this.adminProjectName.isVisible()) {
this.adminProjectName.validate();
}
this.providerUser.validate();
this.providerPW.validate();
return true;
} catch (Exception e) {
ViewUtil.iscNotification(e.getMessage() + ".", Notification.Type.ERROR_MESSAGE);
}
return false;
}
protected void buildForm() {
this.name = new TextField("Name");
this.name.setImmediate(true);
this.virtualizationType = new ComboBox("Type");
this.virtualizationType.setTextInputAllowed(false);
this.virtualizationType.setNullSelectionAllowed(false);
for (VirtualizationType virtualizationType : VirtualizationType.values()) {
this.virtualizationType.addItem(virtualizationType.toString());
}
this.virtualizationType.select(VirtualizationType.OPENSTACK.toString());
// adding not null constraint
this.name.setRequired(true);
this.name.setRequiredError("Name cannot be empty");
this.virtualizationType.setRequired(true);
this.virtualizationType.setRequiredError("Type cannot be empty");
this.form.setMargin(true);
this.form.setSizeUndefined();
this.form.addComponent(this.name);
this.name.focus();
this.form.addComponent(this.virtualizationType);
this.form.addComponent(controllerPanel());
this.form.addComponent(providerPanel());
this.advancedSettings = new Button(SHOW_ADVANCED_SETTINGS_CAPTION);
this.advancedSettings.setImmediate(true);
this.advancedSettings.setVisible(false);
this.advancedSettings.addClickListener(new ClickListener() {
/**
*/
private static final long serialVersionUID = 7124022733079327543L;
@Override
public void buttonClick(ClickEvent event) {
advancedSettingsClicked();
}
});
this.form.addComponent(this.advancedSettings);
}
// Returns OpenStack form
protected Panel providerPanel() {
this.providerPanel = new Panel();
this.providerPanel.setImmediate(true);
this.providerPanel.setCaption(OPENSTACK_CAPTION);
this.providerIP = new TextField("IP");
this.providerIP.setImmediate(true);
this.adminDomainId = new TextField("Admin Domain Id");
this.adminDomainId.setImmediate(true);
this.adminProjectName = new TextField("Admin Project Name");
this.adminProjectName.setImmediate(true);
this.providerUser = new TextField("User Name");
this.providerUser.setImmediate(true);
this.providerPW = new PreplacedwordField("Preplacedword");
this.providerPW.setImmediate(true);
// adding not null constraint
this.adminDomainId.setRequired(true);
this.adminDomainId.setRequiredError(this.providerPanel.getCaption() + " Admin Domain Id cannot be empty");
this.adminProjectName.setRequired(true);
this.adminProjectName.setRequiredError(this.providerPanel.getCaption() + " Admin Project Name cannot be empty");
this.providerIP.setRequired(true);
this.providerIP.setRequiredError(this.providerPanel.getCaption() + " IP cannot be empty");
this.providerUser.setRequired(true);
this.providerUser.setRequiredError(this.providerPanel.getCaption() + " User Name cannot be empty");
this.providerPW.setRequired(true);
this.providerPW.setRequiredError(this.providerPanel.getCaption() + " Preplacedword cannot be empty");
FormLayout providerFormPanel = new FormLayout();
providerFormPanel.addComponent(this.providerIP);
providerFormPanel.addComponent(this.adminDomainId);
providerFormPanel.addComponent(this.adminProjectName);
providerFormPanel.addComponent(this.providerUser);
providerFormPanel.addComponent(this.providerPW);
this.providerPanel.setContent(providerFormPanel);
return this.providerPanel;
}
protected Panel controllerPanel() {
this.controllerPanel = new Panel();
this.controllerPanel.setImmediate(true);
this.controllerPanel.setCaption(SDN_CONTROLLER_CAPTION);
this.controllerType = new ComboBox("Type");
this.controllerType.setTextInputAllowed(false);
this.controllerType.setNullSelectionAllowed(false);
this.controllerType.addItem(NO_CONTROLLER_TYPE);
for (String ct : this.pluginService.getControllerTypes()) {
this.controllerType.addItem(ct);
}
this.controllerType.setVisible(true);
this.controllerIP = new TextField("IP");
this.controllerIP.setImmediate(true);
this.controllerUser = new TextField("User Name");
this.controllerUser.setImmediate(true);
this.controllerPW = new PreplacedwordField("Preplacedword");
this.controllerPW.setImmediate(true);
// adding not null constraint
this.controllerIP.setRequired(true);
this.controllerIP.setRequiredError(this.controllerPanel.getCaption() + " IP cannot be empty");
this.controllerUser.setRequired(true);
this.controllerUser.setRequiredError(this.controllerPanel.getCaption() + " User Name cannot be empty");
this.controllerPW.setRequired(true);
this.controllerPW.setRequiredError(this.controllerPanel.getCaption() + " Preplacedword cannot be empty");
FormLayout sdn = new FormLayout();
sdn.addComponent(this.controllerType);
sdn.addComponent(this.controllerIP);
sdn.addComponent(this.controllerUser);
sdn.addComponent(this.controllerPW);
this.controllerPanel.setContent(sdn);
this.controllerType.addValueChangeListener(event -> updateControllerFields((String) BaseVCWindow.this.controllerType.getValue()));
this.controllerType.select(NO_CONTROLLER_TYPE);
return this.controllerPanel;
}
protected void handleException(final Exception originalException) {
String caption = VmidcMessages.getString(VmidcMessages_.VC_CONFIRM_CAPTION);
String contentText = null;
final Throwable exception;
if (originalException instanceof ErrorTypeException) {
ErrorType errorType = ((ErrorTypeException) originalException).getType();
exception = originalException.getCause();
// TODO this exception leaks large amounts of implementation detail out of the API
if (isOpenstack()) {
switch(errorType) {
case PROVIDER_EXCEPTION:
if (RestClientException.isConnectException(exception)) {
// Keystone Connect Exception
contentText = VmidcMessages.getString(VmidcMessages_.VC_CONFIRM_IP, KEYSTONE_CAPTION);
} else {
contentText = VmidcMessages.getString(VmidcMessages_.VC_CONFIRM_GENERAL, KEYSTONE_CAPTION, exception.getMessage());
}
break;
case PROVIDER_CONNECT_EXCEPTION:
contentText = VmidcMessages.getString(VmidcMessages_.VC_CONFIRM_IP, KEYSTONE_CAPTION);
break;
case PROVIDER_AUTH_EXCEPTION:
contentText = VmidcMessages.getString(VmidcMessages_.VC_CONFIRM_CREDS, KEYSTONE_CAPTION);
break;
case CONTROLLER_EXCEPTION:
contentText = handleControllerException(exception);
break;
case RABBITMQ_EXCEPTION:
contentText = VmidcMessages.getString(VmidcMessages_.VC_CONFIRM_RABBIT, exception.getMessage());
break;
case IP_CHANGED_EXCEPTION:
contentText = VmidcMessages.getString(VmidcMessages_.VC_WARNING_IPUPDATE);
break;
default:
contentText = VmidcMessages.getString(VmidcMessages_.VC_CONFIRM_GENERAL, KEYSTONE_CAPTION, exception.getMessage());
break;
}
}
} else if (originalException instanceof RestClientException) {
RestClientException rce = (RestClientException) originalException;
handleCatchAllException(new Exception(VmidcMessages.getString(VmidcMessages_.GENERAL_REST_ERROR, rce.getHost(), rce.getMessage()), originalException));
return;
} else {
exception = originalException;
}
if (contentText != null) {
final VmidcWindow<OkCancelButtonModel> alertWindow = WindowUtil.createAlertWindow(caption, contentText);
alertWindow.getComponentModel().setOkClickedListener(event -> {
try {
if (originalException instanceof ErrorTypeException) {
ErrorType errorType = ((ErrorTypeException) originalException).getType();
BaseVCWindow.this.errorTypesToIgnore.add(errorType);
}
submitForm();
} catch (Exception e) {
handleException(e);
}
alertWindow.close();
});
ViewUtil.addWindow(alertWindow);
} else {
handleCatchAllException(exception);
}
}
private boolean isOpenstack() {
return VirtualizationType.fromText(this.virtualizationType.getValue().toString()) == VirtualizationType.OPENSTACK;
}
private String handleControllerException(Throwable exception) {
String contentText = null;
if (RestClientException.isCredentialError(exception)) {
// SDN Invalid Credential Exception
contentText = VmidcMessages.getString(VmidcMessages_.VC_CONFIRM_CREDS, this.controllerType.getValue().toString());
} else if (RestClientException.isConnectException(exception)) {
// SDN Controller Connect Exception
contentText = VmidcMessages.getString(VmidcMessages_.VC_CONFIRM_IP, this.controllerType.getValue().toString());
} else {
// SDN Controller Connect Exception
contentText = VmidcMessages.getString(VmidcMessages_.VC_CONFIRM_GENERAL, this.controllerType.getValue().toString(), exception.getMessage());
}
return contentText;
}
void sslAwareHandleException(final Exception originalException) {
if (!(originalException instanceof SslCertificatesExtendedException)) {
handleException(originalException);
return;
}
SslCertificatesExtendedException unknownException = (SslCertificatesExtendedException) originalException;
ArrayList<CertificateResolverModel> certificateResolverModels = unknownException.getCertificateResolverModels();
try {
ViewUtil.addWindow(new AddSSLCertificateWindow(certificateResolverModels, new AddSSLCertificateWindow.SSLCertificateWindowInterface() {
@Override
public void submitFormAction(ArrayList<CertificateResolverModel> certificateResolverModels) {
if (certificateResolverModels != null) {
BaseVCWindow.this.sslCertificateAttrs.addAll(certificateResolverModels.stream().map(crm -> new SslCertificateAttrDto(crm.getAlias(), crm.getSha1())).collect(Collectors.toList()));
}
}
@Override
public void cancelFormAction() {
handleException(originalException);
}
}, this.trustManager));
} catch (Exception e) {
handleException(originalException);
}
}
/**
* Create and submits the add connector request.
*/
protected DryRunRequest<VirtualizationConnectorRequest> createRequest() throws Exception {
DryRunRequest<VirtualizationConnectorRequest> request = new DryRunRequest<>();
request.setDto(new VirtualizationConnectorRequest());
VirtualizationConnectorDto dto = request.getDto();
dto.setName(this.name.getValue().trim());
VirtualizationType virtualizationTypeValue = VirtualizationType.fromText(((String) this.virtualizationType.getValue()).trim());
dto.setType(virtualizationTypeValue);
dto.setControllerIP(this.controllerIP.getValue().trim());
dto.setControllerUser(this.controllerUser.getValue().trim());
dto.setControllerPreplacedword(this.controllerPW.getValue().trim());
dto.setProviderIP(this.providerIP.getValue().trim());
dto.setProviderUser(this.providerUser.getValue().trim());
dto.setProviderPreplacedword(this.providerPW.getValue().trim());
dto.setSslCertificateAttrSet(this.sslCertificateAttrs);
String domainId = this.adminDomainId.getValue();
if (domainId != null) {
dto.setAdminDomainId(domainId.trim());
}
String projectName = this.adminProjectName.getValue();
if (projectName != null) {
dto.setAdminProjectName(projectName.trim());
}
if (virtualizationTypeValue.equals(VirtualizationType.OPENSTACK)) {
dto.setProviderAttributes(this.providerAttributes);
}
request.addErrorsToIgnore(this.errorTypesToIgnore);
// TODO: Future. Get virtualization version this from user.
if (this.virtualizationType.getValue().equals(VirtualizationType.OPENSTACK.toString())) {
request.getDto().setSoftwareVersion(OPENSTACK_ICEHOUSE);
} else {
request.getDto().setSoftwareVersion(KUBERNETES_1_6);
}
request.getDto().setControllerType((String) BaseVCWindow.this.controllerType.getValue());
return request;
}
protected void advancedSettingsClicked() {
try {
ViewUtil.addWindow(new AdvancedSettingsWindow(this));
} catch (Exception e) {
ViewUtil.iscNotification(e.toString() + ".", Notification.Type.ERROR_MESSAGE);
}
}
protected void updateForm(String type) {
this.controllerIP.setValue("");
this.controllerUser.setValue("");
this.controllerPW.setValue("");
this.controllerPanel.setVisible(true);
if (type.equals(VirtualizationType.OPENSTACK.toString())) {
this.controllerPanel.setCaption(SDN_CONTROLLER_CAPTION);
this.providerPanel.setCaption(OPENSTACK_CAPTION);
this.controllerType.setVisible(true);
this.controllerType.setValue(NO_CONTROLLER_TYPE);
updateControllerFields(NO_CONTROLLER_TYPE);
this.adminDomainId.setVisible(true);
this.adminProjectName.setVisible(true);
this.advancedSettings.setVisible(true);
this.advancedSettings.setCaption(SHOW_ADVANCED_SETTINGS_CAPTION);
updateProviderFields();
}
this.controllerIP.setRequiredError(this.controllerPanel.getCaption() + " IP cannot be empty");
this.controllerUser.setRequiredError(this.controllerPanel.getCaption() + " User Name cannot be empty");
this.controllerPW.setRequiredError(this.controllerPanel.getCaption() + " Preplacedword cannot be empty");
this.providerIP.setRequiredError(this.providerPanel.getCaption() + " IP cannot be empty");
this.providerUser.setRequiredError(this.providerPanel.getCaption() + " User Name cannot be empty");
this.providerPW.setRequiredError(this.providerPanel.getCaption() + " Preplacedword cannot be empty");
this.adminDomainId.setRequiredError(this.providerPanel.getCaption() + " Admin Domain Id cannot be empty");
this.adminProjectName.setRequiredError(this.providerPanel.getCaption() + " Admin Project Name cannot be empty");
}
private void updateControllerFields(String type) {
boolean enableFields = false;
if (!type.equals(NO_CONTROLLER_TYPE)) {
try {
enableFields = !this.pluginService.usesProviderCreds(type.toString());
} catch (Exception e) {
log.error("Fail to get controller plugin instance", e);
}
}
BaseVCWindow.this.controllerIP.setEnabled(enableFields);
BaseVCWindow.this.controllerIP.setRequired(enableFields);
BaseVCWindow.this.controllerUser.setEnabled(enableFields);
BaseVCWindow.this.controllerUser.setRequired(enableFields);
BaseVCWindow.this.controllerPW.setEnabled(enableFields);
BaseVCWindow.this.controllerPW.setRequired(enableFields);
if (!enableFields) {
this.controllerIP.setValue("");
this.controllerUser.setValue("");
this.controllerPW.setValue("");
}
}
private void updateProviderFields() {
if (BaseVCWindow.this.virtualizationType.getValue().equals(VirtualizationType.OPENSTACK.toString())) {
// If user does not click advanced Settings we need to populate attributes with default values..
this.providerAttributes.put(ATTRIBUTE_KEY_HTTPS, DEFAULT_HTTPS);
this.providerAttributes.put(ATTRIBUTE_KEY_RABBITMQ_USER, DEFAULT_RABBITMQ_USER);
this.providerAttributes.put(ATTRIBUTE_KEY_RABBITMQ_PORT, DEFAULT_RABBITMQ_PORT);
this.providerAttributes.put(ATTRIBUTE_KEY_RABBITMQ_USER_PreplacedWORD, DEFAULT_RABBITMQ_USER_PreplacedWORD);
}
}
}
19
Source : PluginView.java
with Apache License 2.0
from opensecuritycontroller
with Apache License 2.0
from opensecuritycontroller
private VerticalLayout createComponent(String caption, String replacedle, FormLayout content, String guid) {
VerticalLayout tabSheet = new VerticalLayout();
Panel panel = new Panel();
// creating subHeader inside panel
panel.setContent(content);
panel.setSizeFull();
tabSheet.addComponent(ViewUtil.createSubHeader(replacedle, guid));
tabSheet.addComponent(panel);
return tabSheet;
}
19
Source : MaintenanceView.java
with Apache License 2.0
from opensecuritycontroller
with Apache License 2.0
from opensecuritycontroller
private VerticalLayout createTab(String caption, String replacedle, FormLayout content, String guid) {
VerticalLayout tabSheet = new VerticalLayout();
tabSheet.setCaption(caption);
tabSheet.setStyleName(StyleConstants.TAB_SHEET);
Panel panel = new Panel();
// creating subHeader inside panel
panel.setContent(content);
panel.setSizeFull();
tabSheet.addComponent(ViewUtil.createSubHeader(replacedle, guid));
tabSheet.addComponent(panel);
return tabSheet;
}
19
Source : SslCertificateUploader.java
with Apache License 2.0
from opensecuritycontroller
with Apache License 2.0
from opensecuritycontroller
protected void layout(Panel panel) {
createUpload();
this.verLayout.setSpacing(true);
panel.setWidth("100%");
panel.setContent(this.verLayout);
this.verLayout.addComponent(this.upload);
this.verLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
}
19
Source : PluginUploader.java
with Apache License 2.0
from opensecuritycontroller
with Apache License 2.0
from opensecuritycontroller
@SuppressWarnings("serial")
public clreplaced PluginUploader extends CustomComponent implements Receiver, FailedListener, SucceededListener {
private static final Logger log = LoggerFactory.getLogger(PluginUploader.clreplaced);
private static int TEMP_FOLDER_COUNTER = 0;
private final Upload upload;
private File file;
private final Panel panel = new Panel();
private final VerticalLayout verLayout = new VerticalLayout();
private String uploadPath;
private final ServerApi server;
public interface UploadSucceededListener {
void uploadComplete(String uploadPath);
}
private UploadSucceededListener uploadSucceededListener;
public PluginUploader(ServerApi server) {
this.server = server;
this.upload = new Upload();
this.upload.setButtonCaption("Upload");
this.upload.setReceiver(this);
this.upload.addFailedListener(this);
this.upload.addSucceededListener(this);
this.upload.setImmediate(false);
final UploadInfoWindow uploadInfoWindow = new UploadInfoWindow(this.upload);
this.upload.addStartedListener(new StartedListener() {
@Override
public void uploadStarted(final StartedEvent event) {
if (uploadInfoWindow.getParent() == null) {
ViewUtil.addWindow(uploadInfoWindow);
}
}
});
this.verLayout.setSpacing(true);
this.verLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
this.verLayout.addComponent(this.upload);
this.panel.setWidth("100%");
this.panel.setContent(this.verLayout);
setCompositionRoot(this.panel);
}
@Override
public OutputStream receiveUpload(String filename, String mimeType) {
if (filename == null || filename.isEmpty()) {
return null;
}
log.info("Start uploading file: " + filename);
try {
if (validateFileExtension(filename)) {
this.uploadPath = getTemporaryUploadPath();
File uploadDirectory = new File(this.uploadPath);
if (!uploadDirectory.exists()) {
FileUtils.forceMkdir(uploadDirectory);
}
this.file = new File(this.uploadPath + filename);
return new FileOutputStream(this.file);
}
} catch (Exception e) {
log.error("Error opening file: " + filename, e);
ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_COMMON_ERROR) + e.getMessage(), Notification.Type.ERROR_MESSAGE);
}
return null;
}
/**
* Gets the upload path for the file. If isTmpFolder is set to true, returns a unique temporary upload file path.
* If it is set to false it returns the actual image upload folder.
*
* @param isTmpFolder
* the temporary path the file is uploaded before being moved to the actual image path
*
* @return the temporary path when isTmpFolder is set to true
* the image path when isTmpFolder is set to false
*/
private static String getTemporaryUploadPath() {
String uploadPath = "tmp" + TEMP_FOLDER_COUNTER++ + File.separator;
return uploadPath;
}
@Override
public void uploadSucceeded(SucceededEvent event) {
log.info("Upload Successful! replacedyzing Uploaded Image.....");
try {
// Do the unzip only if there is enough disc space
if (!this.server.isEnoughSpace()) {
String message = VmidcMessages.getString(VmidcMessages_.UPLOAD_PLUGIN_NOSPACE);
throw new VmidcException(message);
}
if (!validateFileExtension(this.file.getName())) {
String message = VmidcMessages.getString(VmidcMessages_.UPLOAD_PLUGIN_FAILED);
throw new VmidcException(message);
}
if (this.uploadSucceededListener != null) {
this.uploadSucceededListener.uploadComplete(this.uploadPath);
}
} catch (Exception e) {
log.error("Failed to unzip uploaded zip file", e);
try {
FileUtils.deleteDirectory(new File(this.uploadPath));
} catch (IOException ex) {
log.error("Failed to cleanup the tmp directory", ex);
}
this.uploadPath = null;
ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
}
}
@Override
public void uploadFailed(FailedEvent event) {
if (event.getFilename() == null || event.getFilename().isEmpty()) {
String message = VmidcMessages.getString(VmidcMessages_.UPLOAD_PLUGIN_NOFILE);
ViewUtil.iscNotification(message, Notification.Type.ERROR_MESSAGE);
} else if (event.getReason() instanceof UploadInterruptedException) {
log.warn(event.getFilename().toString() + " Plugin upload is cancelled by the user");
} else {
String message = VmidcMessages.getString(VmidcMessages_.UPLOAD_PLUGIN_FAILED);
ViewUtil.iscNotification(message, Notification.Type.WARNING_MESSAGE);
}
if (this.uploadPath != null) {
File uploadDirectory = new File(this.uploadPath);
if (uploadDirectory.exists()) {
try {
FileUtils.deleteDirectory(uploadDirectory);
} catch (IOException e) {
log.error("Deleting upload directory: " + this.uploadPath + " failed when upload was cancelled by user.", e);
}
}
}
}
private boolean validateFileExtension(String fileName) {
String extension = FilenameUtils.getExtension(fileName);
return extension.equals("bar");
}
public void addSucceededListener(UploadSucceededListener uploadSucceededListener) {
this.uploadSucceededListener = uploadSucceededListener;
}
public String getUploadPath() {
return this.uploadPath;
}
}
19
Source : PluginsLayout.java
with Apache License 2.0
from opensecuritycontroller
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();
}
}
19
Source : JobsArchiverPanel.java
with Apache License 2.0
from opensecuritycontroller
with Apache License 2.0
from opensecuritycontroller
public clreplaced JobsArchiverPanel extends CustomComponent {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(JobsArchiverPanel.clreplaced);
private VerticalLayout container = null;
private Label triggerLabel = new Label("Triggering:");
private String lastTriggerLabelText = "Last Triggered Timestamp: ";
private Label lastTriggerTimestampLabel = null;
private OptionGroup freqOpt = null;
private CheckBox autoSchedChkBox = null;
private Label thresholdLabel = new Label("Archive Jobs/Alerts older than the last: ");
private OptionGroup thresOpt = null;
private IntStepper archiveThreshold = null;
private Panel panel = new Panel();
private Button updateButton = null;
private Button onDemandButton = null;
private final String TEXT_FREQ_OPT_WEEKLY = "Weekly";
private final String ID_FREQ_OPT_WEEKLY = "WEEKLY";
private final String TEXT_FREQ_OPT_MONTHLY = "Monthly";
private final String ID_FREQ_OPT_MONTHLY = "MONTHLY";
private final String TEXT_THRES_OPT_MONTHS = "Months";
private final String ID_THRES_OPT_MONTHS = "MONTHS";
private final String TEXT_THRES_OPT_YEARS = "Years";
private final String ID_THRES_OPT_YEARS = "YEARS";
private final String UPDATE_SCHED_BUTTON_LABEL = "Update Schedule";
private final String ON_DEMAND_BUTTON_LABEL = "On Demand";
private String ARCHIVE_STYLE = "archive-options";
private JobsArchiveDto dto;
private final ArchiveLayout parentLayout;
private final ArchiveServiceApi archiveService;
private final GetJobsArchiveServiceApi getJobsArchiveService;
private final UpdateJobsArchiveServiceApi updateJobsArchiveService;
public JobsArchiverPanel(ArchiveLayout parentLayout, ArchiveServiceApi archiveService, GetJobsArchiveServiceApi getJobsArchiveService, UpdateJobsArchiveServiceApi updateJobsArchiveService) {
super();
this.parentLayout = parentLayout;
this.archiveService = archiveService;
this.getJobsArchiveService = getJobsArchiveService;
this.updateJobsArchiveService = updateJobsArchiveService;
try {
this.dto = populateJobsArchiveDto().getDto();
// create frequency layout component
VerticalLayout freqLayout = new VerticalLayout();
freqLayout.addComponent(createLastTriggerLabel());
freqLayout.addComponent(createAutoSchedCheckBox());
freqLayout.addComponent(createFrequencyOptionGroup());
freqLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
freqLayout.setSpacing(true);
// create triggering panel component
Panel triggerPanel = new Panel();
triggerPanel.setWidth("50%");
triggerPanel.setContent(freqLayout);
// create threshold layout component
HorizontalLayout thresLayout = new HorizontalLayout();
thresLayout.addComponent(this.thresholdLabel);
thresLayout.addComponent(createArchiveThreshold());
thresLayout.addComponent(createThresholdOptionGroup());
thresLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
thresLayout.setSpacing(true);
// add all components to container
this.container = new VerticalLayout();
this.container.addStyleName(StyleConstants.COMPONENT_SPACING);
this.container.addComponent(this.triggerLabel);
this.container.addComponent(triggerPanel);
this.container.addComponent(thresLayout);
// add buttons component to container
HorizontalLayout buttonLayout = new HorizontalLayout();
buttonLayout.addComponent(createOnDemandScheduleButton());
buttonLayout.addComponent(createUpdateScheduleButton());
buttonLayout.setSpacing(true);
this.container.addComponent(buttonLayout);
// add container to root panel
this.container.setSpacing(true);
this.panel.setWidth("100%");
this.panel.setContent(this.container);
setCompositionRoot(this.panel);
} catch (Exception ex) {
log.error("Failed to init archiver panel", ex);
}
}
private BaseDtoResponse<JobsArchiveDto> populateJobsArchiveDto() throws Exception {
BaseDtoResponse<JobsArchiveDto> res = this.getJobsArchiveService.dispatch(new Request() {
});
return res;
}
Integer convertToPositiveIntegerOrNull(String strVal) {
Integer val = null;
try {
val = Integer.parseInt(strVal);
} catch (Exception ex) {
return null;
}
if (val < 0) {
return null;
}
return val;
}
private Label createLastTriggerLabel() {
String lastTriggerTimestamp = "None";
this.lastTriggerTimestampLabel = new Label();
if (this.dto != null && this.dto.getLastTriggerTimestamp() != null) {
lastTriggerTimestamp = this.dto.getLastTriggerTimestamp().toString();
}
this.lastTriggerTimestampLabel.setCaption(this.lastTriggerLabelText + lastTriggerTimestamp);
return this.lastTriggerTimestampLabel;
}
private CheckBox createAutoSchedCheckBox() {
this.autoSchedChkBox = new CheckBox("Auto Schedule");
this.autoSchedChkBox.setImmediate(true);
if (this.dto == null) {
this.autoSchedChkBox.setValue(false);
} else {
boolean isAuto = this.dto.getAutoSchedule();
this.autoSchedChkBox.setValue(isAuto);
}
return this.autoSchedChkBox;
}
private OptionGroup createFrequencyOptionGroup() {
this.freqOpt = new OptionGroup();
this.freqOpt.addItem(this.ID_FREQ_OPT_WEEKLY);
this.freqOpt.sereplacedemCaption(this.ID_FREQ_OPT_WEEKLY, this.TEXT_FREQ_OPT_WEEKLY);
this.freqOpt.addItem(this.ID_FREQ_OPT_MONTHLY);
this.freqOpt.sereplacedemCaption(this.ID_FREQ_OPT_MONTHLY, this.TEXT_FREQ_OPT_MONTHLY);
this.freqOpt.addStyleName(this.ARCHIVE_STYLE);
this.freqOpt.setImmediate(true);
if (this.dto == null) {
this.freqOpt.select(this.ID_FREQ_OPT_MONTHLY);
} else {
this.freqOpt.select(this.dto.getFrequency());
}
return this.freqOpt;
}
private IntStepper createArchiveThreshold() {
this.archiveThreshold = new IntStepper();
if (this.dto == null) {
this.archiveThreshold.setValue(3);
} else {
this.archiveThreshold.setValue(this.dto.getThresholdValue());
}
this.archiveThreshold.setStepAmount(1);
this.archiveThreshold.setMinValue(1);
this.archiveThreshold.setRequiredError("Archive threshold cannot be empty");
return this.archiveThreshold;
}
private OptionGroup createThresholdOptionGroup() {
this.thresOpt = new OptionGroup();
this.thresOpt.addItem(this.ID_THRES_OPT_MONTHS);
this.thresOpt.sereplacedemCaption(this.ID_THRES_OPT_MONTHS, this.TEXT_THRES_OPT_MONTHS);
this.thresOpt.addItem(this.ID_THRES_OPT_YEARS);
this.thresOpt.sereplacedemCaption(this.ID_THRES_OPT_YEARS, this.TEXT_THRES_OPT_YEARS);
this.thresOpt.addStyleName(this.ARCHIVE_STYLE);
this.thresOpt.setImmediate(true);
if (this.dto == null) {
this.thresOpt.select(this.ID_THRES_OPT_MONTHS);
} else {
this.thresOpt.select(this.dto.getThresholdUnit());
}
return this.thresOpt;
}
@SuppressWarnings("serial")
private Button createUpdateScheduleButton() {
this.updateButton = new Button(this.UPDATE_SCHED_BUTTON_LABEL);
this.updateButton.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
try {
BaseRequest<JobsArchiveDto> request = new BaseRequest<JobsArchiveDto>();
request.setDto(new JobsArchiveDto());
request.getDto().setId(JobsArchiverPanel.this.dto.getId());
request.getDto().setAutoSchedule(JobsArchiverPanel.this.autoSchedChkBox.getValue());
request.getDto().setFrequency(JobsArchiverPanel.this.freqOpt.getValue().toString());
request.getDto().setThresholdUnit(JobsArchiverPanel.this.thresOpt.getValue().toString());
request.getDto().setThresholdValue(JobsArchiverPanel.this.archiveThreshold.getValue());
JobsArchiverPanel.this.updateJobsArchiveService.dispatch(request);
JobsArchiverPanel.this.archiveService.maybeScheduleArchiveJob();
ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.MAINTENANCE_JOBSARCHIVE_SUBMIT_SUCCESSFUL), null, Notification.Type.TRAY_NOTIFICATION);
} catch (Exception e) {
log.error("Fail to update archive schedule", e);
ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.MAINTENANCE_JOBSARCHIVE_SUBMIT_FAILED), Notification.Type.ERROR_MESSAGE);
}
}
});
return this.updateButton;
}
@SuppressWarnings("serial")
private Button createOnDemandScheduleButton() {
this.onDemandButton = new Button(this.ON_DEMAND_BUTTON_LABEL);
this.onDemandButton.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
JobsArchiverPanel.this.onDemandButton.setEnabled(false);
ViewUtil.iscNotification("On demand archiving started in the background", null, Notification.Type.TRAY_NOTIFICATION);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
BaseRequest<JobsArchiveDto> request = new BaseRequest<JobsArchiveDto>();
request.setDto(new JobsArchiveDto());
request.getDto().setFrequency(JobsArchiverPanel.this.freqOpt.getValue().toString());
request.getDto().setThresholdUnit(JobsArchiverPanel.this.thresOpt.getValue().toString());
request.getDto().setThresholdValue(JobsArchiverPanel.this.archiveThreshold.getValue());
try {
JobsArchiverPanel.this.archiveService.dispatch(request);
ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.MAINTENANCE_JOBSARCHIVE_ONDEMAND_SUCCESSFUL), null, Notification.Type.TRAY_NOTIFICATION);
JobsArchiverPanel.this.parentLayout.buildArchivesTable();
JobsArchiverPanel.this.onDemandButton.setEnabled(true);
} catch (Exception e) {
ViewUtil.showError("Error starting on demand archiving", e);
}
}
});
thread.start();
}
});
return this.onDemandButton;
}
}
19
Source : InternalCertReplacementUploader.java
with Apache License 2.0
from opensecuritycontroller
with Apache License 2.0
from opensecuritycontroller
@Override
protected void layout(Panel panel) {
Label warningLabel = new Label(getString(KEYPAIR_UPLOAD_WARN_RESTART));
this.verLayout.addComponent(warningLabel);
super.layout(panel);
}
19
Source : DbRestorer.java
with Apache License 2.0
from opensecuritycontroller
with Apache License 2.0
from opensecuritycontroller
@SuppressWarnings("serial")
public clreplaced DbRestorer extends CustomComponent implements Receiver, FailedListener, SucceededListener {
private static final Logger log = LoggerFactory.getLogger(DbRestorer.clreplaced);
private final Upload upload;
private File file;
private final Panel panel = new Panel();
private final VerticalLayout verLayout = new VerticalLayout();
private final RestoreServiceApi restoreService;
private final ServerApi server;
private final ValidationApi validator;
public DbRestorer(RestoreServiceApi restoreService, ServerApi server, ValidationApi validator) {
this.restoreService = restoreService;
this.server = server;
this.validator = validator;
this.upload = new Upload();
this.upload.setButtonCaption(VmidcMessages.getString(VmidcMessages_.UPLOAD_RESTORE));
this.upload.setReceiver(this);
this.upload.addFailedListener(this);
this.upload.addSucceededListener(this);
this.upload.setImmediate(false);
final UploadInfoWindow uploadInfoWindow = new UploadInfoWindow(this.upload);
this.upload.addStartedListener(new StartedListener() {
@Override
public void uploadStarted(final StartedEvent event) {
if (uploadInfoWindow.getParent() == null) {
ViewUtil.addWindow(uploadInfoWindow);
}
}
});
this.verLayout.setSpacing(true);
this.panel.setWidth("100%");
this.panel.setContent(this.verLayout);
this.verLayout.addComponent(this.upload);
this.verLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
setCompositionRoot(this.panel);
}
@Override
public OutputStream receiveUpload(String filename, String mimeType) {
if (filename == null || filename.isEmpty()) {
return null;
}
// validate uploaded file is a zip file or encrypted backup file
if (!this.restoreService.isValidBackupFilename(filename)) {
ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_RESTORE_INVALID_BACKUP, this.server.getProductName()), Notification.Type.WARNING_MESSAGE);
return null;
}
log.info("Start uploading file: " + filename);
try {
this.file = new File(filename);
return new FileOutputStream(this.file);
} catch (final java.io.FileNotFoundException e) {
log.error("Error opening file: " + filename, e);
ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_COMMON_ERROR) + e.getMessage(), Notification.Type.ERROR_MESSAGE);
}
return null;
}
@Override
public void uploadSucceeded(SucceededEvent event) {
log.info("Upload Successful! Restoring Database ......");
try {
PreplacedwordWindow.SubmitFormListener restoreAction = preplacedword -> {
RestoreRequest req = new RestoreRequest();
req.setBkpFile(this.file);
req.setPreplacedword(preplacedword);
try {
this.restoreService.dispatch(req);
ViewUtil.iscNotification("Upload", VmidcMessages.getString(VmidcMessages_.UPLOAD_RESTORE_UPLOAD_STARTED, this.server.getProductName()), Notification.Type.WARNING_MESSAGE);
} catch (Exception e) {
log.error("Restore Service Failed.", e);
ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
} finally {
// We can delete the uploaded file now since it has been extracted.
this.file.delete();
}
};
if (this.restoreService.isValidEncryptedBackupFilename(event.getFilename())) {
// ask user for decryption preplacedword first
PreplacedwordWindow preplacedwordWindow = new PreplacedwordWindow(this.validator);
preplacedwordWindow.setSubmitFormListener(restoreAction);
ViewUtil.addWindow(preplacedwordWindow);
} else if (this.restoreService.isValidZipBackupFilename(event.getFilename())) {
// perform restore without decryption
restoreAction.submit(null);
}
} catch (Exception e) {
log.error("Restore Service Failed.", e);
// ensure that uploaded file is deleted
this.file.delete();
ViewUtil.iscNotification(e.getMessage(), Notification.Type.ERROR_MESSAGE);
}
}
@Override
public void uploadFailed(FailedEvent event) {
if (event.getFilename() == null || event.getFilename().isEmpty()) {
ViewUtil.iscNotification(VmidcMessages.getString("upload.restore.nofile"), Notification.Type.ERROR_MESSAGE);
} else if (event.getReason() instanceof UploadInterruptedException) {
log.warn("Database backup Upload is cancelled by the user");
} else {
ViewUtil.iscNotification(VmidcMessages.getString("upload.restore.invalid.backup"), Notification.Type.WARNING_MESSAGE);
}
}
}
19
Source : ApplianceUploader.java
with Apache License 2.0
from opensecuritycontroller
with Apache License 2.0
from opensecuritycontroller
@SuppressWarnings("serial")
public clreplaced ApplianceUploader extends CustomComponent implements Receiver, FailedListener {
static final String OVF_UPLOAD_PATH = "data" + File.separator + "ovf" + File.separator;
private static final Logger log = LoggerFactory.getLogger(ApplianceUploader.clreplaced);
private static int TEMP_FOLDER_COUNTER = 0;
private final Upload upload;
private File file;
private final Panel panel = new Panel();
private final VerticalLayout verLayout = new VerticalLayout();
private String uploadPath;
public ApplianceUploader() {
this.upload = new Upload();
this.upload.setButtonCaption(null);
this.upload.setReceiver(this);
this.upload.addFailedListener(this);
this.upload.setImmediate(false);
final UploadInfoWindow uploadInfoWindow = new UploadInfoWindow(this.upload);
this.upload.addStartedListener(new StartedListener() {
@Override
public void uploadStarted(final StartedEvent event) {
if (uploadInfoWindow.getParent() == null) {
ViewUtil.addWindow(uploadInfoWindow);
}
}
});
this.verLayout.setSpacing(true);
this.verLayout.addStyleName(StyleConstants.COMPONENT_SPACING);
this.verLayout.addComponent(this.upload);
this.panel.setWidth("100%");
this.panel.setContent(this.verLayout);
setCompositionRoot(this.panel);
}
public Upload getUpload() {
return this.upload;
}
@Override
public OutputStream receiveUpload(String filename, String mimeType) {
if (filename == null || filename.isEmpty()) {
return null;
}
log.info("Start uploading file: " + filename);
try {
if (validateZipFile(filename)) {
this.uploadPath = getUploadPath(true);
File uploadDirectory = new File(this.uploadPath);
if (!uploadDirectory.exists()) {
FileUtils.forceMkdir(uploadDirectory);
}
this.file = new File(this.uploadPath + filename);
return new FileOutputStream(this.file);
}
} catch (Exception e) {
log.error("Error opening file: " + filename, e);
ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_COMMON_ERROR) + e.getMessage(), Notification.Type.ERROR_MESSAGE);
}
return null;
}
public static String getImageFolderPath() {
return getUploadPath(false);
}
public String getUploadPath() {
return this.uploadPath;
}
/**
* Gets the upload path for the file. If isTmpFolder is set to true, returns a unique temporary upload file path.
* If it is set to false it returns the actual image upload folder.
*
* @param isTmpFolder
* the temporary path the file is uploaded before being moved to the actual image path
*
* @return the temporary path when isTmpFolder is set to true
* the image path when isTmpFolder is set to false
*/
public static String getUploadPath(boolean isTmpFolder) {
String uploadPath = "";
uploadPath += OVF_UPLOAD_PATH;
if (isTmpFolder) {
uploadPath += "tmp" + TEMP_FOLDER_COUNTER++ + File.separator;
}
return uploadPath;
}
@Override
public void uploadFailed(FailedEvent event) {
if (event.getFilename() == null || event.getFilename().isEmpty()) {
ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_APPLIANCE_NOFILE), Notification.Type.ERROR_MESSAGE);
} else if (event.getReason() instanceof UploadInterruptedException) {
log.warn("Appliance Image upload is cancelled by the user");
} else {
ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_APPLIANCE_FAILED), Notification.Type.ERROR_MESSAGE);
}
if (this.uploadPath != null) {
File uploadDirectory = new File(this.uploadPath);
if (uploadDirectory.exists()) {
try {
FileUtils.deleteDirectory(uploadDirectory);
} catch (IOException e) {
log.error("Deleting upload directory: " + this.uploadPath + " failed when upload was cancelled by user.", e);
}
}
}
}
private boolean validateZipFile(String fileName) {
return FilenameUtils.getExtension(fileName).equals("zip");
}
}
19
Source : BaseDeploymentSpecWindow.java
with Apache License 2.0
from opensecuritycontroller
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;
}
}
19
Source : TRAbstractPanel.java
with Apache License 2.0
from ijazfx
with Apache License 2.0
from ijazfx
protected Component createContent() {
MVerticalLayout content = new MVerticalLayout();
content.setSizeFull();
MVerticalLayout contentLayout = new MVerticalLayout().withFullWidth().withStyleName("content-layout");
contentLayout.setSizeFull();
addComponentsToContentLayout(contentLayout);
Panel detailsWrapper = new Panel(contentLayout);
detailsWrapper.setSizeFull();
detailsWrapper.addStyleName(ValoTheme.PANEL_BORDERLESS);
detailsWrapper.addStyleName("scroll-divider");
content.addComponent(detailsWrapper);
content.setExpandRatio(detailsWrapper, 1f);
content.addComponent(buildFooter());
return content;
}
19
Source : TRAbstractForm.java
with Apache License 2.0
from ijazfx
with Apache License 2.0
from ijazfx
@Override
protected Component createContent() {
MVerticalLayout content = new MVerticalLayout().withMargin(true);
content.setSizeFull();
MVerticalLayout contentLayout = new MVerticalLayout().withStyleName("content-layout");
contentLayout.setSizeFull();
contentLayout.add(getFormComponent());
Panel detailsWrapper = new Panel(contentLayout);
detailsWrapper.setSizeFull();
detailsWrapper.addStyleName(ValoTheme.PANEL_BORDERLESS);
detailsWrapper.addStyleName("scroll-divider");
content.addComponent(detailsWrapper);
content.setExpandRatio(detailsWrapper, 1f);
content.addComponent(buildFooter());
return content;
}
19
Source : MeetingCalendar.java
with Apache License 2.0
from blackbluegl
with Apache License 2.0
from blackbluegl
public clreplaced MeetingCalendar extends CustomComponent {
private final Random R = new Random(0);
private MeetingDataProvider eventProvider;
private Calendar<MeetingItem> calendar;
public Panel panel;
public MeetingCalendar() {
setId("meeting-meetings");
setSizeFull();
initCalendar();
VerticalLayout layout = new VerticalLayout();
layout.setMargin(false);
layout.setSpacing(false);
layout.setSizeFull();
panel = new Panel(calendar);
panel.setHeight(100, Unit.PERCENTAGE);
layout.addComponent(panel);
setCompositionRoot(layout);
}
public void switchToMonth(Month month) {
calendar.withMonth(month);
}
public Calendar<MeetingItem> getCalendar() {
return calendar;
}
private void onCalendarRangeSelect(CalendarComponentEvents.RangeSelectEvent event) {
Meeting meeting = new Meeting(!event.getStart().truncatedTo(DAYS).equals(event.getEnd().truncatedTo(DAYS)));
meeting.setStart(event.getStart());
meeting.setEnd(event.getEnd());
meeting.setName("A Name");
meeting.setDetails("A Detail<br>with HTML<br> with more lines");
// Random state
meeting.setState(R.nextInt(2) == 1 ? Meeting.State.planned : Meeting.State.confirmed);
eventProvider.addItem(new MeetingItem(meeting));
}
private void onCalendarClick(CalendarComponentEvents.ItemClickEvent event) {
MeetingItem item = (MeetingItem) event.getCalendarItem();
final Meeting meeting = item.getMeeting();
Notification.show(meeting.getName(), meeting.getDetails(), Type.HUMANIZED_MESSAGE);
}
private void initCalendar() {
eventProvider = new MeetingDataProvider();
calendar = new Calendar<>(eventProvider);
calendar.addStyleName("meetings");
calendar.setWidth(100.0f, Unit.PERCENTAGE);
calendar.setHeight(100.0f, Unit.PERCENTAGE);
calendar.setResponsive(true);
calendar.sereplacedemCaptionAsHtml(true);
calendar.setContentMode(ContentMode.HTML);
// calendar.setLocale(Locale.replacedAN);
// calendar.setZoneId(ZoneId.of("America/Chicago"));
// calendar.setWeeklyCaptionProvider(date -> "<br>" + DateTimeFormatter.ofPattern("dd.MM.YYYY", getLocale()).format(date));
// calendar.setWeeklyCaptionProvider(date -> DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(getLocale()).format(date));
calendar.withVisibleDays(1, 7);
// calendar.withMonth(ZonedDateTime.now().getMonth());
// calendar.setStartDate(ZonedDateTime.of(2017, 9, 10, 0,0,0, 0, calendar.getZoneId()));
// calendar.setEndDate(ZonedDateTime.of(2017, 9, 16, 0,0,0, 0, calendar.getZoneId()));
addCalendarEventListeners();
setupBlockedTimeSlots();
addStyledBlocks();
}
private void addStyledBlocks() {
final LocalDate yesterday = LocalDate.now().minusDays(1);
final long start = LocalTime.of(8, 0).getLong(ChronoField.MILLI_OF_DAY);
final long end = LocalTime.of(23, 0).getLong(ChronoField.MILLI_OF_DAY);
calendar.addTimeBlock(yesterday, start, end, "custom");
}
private void setupBlockedTimeSlots() {
java.util.Calendar cal = java.util.Calendar.getInstance();
// ! clear would not reset the hour of day !
cal.set(java.util.Calendar.HOUR_OF_DAY, 0);
cal.clear(java.util.Calendar.MINUTE);
cal.clear(java.util.Calendar.SECOND);
cal.clear(java.util.Calendar.MILLISECOND);
GregorianCalendar bcal = new GregorianCalendar(UI.getCurrent().getLocale());
bcal.clear();
long start = bcal.getTimeInMillis();
bcal.add(java.util.Calendar.HOUR, 7);
bcal.add(java.util.Calendar.MINUTE, 30);
long end = bcal.getTimeInMillis();
calendar.addTimeBlock(start, end, "blocked");
cal.add(java.util.Calendar.DAY_OF_WEEK, 1);
bcal.clear();
bcal.add(java.util.Calendar.HOUR, 14);
bcal.add(java.util.Calendar.MINUTE, 30);
start = bcal.getTimeInMillis();
bcal.add(java.util.Calendar.MINUTE, 60);
end = bcal.getTimeInMillis();
calendar.addTimeBlock(start, end, "blocked");
}
private void addCalendarEventListeners() {
calendar.setHandler(new BasicDateClickHandler(true));
calendar.setHandler(this::onCalendarClick);
calendar.setHandler(this::onCalendarRangeSelect);
}
private final clreplaced MeetingDataProvider extends BasicItemProvider<MeetingItem> {
void removeAllEvents() {
this.itemList.clear();
fireItemSetChanged();
}
}
}
19
Source : GiftcardUI.java
with Apache License 2.0
from AxonIQ
with Apache License 2.0
from AxonIQ
private Panel bulkIssuePanel() {
TextField number = new TextField("Number");
TextField amount = new TextField("Amount");
Button submit = new Button("Submit");
Panel panel = new Panel("Bulk issue cards");
submit.addClickListener(evt -> {
submit.setEnabled(false);
new BulkIssuer(commandGateway, Integer.parseInt(number.getValue()), Integer.parseInt(amount.getValue()), bulkIssuer -> {
access(() -> {
if (bulkIssuer.getRemaining().get() == 0) {
submit.setEnabled(true);
panel.setCaption("Bulk issue cards");
Notification.show("Bulk issue card completed", Notification.Type.HUMANIZED_MESSAGE).addCloseListener(e -> cardSummaryDataProvider.refreshAll());
} else {
panel.setCaption(String.format("Progress: %d suc, %d fail, %d rem", bulkIssuer.getSuccess().get(), bulkIssuer.getError().get(), bulkIssuer.getRemaining().get()));
cardSummaryDataProvider.refreshAll();
}
});
});
});
FormLayout form = new FormLayout();
form.addComponents(number, amount, submit);
form.setMargin(true);
panel.setContent(form);
return panel;
}
19
Source : GiftcardUI.java
with Apache License 2.0
from AxonIQ
with Apache License 2.0
from AxonIQ
private Panel redeemPanel() {
TextField id = new TextField("Card id");
TextField amount = new TextField("Amount");
Button submit = new Button("Submit");
submit.addClickListener(evt -> {
commandGateway.sendAndWait(new RedeemCmd(id.getValue(), Integer.parseInt(amount.getValue())));
Notification.show("Success", Notification.Type.HUMANIZED_MESSAGE).addCloseListener(e -> cardSummaryDataProvider.refreshAll());
});
FormLayout form = new FormLayout();
form.addComponents(id, amount, submit);
form.setMargin(true);
Panel panel = new Panel("Redeem card");
panel.setContent(form);
return panel;
}
19
Source : GiftcardUI.java
with Apache License 2.0
from AxonIQ
with Apache License 2.0
from AxonIQ
private Panel issuePanel() {
TextField id = new TextField("Card id");
TextField amount = new TextField("Amount");
Button submit = new Button("Submit");
submit.addClickListener(evt -> {
commandGateway.sendAndWait(new IssueCmd(id.getValue(), Integer.parseInt(amount.getValue())));
Notification.show("Success", Notification.Type.HUMANIZED_MESSAGE).addCloseListener(e -> cardSummaryDataProvider.refreshAll());
});
FormLayout form = new FormLayout();
form.addComponents(id, amount, submit);
form.setMargin(true);
Panel panel = new Panel("Issue single card");
panel.setContent(form);
return panel;
}