Package com.abiquo.am.model.ovf

Source Code of com.abiquo.am.model.ovf.TemplateFromOVFEnvelope

/**
* Licensed to Abiquo Holdings S.L. (Abiquo) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you 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 com.abiquo.am.model.ovf;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;

import org.apache.commons.io.FilenameUtils;
import org.dmtf.schemas.ovf.envelope._1.ContentType;
import org.dmtf.schemas.ovf.envelope._1.DiskSectionType;
import org.dmtf.schemas.ovf.envelope._1.EnvelopeType;
import org.dmtf.schemas.ovf.envelope._1.FileType;
import org.dmtf.schemas.ovf.envelope._1.MsgType;
import org.dmtf.schemas.ovf.envelope._1.OperatingSystemSectionType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType.Icon;
import org.dmtf.schemas.ovf.envelope._1.RASDType;
import org.dmtf.schemas.ovf.envelope._1.VirtualDiskDescType;
import org.dmtf.schemas.ovf.envelope._1.VirtualHardwareSectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemCollectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemType;
import org.dmtf.schemas.wbem.wscim._1.cim_schema._2.cim_resourceallocationsettingdata.ResourceType;
import org.dmtf.schemas.wbem.wscim._1.common.CimString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.abiquo.am.model.TemplateDto;
import com.abiquo.am.model.error.AMError;
import com.abiquo.am.model.error.AMException;
import com.abiquo.model.enumerator.OSType;
import com.abiquo.ovfmanager.cim.CIMTypesUtils.CIMResourceTypeEnum;
import com.abiquo.ovfmanager.ovf.OVFEnvelopeUtils;
import com.abiquo.ovfmanager.ovf.exceptions.EmptyEnvelopeException;
import com.abiquo.ovfmanager.ovf.exceptions.IdAlreadyExistsException;
import com.abiquo.ovfmanager.ovf.exceptions.IdNotFoundException;
import com.abiquo.ovfmanager.ovf.exceptions.InvalidSectionException;
import com.abiquo.ovfmanager.ovf.exceptions.RequiredAttributeException;
import com.abiquo.ovfmanager.ovf.exceptions.SectionAlreadyPresentException;
import com.abiquo.ovfmanager.ovf.exceptions.SectionNotPresentException;
import com.abiquo.ovfmanager.ovf.section.DiskFormatOVF;

public class TemplateFromOVFEnvelope
{
    private final static Logger LOG = LoggerFactory.getLogger(TemplateFromOVFEnvelope.class);

    /**
     * Creates an {@link TemplateDto} by simplify an OVF Envelop Document (.ovf)
     *
     * @param ovfId OVF download Url
     * @param envelope the OVF envelope document
     * @return template corresponding to the download OVF
     * @throws RepositoryException, if the envelope do not contain the required info to complete the
     *             Template data
     **/
    public static TemplateDto createTemplateDto(final String ovfId, EnvelopeType envelope)
        throws AMException
    {
        envelope = checkEnvelopeIsValid(envelope);

        TemplateDto diskInfo = null;

        Map<String, VirtualDiskDescType> diskIdToDiskFormat =
            new HashMap<String, VirtualDiskDescType>();
        Map<String, FileType> fileIdToFileType = new HashMap<String, FileType>();
        Map<String, List<String>> diskIdToVSs = new HashMap<String, List<String>>();
        Map<String, TemplateDto> requiredByVSs = new HashMap<String, TemplateDto>();
        DiskSectionType diskSectionType;

        try
        {
            ContentType contentType = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);

            ProductSectionType product =
                OVFEnvelopeUtils.getSection(contentType, ProductSectionType.class);
            OperatingSystemSectionType ossection = null;
            try
            {
                ossection =
                    OVFEnvelopeUtils.getSection(contentType, OperatingSystemSectionType.class);
            }
            catch (Exception e) // no such section
            {
            }

            String description = null;
            if (product.getInfo() != null && product.getInfo().getValue() != null)
            {
                description = product.getInfo().getValue();
            }

            String categoryName = null;
            if (product.getOtherAttributes().containsKey(new QName("CategoryName")))
            {
                categoryName = product.getOtherAttributes().get(new QName("CategoryName"));
            }

            String iconPath = getIconPath(product, fileIdToFileType, ovfId);

            diskSectionType = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);

            for (FileType fileType : envelope.getReferences().getFile())
            {
                fileIdToFileType.put(fileType.getId(), fileType);
            }
            // Create a hash
            for (VirtualDiskDescType virtualDiskDescType : diskSectionType.getDisk())
            {
                diskIdToDiskFormat.put(virtualDiskDescType.getDiskId(), virtualDiskDescType);
            }

            if (contentType instanceof VirtualSystemType)
            {

                VirtualSystemType vs = (VirtualSystemType) contentType;
                TemplateDto req = getDiskInfo(vs, diskIdToDiskFormat, diskIdToVSs);

                requiredByVSs.put(vs.getId(), req);
            }
            else if (contentType instanceof VirtualSystemCollectionType)
            {
                List<VirtualSystemType> virtualSystems =
                    OVFEnvelopeUtils.getVirtualSystems((VirtualSystemCollectionType) contentType);

                for (VirtualSystemType virtualSystemType : virtualSystems)
                {
                    TemplateDto req =
                        getDiskInfo(virtualSystemType, diskIdToDiskFormat, diskIdToVSs);

                    requiredByVSs.put(virtualSystemType.getId(), req);
                }
            }

            for (VirtualDiskDescType diskDescType : diskIdToDiskFormat.values())
            {

                String diskId = diskDescType.getDiskId();
                String fileId = diskDescType.getFileRef();

                if (!fileIdToFileType.containsKey(fileId))
                {
                    String msg = "File Id [" + fileId + "] not found on the ReferencesSection";
                    throw new IdNotFoundException(msg);
                }

                FileType file = fileIdToFileType.get(fileId);
                final String filePath = file.getHref();
                final Long fileSize = file.getSize().longValue();

                String format = diskDescType.getFormat(); // XXX using the same format on the OVF
                // disk

                if (!diskIdToVSs.containsKey(diskId))
                {
                    throw new IdNotFoundException("Any virtualSystem is using diskId[" + diskId
                        + "]"); // XXX warning ??
                }

                if (diskIdToVSs.size() != 1)
                {
                    throw new AMException(AMError.TEMPLATE_INVALID, String.format(
                        "There are more than one virtual system on the OVF Envelope [%s]", ovfId));
                }

                for (String vssName : diskIdToVSs.get(diskId))
                {
                    diskInfo = new TemplateDto();
                    diskInfo.setName(vssName);
                    diskInfo.setUrl(ovfId);
                    diskInfo.setLoginUser(getProductPropertyValue(product, "user"));
                    diskInfo.setLoginPassword(getProductPropertyValue(product, "password"));
                    diskInfo.setOsType(getOSType(ossection));
                    diskInfo.setOsVersion(getOSVersion(ossection));

                    DiskFormatOVF diskFormat = DiskFormatOVF.fromValue(format);

                    diskInfo.setDiskFileFormat(diskFormat.name());
                    diskInfo.setDiskFileSize(fileSize);

                    // Note that getHRef() will now return the relative path
                    // of the file at the downloaded repository space

                    if (filePath.startsWith("http:"))
                    {
                        diskInfo.setDiskFilePath(FilenameUtils.getName(filePath));
                    }
                    else
                    {
                        diskInfo.setDiskFilePath(filePath);
                    }

                    diskInfo.setIconUrl(iconPath);
                    diskInfo.setDescription(description);
                    diskInfo.setCategoryName(categoryName);
                    // XXX diskInfo.setSO(value);

                    if (!requiredByVSs.containsKey(vssName))
                    {
                        throw new IdNotFoundException("VirtualSystem id not found [" + vssName
                            + "]");
                    }

                    TemplateDto requirement = requiredByVSs.get(vssName);

                    // XXX disk format ::: diskInfo.setImageType(requirement.getImageType());

                    diskInfo.setRequiredCpu(requirement.getRequiredCpu());
                    diskInfo.setRequiredRamInMB(requirement.getRequiredRamInMB());
                    diskInfo.setRequiredHDInMB(requirement.getRequiredHDInMB());

                    diskInfo.setEthernetDriverType(requirement.getEthernetDriverType());
                    diskInfo.setDiskControllerType(requirement.getDiskControllerType());

                    // TODO diskInfo.setEnterpriseId(enterpriseId);
                    // diskInfo.setUserId(userId); TODO user ID
                    // diskInfo.getCategories().add(category); TODO category

                }// all vss
            }// all disks
        }
        catch (EmptyEnvelopeException e)
        {
            String msg = "No VirtualSystem or VirtualSystemCollection exists for this OVF package";
            throw new AMException(AMError.TEMPLATE_INVALID, msg, e);
        }
        catch (Exception e)
        {
            throw new AMException(AMError.TEMPLATE_INVALID, e);
        }

        if (diskInfo == null)
        {
            String msg = "No VirtualSystem or VirtualSystemCollection exists for this OVF package";
            throw new AMException(AMError.TEMPLATE_INVALID, msg);
        }

        return diskInfo;
    }

    /**
     * Adds a simple ProductSection if its not found
     */
    public static EnvelopeType fixOVfDocument(EnvelopeType envelope)
    {
        try
        {
            envelope = fixDiskFormtatUriAndFileSizes(envelope);
            envelope = fixMissingProductSection(envelope);
        }
        catch (Exception e)
        {
            throw new AMException(AMError.TEMPLATE_INVALID, e);
        }

        return envelope;
    }

    /**
     * Check for all the abiquo required attributes in the ovf document.
     */
    public static EnvelopeType checkEnvelopeIsValid(final EnvelopeType envelope)
    {
        try
        {
            Map<String, VirtualDiskDescType> diskIdToDiskFormat =
                new HashMap<String, VirtualDiskDescType>();
            Map<String, FileType> fileIdToFileType = new HashMap<String, FileType>();

            DiskSectionType diskSectionType =
                OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);

            if (diskSectionType.getDisk().size() != 1)
            {
                // more than one disk in disk section
                throw new AMException(AMError.TEMPLATE_INVALID_MULTIPLE_DISKS);
            }
            else
            {
                int references = 0;
                for (FileType fileType : envelope.getReferences().getFile())
                {
                    fileIdToFileType.put(fileType.getId(), fileType);
                    if (diskSectionType.getDisk().get(0).getFileRef().equals(fileType.getId()))
                    {
                        references++;
                    }
                }
                if (references != 1)
                {
                    // file referenced in diskSection isn't found in file references or found more
                    // than one
                    throw new AMException(AMError.TEMPLATE_INVALID_MULTIPLE_FILES);
                }
            }
            // Create a hash
            for (VirtualDiskDescType virtualDiskDescType : diskSectionType.getDisk())
            {
                diskIdToDiskFormat.put(virtualDiskDescType.getDiskId(), virtualDiskDescType);
            }

            // /

            ContentType content = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);

            if (content instanceof VirtualSystemCollectionType)
            {
                throw new EmptyEnvelopeException("Current OVF description document includes a VirtualSystemCollection, "
                    + "abicloud only deal with single virtual system based OVFs");
            }

            VirtualSystemType vsystem = (VirtualSystemType) content;

            VirtualHardwareSectionType hardwareSectionType;
            Integer cpu = null;
            Long hd = null;
            Long ram = null;

            try
            {
                hardwareSectionType =
                    OVFEnvelopeUtils.getSection(vsystem, VirtualHardwareSectionType.class);
            }
            catch (InvalidSectionException e)
            {
                throw new SectionNotPresentException("VirtualHardware on a virtualSystem", e);
            }

            for (RASDType rasdType : hardwareSectionType.getItem())
            {

                ResourceType resourceType = rasdType.getResourceType();
                if (resourceType == null) // empty rasd element
                {
                    continue;
                }
                int resTnumeric = Integer.parseInt(resourceType.getValue());

                // Get the information on the ram
                if (CIMResourceTypeEnum.Processor.getNumericResourceType() == resTnumeric)
                {
                    try
                    {
                        String cpuVal = rasdType.getVirtualQuantity().getValue().toString();

                        cpu = Integer.parseInt(cpuVal);
                    }
                    catch (Exception e)
                    {
                        throw new AMException(AMError.TEMPLATE_INVALID,
                            "Invalid CPU virtualQuantity");
                    }
                }
                else if (CIMResourceTypeEnum.Memory.getNumericResourceType() == resTnumeric)
                {
                    try
                    {
                        BigInteger ramVal = rasdType.getVirtualQuantity().getValue();

                        ram = ramVal.longValue();
                    }
                    catch (Exception e)
                    {
                        throw new AMException(AMError.TEMPLATE_INVALID,
                            "Invalid RAM virtualQuantity");
                    }
                }
                else if (CIMResourceTypeEnum.Disk_Drive.getNumericResourceType() == resTnumeric)
                {
                    // HD requirements are extracted from the associated Disk on ''hostResource''
                    String diskId = getVirtualSystemDiskId(rasdType.getHostResource());

                    if (!diskIdToDiskFormat.containsKey(diskId))
                    {
                        throw new RequiredAttributeException("Virtual System makes reference to an undeclared disk "
                            + diskId);
                    }

                    VirtualDiskDescType diskDescType = diskIdToDiskFormat.get(diskId);

                    String capacity = diskDescType.getCapacity();

                    hd = Long.parseLong(capacity);
                }
            }// rasd

            if (cpu == null)
            {
                throw new RequiredAttributeException("Not CPU RASD element found on the envelope");
            }
            if (ram == null)
            {
                throw new RequiredAttributeException("Not RAM RASD element found on the envelope");
            }
            if (hd == null)
            {
                throw new RequiredAttributeException("Not HD RASD element found on the envelope");
            }

        }

        catch (AMException amException)
        {
            throw amException;
        }
        catch (Exception e)
        {
            throw new AMException(AMError.TEMPLATE_INVALID, e);
        }

        return envelope;
    }

    /**
     * Only the first icon on product section is used
     */
    private static String getIconPath(final ProductSectionType product,
        final Map<String, FileType> fileIdToFileType, final String ovfId)
    {
        List<Icon> icons = product.getIcon();
        if (icons == null || icons.size() == 0)
        {
            return null;
        }

        final Icon icon = icons.get(0);
        final String iconRef = icon.getFileRef();

        if (iconRef.startsWith("http"))
        {
            return iconRef;
        }

        if (!fileIdToFileType.containsKey(iconRef))
        {
            return null; // XXX log cause
        }

        final String iconPathRelative = fileIdToFileType.get(iconRef).getHref();

        if (iconPathRelative.startsWith("http"))
        {
            return iconPathRelative;
        }

        final String ovfAbs = ovfId.substring(0, ovfId.lastIndexOf('/'));

        return ovfAbs + '/' + iconPathRelative;
    }

    private static String getProductPropertyValue(final ProductSectionType product,
        final String propertyKey)
    {
        for (Object obj : product.getCategoryOrProperty())
        {
            if (obj instanceof ProductSectionType.Property)
            {
                ProductSectionType.Property prop = (ProductSectionType.Property) obj;
                if (propertyKey.equalsIgnoreCase(prop.getKey()))
                {
                    return prop.getValue();
                }
            }
        }
        return null;
    }

    private static String getOSType(final OperatingSystemSectionType ossection)
    {

        return ossection != null ? OSType.fromCode(ossection.getId()).name() : OSType.UNRECOGNIZED
            .name();
    }

    private static String getOSVersion(final OperatingSystemSectionType ossection)
    {
        try
        {
            return ossection != null ? ossection.getVersion() : null;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    /**
     * TODO TBD
     **/
    private static TemplateDto getDiskInfo(final VirtualSystemType vsystem,
        final Map<String, VirtualDiskDescType> diskDescByName,
        final Map<String, List<String>> diskIdToVSs) throws IdAlreadyExistsException,
        RequiredAttributeException, SectionNotPresentException
    {
        TemplateDto dReq = new TemplateDto();
        VirtualHardwareSectionType hardwareSectionType;

        try
        {
            hardwareSectionType =
                OVFEnvelopeUtils.getSection(vsystem, VirtualHardwareSectionType.class);
        }
        catch (InvalidSectionException e)
        {
            throw new SectionNotPresentException("VirtualHardware on a virtualSystem", e);
        }

        dReq.setRequiredCpu(-1);
        dReq.setRequiredRamInMB(-1l);
        dReq.setRequiredHDInMB(-1l);

        // XXX now we are using ONLY the Disk format

        // XXX String vsType = hardwareSectionType.getSystem().getVirtualSystemType().getValue();
        // XXX dReq.setImageType(vsType);
        // XXX log.debug("Using ''virtualSystemType'' [{}]", vsType);

        for (RASDType rasdType : hardwareSectionType.getItem())
        {
            ResourceType resourceType = rasdType.getResourceType();
            int resTnumeric = Integer.parseInt(resourceType.getValue());

            // TODO use CIMResourceTypeEnum from value and then a SWITCH

            // Get the information on the ram
            if (CIMResourceTypeEnum.Processor.getNumericResourceType() == resTnumeric)
            {
                String cpuVal = rasdType.getVirtualQuantity().getValue().toString();

                dReq.setRequiredCpu(Integer.parseInt(cpuVal));

                // TODO if(rasdType.getAllocationUnits()!= null)
            }
            else if (CIMResourceTypeEnum.Memory.getNumericResourceType() == resTnumeric)
            {
                Long ramVal = rasdType.getVirtualQuantity().getValue().longValue();
                String allocationUnits = allocationUnits(rasdType);

                dReq.setRequiredRamInMB(getMegaByes(ramVal, allocationUnits));
            }
            else if (CIMResourceTypeEnum.Disk_Drive.getNumericResourceType() == resTnumeric)
            {
                // HD requirements are extracted from the associated Disk on ''hostResource''
                String diskId = getVirtualSystemDiskId(rasdType.getHostResource());

                if (!diskDescByName.containsKey(diskId))
                {
                    String msg = "DiskId [" + diskId + "] not found on disk section";
                    throw new IdAlreadyExistsException(msg);
                }

                if (!diskIdToVSs.containsKey(diskId))
                {
                    List<String> vss = new LinkedList<String>();
                    vss.add(vsystem.getId()); // XXX

                    diskIdToVSs.put(diskId, vss);
                }
                else
                {
                    diskIdToVSs.get(diskId).add(vsystem.getId());
                }

                VirtualDiskDescType diskDescType = diskDescByName.get(diskId);
                final String capacity = diskDescType.getCapacity();
                final String allocationUnits = diskDescType.getCapacityAllocationUnits();

                dReq.setRequiredHDInMB(getMegaByes(Long.parseLong(capacity), allocationUnits));
            }
            else if (CIMResourceTypeEnum.Ethernet_Adapter.getNumericResourceType() == resTnumeric)
            {
                String ethDriver = null;
                try
                {
                    ethDriver = rasdType.getResourceSubType().getValue();
                }
                catch (Exception e)
                {
                    LOG.error("Invalid ethernet adapter type {}", ethDriver != null ? ethDriver
                        : "-ResourceSubType- not found");
                }

                if (ethDriver != null)
                {
                    dReq.setEthernetDriverType(ethDriver);
                }
            }
            else if (CIMResourceTypeEnum.IDE_Controller.getNumericResourceType() == resTnumeric)
            {
                dReq.setDiskControllerType("IDE");
            }
            else if (CIMResourceTypeEnum.Parallel_SCSI_HBA.getNumericResourceType() == resTnumeric)
            {
                dReq.setDiskControllerType("SCSI");
            }
        }// rasd

        // if the Ethernet/Disk controller is not specified let the API properties be used as
        // default

        if (dReq.getRequiredCpu() == -1)
        {
            throw new RequiredAttributeException("Not CPU RASD element found on the envelope");
        }
        if (dReq.getRequiredRamInMB() == -1)
        {
            throw new RequiredAttributeException("Not RAM RASD element found on the envelope");
        }
        if (dReq.getRequiredHDInMB() == -1)
        {
            throw new RequiredAttributeException("Not HD RASD element found on the envelope");
        }

        return dReq;
    }

    private static String allocationUnits(final RASDType rasdType)
    {
        if (rasdType.getAllocationUnits() != null
            & rasdType.getAllocationUnits().getValue() != null)
        {
            return rasdType.getAllocationUnits().getValue();
        }
        return null;
    }

    /**
     * Decode CimStrings (on the OVF namespce) on the Disk RASD's HostResource attribute to delete
     * the ''ovf://disk/'' prefix
     **/
    private static String getVirtualSystemDiskId(final List<CimString> cimStrs)
    {
        String cimStringVal = "";
        for (CimString cimString : cimStrs)
        {
            cimStringVal = cimString.getValue();

            if (cimStringVal.startsWith("ovf:/disk/"))
            {
                cimStringVal = cimStringVal.replace("ovf:/disk/", "");
                break;
            }
            else if (cimStringVal.startsWith("/disk/"))
            {
                cimStringVal = cimStringVal.replace("/disk/", "");
                break;
            }
        }

        return cimStringVal;
    }

    private static EnvelopeType fixDiskFormtatUriAndFileSizes(final EnvelopeType envelope)
        throws SectionNotPresentException, InvalidSectionException
    {

        DiskSectionType diskSection = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);

        if (diskSection.getDisk().size() != 1)
        {
            final String message =
                "abicloud only supports single disk definition on the OVF, the current envelope contains multiple disk";
            throw new InvalidSectionException(message);
        }

        VirtualDiskDescType vdisk = diskSection.getDisk().get(0);

        String formatUri = vdisk.getFormat();

        if (formatUri == null || formatUri.isEmpty())
        {
            final String message = "Missing ''format'' attribute for the Disk element";
            throw new InvalidSectionException(message);
        }

        DiskFormatOVF format = DiskFormatOVF.fromValue(formatUri);

        if (format == null) // the format URI isn't on the abicloud enumeration. FIX it
        {
            // vbox/vmware
            // http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized
            // abiquo
            // http://www.vmware.com/technical-resources/interfaces/vmdk_access.html#streamOptimized

            if (formatUri.contains("interfaces/specifications/vmdk.html"))
            {
                formatUri =
                    formatUri.replace("interfaces/specifications/vmdk.html",
                        "technical-resources/interfaces/vmdk_access.html");

                format = DiskFormatOVF.fromValue(formatUri);

                if (format == null)
                {
                    throw new InvalidSectionException(String.format(
                        "Invalid disk format type [%s]", formatUri));
                }

                vdisk.setFormat(formatUri);
            }

        }

        // try
        // {
        // for (FileType ftype : envelope.getReferences().getFile())
        // {
        // if (ftype.getSize() == null)
        // {
        // String fileUrl = getFileUrl(ftype.getHref(), ovfId);
        // Long size = new ExternalHttpConnection().headFile(fileUrl);
        //
        // ftype.setSize(BigInteger.valueOf(size));
        // }
        // }
        // }
        // catch (Exception e)
        // {
        // throw new InvalidSectionException(String.format("Invalid File References section "
        // + "(check all the files on the OVF document contains the ''size'' attribute):\n",
        // e.toString()));
        // }

        return envelope;
    }

    /**
     * If product section is not present use the VirtualSystemType to set it.
     *
     * @throws EmptyEnvelopeException
     */
    private static EnvelopeType fixMissingProductSection(final EnvelopeType envelope)
        throws InvalidSectionException, EmptyEnvelopeException
    {

        ContentType contentType = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);

        if (!(contentType instanceof VirtualSystemType))
        {
            throw new InvalidSectionException("abicloud only suport single virtual system definition,"
                + " current OVF envelope defines a VirtualSystemCollection");
        }

        VirtualSystemType vsystem = (VirtualSystemType) contentType;

        try
        {
            OVFEnvelopeUtils.getSection(vsystem, ProductSectionType.class);
        }
        catch (SectionNotPresentException e)
        {

            String vsystemName =
                vsystem.getName() != null && vsystem.getName().getValue() != null ? vsystem
                    .getName().getValue() : vsystem.getId();

            MsgType prod = new MsgType();
            prod.setValue(vsystemName);

            ProductSectionType product = new ProductSectionType();
            product.setInfo(vsystem.getInfo());
            product.setProduct(prod);

            try
            {
                OVFEnvelopeUtils.addSection(vsystem, product);
            }
            catch (SectionAlreadyPresentException e1)
            {
            }
        }

        return envelope;
    }

    public static String getDiskFileRef(final EnvelopeType envelope)
    {
        DiskSectionType diskSection = null;
        try
        {
            diskSection = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);
        }
        catch (Exception e)// SectionNotPresentException InvalidSectionException
        {
            throw new AMException(AMError.TEMPLATE_INVALID, "missing DiskSection");
        }

        List<VirtualDiskDescType> disks = diskSection.getDisk();

        if (disks == null || disks.isEmpty() || disks.size() != 1)
        {
            throw new AMException(AMError.TEMPLATE_INVALID, "multiple Disk not supported");
        }

        return disks.get(0).getFileRef();

    }

    /**
     * Gets the disk capacity on bytes.
     *
     * @param capacity, numeric value
     * @param alloctionUnit, bytes by default but can be Kb, Mb, Gb or Tb.
     * @return capacity on bytes
     **/
    private static Long getMegaByes(final Long capacity, final String allocationUnits)
    {
        BigInteger bytes = null;
        BigInteger capa = BigInteger.valueOf(capacity);

        if (allocationUnits == null)
        {
            bytes = capa;
        }

        BigInteger factor = new BigInteger("2");

        if ("byte".equalsIgnoreCase(allocationUnits) || "bytes".equalsIgnoreCase(allocationUnits))
        {
            bytes = capa;
        }
        else if ("byte * 2^10".equals(allocationUnits) || "KB".equalsIgnoreCase(allocationUnits)
            || "KILOBYTE".equalsIgnoreCase(allocationUnits)
            || "KILOBYTES".equalsIgnoreCase(allocationUnits)) // kb
        {
            bytes = capa.multiply(factor.pow(10));
        }
        else if ("byte * 2^20".equals(allocationUnits) || "MB".equalsIgnoreCase(allocationUnits)
            || "MEGABYTE".equalsIgnoreCase(allocationUnits)
            || "MEGABYTES".equalsIgnoreCase(allocationUnits)) // mb
        {
            bytes = capa.multiply(factor.pow(20));
        }
        else if ("byte * 2^30".equals(allocationUnits) || "GB".equalsIgnoreCase(allocationUnits)
            || "GIGABYTE".equalsIgnoreCase(allocationUnits)
            || "GIGABYTES".equalsIgnoreCase(allocationUnits)) // gb
        {
            bytes = capa.multiply(factor.pow(30));
        }
        else if ("byte * 2^40".equals(allocationUnits) || "TB".equalsIgnoreCase(allocationUnits)
            || "TERABYTE".equalsIgnoreCase(allocationUnits)
            || "TERABYTES".equalsIgnoreCase(allocationUnits)) // tb
        {
            bytes = capa.multiply(factor.pow(40));
        }
        else
        {
            final String msg =
                "Unknow disk capacityAllocationUnits factor [" + allocationUnits + "]";
            throw new RuntimeException(msg);
        }

        return bytes.divide(factor.pow(20)).longValue();
    }
}
TOP

Related Classes of com.abiquo.am.model.ovf.TemplateFromOVFEnvelope

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.