Java tutorial
/* * Copyright 2012 AMG.lab, a Bull Group Company * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xlcloud.console.images.controllers; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.PostConstruct; import javax.faces.event.ValueChangeEvent; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Predicate; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.primefaces.event.FileUploadEvent; import org.primefaces.model.UploadedFile; import org.xlcloud.console.context.IdentityContext; import org.xlcloud.console.controllers.i18n.MessageController; import org.xlcloud.console.controllers.request.RequestParameters; import org.xlcloud.console.controllers.request.RequestRedirectionResolver; import org.xlcloud.console.controllers.request.exception.VcmsExceptionMessageResolver; import org.xlcloud.console.controllers.request.path.VcmsGuiPathParams; import org.xlcloud.console.controllers.request.path.VcmsGuiPaths; import org.xlcloud.console.images.entitlements.ImagesEntitlementsEngineWrapper; import org.xlcloud.console.images.repository.ImagesRepository; import org.xlcloud.console.scope.ViewScoped; import org.xlcloud.service.CatalogScopeType; import org.xlcloud.service.Image; import org.xlcloud.service.Image.ContainerFormat; import org.xlcloud.service.Image.DiskFormat; import org.xlcloud.service.Image.Properties; import org.xlcloud.service.Image.Properties.Property; import org.xlcloud.service.exception.VcmsException; import org.xlcloud.service.exception.VcmsForbiddenException; /** */ @Named @ViewScoped public class ImageCreateBean { private final static Logger LOG = Logger.getLogger(ImageCreateBean.class); private static final String SUCCESS_URL = VcmsGuiPaths.IMAGES; private static final int MAX_MIN_DISK = 16384; private static final int MAX_MIN_RAM = 65536; /** * URL parameter name for application id */ @Inject private ImagesRepository imagesRepository; @Inject private ImagesEntitlementsEngineWrapper imageEntitlements; @Inject private IdentityContext identityContext; @Inject private MessageController messages; private Image image; private List<String> availableScopes; private String selectedScope; private UploadedFile file; private String minRam; private String minDisk; private Property newProperty = new Property(); @Inject private RequestRedirectionResolver redirectionResolver; @Inject private RequestParameters requestParameters; /** * Initializes bean by new Application */ @PostConstruct public void loadImage() { initRedirectionResolver(); if (image == null) { image = new Image(); image.setDiskFormat(DiskFormat.RAW); //RAW disk format is selected by default image.setContainerFormat(ContainerFormat.BARE); //BARE disk format is selected by default availableScopes = new ArrayList<String>(); availableScopes = imageEntitlements.listAvailableScopes(); if (availableScopes.size() == 0) { LOG.warn("User: " + identityContext.getUserId() + "does not have entitlements to register image"); throw new VcmsForbiddenException("You do not have entitlement to register image"); } else if (availableScopes.size() == 1) { selectedScope = availableScopes.get(0); availableScopes.clear(); } else { String requestedScope = getRequestedCatalogScope(); if (availableScopes.contains(requestedScope)) { selectedScope = requestedScope; } } } image.setProperties(new Properties()); this.completeAuthorname(); } /** * Creates application in VCMS API */ public String createImage() { try { if (CatalogScopeType.PRIVATE.value().equals(selectedScope)) { image.setCatalogScope(CatalogScopeType.PRIVATE); Long accountId = identityContext.getAccountId(); if (accountId == null) { throw new VcmsException("No account id available in context"); } } else { image.setCatalogScope(CatalogScopeType.PUBLIC); } removeEmptyProperties(image); if (!validateProperties(image)) { messages.addErrorMessage("images.properties.badFormat"); return null; } if (file == null) { messages.addErrorMessage("images.validation.fileRequired"); return null; } if (!validateDiskRamSize()) { return null; } image = imagesRepository.create(image); imagesRepository.saveImageFile(image.getId(), file.getInputstream()); messages.addMessage("images.create.successfully"); return returnUrl(); } catch (VcmsException exception) { VcmsExceptionMessageResolver messageResolver = new VcmsExceptionMessageResolver(exception); messages.addError(messageResolver.getExceptionMessage()); return null; } catch (IOException e) { messages.addErrorMessage("images.file.fileProblem"); return null; } } public String returnUrl() { return redirectionResolver.getRedirectionURL(requestParameters); } /** * Returns the application details * * @return application details */ public Image getImage() { return this.image; } /** * @return {@code true} if the image file was already uploaded, {@code false} otherwise */ public boolean isImageFileUploaded() { return (this.file != null); } /** * Gets the value of {@link #availableScopes}. * * @return value of {@link #availableScopes} */ public List<String> getAvailableScopes() { return availableScopes; } /** * Sets the value of {@link #availableScopes}. * * @param availableScopes * - value */ public void setAvailableScopes(List<String> availableScopes) { this.availableScopes = availableScopes; } /** * Gets the value of {@link #selectedScope}. * * @return value of {@link #selectedScope} */ public String getSelectedScope() { return selectedScope; } /** * Sets the value of {@link #selectedScope}. * * @param selectedScope * - value */ public void setSelectedScope(String selectedScope) { this.selectedScope = selectedScope; } /** * Gets the value of {@link #imageEntitlements}. * * @return value of {@link #imageEntitlements} */ public ImagesEntitlementsEngineWrapper getImageEntitlements() { return imageEntitlements; } /** * Sets the value of {@link #imageEntitlements}. * * @param imageEntitlements * - value */ public void setImageEntitlements(ImagesEntitlementsEngineWrapper imageEntitlements) { this.imageEntitlements = imageEntitlements; } /** * Gets the value of {@link #diskFormat}. * @return value of {@link #diskFormat} */ public String getDiskFormat() { return (image.getDiskFormat() != null ? image.getDiskFormat().toString() : null); } /** * Sets the value of {@link #diskFormat}. * @param diskFormat - value */ public void setDiskFormat(String diskFormat) { image.parseDiskFormat(diskFormat); } /** * Gets the value of {@link #containerFormat}. * @return value of {@link #containerFormat} */ public String getContainerFormat() { return (image.getContainerFormat() != null ? image.getContainerFormat().toString() : null); } /** * Sets the value of {@link #containerFormat}. * @param containerFormat - value */ public void setContainerFormat(String containerFormat) { image.parseContainerFormat(containerFormat); } /** * Returns all available disk formats * @return available disk formats */ public List<String> getDiskFormats() { return DiskFormat.stringValues; } /** * Returns container formats available to be selected for new cloud image * @return available container formats */ public List<String> getContainerFormats() { List<String> formats = new ArrayList<String>(); if (image.getDiskFormat() != null) { switch (image.getDiskFormat()) { case AKI: formats.add(ContainerFormat.AKI.toString()); break; case ARI: formats.add(ContainerFormat.ARI.toString()); break; case AMI: formats.add(ContainerFormat.AMI.toString()); break; default: formats.add(ContainerFormat.BARE.toString()); formats.add(ContainerFormat.OVF.toString()); } } return formats; } /** * @return {@code true} if container format is locked (there are none or only one container format available, {@code false} otherwise */ public boolean isContainerFormatLocked() { return (getContainerFormats().size() < 2); } public String getImageMinRam() { return minRam; } public void setImageMinRam(String value) { this.minRam = value; } public String getImageMinDisk() { return minDisk; } public void setImageMinDisk(String value) { this.minDisk = value; } public void handleFileUpload(FileUploadEvent event) { file = event.getFile(); completeImageName(); } public String getFileName() { return file == null ? "" : file.getFileName(); } private String getRequestedCatalogScope() { return requestParameters.getParameter(VcmsGuiPathParams.CATALOG_SCOPE); } public void addProperty() { image.getProperties().getProperty().add(newProperty); newProperty = new Property(); } public void removeProperty(Property property) { image.getProperties().getProperty().remove(property); } /** * Gets the value of {@link #newProperty}. * @return value of {@link #newProperty} */ public Property getNewProperty() { return newProperty; } /** * Sets the value of {@link #newProperty}. * @param newProperty - value */ public void setNewProperty(Property newProperty) { this.newProperty = newProperty; } /** * It handles disk format change event. * Disk format name is parsed using {@link DiskFormat#fromValue(String)} method * and appropriate container format is selected. * @param event - disk format value change event */ public void handleDiskFormatChange(ValueChangeEvent event) { image.parseDiskFormat((String) event.getNewValue()); completeContainerFormat(); } private void initRedirectionResolver() { String redirectionURL = requestParameters.getParameter(VcmsGuiPathParams.REDIRECTION_PARAMETER_NAME); String successUrl = StringUtils.isNotBlank(redirectionURL) ? redirectionURL : SUCCESS_URL; redirectionResolver.setDefaultRedirectionURL(successUrl); } private boolean validateDiskRamSize() { if (StringUtils.isNotBlank(minRam)) { try { image.setMinRam(Integer.parseInt(minRam)); if (image.getMinRam() > MAX_MIN_RAM) { messages.addErrorMessage("images.validation.minRam"); return false; } } catch (NumberFormatException e) { messages.addErrorMessage("images.validation.minRam"); return false; } } if (StringUtils.isNotBlank(minDisk)) { try { image.setMinDisk(Integer.parseInt(minDisk)); if (image.getMinDisk() > MAX_MIN_DISK) { messages.addErrorMessage("images.validation.minDisk"); return false; } } catch (NumberFormatException e) { messages.addErrorMessage("images.validation.minDisk"); return false; } } return true; } private boolean validateProperties(Image image) { Set<String> namesSet = new HashSet<String>(); for (Property property : image.getProperties().getProperty()) { property.setName(property.getName().toLowerCase()); if (!property.getName().matches("[a-zA-Z0-9_]+")) { return false; } else if (StringUtils.isBlank(property.getValue())) { return false; } else if (namesSet.contains(property.getName())) { return false; } namesSet.add(property.getName()); } return true; } private void removeEmptyProperties(Image image) { CollectionUtils.filter(image.getProperties().getProperty(), new Predicate() { public boolean evaluate(Object object) { Property property = (Property) object; return StringUtils.isNotBlank(property.getName()) || StringUtils.isNotBlank(property.getValue()); } }); } private void completeImageName() { if (file != null) { String imageName = FilenameUtils.removeExtension(file.getFileName()); if (StringUtils.isNotBlank(imageName)) { this.image.setName(imageName); } } } private void completeAuthorname() { if (StringUtils.isNotBlank(this.identityContext.getName())) { this.image.setAuthor(this.identityContext.getName()); } } private void completeContainerFormat() { if (image.getDiskFormat() != null) { switch (image.getDiskFormat()) { case AKI: image.setContainerFormat(ContainerFormat.AKI); break; case ARI: image.setContainerFormat(ContainerFormat.ARI); break; case AMI: image.setContainerFormat(ContainerFormat.AMI); break; default: image.setContainerFormat(ContainerFormat.BARE); } } } }