Example usage for org.w3c.dom Node hasChildNodes

List of usage examples for org.w3c.dom Node hasChildNodes

Introduction

In this page you can find the example usage for org.w3c.dom Node hasChildNodes.

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:org.dasein.cloud.azure.AzureLocation.java

@Override
public @Nonnull Collection<DataCenter> listDataCenters(@Nonnull String providerRegionId)
        throws InternalException, CloudException {
    Region region = getRegion(providerRegionId);

    if (region == null) {
        return Collections.emptyList();
    }/*from  w ww  .  j  av a2s. co m*/

    ProviderContext ctx = provider.getContext();
    if (ctx == null) {
        throw new AzureConfigException("No context was specified for this request");
    }

    Cache<DataCenter> cache = Cache.getInstance(provider, "dataCenters", DataCenter.class,
            CacheLevel.REGION_ACCOUNT, new TimePeriod<Minute>(15, TimePeriod.MINUTE));
    Collection<DataCenter> dcs = (Collection<DataCenter>) cache.get(ctx);

    if (dcs == null) {
        dcs = new ArrayList<DataCenter>();
        logger.info("Get affinity group for " + providerRegionId + " for account " + ctx.getAccountNumber());
        AzureMethod method = new AzureMethod(provider);

        Document doc = method.getAsXML(ctx.getAccountNumber(), "/affinitygroups");

        NodeList entries = doc.getElementsByTagName("AffinityGroup");

        String affinityGroup = "";
        String affinityRegion = "";

        for (int i = 0; i < entries.getLength(); i++) {
            Node entry = entries.item(i);

            NodeList attributes = entry.getChildNodes();

            for (int j = 0; j < attributes.getLength(); j++) {
                Node attribute = attributes.item(j);
                if (attribute.getNodeType() == Node.TEXT_NODE)
                    continue;
                String nodeName = attribute.getNodeName();

                if (nodeName.equalsIgnoreCase("name") && attribute.hasChildNodes()) {
                    affinityGroup = attribute.getFirstChild().getNodeValue().trim();
                } else if (nodeName.equalsIgnoreCase("location") && attribute.hasChildNodes()) {
                    affinityRegion = attribute.getFirstChild().getNodeValue().trim();
                    if (providerRegionId.equalsIgnoreCase(affinityRegion)) {
                        if (affinityGroup != null && !affinityGroup.equals("")) {
                            DataCenter dc = new DataCenter();

                            dc.setActive(true);
                            dc.setAvailable(true);
                            dc.setName(affinityGroup);
                            dc.setProviderDataCenterId(affinityGroup);
                            dc.setRegionId(providerRegionId);
                            dcs.add(dc);
                        }
                    } else {
                        affinityGroup = null;
                        affinityRegion = null;
                    }
                }
            }
            cache.put(ctx, dcs);
        }
        cache.put(ctx, dcs);
        if (dcs.isEmpty()) {
            logger.info("Create new affinity group for " + providerRegionId);
            //create new affinityGroup
            String name = "Affinity" + (providerRegionId.replaceAll(" ", ""));
            logger.info(name);
            String label;
            try {
                StringBuilder xml = new StringBuilder();

                try {
                    label = new String(Base64.encodeBase64(name.getBytes("utf-8")));
                } catch (UnsupportedEncodingException e) {
                    throw new InternalException(e);
                }

                xml.append("<CreateAffinityGroup xmlns=\"http://schemas.microsoft.com/windowsazure\">");
                xml.append("<Name>").append(name).append("</Name>");
                xml.append("<Label>").append(label).append("</Label>");
                xml.append("<Location>").append(providerRegionId).append("</Location>");
                xml.append("</CreateAffinityGroup>");
                method.post(ctx.getAccountNumber(), "/affinitygroups", xml.toString());
            } catch (CloudException e) {
                logger.error("Unable to create affinity group", e);
                throw new CloudException(e);
            }
            affinityGroup = name;
            DataCenter dc = new DataCenter();

            dc.setActive(true);
            dc.setAvailable(true);
            dc.setName(affinityGroup);
            dc.setProviderDataCenterId(affinityGroup);
            dc.setRegionId(providerRegionId);
            dcs.add(dc);
            cache.put(ctx, dcs);
        }
    }
    return dcs;
}

From source file:org.dasein.cloud.azure.AzureLocation.java

private @Nullable Region toRegion(@Nullable Node entry) {
    if (entry == null) {
        return null;
    }//  w w w . j a  v a2s  .c  o m
    Region region = new Region();

    NodeList attributes = entry.getChildNodes();

    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        String nodeName = attribute.getNodeName();

        if (nodeName.equalsIgnoreCase("name") && attribute.hasChildNodes()) {
            region.setProviderRegionId(attribute.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("displayName") && attribute.hasChildNodes()) {
            region.setName(attribute.getFirstChild().getNodeValue().trim());
        }
    }
    if (region.getProviderRegionId() == null) {
        return null;
    }
    if (region.getName() == null) {
        region.setName(region.getProviderRegionId());
    }
    region.setActive(true);
    region.setAvailable(true);
    region.setJurisdiction("US");
    return region;
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

private void fetchKeys() throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was set for this request");
    }/*from ww  w  .  java 2 s.c o m*/

    if (ctx.getStoragePrivate() == null) {
        AzureMethod method = new AzureMethod(provider);

        String storageService = provider.getStorageService();
        if (storageService == null || storageService.isEmpty()) {
            throw new CloudException(
                    "Unable to find storage service in the current region: " + ctx.getRegionId());
        }

        Document doc = method.getAsXML(ctx.getAccountNumber(),
                "/services/storageservices/" + storageService + "/keys");

        if (doc == null) {
            throw new CloudException("Unable to identify the storage keys for this account");
        }
        NodeList keys = doc.getElementsByTagName("StorageServiceKeys");

        for (int i = 0; i < keys.getLength(); i++) {
            Node key = keys.item(i);

            if (key.getNodeName().equalsIgnoreCase("StorageServiceKeys") && key.hasChildNodes()) {
                NodeList parts = key.getChildNodes();
                String p = null, s = null;

                for (int j = 0; j < parts.getLength(); j++) {
                    Node part = parts.item(j);

                    if (part.getNodeName().equalsIgnoreCase("primary") && part.hasChildNodes()) {
                        p = part.getFirstChild().getNodeValue().trim();
                    } else if (part.getNodeName().equalsIgnoreCase("secondary") && part.hasChildNodes()) {
                        s = part.getFirstChild().getNodeValue().trim();
                    }
                }
                if (p != null) {
                    try {
                        ctx.setStoragePrivate(p.getBytes("utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        logger.error("UTF-8 not supported: " + e.getMessage());
                        throw new InternalException(e);
                    }
                    break;
                } else if (s != null) {
                    try {
                        ctx.setStoragePrivate(s.getBytes("utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        logger.error("UTF-8 not supported: " + e.getMessage());
                        throw new InternalException(e);
                    }
                    break;
                }
            }
        }
    }
}

From source file:org.dasein.cloud.azure.compute.disk.AzureDisk.java

private String getDiskLun(String providerVolumeId, String providerVirtualMachineId)
        throws InternalException, CloudException {

    AzureMethod method = new AzureMethod(provider);

    VirtualMachine vm = provider.getComputeServices().getVirtualMachineSupport()
            .getVirtualMachine(providerVirtualMachineId);

    String resourceDir = HOSTED_SERVICES + "/" + vm.getTag("serviceName") + "/deployments" + "/"
            + vm.getTag("deploymentName");

    Document doc = method.getAsXML(provider.getContext().getAccountNumber(), resourceDir);

    if (doc == null) {
        return null;
    }//  ww  w . j  a va2 s  .com
    NodeList entries = doc.getElementsByTagName("DataVirtualHardDisk");

    if (entries.getLength() < 1) {
        return null;
    }

    for (int i = 0; i < entries.getLength(); i++) {
        Node detail = entries.item(i);

        NodeList attributes = detail.getChildNodes();
        String diskName = null, lunValue = null;
        for (int j = 0; j < attributes.getLength(); j++) {
            Node attribute = attributes.item(j);

            if (attribute.getNodeType() == Node.TEXT_NODE)
                continue;

            if (attribute.getNodeName().equalsIgnoreCase("DiskName") && attribute.hasChildNodes()) {
                diskName = attribute.getFirstChild().getNodeValue().trim();
            } else if (attribute.getNodeName().equalsIgnoreCase("Lun") && attribute.hasChildNodes()) {
                if (diskName != null && diskName.equalsIgnoreCase(providerVolumeId)) {
                    lunValue = attribute.getFirstChild().getNodeValue().trim();
                }
            }
        }
        if (diskName != null && diskName.equalsIgnoreCase(providerVolumeId)) {
            if (lunValue == null) {
                lunValue = "0";
            }
            return lunValue;
        }
    }

    return null;
}

From source file:org.dasein.cloud.azure.compute.disk.AzureDisk.java

private @Nullable Volume toVolume(@Nonnull ProviderContext ctx, @Nullable Node volumeNode)
        throws InternalException, CloudException {
    if (volumeNode == null) {
        return null;
    }//www. j a v  a  2s .c o m

    String regionId = ctx.getRegionId();

    if (regionId == null) {
        throw new AzureConfigException("No region ID was specified for this request");
    }
    Volume disk = new Volume();
    disk.setProviderRegionId(regionId);
    disk.setCurrentState(VolumeState.AVAILABLE);
    disk.setType(VolumeType.HDD);
    boolean mediaLocationFound = false;

    NodeList attributes = volumeNode.getChildNodes();

    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        if (attribute.getNodeType() == Node.TEXT_NODE)
            continue;

        if (attribute.getNodeName().equalsIgnoreCase("AttachedTo") && attribute.hasChildNodes()) {
            NodeList attachAttributes = attribute.getChildNodes();
            String hostedServiceName = null;
            String deploymentName = null;
            String vmRoleName = null;
            for (int k = 0; k < attachAttributes.getLength(); k++) {
                Node attach = attachAttributes.item(k);
                if (attach.getNodeType() == Node.TEXT_NODE)
                    continue;

                if (attach.getNodeName().equalsIgnoreCase("HostedServiceName") && attach.hasChildNodes()) {
                    hostedServiceName = attach.getFirstChild().getNodeValue().trim();
                } else if (attach.getNodeName().equalsIgnoreCase("DeploymentName") && attach.hasChildNodes()) {
                    deploymentName = attach.getFirstChild().getNodeValue().trim();
                } else if (attach.getNodeName().equalsIgnoreCase("RoleName") && attach.hasChildNodes()) {
                    vmRoleName = attach.getFirstChild().getNodeValue().trim();
                }
            }

            if (hostedServiceName != null && deploymentName != null && vmRoleName != null) {
                disk.setProviderVirtualMachineId(hostedServiceName + ":" + deploymentName + ":" + vmRoleName);
            }
        } else if (attribute.getNodeName().equalsIgnoreCase("OS") && attribute.hasChildNodes()) {
            disk.setGuestOperatingSystem(Platform.guess(attribute.getFirstChild().getNodeValue().trim()));
        }

        // disk may have either affinity group or location depending on how storage account is set up
        else if (attribute.getNodeName().equalsIgnoreCase("AffinityGroup") && attribute.hasChildNodes()) {
            //get the region for this affinity group
            String affinityGroup = attribute.getFirstChild().getNodeValue().trim();
            if (affinityGroup != null && !affinityGroup.equals("")) {
                DataCenter dc = provider.getDataCenterServices().getDataCenter(affinityGroup);
                if (dc.getRegionId().equals(disk.getProviderRegionId())) {
                    disk.setProviderDataCenterId(dc.getProviderDataCenterId());
                    mediaLocationFound = true;
                } else {
                    // not correct region/datacenter
                    return null;
                }
            }
        } else if (attribute.getNodeName().equalsIgnoreCase("Location") && attribute.hasChildNodes()) {
            if (!mediaLocationFound && !regionId.equals(attribute.getFirstChild().getNodeValue().trim())) {
                return null;
            }
        } else if (attribute.getNodeName().equalsIgnoreCase("LogicalDiskSizeInGB")
                && attribute.hasChildNodes()) {
            disk.setSize(Storage.valueOf(Integer.valueOf(attribute.getFirstChild().getNodeValue().trim()),
                    "gigabyte"));
        } else if (attribute.getNodeName().equalsIgnoreCase("MediaLink") && attribute.hasChildNodes()) {
            disk.setMediaLink(attribute.getFirstChild().getNodeValue().trim());
        } else if (attribute.getNodeName().equalsIgnoreCase("Name") && attribute.hasChildNodes()) {
            disk.setProviderVolumeId(attribute.getFirstChild().getNodeValue().trim());
        } else if (attribute.getNodeName().equalsIgnoreCase("SourceImageName") && attribute.hasChildNodes()) {
            disk.setProviderSnapshotId(attribute.getFirstChild().getNodeValue().trim());
        }
    }

    if (disk.getGuestOperatingSystem() == null) {
        disk.setGuestOperatingSystem(Platform.UNKNOWN);
    }
    if (disk.getName() == null) {
        disk.setName(disk.getProviderVolumeId());
    }
    if (disk.getDescription() == null) {
        disk.setDescription(disk.getName());
    }
    if (disk.getProviderDataCenterId() == null) {
        DataCenter dc = provider.getDataCenterServices().listDataCenters(regionId).iterator().next();
        disk.setProviderDataCenterId(dc.getProviderDataCenterId());
    }

    return disk;
}

From source file:org.dasein.cloud.azure.compute.disk.AzureDisk.java

private @Nullable ResourceStatus toStatus(@Nonnull ProviderContext ctx, @Nullable Node volumeNode)
        throws InternalException, CloudException {
    if (volumeNode == null) {
        return null;
    }/*from  www . ja v  a  2 s.c  o m*/

    String regionId = ctx.getRegionId();

    if (regionId == null) {
        throw new AzureConfigException("No region ID was specified for this request");
    }

    String id = "";
    boolean mediaLocationFound = false;

    NodeList attributes = volumeNode.getChildNodes();

    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        if (attribute.getNodeType() == Node.TEXT_NODE)
            continue;

        if (attribute.getNodeName().equalsIgnoreCase("Name") && attribute.hasChildNodes()) {
            id = attribute.getFirstChild().getNodeValue().trim();
        } else if (attribute.getNodeName().equalsIgnoreCase("AffinityGroup") && attribute.hasChildNodes()) {
            //get the region for this affinity group
            String affinityGroup = attribute.getFirstChild().getNodeValue().trim();
            if (affinityGroup != null && !affinityGroup.equals("")) {
                DataCenter dc = provider.getDataCenterServices().getDataCenter(affinityGroup);
                if (dc.getRegionId().equals(regionId)) {
                    mediaLocationFound = true;
                } else {
                    // not correct region/datacenter
                    return null;
                }
            }
        } else if (attribute.getNodeName().equalsIgnoreCase("Location") && attribute.hasChildNodes()) {
            if (!mediaLocationFound && !regionId.equals(attribute.getFirstChild().getNodeValue().trim())) {
                return null;
            }
        }
    }

    ResourceStatus status = new ResourceStatus(id, VolumeState.AVAILABLE);

    return status;
}

From source file:org.dasein.cloud.azure.compute.image.AzureOSImage.java

public ResourceStatus toStatus(@Nonnull ProviderContext ctx, @Nullable Node entry)
        throws CloudException, InternalException {
    String regionId = ctx.getRegionId();
    String id = "";

    NodeList attributes = entry.getChildNodes();
    for (int j = 0; j < attributes.getLength(); j++) {
        Node attribute = attributes.item(j);
        if (attribute.getNodeType() == Node.TEXT_NODE)
            continue;
        String nodeName = attribute.getNodeName();

        if (nodeName.equalsIgnoreCase("name") && attribute.hasChildNodes()) {
            id = (attribute.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("category") && attribute.hasChildNodes()) {
            if (!"user".equalsIgnoreCase(attribute.getFirstChild().getNodeValue().trim())) {
                return null;
            }/*from w w  w  . j a va 2s .c  om*/
        } else if (nodeName.equalsIgnoreCase("location") && attribute.hasChildNodes()) {
            if (!regionId.equalsIgnoreCase(attribute.getFirstChild().getNodeValue().trim())) {
                return null;
            }
        }
    }
    return new ResourceStatus(id, MachineImageState.ACTIVE);
}

From source file:org.dasein.cloud.azure.compute.image.AzureOSImage.java

private @Nullable AzureMachineImage toImage(@Nonnull ProviderContext ctx, @Nullable Node entry)
        throws CloudException, InternalException {
    if (entry == null) {
        return null;
    }//from   w w w  .j ava2s . c  om

    String regionID = ctx.getRegionId();
    AzureMachineImage image = new AzureMachineImage();

    HashMap<String, String> tags = new HashMap<String, String>();
    image.setCurrentState(MachineImageState.ACTIVE);
    image.setProviderRegionId(ctx.getRegionId());
    image.setArchitecture(Architecture.I64);

    NodeList attributes = entry.getChildNodes();

    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        if (attribute.getNodeType() == Node.TEXT_NODE)
            continue;
        String nodeName = attribute.getNodeName();

        if (nodeName.equalsIgnoreCase("name") && attribute.hasChildNodes()) {
            image.setProviderMachineImageId(attribute.getFirstChild().getNodeValue().trim());
        }
        if (nodeName.equalsIgnoreCase("category") && attribute.hasChildNodes()) {
            String c = attribute.getFirstChild().getNodeValue().trim();
            if ("user".equalsIgnoreCase(c)) {
                image.setProviderOwnerId(ctx.getAccountNumber());
            } else if (c.toLowerCase().contains("microsoft")) {
                image.setProviderOwnerId(MICROSOFT);
            } else if (c.toLowerCase().contains("partner")) {
                image.setProviderOwnerId("--public--");
            } else if (c.toLowerCase().contains("canonical")) {
                image.setProviderOwnerId("--Canonical--");
            } else if (c.toLowerCase().contains("rightscale with linux")) {
                image.setProviderOwnerId("--RightScaleLinux--");
            } else if (c.toLowerCase().contains("rightscale with windows")) {
                image.setProviderOwnerId("--RightScaleWindows--");
            } else if (c.toLowerCase().contains("openlogic")) {
                image.setProviderOwnerId("--OpenLogic--");
            } else if (c.toLowerCase().contains("suse")) {
                image.setProviderOwnerId("--SUSE--");
            }
        } else if (nodeName.equalsIgnoreCase("label") && attribute.hasChildNodes()) {
            image.setName(attribute.getFirstChild().getNodeValue().trim());

        } else if (nodeName.equalsIgnoreCase("description") && attribute.hasChildNodes()) {
            image.setDescription(attribute.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("location") && attribute.hasChildNodes()) {
            String location = attribute.getFirstChild().getNodeValue().trim();
            String[] locations = location.split(";");
            boolean found = false;
            for (String loc : locations) {
                if (regionID.equalsIgnoreCase(loc)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return null;
            }
        } else if (nodeName.equalsIgnoreCase("medialink") && attribute.hasChildNodes()) {
            image.setMediaLink(attribute.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("os") && attribute.hasChildNodes()) {
            String os = attribute.getFirstChild().getNodeValue().trim();

            if (os.equalsIgnoreCase("windows")) {
                image.setPlatform(Platform.WINDOWS);
            } else if (os.equalsIgnoreCase("linux")) {
                image.setPlatform(Platform.UNIX);
            }
        }
    }
    if (image.getProviderMachineImageId() == null) {
        return null;
    }
    if (image.getName() == null) {
        image.setName(image.getProviderMachineImageId());
    }
    if (image.getDescription() == null) {
        image.setDescription(image.getName());
    }
    String descriptor = image.getProviderMachineImageId() + " " + image.getName() + " "
            + image.getDescription();

    if (image.getPlatform() == null || image.getPlatform().equals(Platform.UNIX)) {
        Platform p = Platform.guess(descriptor);

        if (image.getPlatform() == null || !Platform.UNKNOWN.equals(p)) {
            image.setPlatform(p);
        }
    }
    image.setSoftware(descriptor.contains("SQL Server") ? "SQL Server" : "");
    image.setTags(tags);
    image.setType(MachineImageType.VOLUME);

    return image;
}

From source file:org.dasein.cloud.azure.compute.vm.AzureVM.java

@Override
public VirtualMachine alterVirtualMachineProduct(@Nonnull String virtualMachineId, @Nonnull String productId)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER: " + AzureVM.class.getName() + ".alterVM()");
    }//from www .  ja  v  a  2s  . c  om

    if (virtualMachineId == null || productId == null) {
        throw new AzureConfigException("No virtual machine id and/or product id set for this operation");
    }

    if (!isValidProductId(productId))
        throw new InternalException(
                "Product id invalid: should be one of ExtraSmall, Small, Medium, Large, ExtraLarge");

    VirtualMachine vm = getVirtualMachine(virtualMachineId);

    if (vm == null) {
        throw new CloudException("No such virtual machine: " + virtualMachineId);
    }
    ProviderContext ctx = getProvider().getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was set for this request");
    }
    String serviceName, deploymentName, roleName;

    serviceName = vm.getTag("serviceName").toString();
    deploymentName = vm.getTag("deploymentName").toString();
    roleName = vm.getTag("roleName").toString();

    String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roles/"
            + roleName;

    try {
        AzureMethod method = new AzureMethod(getProvider());

        Document doc = method.getAsXML(ctx.getAccountNumber(), resourceDir);
        StringBuilder xml = new StringBuilder();

        NodeList roles = doc.getElementsByTagName("PersistentVMRole");
        Node role = roles.item(0);

        NodeList entries = role.getChildNodes();
        boolean changeProduct = false;

        for (int i = 0; i < entries.getLength(); i++) {
            Node vn = entries.item(i);
            String vnName = vn.getNodeName();

            if (vnName.equalsIgnoreCase("RoleSize") && vn.hasChildNodes()) {
                if (!productId.equals(vn.getFirstChild().getNodeValue())) {
                    vn.getFirstChild().setNodeValue(productId);
                    changeProduct = true;
                } else {
                    logger.info("No product change required");
                }
                break;
            }
        }

        String requestId = null;

        if (changeProduct) {
            String output = "";
            try {
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                StringWriter writer = new StringWriter();
                transformer.transform(new DOMSource(doc), new StreamResult(writer));
                output = writer.getBuffer().toString().replaceAll("\n|\r", "");
            } catch (Exception e) {
                System.err.println(e);
            }
            xml.append(output);

            logger.debug(xml);
            logger.debug("___________________________________________________");

            resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roles/"
                    + roleName;
            requestId = method.invoke("PUT", ctx.getAccountNumber(), resourceDir, xml.toString());
        } else {
            requestId = "noChange";
        }

        if (requestId != null) {
            int httpCode = -1;
            if (!requestId.equals("noChange")) {
                httpCode = method.getOperationStatus(requestId);
                while (httpCode == -1) {
                    try {
                        Thread.sleep(15000L);
                    } catch (InterruptedException ignored) {
                    }
                    httpCode = method.getOperationStatus(requestId);
                }
            }
        }

        return getVirtualMachine(virtualMachineId);

    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT: " + AzureVM.class.getName() + ".alterVM()");
        }
    }
}

From source file:org.dasein.cloud.azure.compute.vm.AzureVM.java

@Override
public @Nullable VirtualMachine getVirtualMachine(@Nonnull String vmId)
        throws InternalException, CloudException {
    if (vmId == null)
        throw new InternalException("The id of the Virtual Machine cannot be null.");

    String[] parts = vmId.split(":");
    String sName, deploymentName, roleName;

    if (parts.length == 3) {
        sName = parts[0];/*w  w  w.  j ava  2s .  c  om*/
        deploymentName = parts[1];
        roleName = parts[2];
    } else if (parts.length == 2) {
        sName = parts[0];
        deploymentName = parts[1];
        roleName = sName;
    } else {
        sName = vmId;
        deploymentName = vmId;
        roleName = vmId;
    }
    DataCenter dc = null;
    AffinityGroup ag = null;
    ProviderContext ctx = getProvider().getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was specified for this request");
    }
    AzureMethod method = new AzureMethod(getProvider());

    Document doc = method.getAsXML(ctx.getAccountNumber(),
            HOSTED_SERVICES + "/" + sName + "?embed-detail=true");
    if (doc == null) {
        return null;
    }
    NodeList entries = doc.getElementsByTagName("HostedService");
    for (int h = 0; h < entries.getLength(); h++) {
        Node entry = entries.item(h);
        NodeList attributes = entry.getChildNodes();

        boolean mediaLocationFound = false;

        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);

            if (attribute.getNodeType() == Node.TEXT_NODE) {
                continue;
            }
            if (attribute.getNodeName().equalsIgnoreCase("hostedserviceproperties")
                    && attribute.hasChildNodes()) {
                NodeList properties = attribute.getChildNodes();

                for (int j = 0; j < properties.getLength(); j++) {
                    Node property = properties.item(j);

                    if (property.getNodeType() == Node.TEXT_NODE) {
                        continue;
                    }
                    if (property.getNodeName().equalsIgnoreCase("AffinityGroup") && property.hasChildNodes()) {
                        //get the region for this affinity group
                        String affinityGroup = property.getFirstChild().getNodeValue().trim();
                        if (affinityGroup != null && !affinityGroup.equals("")) {
                            ag = getProvider().getComputeServices().getAffinityGroupSupport()
                                    .get(affinityGroup);
                            if (ag == null)
                                return null;

                            dc = getProvider().getDataCenterServices().getDataCenter(ag.getDataCenterId());
                            if (dc != null && dc.getRegionId().equals(ctx.getRegionId())) {
                                mediaLocationFound = true;
                            } else {
                                // not correct region/datacenter
                                return null;
                            }
                        }
                    } else if (property.getNodeName().equalsIgnoreCase("location")
                            && property.hasChildNodes()) {
                        if (!mediaLocationFound
                                && !ctx.getRegionId().equals(property.getFirstChild().getNodeValue().trim())) {
                            return null;
                        }
                    }
                }
            }
        }

    }

    ArrayList<VirtualMachine> list = new ArrayList<VirtualMachine>();
    NodeList deployments = doc.getElementsByTagName("Deployments");
    for (int i = 0; i < deployments.getLength(); i++) {
        Node deployNode = deployments.item(i);
        NodeList deployAttributes = deployNode.getChildNodes();

        String depName = "";
        for (int j = 0; j < deployAttributes.getLength(); j++) {
            Node deployment = deployAttributes.item(j);

            if (deployment.getNodeType() == Node.TEXT_NODE) {
                continue;
            }

            if (deployment.getNodeName().equalsIgnoreCase("Deployment") && deployment.hasChildNodes()) {
                NodeList dAttribs = deployment.getChildNodes();
                for (int k = 0; k < dAttribs.getLength(); k++) {
                    Node mynode = dAttribs.item(k);

                    if (mynode.getNodeName().equalsIgnoreCase("name") && mynode.hasChildNodes()) {
                        depName = mynode.getFirstChild().getNodeValue().trim();
                        if (depName.equalsIgnoreCase(deploymentName)) {
                            parseDeployment(ctx, ctx.getRegionId(), sName + ":" + deploymentName, deployment,
                                    list);
                            if (list != null && list.size() > 0) {
                                for (VirtualMachine vm : list) {
                                    if (vm.getTag("roleName").toString().equalsIgnoreCase(roleName)) {
                                        if (dc != null) {
                                            vm.setProviderDataCenterId(dc.getProviderDataCenterId());
                                        } else {
                                            Collection<DataCenter> dcs = getProvider().getDataCenterServices()
                                                    .listDataCenters(ctx.getRegionId());
                                            vm.setProviderDataCenterId(
                                                    dcs.iterator().next().getProviderDataCenterId());
                                        }
                                        if (ag != null) {
                                            vm.setAffinityGroupId(ag.getAffinityGroupId());
                                        }
                                        return vm;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return null;
}