Example usage for org.w3c.dom Node TEXT_NODE

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

Introduction

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

Prototype

short TEXT_NODE

To view the source code for org.w3c.dom Node TEXT_NODE.

Click Source Link

Document

The node is a Text node.

Usage

From source file:jef.tools.XMLUtils.java

/**
 * ?(Trimed)//from w  w  w.j a v  a  2s.  c o  m
 * 
 * @param element
 *            
 * @return xml
 */
public static String nodeText(Node element) {
    Node first = first(element, Node.TEXT_NODE, Node.CDATA_SECTION_NODE);
    if (first != null && first.getNodeType() == Node.CDATA_SECTION_NODE) {
        return ((CDATASection) first).getTextContent();
    }
    StringBuilder sb = new StringBuilder();
    if (first == null || StringUtils.isBlank(first.getTextContent())) {
        for (Node n : toArray(element.getChildNodes())) {
            if (n.getNodeType() == Node.TEXT_NODE) {
                sb.append(n.getTextContent());
            } else if (n.getNodeType() == Node.CDATA_SECTION_NODE) {
                sb.append(((CDATASection) n).getTextContent());
            }
        }
    } else {
        sb.append(first.getTextContent());
    }
    return StringUtils.trimToNull(StringEscapeUtils.unescapeHtml(sb.toString()));
}

From source file:jef.tools.XMLUtils.java

/**
 * text/* w w  w .ja v a2s  .c o  m*/
 * 
 * @param element
 *            
 * @param withChildren
 *            ???
 * @return xml
 */
public static String nodeText(Node element, boolean withChildren) {
    StringBuilder sb = new StringBuilder();
    for (Node node : toArray(element.getChildNodes())) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            sb.append(node.getNodeValue().trim());
        } else if (node.getNodeType() == Node.CDATA_SECTION_NODE) {
            sb.append(((CDATASection) node).getTextContent());
        } else if (withChildren) {
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                sb.append(nodeText((Element) node, true));
            }
        }
    }
    return sb.toString();
}

From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java

/**
 * LOCK Method.//  w w w. j a  v a  2s.c om
 *
 * @param req  Description of the Parameter
 * @param resp Description of the Parameter
 * @throws javax.servlet.ServletException Description of the Exception
 * @throws java.io.IOException            Description of the Exception
 */
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (readOnly) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;
    }

    WebdavServlet.LockInfo lock = new WebdavServlet.LockInfo();

    // Parsing lock request

    // Parsing depth header

    String depthStr = req.getHeader("Depth");

    if (depthStr == null) {
        lock.depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            lock.depth = 0;
        } else {
            lock.depth = INFINITY;
        }
    }

    // Parsing timeout header

    int lockDuration = DEFAULT_TIMEOUT;
    String lockDurationStr = req.getHeader("Timeout");
    if (lockDurationStr == null) {
        lockDuration = DEFAULT_TIMEOUT;
    } else {
        int commaPos = lockDurationStr.indexOf(",");
        // If multiple timeouts, just use the first
        if (commaPos != -1) {
            lockDurationStr = lockDurationStr.substring(0, commaPos);
        }
        if (lockDurationStr.startsWith("Second-")) {
            lockDuration = (new Integer(lockDurationStr.substring(7))).intValue();
        } else {
            if (lockDurationStr.equalsIgnoreCase("infinity")) {
                lockDuration = MAX_TIMEOUT;
            } else {
                try {
                    lockDuration = (new Integer(lockDurationStr)).intValue();
                } catch (NumberFormatException e) {
                    lockDuration = MAX_TIMEOUT;
                }
            }
        }
        if (lockDuration == 0) {
            lockDuration = DEFAULT_TIMEOUT;
        }
        if (lockDuration > MAX_TIMEOUT) {
            lockDuration = MAX_TIMEOUT;
        }
    }
    lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000);

    int lockRequestType = LOCK_CREATION;

    Node lockInfoNode = null;

    DocumentBuilder documentBuilder = getDocumentBuilder();

    try {
        Document document = documentBuilder.parse(new InputSource(req.getInputStream()));

        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        lockInfoNode = rootElement;
    } catch (Exception e) {
        lockRequestType = LOCK_REFRESH;
    }

    if (lockInfoNode != null) {

        // Reading lock information

        NodeList childList = lockInfoNode.getChildNodes();
        StringWriter strWriter = null;
        DOMWriter domWriter = null;

        Node lockScopeNode = null;
        Node lockTypeNode = null;
        Node lockOwnerNode = null;

        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentNode.getNodeName();
                if (nodeName.endsWith("lockscope")) {
                    lockScopeNode = currentNode;
                }
                if (nodeName.endsWith("locktype")) {
                    lockTypeNode = currentNode;
                }
                if (nodeName.endsWith("owner")) {
                    lockOwnerNode = currentNode;
                }
                break;
            }
        }

        if (lockScopeNode != null) {

            childList = lockScopeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempScope = currentNode.getNodeName();
                    if (tempScope.indexOf(':') != -1) {
                        lock.scope = tempScope.substring(tempScope.indexOf(':') + 1);
                    } else {
                        lock.scope = tempScope;
                    }
                    break;
                }
            }

            if (lock.scope == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockTypeNode != null) {

            childList = lockTypeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempType = currentNode.getNodeName();
                    if (tempType.indexOf(':') != -1) {
                        lock.type = tempType.substring(tempType.indexOf(':') + 1);
                    } else {
                        lock.type = tempType;
                    }
                    break;
                }
            }

            if (lock.type == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockOwnerNode != null) {

            childList = lockOwnerNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    lock.owner += currentNode.getNodeValue();
                    break;
                case Node.ELEMENT_NODE:
                    strWriter = new StringWriter();
                    domWriter = new DOMWriter(strWriter, true);
                    domWriter.setQualifiedNames(false);
                    domWriter.print(currentNode);
                    lock.owner += strWriter.toString();
                    break;
                }
            }

            if (lock.owner == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            lock.owner = new String();
        }

    }

    String path = getRelativePath(req);

    lock.path = path;

    // Retrieve the resources
    DirContext resources = getResources();

    if (resources == null) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    boolean exists = true;
    Object object = null;
    try {
        object = resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    Enumeration locksList = null;

    if (lockRequestType == LOCK_CREATION) {

        // Generating lock id
        String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-"
                + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-"
                + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret;
        String lockToken = md5Encoder.encode(md5Helper.digest(lockTokenStr.getBytes()));

        if ((exists) && (object instanceof DirContext) && (lock.depth == INFINITY)) {

            // Locking a collection (and all its member resources)

            // Checking if a child resource of this collection is
            // already locked
            Vector lockPaths = new Vector();
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {
                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child collection of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }
            locksList = resourceLocks.elements();
            while (locksList.hasMoreElements()) {
                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child resource of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }

            if (!lockPaths.isEmpty()) {

                // One of the child paths was locked
                // We generate a multistatus error report

                Enumeration lockPathsList = lockPaths.elements();

                resp.setStatus(WebdavStatus.SC_CONFLICT);

                XMLWriter generatedXML = new XMLWriter();
                generatedXML.writeXMLHeader();

                generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                        XMLWriter.OPENING);

                while (lockPathsList.hasMoreElements()) {
                    generatedXML.writeElement(null, "response", XMLWriter.OPENING);
                    generatedXML.writeElement(null, "href", XMLWriter.OPENING);
                    generatedXML.writeText((String) lockPathsList.nextElement());
                    generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
                    generatedXML.writeElement(null, "status", XMLWriter.OPENING);
                    generatedXML.writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " "
                            + WebdavStatus.getStatusText(WebdavStatus.SC_LOCKED));
                    generatedXML.writeElement(null, "status", XMLWriter.CLOSING);

                    generatedXML.writeElement(null, "response", XMLWriter.CLOSING);
                }

                generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);

                Writer writer = resp.getWriter();
                writer.write(generatedXML.toString());
                writer.close();

                return;
            }

            boolean addLock = true;

            // Checking if there is already a shared lock on this path
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {

                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.path.equals(lock.path)) {

                    if (currentLock.isExclusive()) {
                        resp.sendError(WebdavStatus.SC_LOCKED);
                        return;
                    } else {
                        if (lock.isExclusive()) {
                            resp.sendError(WebdavStatus.SC_LOCKED);
                            return;
                        }
                    }

                    currentLock.tokens.addElement(lockToken);
                    lock = currentLock;
                    addLock = false;

                }
            }

            if (addLock) {
                lock.tokens.addElement(lockToken);
                collectionLocks.addElement(lock);
            }
        } else {

            // Locking a single resource

            // Retrieving an already existing lock on that resource
            WebdavServlet.LockInfo presentLock = (WebdavServlet.LockInfo) resourceLocks.get(lock.path);
            if (presentLock != null) {

                if ((presentLock.isExclusive()) || (lock.isExclusive())) {
                    // If either lock is exclusive, the lock can't be
                    // granted
                    resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
                    return;
                } else {
                    presentLock.tokens.addElement(lockToken);
                    lock = presentLock;
                }

            } else {

                lock.tokens.addElement(lockToken);
                resourceLocks.put(lock.path, lock);

                // Checking if a resource exists at this path
                exists = true;
                try {
                    object = resources.lookup(path);
                } catch (NamingException e) {
                    exists = false;
                }
                if (!exists) {

                    // "Creating" a lock-null resource
                    int slash = lock.path.lastIndexOf('/');
                    String parentPath = lock.path.substring(0, slash);

                    Vector lockNulls = (Vector) lockNullResources.get(parentPath);
                    if (lockNulls == null) {
                        lockNulls = new Vector();
                        lockNullResources.put(parentPath, lockNulls);
                    }

                    lockNulls.addElement(lock.path);

                }
                // Add the Lock-Token header as by RFC 2518 8.10.1
                // - only do this for newly created locks
                resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">");
            }

        }

    }

    if (lockRequestType == LOCK_REFRESH) {

        String ifHeader = req.getHeader("If");
        if (ifHeader == null) {
            ifHeader = "";
        }

        // Checking resource locks

        WebdavServlet.LockInfo toRenew = (WebdavServlet.LockInfo) resourceLocks.get(path);
        Enumeration tokenList = null;
        if (lock != null) {

            // At least one of the tokens of the locks must have been given

            tokenList = toRenew.tokens.elements();
            while (tokenList.hasMoreElements()) {
                String token = (String) tokenList.nextElement();
                if (ifHeader.indexOf(token) != -1) {
                    toRenew.expiresAt = lock.expiresAt;
                    lock = toRenew;
                }
            }

        }

        // Checking inheritable collection locks

        Enumeration collectionLocksList = collectionLocks.elements();
        while (collectionLocksList.hasMoreElements()) {
            toRenew = (WebdavServlet.LockInfo) collectionLocksList.nextElement();
            if (path.equals(toRenew.path)) {

                tokenList = toRenew.tokens.elements();
                while (tokenList.hasMoreElements()) {
                    String token = (String) tokenList.nextElement();
                    if (ifHeader.indexOf(token) != -1) {
                        toRenew.expiresAt = lock.expiresAt;
                        lock = toRenew;
                    }
                }

            }
        }

    }

    // Set the status, then generate the XML response containing
    // the lock information
    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "prop" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.OPENING);

    lock.toXML(generatedXML);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.CLOSING);

    generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);

    resp.setStatus(WebdavStatus.SC_OK);
    resp.setContentType("text/xml; charset=UTF-8");
    Writer writer = resp.getWriter();
    writer.write(generatedXML.toString());
    writer.close();

}

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;// w  ww .ja  v  a  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.pentaho.di.trans.steps.webservices.WebService.java

private boolean getNodeValue(Object[] outputRowData, Node node, WebServiceField field, Transformer transformer,
        boolean singleRowScenario) throws KettleException {

    Integer outputIndex = data.indexMap.get(field.getWsName());
    if (outputIndex == null) {
        // Unknown field : don't look any further, it's not a field we want to use.
        ////  ww w .j a v  a 2s.  c  o m
        return false;
    }

    // if it's a text node or if we recognize the field type, we just grab the value
    //
    if (node.getNodeType() == Node.TEXT_NODE || !field.isComplex()) {
        Object rowValue = null;

        // See if this is a node we expect as a return value...
        //
        String textContent = node.getTextContent();
        try {
            rowValue = getValue(textContent, field);
            outputRowData[outputIndex] = rowValue;
            return true;
        } catch (Exception e) {
            throw new KettleException("Unable to convert value [" + textContent + "] for field ["
                    + field.getWsName() + "], type [" + field.getXsdType() + "]", e);
        }
    } else if (node.getNodeType() == Node.ELEMENT_NODE) {
        // Perhaps we're dealing with complex data types.
        // Perhaps we can just ship the XML snippet over to the next steps.
        //
        try {
            StringWriter childNodeXML = new StringWriter();
            transformer.transform(new DOMSource(node), new StreamResult(childNodeXML));
            outputRowData[outputIndex] = childNodeXML.toString();
            return true;
        } catch (Exception e) {
            throw new KettleException(
                    "Unable to transform DOM node with name [" + node.getNodeName() + "] to XML", e);
        }
    }

    // Nothing found, return false
    //
    return false;
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

private static boolean compareNodeList(NodeList a, NodeList b, boolean considerNamespacePrefixes) {
    if (a == b) {
        return true;
    }//from ww  w.  j a  v  a  2s .c om
    if (a == null && b == null) {
        return true;
    }
    if (a == null || b == null) {
        return false;
    }

    List<Node> aList = canonizeNodeList(a);
    List<Node> bList = canonizeNodeList(b);

    if (aList.size() != bList.size()) {
        return false;
    }

    Iterator<Node> aIterator = aList.iterator();
    Iterator<Node> bIterator = bList.iterator();
    while (aIterator.hasNext()) {
        Node aItem = aIterator.next();
        Node bItem = bIterator.next();
        if (aItem.getNodeType() != bItem.getNodeType()) {
            return false;
        }
        if (aItem.getNodeType() == Node.ELEMENT_NODE) {
            if (!compareElement((Element) aItem, (Element) bItem, considerNamespacePrefixes)) {
                return false;
            }
        } else if (aItem.getNodeType() == Node.TEXT_NODE) {
            if (!compareTextNodeValues(aItem.getTextContent(), bItem.getTextContent())) {
                return false;
            }
        }
    }
    return true;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.ClinicalDateObscurer.java

/**
 * This method removes a child from its parent (how horrible) and any preceding newlines and whitespace
 *
 * @param parent the Node holdind the child to be removed
 * @param child the Node to be removed/*from ww w  . j  a  va  2 s .c om*/
 */
private void removeChildNode(final Node parent, final Node child) {

    Node childPreviousSibling = child.getPreviousSibling();

    if (childPreviousSibling != null && childPreviousSibling.getNodeType() == Node.TEXT_NODE
            && childPreviousSibling.getTextContent().trim().equals("")) {

        //We want to remove newlines (and whitespace) preceding the child to be removed
        //so has to avoid blank lines in the XML after the child is removed
        parent.removeChild(childPreviousSibling);
    }

    //Remove child
    parent.removeChild(child);
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

/**
 * Remove comments and whitespace-only text nodes
 *///from w w  w . j  a va2s.  c  o  m
private static List<Node> canonizeNodeList(NodeList nodelist) {
    List<Node> list = new ArrayList<Node>(nodelist.getLength());
    for (int i = 0; i < nodelist.getLength(); i++) {
        Node aItem = nodelist.item(i);
        if (aItem.getNodeType() == Node.COMMENT_NODE) {
            continue;
        } else if (aItem.getNodeType() == Node.TEXT_NODE) {
            if (aItem.getTextContent().matches("\\s*")) {
                continue;
            }
        }
        list.add(aItem);
    }
    return list;
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static boolean isJunk(Node node) {
    if (node.getNodeType() == Node.COMMENT_NODE) {
        return true;
    }/*from   w  w w .  j a  v  a2  s.  c om*/
    if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        return true;
    }
    if (node.getNodeType() == Node.TEXT_NODE) {
        Text text = (Text) node;
        if (text.getTextContent().matches("^\\s*$")) {
            return true;
        }
        return false;
    }
    return false;
}