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.aws.platform.RDS.java

private void populateParameterList(String cfgId, DatabaseEngine engine,
        Jiterator<ConfigurationParameter> iterator) throws CloudException, InternalException {
    APITrace.begin(getProvider(), "RDBMS.populateParameterList");
    try {//from w  ww . ja v  a 2 s.c  o m
        String marker = null;

        do {
            Map<String, String> parameters;
            EC2Method method;
            NodeList blocks;
            Document doc;

            if (cfgId != null) {
                parameters = getProvider().getStandardRdsParameters(getProvider().getContext(),
                        DESCRIBE_DB_PARAMETERS);
                parameters.put("DBParameterGroupName", cfgId);
            } else {
                parameters = getProvider().getStandardRdsParameters(getProvider().getContext(),
                        DESCRIBE_ENGINE_DEFAULT_PARAMETERS);
                parameters.put("Engine", getEngineString(engine));
            }
            if (marker != null) {
                parameters.put("Marker", marker);
            }
            method = new EC2Method(SERVICE_ID, getProvider(), parameters);
            try {
                doc = method.invoke();
            } catch (EC2Exception e) {
                throw new CloudException(e);
            }
            marker = null;
            blocks = doc.getElementsByTagName("Marker");
            if (blocks.getLength() > 0) {
                for (int i = 0; i < blocks.getLength(); i++) {
                    Node item = blocks.item(i);

                    if (item.hasChildNodes()) {
                        marker = item.getFirstChild().getNodeValue().trim();
                    }
                }
                if (marker != null) {
                    break;
                }
            }
            blocks = doc.getElementsByTagName("Parameters");
            for (int i = 0; i < blocks.getLength(); i++) {
                NodeList items = blocks.item(i).getChildNodes();

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

                    if (item.getNodeName().equals("Parameter")) {
                        ConfigurationParameter param = toParameter(item);

                        if (param != null) {
                            iterator.push(param);
                        }
                    }
                }
            }
        } while (marker != null);
    } finally {
        APITrace.end();
    }
}

From source file:org.dasein.cloud.aws.platform.RDS.java

private void populateSnapshotList(String snapshotId, String databaseId, Jiterator<DatabaseSnapshot> iterator)
        throws CloudException, InternalException {
    APITrace.begin(getProvider(), "RDBMS.populateDBSnapshotList");
    try {//from  ww w  .ja  va 2 s .co m
        String marker = null;

        do {
            Map<String, String> parameters = getProvider().getStandardRdsParameters(getProvider().getContext(),
                    DESCRIBE_DB_SNAPSHOTS);
            EC2Method method;
            NodeList blocks;
            Document doc;

            if (marker != null) {
                parameters.put("Marker", marker);
            }
            if (snapshotId != null) {
                parameters.put("DBSnapshotIdentifier", snapshotId);
            }
            if (databaseId != null) {
                parameters.put("DBInstanceIdentifier", databaseId);
            }
            method = new EC2Method(SERVICE_ID, getProvider(), parameters);
            try {
                doc = method.invoke();
            } catch (EC2Exception e) {
                String code = e.getCode();

                if (code != null && code.equals("DBSnapshotNotFound")) {
                    return;
                }
                throw new CloudException(e);
            }
            marker = null;
            blocks = doc.getElementsByTagName("Marker");
            if (blocks.getLength() > 0) {
                for (int i = 0; i < blocks.getLength(); i++) {
                    Node item = blocks.item(i);

                    if (item.hasChildNodes()) {
                        marker = item.getFirstChild().getNodeValue().trim();
                    }
                }
                if (marker != null) {
                    break;
                }
            }
            blocks = doc.getElementsByTagName("DBSnapshots");
            for (int i = 0; i < blocks.getLength(); i++) {
                NodeList items = blocks.item(i).getChildNodes();

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

                    if (item.getNodeName().equals("DBSnapshot")) {
                        DatabaseSnapshot snapshot = toSnapshot(item);

                        if (snapshot != null) {
                            iterator.push(snapshot);
                        }
                    }
                }
            }
        } while (marker != null);
    } finally {
        APITrace.end();
    }
}

From source file:org.dasein.cloud.aws.platform.RDS.java

private Iterable<Database> listDatabases(String targetId) throws CloudException, InternalException {
    APITrace.begin(getProvider(), "RDBMS.listDatabases");
    try {// w w w  . j av  a  2 s.  co  m
        ArrayList<Database> list = new ArrayList<Database>();
        String marker = null;

        do {
            Map<String, String> parameters = getProvider().getStandardRdsParameters(getProvider().getContext(),
                    DESCRIBE_DB_INSTANCES);
            EC2Method method;
            NodeList blocks;
            Document doc;

            if (marker != null) {
                parameters.put("Marker", marker);
            }
            if (targetId != null) {
                parameters.put("DBInstanceIdentifier", targetId);
            }
            method = new EC2Method(SERVICE_ID, getProvider(), parameters);
            try {
                doc = method.invoke();
            } catch (EC2Exception e) {
                if (targetId != null) {
                    String code = e.getCode();

                    if (code != null && code.equals("DBInstanceNotFound")
                            || code.equals("InvalidParameterValue")) {
                        return list;
                    }
                }
                throw new CloudException(e);
            }
            marker = null;
            blocks = doc.getElementsByTagName("Marker");
            if (blocks.getLength() > 0) {
                for (int i = 0; i < blocks.getLength(); i++) {
                    Node item = blocks.item(i);

                    if (item.hasChildNodes()) {
                        marker = item.getFirstChild().getNodeValue().trim();
                    }
                }
                if (marker != null) {
                    break;
                }
            }
            blocks = doc.getElementsByTagName("DBInstances");
            for (int i = 0; i < blocks.getLength(); i++) {
                NodeList items = blocks.item(i).getChildNodes();

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

                    if (item.getNodeName().equals("DBInstance")) {
                        Database db = toDatabase(item);

                        if (db != null) {
                            list.add(db);
                        }
                    }
                }
            }
        } while (marker != null);
        return list;
    } finally {
        APITrace.end();
    }
}

From source file:org.dasein.cloud.aws.platform.RDS.java

@Override
public Iterable<String> getSupportedVersions(DatabaseEngine forEngine)
        throws CloudException, InternalException {
    APITrace.begin(getProvider(), "RDBMS.getSupportedVersions");
    try {/*from   www  .j  a  va2  s.co m*/
        Collection<String> versions = engineVersions.get(forEngine);

        if (versions == null) {
            ArrayList<String> list = new ArrayList<String>();
            String marker = null;

            do {
                Map<String, String> parameters = getProvider()
                        .getStandardRdsParameters(getProvider().getContext(), DESCRIBE_DB_ENGINE_VERSIONS);
                EC2Method method;
                Document doc;

                parameters.put("Engine", getEngineString(forEngine));
                method = new EC2Method(SERVICE_ID, getProvider(), parameters);
                try {
                    doc = method.invoke();
                } catch (EC2Exception e) {
                    throw new CloudException(e);
                }
                marker = null;
                NodeList blocks;
                blocks = doc.getElementsByTagName("Marker");
                if (blocks.getLength() > 0) {
                    for (int i = 0; i < blocks.getLength(); i++) {
                        Node item = blocks.item(i);

                        if (item.hasChildNodes()) {
                            marker = item.getFirstChild().getNodeValue().trim();
                        }
                    }
                    if (marker != null) {
                        break;
                    }
                }
                blocks = doc.getElementsByTagName("DBEngineVersions");
                for (int i = 0; i < blocks.getLength(); i++) {
                    NodeList items = blocks.item(i).getChildNodes();

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

                        if (item.getNodeName().equals("DBEngineVersion")) {
                            NodeList attrs = item.getChildNodes();

                            for (int k = 0; k < attrs.getLength(); k++) {
                                Node attr = attrs.item(k);

                                if (attr.getNodeName().equals("EngineVersion")) {
                                    list.add(attr.getFirstChild().getNodeValue().trim());
                                }
                            }
                        }
                    }
                }
            } while (marker != null);
            if (list.isEmpty()) {
                return Collections.emptyList();
            }
            versions = list;
            engineVersions.put(forEngine, versions);
        }
        return versions;
    } finally {
        APITrace.end();
    }
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

private void escapeNodeText(final NodeList nodes) {

    int l = nodes.getLength();

    if (nodes != null && l > 0) {
        for (int i = 0; i < l; i++) {
            Node currentNode = nodes.item(i);

            //node value
            if (currentNode.getNodeType() == Node.TEXT_NODE) {
                currentNode.setNodeValue(StringEscapeUtils.escapeXml(currentNode.getNodeValue()));
            }// www  .  ja  v a 2s .  c  o m
            //attributes
            NamedNodeMap attributes = currentNode.getAttributes();

            if (attributes != null) {
                int len = attributes.getLength();

                for (int j = 0; j < len; j++) {
                    Node attribute = attributes.item(j);
                    attribute.setNodeValue(StringEscapeUtils.escapeXml(attribute.getNodeValue()));
                }
            }

            if (currentNode.hasChildNodes()) {
                escapeNodeText(currentNode.getChildNodes());
            }

            //logger.info("current: " + DomUtils.elementToString(currentNode, true, Encoding.ISO8859_1));
        }
    }

}

From source file:org.dasein.cloud.vcloud.vCloudMethod.java

private @Nonnull Version getVersion() throws CloudException, InternalException {
    Cache<Version> cache = Cache.getInstance(provider, "vCloudVersions", Version.class, CacheLevel.CLOUD,
            new TimePeriod<Day>(1, TimePeriod.DAY));

    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new CloudException("No context was defined for this request");
    }/* ww  w.  ja  va  2s  . c  o  m*/
    {
        Iterable<Version> versions = cache.get(ctx);

        Iterator<Version> it = (versions == null ? null : versions.iterator());

        if (it != null && it.hasNext()) {
            return it.next();
        }
    }
    // TODO: how does vCHS do version discovery?
    if (ctx.getCloud().getEndpoint().startsWith("https://vchs")) {
        // This is a complete hack that needs to be changed to reflect vCHS version discovery
        Version version = new Version();

        version.loginUrl = ctx.getCloud().getEndpoint() + "/api/vchs/sessions";
        version.version = "5.6";
        cache.put(ctx, Collections.singletonList(version));
        return version;
    }
    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(">>> [GET (" + (new Date()) + ")] -> " + ctx.getCloud().getEndpoint()
                + " >--------------------------------------------------------------------------------------");
    }
    try {
        final String[] preferred = provider.getVersionPreference();
        HttpClient client = getClient(false);
        HttpGet method = new HttpGet(ctx.getCloud().getEndpoint() + "/api/versions");

        if (wire.isDebugEnabled()) {
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;
        StatusLine status;

        try {
            APITrace.trace(provider, "GET versions");
            response = client.execute(method);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
            status = response.getStatusLine();
        } catch (IOException e) {
            throw new CloudException(e);
        }
        if (status.getStatusCode() == HttpServletResponse.SC_OK) {
            HttpEntity entity = response.getEntity();
            String body;

            try {
                body = EntityUtils.toString(entity);
                if (wire.isDebugEnabled()) {
                    wire.debug(body);
                    wire.debug("");
                }
            } catch (IOException e) {
                throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            try {
                ByteArrayInputStream bas = new ByteArrayInputStream(body.getBytes());

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder parser = factory.newDocumentBuilder();
                Document doc = parser.parse(bas);

                bas.close();

                NodeList versions = doc.getElementsByTagName("VersionInfo");
                TreeSet<Version> set = new TreeSet<Version>(new Comparator<Version>() {
                    public int compare(Version version1, Version version2) {
                        if (version1.equals(version2)) {
                            return 0;
                        }
                        if (preferred != null) {
                            for (String v : preferred) {
                                if (v.equals(version1.version)) {
                                    return -1;
                                } else if (v.equals(version2.version)) {
                                    return 1;
                                }
                            }
                        }
                        for (String v : VERSIONS) {
                            if (v.equals(version1.version)) {
                                return -1;
                            } else if (v.equals(version2.version)) {
                                return 1;
                            }
                        }
                        return -version1.version.compareTo(version2.version);
                    }
                });
                for (int i = 0; i < versions.getLength(); i++) {
                    Node versionInfo = versions.item(i);
                    NodeList vattrs = versionInfo.getChildNodes();
                    String version = null;
                    String url = null;

                    for (int j = 0; j < vattrs.getLength(); j++) {
                        Node attr = vattrs.item(j);

                        if (attr.getNodeName().equalsIgnoreCase("Version") && attr.hasChildNodes()) {
                            version = attr.getFirstChild().getNodeValue().trim();
                        } else if (attr.getNodeName().equalsIgnoreCase("LoginUrl") && attr.hasChildNodes()) {
                            url = attr.getFirstChild().getNodeValue().trim();
                        }
                    }
                    if (version == null || url == null || !isSupported(version)) {

                        continue;
                    }
                    Version v = new Version();
                    v.version = version;
                    v.loginUrl = url;
                    set.add(v);
                }
                if (set.isEmpty()) {
                    throw new CloudException("Unable to identify a supported version");
                }
                Version v = set.iterator().next();

                cache.put(ctx, set);
                return v;
            } catch (IOException e) {
                throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            } catch (ParserConfigurationException e) {
                throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            } catch (SAXException e) {
                throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
        } else {

            logger.error("Expected OK for GET request, got " + status.getStatusCode());
            String xml = null;

            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    xml = EntityUtils.toString(entity);
                    if (wire.isDebugEnabled()) {
                        wire.debug(xml);
                        wire.debug("");
                    }
                }
            } catch (IOException e) {
                logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
                throw new CloudException(e);
            }

            vCloudException.Data data = null;

            if (xml != null && !xml.equals("")) {
                Document doc = parseXML(xml);
                String docElementTagName = doc.getDocumentElement().getTagName();
                String nsString = "";
                if (docElementTagName.contains(":"))
                    nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1);
                NodeList errors = doc.getElementsByTagName(nsString + "Error");

                if (errors.getLength() > 0) {
                    data = vCloudException.parseException(status.getStatusCode(), errors.item(0));
                }
            }
            if (data == null) {
                throw new vCloudException(CloudErrorType.GENERAL, status.getStatusCode(),
                        response.getStatusLine().getReasonPhrase(), "No further information");
            }
            logger.error("[" + status.getStatusCode() + " : " + data.title + "] " + data.description);
            throw new vCloudException(data);
        }
    } finally {
        if (wire.isDebugEnabled()) {
            wire.debug("<<< [GET (" + (new Date()) + ")] -> " + ctx.getEndpoint()
                    + " <--------------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
}

From source file:com.flexive.core.storage.GenericDivisionImporter.java

/**
 * Import briefcases//from  w  w w .j  a  v  a2  s . c o m
 *
 * @param con        an open and valid connection to store imported data
 * @param zip        zip file containing the data
 * @param exportInfo information about the exported data
 * @throws Exception on errors
 */
public void importFlatStorages(Connection con, ZipFile zip, FxDivisionExportInfo exportInfo) throws Exception {
    if (!canImportFlatStorages(exportInfo)) {
        importFlatStoragesHierarchical(con, zip);
        return;
    }
    ZipEntry ze = getZipEntry(zip, FILE_FLATSTORAGE_META);
    Statement stmt = con.createStatement();
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(zip.getInputStream(ze));
        XPath xPath = XPathFactory.newInstance().newXPath();

        NodeList nodes = (NodeList) xPath.evaluate("/flatstorageMeta/storageMeta", document,
                XPathConstants.NODESET);
        Node currNode;
        List<String> storages = new ArrayList<String>(5);
        for (int i = 0; i < nodes.getLength(); i++) {
            currNode = nodes.item(i);
            int cbigInt = Integer.parseInt(currNode.getAttributes().getNamedItem("bigInt").getNodeValue());
            int cdouble = Integer.parseInt(currNode.getAttributes().getNamedItem("double").getNodeValue());
            int cselect = Integer.parseInt(currNode.getAttributes().getNamedItem("select").getNodeValue());
            int cstring = Integer.parseInt(currNode.getAttributes().getNamedItem("string").getNodeValue());
            int ctext = Integer.parseInt(currNode.getAttributes().getNamedItem("text").getNodeValue());
            String tableName = null;
            String description = null;
            if (currNode.hasChildNodes()) {
                for (int j = 0; j < currNode.getChildNodes().getLength(); j++)
                    if (currNode.getChildNodes().item(j).getNodeName().equals("name")) {
                        tableName = currNode.getChildNodes().item(j).getTextContent();
                    } else if (currNode.getChildNodes().item(j).getNodeName().equals("description")) {
                        description = currNode.getChildNodes().item(j).getTextContent();
                    }
            }
            if (tableName != null) {
                if (description == null)
                    description = "FlatStorage " + tableName;
                final FxFlatStorage flatStorage = FxFlatStorageManager.getInstance();
                for (FxFlatStorageInfo fi : flatStorage.getFlatStorageInfos()) {
                    if (fi.getName().equals(tableName)) {
                        flatStorage.removeFlatStorage(tableName);
                        break;
                    }
                }
                // TODO - flat storage type detection
                flatStorage.createFlatStorage(con, tableName, FxFlatStorageInfo.Type.TypeNormal, description,
                        cstring, ctext, cbigInt, cdouble, cselect);
                storages.add(tableName);
            }
        }

        importTable(stmt, zip, ze, "flatstorageMeta/mapping", DatabaseConst.TBL_STRUCT_FLATSTORE_MAPPING);

        ZipEntry zeData = getZipEntry(zip, FILE_DATA_FLAT);
        for (String storage : storages)
            importTable(stmt, zip, zeData, "flatstorages/storage[@name='" + storage + "']/data", storage);
    } finally {
        Database.closeObjects(GenericDivisionImporter.class, stmt);
    }
}

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

private void parseDeployment(@Nonnull ProviderContext ctx, @Nonnull String regionId,
        @Nonnull String serviceName, @Nonnull Node node, @Nonnull List<VirtualMachine> virtualMachines) {
    ArrayList<VirtualMachine> list = new ArrayList<VirtualMachine>();
    NodeList attributes = node.getChildNodes();
    String deploymentSlot = null;
    String deploymentId = null;//from   w  w w. ja va  2  s  .c o  m
    String dnsName = null;
    String vmRoleName = null;
    String imageId = null;
    String vmImageId = null;
    String diskOS = null;
    String mediaLink = null;
    String vlan = null;
    String subnetName = null;
    boolean isLocked = 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("deploymentslot") && attribute.hasChildNodes()) {
            deploymentSlot = attribute.getFirstChild().getNodeValue().trim();
        } else if (attribute.getNodeName().equalsIgnoreCase("privateid") && attribute.hasChildNodes()) {
            deploymentId = attribute.getFirstChild().getNodeValue().trim();
        } else if (attribute.getNodeName().equalsIgnoreCase("locked") && attribute.hasChildNodes()) {
            if (attribute.getFirstChild().getNodeValue().trim().equalsIgnoreCase("true")) {
                isLocked = true;
            }
        } else if (attribute.getNodeName().equalsIgnoreCase("url") && attribute.hasChildNodes()) {
            try {
                URI u = new URI(attribute.getFirstChild().getNodeValue().trim());

                dnsName = u.getHost();
            } catch (URISyntaxException e) {
                // ignore
            }
        } else if (attribute.getNodeName().equalsIgnoreCase("roleinstancelist") && attribute.hasChildNodes()) {
            NodeList roleInstances = attribute.getChildNodes();

            for (int j = 0; j < roleInstances.getLength(); j++) {
                Node roleInstance = roleInstances.item(j);

                if (roleInstance.getNodeType() == Node.TEXT_NODE) {
                    continue;
                }
                if (roleInstance.getNodeName().equalsIgnoreCase("roleinstance")
                        && roleInstance.hasChildNodes()) {
                    VirtualMachine role = new VirtualMachine();

                    role.setArchitecture(Architecture.I64);
                    role.setClonable(false);
                    role.setCurrentState(VmState.TERMINATED);
                    role.setImagable(false);
                    role.setPersistent(true);
                    role.setPlatform(Platform.UNKNOWN);
                    role.setProviderOwnerId(ctx.getAccountNumber());
                    role.setProviderRegionId(regionId);
                    role.setProviderDataCenterId(regionId);

                    NodeList roleAttributes = roleInstance.getChildNodes();

                    for (int l = 0; l < roleAttributes.getLength(); l++) {
                        Node roleAttribute = roleAttributes.item(l);

                        if (roleAttribute.getNodeType() == Node.TEXT_NODE) {
                            continue;
                        }
                        if (roleAttribute.getNodeName().equalsIgnoreCase("RoleName")
                                && roleAttribute.hasChildNodes()) {
                            String vmId = roleAttribute.getFirstChild().getNodeValue().trim();

                            role.setProviderVirtualMachineId(serviceName + ":" + vmId);
                            role.setName(vmId);
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("instancesize")
                                && roleAttribute.hasChildNodes()) {
                            role.setProductId(roleAttribute.getFirstChild().getNodeValue().trim());
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("instanceupgradedomain")
                                && roleAttribute.hasChildNodes()) {
                            role.setTag("UpgradeDomain", roleAttribute.getFirstChild().getNodeValue().trim());
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("instanceerrorcode")
                                && roleAttribute.hasChildNodes()) {
                            role.setTag("ErrorCode", roleAttribute.getFirstChild().getNodeValue().trim());
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("instancefaultdomain")
                                && roleAttribute.hasChildNodes()) {
                            role.setTag("FaultDomain", roleAttribute.getFirstChild().getNodeValue().trim());
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("fqdn")
                                && roleAttribute.hasChildNodes()) {
                            role.setPrivateDnsAddress(roleAttribute.getFirstChild().getNodeValue().trim());
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("ipaddress")
                                && roleAttribute.hasChildNodes()) {
                            role.setPrivateAddresses(new RawAddress[] {
                                    new RawAddress(roleAttribute.getFirstChild().getNodeValue().trim()) });
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("instanceendpoints")
                                && roleAttribute.hasChildNodes()) {
                            NodeList endpoints = roleAttribute.getChildNodes();

                            for (int m = 0; m < endpoints.getLength(); m++) {
                                Node endpoint = endpoints.item(m);

                                if (endpoint.hasChildNodes()) {
                                    NodeList ea = endpoint.getChildNodes();

                                    for (int n = 0; n < ea.getLength(); n++) {
                                        Node a = ea.item(n);

                                        if (a.getNodeName().equalsIgnoreCase("vip") && a.hasChildNodes()) {
                                            String addr = a.getFirstChild().getNodeValue().trim();
                                            RawAddress[] ips = role.getPublicAddresses();

                                            if (ips == null || ips.length < 1) {
                                                role.setPublicAddresses(
                                                        new RawAddress[] { new RawAddress(addr) });
                                            } else {
                                                boolean found = false;

                                                for (RawAddress ip : ips) {
                                                    if (ip.getIpAddress().equals(addr)) {
                                                        found = true;
                                                        break;
                                                    }
                                                }
                                                if (!found) {
                                                    RawAddress[] tmp = new RawAddress[ips.length + 1];

                                                    System.arraycopy(ips, 0, tmp, 0, ips.length);
                                                    tmp[tmp.length - 1] = new RawAddress(addr);
                                                    role.setPublicAddresses(tmp);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("PowerState")
                                && roleAttribute.hasChildNodes()) {
                            String powerStatus = roleAttribute.getFirstChild().getNodeValue().trim();

                            if ("Started".equalsIgnoreCase(powerStatus)) {
                                role.setCurrentState(VmState.RUNNING);
                            } else if ("Stopped".equalsIgnoreCase(powerStatus)) {
                                role.setCurrentState(VmState.STOPPED);
                                role.setImagable(true);
                            } else if ("Stopping".equalsIgnoreCase(powerStatus)) {
                                role.setCurrentState(VmState.STOPPING);
                            } else if ("Starting".equalsIgnoreCase(powerStatus)) {
                                role.setCurrentState(VmState.PENDING);
                            } else {
                                logger.warn("DEBUG: Unknown Azure status: " + powerStatus);
                            }
                        }
                    }
                    if (role.getProviderVirtualMachineId() == null) {
                        continue;
                    }
                    if (role.getName() == null) {
                        role.setName(role.getProviderVirtualMachineId());
                    }
                    if (role.getDescription() == null) {
                        role.setDescription(role.getName());
                    }
                    if (role.getPlatform().equals(Platform.UNKNOWN)) {
                        String descriptor = (role.getProviderVirtualMachineId() + " " + role.getName() + " "
                                + role.getDescription() + " " + role.getProviderMachineImageId())
                                        .replaceAll("_", " ");

                        role.setPlatform(Platform.guess(descriptor));
                    } else if (role.getPlatform().equals(Platform.UNIX)) {
                        String descriptor = (role.getProviderVirtualMachineId() + " " + role.getName() + " "
                                + role.getDescription() + " " + role.getProviderMachineImageId())
                                        .replaceAll("_", " ");
                        Platform p = Platform.guess(descriptor);

                        if (p.isUnix()) {
                            role.setPlatform(p);
                        }
                    }
                    list.add(role);
                }
            }
        }
        //Contain the information about disk and firewall;
        else if (attribute.getNodeName().equalsIgnoreCase("rolelist") && attribute.hasChildNodes()) {
            NodeList roles = attribute.getChildNodes();

            for (int k = 0; k < roles.getLength(); k++) {
                Node role = roles.item(k);

                if (role.getNodeName().equalsIgnoreCase("role") && role.hasChildNodes()) {
                    if (role.hasAttributes()) {
                        Node n = role.getAttributes().getNamedItem("i:type");

                        if (n != null) {
                            String val = n.getNodeValue();

                            if (!"PersistentVMRole".equalsIgnoreCase(val)) {
                                continue;
                            }
                        }
                    }
                    NodeList roleAttributes = role.getChildNodes();

                    for (int l = 0; l < roleAttributes.getLength(); l++) {
                        Node roleAttribute = roleAttributes.item(l);

                        if (roleAttribute.getNodeType() == Node.TEXT_NODE) {
                            continue;
                        }
                        if (roleAttribute.getNodeName().equalsIgnoreCase("osvirtualharddisk")
                                && roleAttribute.hasChildNodes()) {
                            NodeList diskAttributes = roleAttribute.getChildNodes();

                            for (int m = 0; m < diskAttributes.getLength(); m++) {
                                Node diskAttribute = diskAttributes.item(m);

                                if (diskAttribute.getNodeName().equalsIgnoreCase("SourceImageName")
                                        && diskAttribute.hasChildNodes()) {
                                    imageId = diskAttribute.getFirstChild().getNodeValue().trim();
                                } else if (diskAttribute.getNodeName().equalsIgnoreCase("medialink")
                                        && diskAttribute.hasChildNodes()) {
                                    mediaLink = diskAttribute.getFirstChild().getNodeValue().trim();
                                } else if (diskAttribute.getNodeName().equalsIgnoreCase("OS")
                                        && diskAttribute.hasChildNodes()) {
                                    diskOS = diskAttribute.getFirstChild().getNodeValue().trim();
                                }
                            }
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("RoleName")
                                && roleAttribute.hasChildNodes()) {
                            vmRoleName = roleAttribute.getFirstChild().getNodeValue().trim();
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("VMImageName")
                                && roleAttribute.hasChildNodes()) {
                            vmImageId = roleAttribute.getFirstChild().getNodeValue().trim();
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("ConfigurationSets")
                                && roleAttribute.hasChildNodes()) {
                            NodeList configs = ((Element) roleAttribute)
                                    .getElementsByTagName("ConfigurationSet");

                            for (int n = 0; n < configs.getLength(); n++) {
                                boolean foundNetConfig = false;
                                Node config = configs.item(n);

                                if (config.hasAttributes()) {
                                    Node c = config.getAttributes().getNamedItem("i:type");

                                    if (c != null) {
                                        String val = c.getNodeValue();

                                        if (!"NetworkConfigurationSet".equalsIgnoreCase(val)) {
                                            continue;
                                        }
                                    }
                                }

                                if (config.hasChildNodes()) {
                                    NodeList configAttribs = config.getChildNodes();

                                    for (int o = 0; o < configAttribs.getLength(); o++) {
                                        Node attrib = configAttribs.item(o);
                                        if (attrib.getNodeName().equalsIgnoreCase("SubnetNames")
                                                && attrib.hasChildNodes()) {
                                            NodeList subnets = attrib.getChildNodes();

                                            for (int p = 0; p < subnets.getLength(); p++) {
                                                Node subnet = subnets.item(p);
                                                if (subnet.getNodeName().equalsIgnoreCase("SubnetName")
                                                        && subnet.hasChildNodes()) {
                                                    subnetName = subnet.getFirstChild().getNodeValue().trim();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if (attribute.getNodeName().equalsIgnoreCase("virtualnetworkname")
                && attribute.hasChildNodes()) {
            vlan = attribute.getFirstChild().getNodeValue().trim();
        }
    }
    if (vmRoleName != null) {
        for (VirtualMachine vm : list) {
            if (deploymentSlot != null) {
                vm.setTag("environment", deploymentSlot);
            }
            if (deploymentId != null) {
                vm.setTag("deploymentId", deploymentId);
            }
            if (dnsName != null) {
                vm.setPublicDnsAddress(dnsName);
            }
            if (vmImageId != null) {
                vm.setProviderMachineImageId(vmImageId);
                vm.setPlatform(Platform.guess(diskOS));
            } else if (imageId != null) {
                Platform fallback = vm.getPlatform();

                vm.setProviderMachineImageId(imageId);
                vm.setPlatform(Platform.guess(vm.getProviderMachineImageId()));
                if (vm.getPlatform().equals(Platform.UNKNOWN)) {
                    try {
                        MachineImage img = getProvider().getComputeServices().getImageSupport()
                                .getMachineImage(vm.getProviderMachineImageId());

                        if (img != null) {
                            vm.setPlatform(img.getPlatform());
                        }
                    } catch (Throwable t) {
                        logger.warn("Error loading machine image: " + t.getMessage());
                    }
                    if (vm.getPlatform().equals(Platform.UNKNOWN)) {
                        vm.setPlatform(fallback);
                    }
                }
            }

            if (vlan != null) {
                String providerVlanId = null;

                try {
                    providerVlanId = getProvider().getNetworkServices().getVlanSupport().getVlan(vlan)
                            .getProviderVlanId();
                    vm.setProviderVlanId(providerVlanId);
                } catch (CloudException e) {
                    logger.error("Error getting vlan id for vlan " + vlan);
                    continue;
                } catch (InternalException ie) {
                    logger.error("Error getting vlan id for vlan " + vlan);
                    continue;
                }

                if (subnetName != null) {
                    vm.setProviderSubnetId(subnetName + "_" + providerVlanId);
                }
            }

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

            if (parts.length == 3) {
                sName = parts[0];
                deploymentName = parts[1];
                roleName = parts[2];
            } else if (parts.length == 2) {
                sName = parts[0];
                deploymentName = parts[1];
                roleName = deploymentName;
            } else {
                sName = serviceName;
                deploymentName = serviceName;
                roleName = serviceName;
            }
            vm.setTag("serviceName", sName);
            vm.setTag("deploymentName", deploymentName);
            vm.setTag("roleName", roleName);
            if (isLocked) {
                vm.setTag("locked", String.valueOf(isLocked));
            }
            if (mediaLink != null) {
                vm.setTag("mediaLink", mediaLink);
            }
            virtualMachines.add(vm);
        }
    }
}

From source file:org.dasein.cloud.aws.platform.RDS.java

private void populateAccess(String securityGroupId, Jiterator<String> iterator)
        throws CloudException, InternalException {
    APITrace.begin(getProvider(), "RDBMS.populateDBSGAccess");
    try {/*from   w  ww. j a v  a 2s  . c o m*/
        Map<String, String> parameters = getProvider().getStandardRdsParameters(getProvider().getContext(),
                DESCRIBE_DB_SECURITY_GROUPS);
        EC2Method method;
        NodeList blocks;
        Document doc;

        parameters.put("DBSecurityGroupName", securityGroupId);
        method = new EC2Method(SERVICE_ID, getProvider(), parameters);
        try {
            doc = method.invoke();
        } catch (EC2Exception e) {
            throw new CloudException(e);
        }
        blocks = doc.getElementsByTagName("DBSecurityGroups");
        for (int i = 0; i < blocks.getLength(); i++) {
            NodeList items = blocks.item(i).getChildNodes();

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

                if (item.getNodeName().equals("DBSecurityGroup")) {
                    NodeList attrs = item.getChildNodes();

                    for (int k = 0; k < attrs.getLength(); k++) {
                        Node attr = attrs.item(k);
                        String name;

                        name = attr.getNodeName();
                        if (name.equalsIgnoreCase("IPRanges")) {
                            if (attr.hasChildNodes()) {
                                NodeList ranges = attr.getChildNodes();

                                for (int l = 0; l < ranges.getLength(); l++) {
                                    Node range = ranges.item(l);

                                    if (range.hasChildNodes()) {
                                        NodeList rangeAttrs = range.getChildNodes();
                                        String cidr = null;
                                        boolean authorized = false;

                                        for (int m = 0; m < rangeAttrs.getLength(); m++) {
                                            Node ra = rangeAttrs.item(m);

                                            if (ra.getNodeName().equalsIgnoreCase("Status")) {
                                                authorized = ra.getFirstChild().getNodeValue().trim()
                                                        .equalsIgnoreCase("authorized");
                                            } else if (ra.getNodeName().equalsIgnoreCase("CIDRIP")) {
                                                cidr = ra.getFirstChild().getNodeValue().trim();
                                            }
                                        }
                                        if (cidr != null && authorized) {
                                            iterator.push(cidr);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } finally {
        APITrace.end();
    }
}

From source file:org.dasein.cloud.aws.platform.RDS.java

private void populateSecurityGroupIds(String providerDatabaseId, Jiterator<String> iterator)
        throws CloudException, InternalException {
    APITrace.begin(getProvider(), "RDBMS.populateDBSecurityGroups");
    try {/*from w  ww  .jav a  2 s  . co  m*/
        Map<String, String> parameters = getProvider().getStandardRdsParameters(getProvider().getContext(),
                DESCRIBE_DB_INSTANCES);
        EC2Method method;
        NodeList blocks;
        Document doc;

        parameters.put("DBInstanceIdentifier", providerDatabaseId);
        method = new EC2Method(SERVICE_ID, getProvider(), parameters);
        try {
            doc = method.invoke();
        } catch (EC2Exception e) {
            throw new CloudException(e);
        }
        blocks = doc.getElementsByTagName("DBInstances");
        for (int i = 0; i < blocks.getLength(); i++) {
            NodeList items = blocks.item(i).getChildNodes();

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

                if (item.getNodeName().equals("DBInstance")) {
                    NodeList attrs = item.getChildNodes();

                    for (int k = 0; k < attrs.getLength(); k++) {
                        Node attr = attrs.item(k);
                        String name;

                        name = attr.getNodeName();
                        if (name.equalsIgnoreCase("DBSecurityGroups")) {
                            if (attr.hasChildNodes()) {
                                NodeList groups = attr.getChildNodes();

                                for (int l = 0; l < groups.getLength(); l++) {
                                    Node group = groups.item(l);

                                    if (group.hasChildNodes()) {
                                        NodeList groupAttrs = group.getChildNodes();
                                        String groupName = null;
                                        boolean active = false;

                                        for (int m = 0; m < groupAttrs.getLength(); m++) {
                                            Node ga = groupAttrs.item(m);

                                            if (ga.getNodeName().equalsIgnoreCase("Status")) {
                                                active = ga.getFirstChild().getNodeValue().trim()
                                                        .equalsIgnoreCase("active");
                                            } else if (ga.getNodeName()
                                                    .equalsIgnoreCase("DBSecurityGroupName")) {
                                                groupName = ga.getFirstChild().getNodeValue().trim();
                                            }
                                        }
                                        if (groupName != null && active) {
                                            iterator.push(groupName);
                                        }
                                    }
                                }
                            }
                        } else if (name.equalsIgnoreCase("VpcSecurityGroups")) {
                            if (attr.hasChildNodes()) {
                                NodeList groups = attr.getChildNodes(); // VpcSecurityGroupMembership

                                for (int l = 0; l < groups.getLength(); l++) {
                                    Node group = groups.item(l);

                                    if (group.hasChildNodes()) {
                                        NodeList groupAttrs = group.getChildNodes();
                                        String groupName = null;
                                        boolean active = false;

                                        for (int m = 0; m < groupAttrs.getLength(); m++) {
                                            Node ga = groupAttrs.item(m);

                                            if (ga.getNodeName().equalsIgnoreCase("Status")) {
                                                active = ga.getFirstChild().getNodeValue().trim()
                                                        .equalsIgnoreCase("active");
                                            } else if (ga.getNodeName()
                                                    .equalsIgnoreCase("VpcSecurityGroupId")) {
                                                groupName = ga.getFirstChild().getNodeValue().trim();
                                            }
                                        }
                                        if (groupName != null && active) {
                                            iterator.push(groupName);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } finally {
        APITrace.end();
    }
}