Example usage for org.w3c.dom Node hasAttributes

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

Introduction

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

Prototype

public boolean hasAttributes();

Source Link

Document

Returns whether this node (if it is an element) has any attributes.

Usage

From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java

private void startVapp(@Nonnull String vappId, boolean wait) throws CloudException, InternalException {
    vCloudMethod method = new vCloudMethod(getProvider());
    String xml = method.get("vApp", vappId);

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

        if (nodes.getLength() < 1) {
            nodes = doc.getElementsByTagName(nsString + "Vm");
        }/*from   ww  w  .  j a  v  a  2s. c om*/
        for (int i = 0; i < nodes.getLength(); i++) {
            NodeList links = nodes.item(i).getChildNodes();

            for (int j = 0; j < links.getLength(); j++) {
                Node node = links.item(j);
                if (node.getNodeName().contains(":"))
                    nsString = node.getNodeName().substring(0, node.getNodeName().indexOf(":") + 1);
                else
                    nsString = "";

                if (node.getNodeName().equalsIgnoreCase(nsString + "Link") && node.hasAttributes()) {
                    Node rel = node.getAttributes().getNamedItem("rel");

                    if (rel != null && rel.getNodeValue().trim().equalsIgnoreCase("power:powerOn")) {
                        Node href = node.getAttributes().getNamedItem("href");

                        if (href != null) {
                            String endpoint = href.getNodeValue().trim();
                            String action = method.getAction(endpoint);

                            String task = method.post(action, endpoint, null, null);

                            if (wait) {
                                method.waitFor(task);
                            }
                            break;
                        }
                    }
                }
            }
        }
    }
}

From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java

private void stopVappOrOneVm(String vAppId, String vmId, boolean force)
        throws CloudException, InternalException {

    // 3. Does the vApp contain multiple VMs?
    vCloudMethod method = new vCloudMethod(getProvider());
    String xml = method.get("vApp", vAppId);
    if (xml == null) {
        throw new CloudException("No information returned for ID: " + vAppId);
    }//from   w  ww  .  j  a v a  2 s.c o m

    Document doc = method.parseXML(xml);
    String docElementTagName = doc.getDocumentElement().getTagName();
    String nsString = "";
    if (docElementTagName.contains(":"))
        nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1);
    NodeList nodes = doc.getElementsByTagName(nsString + "VApp");
    NodeList attributes = nodes.item(0).getChildNodes();

    int count = 0;
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        if (attribute.getNodeName().contains(":"))
            nsString = attribute.getNodeName().substring(0, attribute.getNodeName().indexOf(":") + 1);
        else
            nsString = "";

        if (attribute.getNodeName().equals(nsString + "Children") && attribute.hasChildNodes()) {
            NodeList children = attribute.getChildNodes();

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

                if (vmNode.getNodeName().equalsIgnoreCase(nsString + "Vm") && vmNode.hasAttributes()) {
                    count++;
                }
            }
        }
    }

    String powerAction = null;
    if (!force) {
        powerAction = "shutdown";
    }

    if (count > 1) {
        // 4a. If the vApp contains multiple VMs, undeploy VM
        undeploy(vmId, powerAction);
    } else if (count == 1) {
        // 4b. If the vApp contains just one VM, undeploy the vApp
        undeploy(vAppId, powerAction);
    } else {
        throw new CloudException("Expected at least one VM");
    }
}

From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java

private void stop(String vAppId, @Nonnull String vmId, boolean force, boolean wait, boolean killByVM)
        throws CloudException, InternalException {
    vCloudMethod method = new vCloudMethod(getProvider());
    String xml = method.get("vApp", vmId);

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

        if (nodes.getLength() < 1) {
            nodes = doc.getElementsByTagName(nsString + "Vm");
        }/*  w  w w  .j a va  2 s  . c  o m*/

        for (int i = 0; i < nodes.getLength(); i++) {
            NodeList links = nodes.item(i).getChildNodes();

            for (int j = 0; j < links.getLength(); j++) {
                Node node = links.item(j);
                if (node.getNodeName().contains(":"))
                    nsString = node.getNodeName().substring(0, node.getNodeName().indexOf(":") + 1);
                else
                    nsString = "";

                if (node.getNodeName().equalsIgnoreCase(nsString + "Link") && node.hasAttributes()) {
                    Node rel = node.getAttributes().getNamedItem("rel");

                    if (force && rel != null && rel.getNodeValue().trim().equalsIgnoreCase("power:powerOff")) {
                        Node href = node.getAttributes().getNamedItem("href");

                        if (href != null) {
                            String endpoint = href.getNodeValue().trim();
                            String action = method.getAction(endpoint);

                            String task = method.post(action, endpoint, null, null);

                            if (wait) {
                                method.waitFor(task);
                            }
                            break;
                        }
                    } else if (!force && rel != null
                            && rel.getNodeValue().trim().equalsIgnoreCase("power:shutdown")) {
                        Node href = node.getAttributes().getNamedItem("href");

                        if (href != null) {
                            String endpoint = href.getNodeValue().trim();
                            String action = method.getAction(endpoint);

                            String task = method.post(action, endpoint, null, null);

                            if (wait) {
                                method.waitFor(task);
                            }
                            break;
                        }
                    }
                }
            }
        }
    }
}

From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java

private String parseParentVappId(NodeList nodes, vCloudMethod method) {
    String nsString = "";
    for (int i = 0; i < nodes.getLength(); i++) {
        NodeList links = nodes.item(i).getChildNodes();

        for (int j = 0; j < links.getLength(); j++) {
            Node node = links.item(j);
            if (node.getNodeName().contains(":"))
                nsString = node.getNodeName().substring(0, node.getNodeName().indexOf(":") + 1);
            else/*from  w ww .j a  v a  2s.  co  m*/
                nsString = "";

            if (node.getNodeName().equalsIgnoreCase(nsString + "Link") && node.hasAttributes()) {
                Node rel = node.getAttributes().getNamedItem("rel");

                if (rel != null && rel.getNodeValue().trim().equalsIgnoreCase("up")) {
                    Node type = node.getAttributes().getNamedItem("type");
                    if (type != null && type.getNodeValue().trim().equals(method.getMediaTypeForVApp())) {
                        Node href = node.getAttributes().getNamedItem("href");
                        if (href != null) {
                            return getProvider().toID(href.getNodeValue().trim());
                        }
                    }
                }
            }
        }
    }
    return null;
}

From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java

private void suspendVapp(@Nonnull String vappId) throws CloudException, InternalException {
    vCloudMethod method = new vCloudMethod(getProvider());
    String xml = method.get("vApp", vappId);

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

        if (nodes.getLength() < 1) {
            nodes = doc.getElementsByTagName(nsString + "Vm");
        }//from   w w  w.j  av a 2  s.  co m
        for (int i = 0; i < nodes.getLength(); i++) {
            NodeList links = nodes.item(i).getChildNodes();

            for (int j = 0; j < links.getLength(); j++) {
                Node node = links.item(j);
                if (node.getNodeName().contains(":"))
                    nsString = node.getNodeName().substring(0, node.getNodeName().indexOf(":") + 1);
                else
                    nsString = "";

                if (node.getNodeName().equalsIgnoreCase(nsString + "Link") && node.hasAttributes()) {
                    Node rel = node.getAttributes().getNamedItem("rel");

                    if (rel != null && rel.getNodeValue().trim().equalsIgnoreCase("power:suspend")) {
                        Node href = node.getAttributes().getNamedItem("href");

                        if (href != null) {
                            String endpoint = href.getNodeValue().trim();
                            String action = method.getAction(endpoint);

                            method.post(action, endpoint, null, null);
                            break;
                        }
                    }
                }
            }
        }
    }
}

From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java

private @Nullable VirtualMachine toVirtualMachine(@Nonnull String vdcId, @Nonnull String parentVAppId,
        @Nonnull Node vmNode, @Nonnull Iterable<VLAN> vlans) throws CloudException, InternalException {
    Node n = vmNode.getAttributes().getNamedItem("href");
    VirtualMachine vm = new VirtualMachine();

    vm.setProviderMachineImageId("unknown");
    vm.setArchitecture(Architecture.I64);
    vm.setClonable(true);// ww  w . j  av  a2 s .c om
    vm.setCreationTimestamp(0L);
    vm.setCurrentState(VmState.PENDING);
    vm.setImagable(true);
    vm.setLastBootTimestamp(0L);
    vm.setLastPauseTimestamp(0L);
    vm.setPausable(false);
    vm.setPersistent(true);
    vm.setPlatform(Platform.UNKNOWN);
    vm.setProviderOwnerId(getContext().getAccountNumber());
    vm.setRebootable(true);
    vm.setProviderRegionId(getContext().getRegionId());
    vm.setProviderDataCenterId(vdcId);

    if (n != null) {
        vm.setProviderVirtualMachineId((getProvider()).toID(n.getNodeValue().trim()));
    }
    n = vmNode.getAttributes().getNamedItem("status");
    if (n != null) {
        vm.setCurrentState(toState(n.getNodeValue().trim()));
    }
    String vmName = null;
    String computerName = null;
    n = vmNode.getAttributes().getNamedItem("name");
    if (n != null) {
        vmName = n.getNodeValue().trim();
    }
    NodeList attributes = vmNode.getChildNodes();

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

        if (attribute.getNodeName().equalsIgnoreCase("Description") && attribute.hasChildNodes()) {
            vm.setDescription(attribute.getFirstChild().getNodeValue().trim());
        } else if (attribute.getNodeName().equalsIgnoreCase("GuestCustomizationSection")
                && attribute.hasChildNodes()) {
            NodeList elements = attribute.getChildNodes();
            String adminPassword = null;

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

                if (element.getNodeName().equalsIgnoreCase("AdminPassword") && element.hasChildNodes()) {
                    adminPassword = element.getFirstChild().getNodeValue().trim();
                } else if (element.getNodeName().equalsIgnoreCase("ComputerName") && element.hasChildNodes()) {
                    computerName = element.getFirstChild().getNodeValue().trim();
                }
            }
            if (adminPassword != null) {
                vm.setRootUser(vm.getPlatform().isWindows() ? "administrator" : "root");
                vm.setRootPassword(adminPassword);
            }
        } else if (attribute.getNodeName().equalsIgnoreCase("DateCreated") && attribute.hasChildNodes()) {
            vm.setCreationTimestamp((getProvider()).parseTime(attribute.getFirstChild().getNodeValue().trim()));
        } else if (attribute.getNodeName().equalsIgnoreCase("NetworkConnectionSection")
                && attribute.hasChildNodes()) {
            NodeList elements = attribute.getChildNodes();
            TreeSet<String> addrs = new TreeSet<String>();

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

                if (element.getNodeName().equalsIgnoreCase("NetworkConnection")) {
                    if (element.hasChildNodes()) {
                        NodeList parts = element.getChildNodes();
                        Boolean connected = null;
                        String addr = null;

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

                            if (part.getNodeName().equalsIgnoreCase("IpAddress") && part.hasChildNodes()) {
                                addr = part.getFirstChild().getNodeValue().trim();
                            }
                            if (part.getNodeName().equalsIgnoreCase("IsConnected") && part.hasChildNodes()) {
                                connected = part.getFirstChild().getNodeValue().trim().equalsIgnoreCase("true");
                            }
                        }
                        if ((connected == null || connected) && addr != null) {
                            addrs.add(addr);
                        }
                    }
                    if (element.hasAttributes()) {
                        Node net = element.getAttributes().getNamedItem("network");

                        if (net != null) {
                            String netNameOrId = net.getNodeValue().trim();
                            boolean compat = (getProvider()).isCompat();

                            for (VLAN vlan : vlans) {
                                boolean matches = false;

                                if (!compat && vlan.getProviderVlanId().equals(netNameOrId)) {
                                    matches = true;
                                } else if (compat
                                        && vlan.getProviderVlanId().equals("/network/" + netNameOrId)) {
                                    matches = true;
                                } else if (vlan.getName().equals(netNameOrId)) {
                                    matches = true;
                                }
                                if (matches) {
                                    vm.setProviderVlanId(vlan.getProviderVlanId());
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if (addrs.size() > 0) {
                if (addrs.size() == 1) {
                    RawAddress a = new RawAddress(addrs.iterator().next());

                    if (isPublicIpAddress(a)) {
                        vm.setPublicAddresses(a);
                    } else {
                        vm.setPrivateAddresses(a);
                    }
                } else {
                    ArrayList<RawAddress> pub = new ArrayList<RawAddress>();
                    ArrayList<RawAddress> priv = new ArrayList<RawAddress>();

                    for (String addr : addrs) {
                        RawAddress r = new RawAddress(addr);

                        if (isPublicIpAddress(r)) {
                            pub.add(r);
                        } else {
                            priv.add(r);
                        }
                    }
                    if (priv.size() > 0) {
                        vm.setPrivateAddresses(priv.toArray(new RawAddress[priv.size()]));
                    }
                    if (pub.size() > 0) {
                        vm.setPublicAddresses(pub.toArray(new RawAddress[pub.size()]));
                    }
                }
            }
        } else if (attribute.getNodeName().equalsIgnoreCase("ovf:OperatingSystemSection")
                && attribute.hasChildNodes()) {
            NodeList os = attribute.getChildNodes();

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

                if (osdesc.getNodeName().equalsIgnoreCase("ovf:Description") && osdesc.hasChildNodes()) {
                    String desc = osdesc.getFirstChild().getNodeValue();

                    vm.setPlatform(Platform.guess(desc));

                    if (desc.contains("32") || (desc.contains("x86") && !desc.contains("64"))) {
                        vm.setArchitecture(Architecture.I32);
                    }
                }
            }
        } else if (attribute.getNodeName().equalsIgnoreCase("ovf:VirtualHardwareSection")
                && attribute.hasChildNodes()) {
            NodeList hardware = attribute.getChildNodes();
            int memory = 0, cpu = 0;

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

                if (item.getNodeName().equalsIgnoreCase("ovf:item") && item.hasChildNodes()) {
                    NodeList bits = item.getChildNodes();
                    String rt = null;
                    int qty = 0;

                    for (int k = 0; k < bits.getLength(); k++) {
                        Node bit = bits.item(k);

                        if (bit.getNodeName().equalsIgnoreCase("rasd:ResourceType") && bit.hasChildNodes()) {
                            rt = bit.getFirstChild().getNodeValue().trim();
                        } else if (bit.getNodeName().equalsIgnoreCase("rasd:VirtualQuantity")
                                && bit.hasChildNodes()) {
                            try {
                                qty = Integer.parseInt(bit.getFirstChild().getNodeValue().trim());
                            } catch (NumberFormatException ignore) {
                                // ignore
                            }
                        }

                    }
                    if (rt != null) {
                        if (rt.equals("3")) { // cpu
                            cpu = qty;
                        } else if (rt.equals("4")) { // memory
                            memory = qty;
                        }
                        /*
                        else if( rt.equals("10") ) {     // NIC
                                
                        }
                        else if( rt.equals("17") ) {     // disk
                                
                        }
                        */
                    }
                }
            }
            VirtualMachineProduct product = null;

            for (VirtualMachineProduct prd : listProducts("bogus",
                    VirtualMachineProductFilterOptions.getInstance().withArchitecture(Architecture.I64))) {
                if (prd.getCpuCount() == cpu && memory == prd.getRamSize().intValue()) {
                    product = prd;
                    break;
                }
            }
            if (product == null) {
                vm.setProductId("custom:" + cpu + ":" + memory);
            } else {
                vm.setProductId(product.getProviderProductId());
            }
        }
    }
    if (vm.getProviderVirtualMachineId() == null) {
        return null;
    }
    if (vmName != null) {
        vm.setName(vmName);
    } else if (computerName != null) {
        vm.setName(computerName);
    } else {
        vm.setName(vm.getProviderVirtualMachineId());
    }
    if (vm.getDescription() == null) {
        vm.setDescription(vm.getName());
    }
    Platform p = vm.getPlatform();

    if (p == null || p.equals(Platform.UNKNOWN) || p.equals(Platform.UNIX)) {
        p = Platform.guess(vm.getName() + " " + vm.getDescription());
        if (Platform.UNIX.equals(vm.getPlatform())) {
            if (p.isUnix()) {
                vm.setPlatform(p);
            }
        } else {
            vm.setPlatform(p);
        }
    }
    try {
        vCloudMethod method = new vCloudMethod(getProvider());
        String xml = method.get("vApp", vm.getProviderVirtualMachineId() + "/metadata");

        if (xml != null && !xml.equals("")) {
            method.parseMetaData(vm, xml);

            String t;

            if (vm.getCreationTimestamp() < 1L) {
                t = (String) vm.getTag("dsnCreated");
                if (t != null) {
                    try {
                        vm.setCreationTimestamp(Long.parseLong(t));
                    } catch (Throwable parseWarning) {
                        if (logger.isDebugEnabled()) {
                            logger.warn("Failed to parse creation timestamp.", parseWarning);
                        } else {
                            logger.warn("Failed to parse creation timestamp.");
                        }
                    }
                }
            }
            t = (String) vm.getTag("dsnImageId");
            logger.debug("dsnImageId = " + t);
            if (t != null && "unknown".equals(vm.getProviderMachineImageId())) {
                vm.setProviderMachineImageId(t);
                logger.debug("Set provider machine image to " + t);
            }
        }
    } catch (Throwable warning) {
        if (logger.isDebugEnabled()) {
            logger.warn("Failed to get and parse vm metadata.", warning);
        } else {
            logger.warn("Failed to get and parse vm metadata.");
        }
    }
    vm.setTag(PARENT_VAPP_ID, parentVAppId);
    return vm;
}

From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java

/**
 * Default undeploy, uses supplied string for UndeployPowerAction
 * @param vmId VM or vApp ID// w w w  . j a  va2s  . c o  m
 * @param powerAction UndeployPowerAction. If null, use default.
 * @throws CloudException
 * @throws InternalException
 */
public void undeploy(@Nonnull String vmId, String powerAction) throws CloudException, InternalException {
    vCloudMethod method = new vCloudMethod(getProvider());
    String xml = method.get("vApp", vmId);

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

        if (nodes.getLength() < 1) {
            nodes = doc.getElementsByTagName(nsString + "Vm");
        }
        for (int i = 0; i < nodes.getLength(); i++) {
            NodeList links = nodes.item(i).getChildNodes();

            for (int j = 0; j < links.getLength(); j++) {
                Node node = links.item(j);
                if (node.getNodeName().contains(":"))
                    nsString = node.getNodeName().substring(0, node.getNodeName().indexOf(":") + 1);
                else
                    nsString = "";

                if (node.getNodeName().equalsIgnoreCase(nsString + "Link") && node.hasAttributes()) {
                    Node rel = node.getAttributes().getNamedItem("rel");

                    if (rel != null && rel.getNodeValue().trim().equalsIgnoreCase("undeploy")) {
                        Node href = node.getAttributes().getNamedItem("href");

                        if (href != null) {
                            String endpoint = href.getNodeValue().trim();
                            String action = method.getAction(endpoint);
                            StringBuilder payload = new StringBuilder();

                            if (powerAction == null) {
                                payload.append(
                                        "<UndeployVAppParams xmlns=\"http://www.vmware.com/vcloud/v1.5\"/>");
                            } else {
                                payload.append(
                                        "<UndeployVAppParams xmlns=\"http://www.vmware.com/vcloud/v1.5\"><UndeployPowerAction>");
                                payload.append(powerAction);
                                payload.append("</UndeployPowerAction></UndeployVAppParams>");
                            }
                            try {
                                method.waitFor(method.post(action, endpoint,
                                        method.getMediaTypeForActionUndeployVApp(), payload.toString()));
                            } catch (vCloudException e) {
                                if (e.getProviderCode().contains("BUSY_ENTITY")) {
                                    try {
                                        Thread.sleep(15000L);
                                    } catch (InterruptedException ignore) {
                                    }
                                    undeploy(vmId);
                                    return;
                                }
                                throw e;
                            }
                            break;
                        }
                    }
                }
            }
        }
    }
}

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

public @Nonnull Org authenticate(boolean force) throws CloudException, InternalException {
    Cache<Org> cache = Cache.getInstance(provider, "vCloudOrgs", Org.class, CacheLevel.CLOUD_ACCOUNT,
            new TimePeriod<Minute>(25, TimePeriod.MINUTE));
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new CloudException("No context was defined for this request");
    }//from   w  w  w. j  av  a2s .c  o m
    String accountNumber = ctx.getAccountNumber();
    Iterable<Org> orgs = cache.get(ctx);
    Iterator<Org> it = ((force || orgs == null) ? null : orgs.iterator());

    if (it == null || !it.hasNext()) {
        String endpoint = getVersion().loginUrl;

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [POST (" + (new Date()) + ")] -> " + endpoint
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            HttpClient client = getClient(true);
            HttpPost method = new HttpPost(endpoint);
            Org org = new Org();

            org.version = getVersion();
            method.addHeader("Accept", "application/*+xml;version=" + org.version.version
                    + ",application/*+xml;version=" + org.version.version);

            String accessPublic = null;
            String accessPrivate = null;
            try {
                List<ContextRequirements.Field> fields = provider.getContextRequirements()
                        .getConfigurableValues();
                for (ContextRequirements.Field f : fields) {
                    if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                        byte[][] keyPair = (byte[][]) provider.getContext().getConfigurationValue(f);
                        accessPublic = new String(keyPair[0], "utf-8");
                        accessPrivate = new String(keyPair[1], "utf-8");
                    }
                }
            } catch (UnsupportedEncodingException e) {
                throw new InternalException(e);
            }

            String password = accessPrivate;
            String userName;

            if (matches(getAPIVersion(), "0.8", "0.8")) {
                userName = accessPublic;
            } else if (getAPIVersion().equals("5.6")) {
                userName = accessPublic;
            } else {
                userName = accessPublic + "@" + ctx.getAccountNumber();
            }
            String auth = new String(Base64.encodeBase64((userName + ":" + password).getBytes()));

            method.addHeader("Authorization", "Basic " + auth);
            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, "POST sessions");
                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) {
                if (matches(getAPIVersion(), "0.8", "0.8")) {
                    for (Header h : response.getHeaders("Set-Cookie")) {
                        String value = h.getValue();

                        if (value != null) {
                            value = value.trim();
                            if (value.startsWith("vcloud-token")) {
                                value = value.substring("vcloud-token=".length());

                                int idx = value.indexOf(";");

                                if (idx == -1) {
                                    org.token = value;
                                } else {
                                    org.token = value.substring(0, idx);
                                }
                            }
                        }
                    }
                } else {
                    org.token = response.getFirstHeader("x-vcloud-authorization").getValue();
                }
                if (org.token == null) {
                    throw new CloudException(CloudErrorType.AUTHENTICATION, 200, "Token Empty",
                            "No token was provided");
                }
                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();
                    if (matches(org.version.version, "1.5", null)) {
                        NodeList orgNodes = doc.getElementsByTagName("Link");
                        String orgList = null;

                        for (int i = 0; i < orgNodes.getLength(); i++) {
                            Node orgNode = orgNodes.item(i);

                            if (orgNode.hasAttributes()) {
                                Node type = orgNode.getAttributes().getNamedItem("type");

                                if (type != null && type.getNodeValue().trim().equals(getMediaTypeForOrg())) {
                                    Node name = orgNode.getAttributes().getNamedItem("name");

                                    if (name != null && name.getNodeValue().trim().equals(accountNumber)) {
                                        Node href = orgNode.getAttributes().getNamedItem("href");

                                        if (href != null) {
                                            Region region = new Region();
                                            String url = href.getNodeValue().trim();

                                            region.setActive(true);
                                            region.setAvailable(true);
                                            if (provider.isCompat()) {
                                                region.setProviderRegionId(
                                                        "/org/" + url.substring(url.lastIndexOf('/') + 1));
                                            } else {
                                                region.setProviderRegionId(
                                                        url.substring(url.lastIndexOf('/') + 1));
                                            }
                                            region.setJurisdiction("US");
                                            region.setName(name.getNodeValue().trim());

                                            org.endpoint = url.substring(0, url.lastIndexOf("/api/org"));
                                            org.region = region;
                                            org.url = url;
                                        }
                                    }
                                }
                                if (type != null
                                        && type.getNodeValue().trim().equals(getMediaTypeForOrgList())) {
                                    Node href = orgNode.getAttributes().getNamedItem("href");

                                    if (href != null) {
                                        orgList = href.getNodeValue().trim();
                                    }
                                }
                            }
                        }
                        if (org.endpoint == null && orgList != null) {
                            loadOrg(orgList, org, accountNumber);
                        }
                    } else {
                        NodeList orgNodes = doc.getElementsByTagName("Org");

                        for (int i = 0; i < orgNodes.getLength(); i++) {
                            Node orgNode = orgNodes.item(i);

                            if (orgNode.hasAttributes()) {
                                Node name = orgNode.getAttributes().getNamedItem("name");
                                Node href = orgNode.getAttributes().getNamedItem("href");

                                if (href != null) {
                                    String url = href.getNodeValue().trim();
                                    Region region = new Region();

                                    if (!url.endsWith("/org/" + accountNumber)) {
                                        continue;
                                    }
                                    region.setActive(true);
                                    region.setAvailable(true);
                                    if (provider.isCompat()) {
                                        region.setProviderRegionId(
                                                "/org/" + url.substring(url.lastIndexOf('/') + 1));
                                    } else {
                                        region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1));
                                    }
                                    region.setJurisdiction("US");
                                    region.setName(name == null ? accountNumber : name.getNodeValue().trim());
                                    org.endpoint = url.substring(0, url.lastIndexOf("/org/"));
                                    org.region = region;
                                    org.url = url;
                                }
                            }
                        }
                    }
                } 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 {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    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());
                    }
                    vCloudException.Data data = null;

                    if (body != null && !body.equals("")) {
                        Document doc = parseXML(body);
                        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);
                }
                throw new CloudException(CloudErrorType.AUTHENTICATION, status.getStatusCode(),
                        status.getReasonPhrase(), "Authentication failed");
            }
            if (org.endpoint == null) {
                throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "No Org",
                        "No org was identified for " + ctx.getAccountNumber());
            }
            cache.put(ctx, Collections.singletonList(org));
            loadVDCs(org);
            return org;
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [POST (" + (new Date()) + ")] -> " + endpoint
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } else {
        return it.next();
    }
}

From source file:org.eclipse.wst.xsl.xalan.debugger.XalanVariable.java

private String createElement(String value, Node node) {
    value = value + "<";
    //      if (node.getPrefix() != null && node.getPrefix().length() > 0) {
    //         value = value + node.getPrefix() + ":";
    //      }//from w  ww  . j  a  va  2s.c om
    if (node.getNodeName() != null) {
        value = value + node.getNodeName();
        if (node.hasAttributes()) {
            NamedNodeMap attr = node.getAttributes();
            value = value + buildAttributes(attr);
        }
        value = value + ">";
        if (node.getNodeValue() != null) {
            value = value + node.getNodeValue();
        }
    }
    if (node.hasChildNodes()) {
        value = value + processNodeList(node.getChildNodes());
    }
    value = value + "</" + node.getNodeName() + ">";
    return value;
}

From source file:org.etudes.mneme.impl.ImportQti2ServiceImpl.java

/**
 * //  www  .j ava2 s  .c om
 * @param node
 * @param textContent
 * @return
 */
private String getAllLevelsTextContent(Node node, StringBuilder textContent, boolean wholeText,
        String unzipLocation, String context, List<String> embedMedia) {
    NodeList list = node.getChildNodes();

    for (int i = 0; i < list.getLength(); ++i) {
        Node child = list.item(i);

        String childTagName = child.getNodeName();

        if (child.getNodeType() == Node.TEXT_NODE) {
            textContent.append(child.getTextContent());

        }
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            if (wholeText && ("img".equalsIgnoreCase(childTagName) || "a".equalsIgnoreCase(childTagName)
                    || "object".equalsIgnoreCase(childTagName))) {
                try {
                    processEmbedMedia((Element) child, unzipLocation, context, embedMedia);
                } catch (Exception e) {
                    // do nothing
                }
            }

            if (!wholeText && child.getNodeName().contains("Interaction")) {
                if (child.getTextContent() != null)
                    textContent.append(child.getTextContent());
            } else if (child.getNodeName().contains("feedback")) {
                // do nothing skip it
            } else if (child.getNodeName().contains("printedVariable")) {
                Element printedVariableTemplate = null;
                Element currNodeElement = (Element) child;
                String id = currNodeElement.getAttribute("identifier");
                try {
                    XPath printedPath = new DOMXPath(
                            ".//setTemplateValue[@identifier='" + id + "']//randomInteger");
                    printedVariableTemplate = (Element) printedPath.selectSingleNode(child.getOwnerDocument());
                } catch (Exception e) {
                    printedVariableTemplate = null;
                }
                if (printedVariableTemplate != null)
                    textContent.append(this.messages.getString("import_qti2_printedVariable_text")
                            + printedVariableTemplate.getAttribute("min") + " - "
                            + printedVariableTemplate.getAttribute("max") + " "
                            + this.messages.getString("import_qti2_printedVariable_text2"));
            } else {
                textContent.append("<" + child.getNodeName());

                if (child.hasAttributes()) {
                    NamedNodeMap attrs = child.getAttributes();
                    for (int k = 0; k < attrs.getLength(); k++) {
                        Node attr = attrs.item(k);
                        textContent.append(" " + attr.getNodeName() + " = \"" + attr.getTextContent() + "\" ");
                    }
                }
                textContent.append(">");

                getAllLevelsTextContent(child, textContent, wholeText, unzipLocation, context, embedMedia);

                textContent.append("</" + child.getNodeName() + ">");
            }
        }
    }
    return textContent.toString();
}