Example usage for org.w3c.dom Node hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

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

private String checkError(NodeList s, String httpCode) throws CloudException, InternalException {
    String errMsg = httpCode + ": ";
    for (int i = 0; i < s.getLength(); i++) {
        Node attribute = s.item(i);
        if (attribute.getNodeType() == Node.TEXT_NODE) {
            continue;
        }/*ww w  .  j a  v a2 s  . c  o  m*/
        if (attribute.getNodeName().equalsIgnoreCase("Error") && attribute.hasChildNodes()) {
            NodeList errors = attribute.getChildNodes();
            for (int error = 0; error < errors.getLength(); error++) {
                Node node = errors.item(error);
                if (node.getNodeName().equalsIgnoreCase("code") && node.hasChildNodes()) {
                    errMsg = errMsg + node.getFirstChild().getNodeValue().trim();
                    continue;
                }
                if (node.getNodeName().equalsIgnoreCase("message") && node.hasChildNodes()) {
                    errMsg = errMsg + ". reason: " + node.getFirstChild().getNodeValue().trim();
                }
            }
        }
    }
    return errMsg;
}

From source file:bridge.toolkit.commands.S1000DConverter.java

/**
 * Iterate through the DOM tree/*ww w. j  a  v  a 2 s .  c  o  m*/
 * 
 * @param node
 * @param output
 * @throws IOException
 */
public static void writeNode(Node node, Writer output) throws IOException {

    int type = node.getNodeType();

    switch (type) {
    case Node.ATTRIBUTE_NODE:
        output.write(' ');
        output.write(node.getNodeName());
        output.write("=\"");
        writeXMLData(node.getNodeValue(), true, output);
        output.write('"');
        break;
    case Node.CDATA_SECTION_NODE:
    case Node.TEXT_NODE:
        writeXMLData(node.getNodeValue(), false, output);
        break;
    case Node.COMMENT_NODE:
        output.write("<!--");
        output.write(((Comment) node).getNodeValue());
        output.write("-->");
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        writeNodes(node.getChildNodes(), output);
        break;
    case Node.DOCUMENT_NODE:
        writeNodes(node.getChildNodes(), output);
        break;
    case Node.DOCUMENT_TYPE_NODE:
        break;
    case Node.ELEMENT_NODE: {
        NamedNodeMap atts = node.getAttributes();

        output.write('<');
        output.write(node.getNodeName());
        if (atts != null) {
            int length = atts.getLength();
            for (int i = 0; i < length; i++)
                writeNode(atts.item(i), output);
        }

        if (node.hasChildNodes()) {
            output.write('>');
            writeNodes(node.getChildNodes(), output);
            output.write("</");
            output.write(node.getNodeName());
            output.write('>');
        } else {
            output.write("/>");
        }
        break;
    }
    case Node.ENTITY_NODE:
        break;
    case Node.ENTITY_REFERENCE_NODE:
        writeNodes(node.getChildNodes(), output);
        break;
    case Node.NOTATION_NODE:
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        break;
    default:
        throw new Error("Unexpected DOM node type: " + type);
    }
}

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

public @Nonnull int getOperationStatus(String requestID) throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();
    Document doc = getAsXML(ctx.getAccountNumber(), "/operations/" + requestID);

    if (doc == null) {
        return -2;
    }//from  w ww.ja  v  a 2  s  . c o m

    NodeList entries = doc.getElementsByTagName("Operation");
    Node entry = entries.item(0);

    NodeList s = entry.getChildNodes();

    String status = "";
    String httpCode = "";

    for (int i = 0; i < s.getLength(); i++) {
        Node attribute = s.item(i);
        if (attribute.getNodeType() == Node.TEXT_NODE) {
            continue;
        }
        if (attribute.getNodeName().equalsIgnoreCase("status") && attribute.hasChildNodes()) {
            status = attribute.getFirstChild().getNodeValue().trim();
            continue;
        }
        if (status.length() > 0 && !status.equalsIgnoreCase("inProgress")) {
            if (attribute.getNodeName().equalsIgnoreCase("httpstatuscode") && attribute.hasChildNodes()) {
                httpCode = attribute.getFirstChild().getNodeValue().trim();
            }
        }
    }

    if (status.equalsIgnoreCase("succeeded")) {
        return HttpServletResponse.SC_OK;
    } else if (status.equalsIgnoreCase("failed")) {
        String errMsg = checkError(s, httpCode);
        throw new CloudException(errMsg);
    }
    return -1;
}

From source file:org.dasein.cloud.ibm.sce.compute.vm.SCEVirtualMachine.java

@Override
public Iterable<VirtualMachineProduct> listProducts(Architecture architecture)
        throws InternalException, CloudException {
    if (products == null) {
        ProviderContext ctx = provider.getContext();

        if (ctx == null) {
            throw new SCEConfigException("No context was configured for this request");
        }/* w  w w  .  ja  va  2s .c o  m*/
        SCEMethod method = new SCEMethod(provider);

        Document xml = method.getAsXML("offerings/image");

        if (xml == null) {
            return Collections.emptyList();
        }
        HashMap<String, VirtualMachineProduct> t = new HashMap<String, VirtualMachineProduct>();
        HashMap<String, VirtualMachineProduct> s = new HashMap<String, VirtualMachineProduct>();
        NodeList items = xml.getElementsByTagName("Image");

        for (int i = 0; i < items.getLength(); i++) {
            HashMap<String, VirtualMachineProduct> prdMap = new HashMap<String, VirtualMachineProduct>();
            NodeList attrs = items.item(i).getChildNodes();
            Architecture a = null;

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

                if (attr.getNodeName().equalsIgnoreCase("Architecture") && attr.hasChildNodes()) {
                    String val = attr.getFirstChild().getNodeValue().trim();

                    if (val.equals("i386")) {
                        a = Architecture.I32;
                    } else if (val.startsWith("x86")) {
                        a = Architecture.I64;
                    } else {
                        System.out.println("DEBUG: Unknown architecture: " + val);
                        a = Architecture.I32;
                    }
                } else if (attr.getNodeName().equalsIgnoreCase("SupportedInstanceTypes")
                        && attr.hasChildNodes()) {
                    NodeList types = attr.getChildNodes();

                    for (int k = 0; k < types.getLength(); k++) {
                        Node type = types.item(k);

                        if (type.getNodeName().equalsIgnoreCase("InstanceType") && type.hasChildNodes()) {
                            VirtualMachineProduct prd = new VirtualMachineProduct();
                            NodeList nodes = type.getChildNodes();

                            for (int l = 0; l < nodes.getLength(); l++) {
                                Node node = nodes.item(l);

                                if (node.getNodeName().equals("ID") && node.hasChildNodes()) {
                                    prd.setProviderProductId(node.getFirstChild().getNodeValue().trim());
                                } else if (node.getNodeName().equals("Label") && node.hasChildNodes()) {
                                    prd.setName(node.getFirstChild().getNodeValue().trim());
                                } else if (node.getNodeName().equals("Detail") && node.hasChildNodes()) {
                                    prd.setDescription(node.getFirstChild().getNodeValue().trim());
                                }
                            }
                            if (prd.getProviderProductId() != null) {
                                String[] parts = prd.getProviderProductId().split("/");

                                if (parts.length == 3) {
                                    String[] sub = parts[0].split("\\.");

                                    if (sub.length > 0) {
                                        parts[0] = sub[sub.length - 1];
                                    }
                                    try {
                                        prd.setCpuCount(Integer.parseInt(parts[0]));
                                    } catch (NumberFormatException ignore) {
                                        // ignore
                                    }
                                    try {
                                        prd.setRamSize(new Storage<Megabyte>(Integer.parseInt(parts[1]),
                                                Storage.MEGABYTE));
                                    } catch (NumberFormatException ignore) {
                                        // ignore
                                    }
                                    try {
                                        int idx = parts[2].indexOf("*");

                                        if (idx < 1) {
                                            prd.setRootVolumeSize(new Storage<Gigabyte>(
                                                    Integer.parseInt(parts[2]), Storage.GIGABYTE));
                                        } else {
                                            prd.setRootVolumeSize(new Storage<Gigabyte>(
                                                    Integer.parseInt(parts[2].substring(0, idx)),
                                                    Storage.GIGABYTE));
                                        }
                                    } catch (NumberFormatException ignore) {
                                        // ignore
                                    }
                                }
                                prdMap.put(prd.getProviderProductId(), prd);
                            }
                        }
                    }
                }
            }
            if (a != null) {
                if (a.equals(Architecture.I32)) {
                    t.putAll(prdMap);
                } else if (a.equals(Architecture.I64)) {
                    s.putAll(prdMap);
                }
            }
        }
        HashMap<Architecture, Collection<VirtualMachineProduct>> tmp = new HashMap<Architecture, Collection<VirtualMachineProduct>>();

        tmp.put(Architecture.I32, Collections.unmodifiableCollection(t.values()));
        tmp.put(Architecture.I64, Collections.unmodifiableCollection(s.values()));
        products = tmp;
    }
    return products.get(architecture);
}

From source file:org.dasein.cloud.atmos.AtmosMethod.java

private @Nonnull Blob toBlob(@Nonnull ProviderContext ctx, @Nonnull Node node, @Nonnull String directory)
        throws CloudException, InternalException {
    String regionId = ctx.getRegionId();

    if (regionId == null) {
        throw new CloudException("No region was specified for this request");
    }//  ww  w .j  a va2s  . c  o  m
    String objectId = null, objectName = null;
    NodeList attrs = node.getChildNodes();
    boolean bucket = false;
    Storage<?> size = null;
    long created = 0L;

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

        if (attr.getNodeName().equalsIgnoreCase("objectid") && attr.hasChildNodes()) {
            objectId = attr.getFirstChild().getNodeValue().trim();
        } else if (attr.getNodeName().equalsIgnoreCase("filename") && attr.hasChildNodes()) {
            objectName = attr.getFirstChild().getNodeValue().trim();
        } else if (attr.getNodeName().equalsIgnoreCase("filetype") && attr.hasChildNodes()) {
            bucket = attr.getFirstChild().getNodeValue().trim().equalsIgnoreCase("directory");
        } else if ((attr.getNodeName().equalsIgnoreCase("systemmetadatalist")
                || attr.getNodeName().equalsIgnoreCase("usermetadatalist")) && attr.hasChildNodes()) {
            NodeList metas = attr.getChildNodes();

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

                if (meta.getNodeName().equalsIgnoreCase("metadata") && meta.hasChildNodes()) {
                    NodeList childNodes = meta.getChildNodes();
                    String name = null, value = null;

                    for (int k = 0; k < childNodes.getLength(); k++) {
                        Node child = childNodes.item(k);

                        if (child.getNodeName().equalsIgnoreCase("name") && child.hasChildNodes()) {
                            name = child.getFirstChild().getNodeValue().trim();
                        } else if (child.getNodeName().equalsIgnoreCase("value") && child.hasChildNodes()) {
                            value = child.getFirstChild().getNodeValue().trim();
                        }
                    }
                    if (name != null && value != null) {
                        if (name.equalsIgnoreCase("itime")) {
                            created = provider.parseTime(value);
                        } else if (name.equalsIgnoreCase("size")) {
                            size = new Storage<org.dasein.util.uom.storage.Byte>(Long.parseLong(value),
                                    Storage.BYTE);
                        }
                    }
                }
            }
        }
    }
    if (objectId == null) {
        return null;
    }
    while (!directory.equals("/") && directory.startsWith("/")) {
        directory = directory.substring(1);
    }
    while (!directory.equals("/") && directory.endsWith("/")) {
        directory = directory.substring(0, directory.length() - 1);
    }
    if (directory.equals("/")) {
        directory = null;
    }
    if (bucket) {
        return Blob.getInstance(regionId, "/rest/objects/" + objectId,
                (directory == null ? objectName : (directory + "/" + objectName)), created);
    } else {
        if (size == null) {
            size = new Storage<Gigabyte>(0, Storage.GIGABYTE);
        }
        return Blob.getInstance(regionId, "/rest/objects/" + objectId, directory, objectName, created, size);
    }
}

From source file:de.betterform.xml.xforms.model.Instance.java

private void setDatatypeOnChilds(Node originNode, Node insertedNode) {
    NodeList originChilds = originNode.getChildNodes();
    NodeList insertedChilds = insertedNode.getChildNodes();
    if (insertedChilds.getLength() == originChilds.getLength()) {
        for (int i = 0; i < originChilds.getLength(); i++) {
            Node originChild = originChilds.item(i);
            Node insertedChild = insertedChilds.item(i);

            ModelItem modelItemOrigin = getModelItem(originChild);
            ModelItem modelItemInserted = getModelItem(insertedChild);
            modelItemInserted.getDeclarationView()
                    .setDatatype(modelItemOrigin.getDeclarationView().getDatatype());

            if (originChild.hasChildNodes()) {
                setDatatypeOnChilds(originChild, insertedChild);
            }/*  w  ww . j a v  a2 s. c  o  m*/
        }
    } else {
        LOGGER.debug(this + " inserted node has fewer child than origin.");
    }
}

From source file:Main.java

/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.//from   w w  w  . j a  v  a2 s.  c o m
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start = src;
    Node parent = src;
    Node place = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr) attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl) element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException(
                    "can't copy node type, " + type + " (" + node.getNodeName() + ')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place = place.getFirstChild();
            dest = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place = parent.getNextSibling();
                parent = parent.getParentNode();
                dest = dest.getParentNode();
            }
        }

    }

}

From source file:org.dasein.cloud.ibm.sce.compute.vm.SCEVirtualMachine.java

public @Nullable VirtualMachine toVirtualMachine(@Nonnull ProviderContext ctx, @Nullable Node node)
        throws CloudException, InternalException {
    if (node == null) {
        return null;
    }/*from  www  . j  a v  a2 s  . c om*/
    VirtualMachine vm = new VirtualMachine();

    vm.setRebootable(true);
    vm.setArchitecture(Architecture.I64);
    vm.setClonable(false);
    vm.setCurrentState(VmState.PENDING);
    vm.setImagable(true);
    vm.setPausable(false);
    vm.setPersistent(true);
    vm.setPlatform(Platform.UNKNOWN);
    NodeList nodes = node.getChildNodes();

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

        if (nodeName.equalsIgnoreCase("ID") && attr.hasChildNodes()) {
            vm.setProviderVirtualMachineId(attr.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("Name") && attr.hasChildNodes()) {
            vm.setName(attr.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("Location") && attr.hasChildNodes()) {
            vm.setProviderRegionId(attr.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("Owner") && attr.hasChildNodes()) {
            vm.setProviderOwnerId(attr.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("Hostname") && attr.hasChildNodes()) {
            vm.setPublicDnsAddress(attr.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("IP") && attr.hasChildNodes()) {
            String ip = attr.getFirstChild().getNodeValue().trim();
            boolean isPublic = isPublicIpAddress(ip);
            String[] addrs;
            if (isPublic) {
                addrs = vm.getPublicIpAddresses();
            } else {
                addrs = vm.getPrivateIpAddresses();
            }

            if (addrs == null || addrs.length == 0) {
                if (isPublic) {
                    vm.setPublicIpAddresses(new String[] { ip });
                } else {
                    vm.setPrivateIpAddresses(new String[] { ip });
                }
            } else {
                String[] tmp = new String[addrs.length + 1];

                //noinspection ManualArrayCopy
                for (int idx = 0; idx < addrs.length; idx++) {
                    tmp[idx] = addrs[idx];
                }
                tmp[tmp.length - 1] = ip;
                addrs = tmp;
                if (isPublic) {
                    vm.setPublicIpAddresses(addrs);
                } else {
                    vm.setPrivateIpAddresses(addrs);
                }
            }
        } else if (nodeName.equalsIgnoreCase("ImageID") && attr.hasChildNodes()) {
            vm.setProviderMachineImageId(attr.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("InstanceType") && attr.hasChildNodes()) {
            vm.setProductId(attr.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("Status") && attr.hasChildNodes()) {
            String status = attr.getFirstChild().getNodeValue().trim();

            vm.setCurrentState(toVmState(status));
        } else if (nodeName.equalsIgnoreCase("LaunchTime") && attr.hasChildNodes()) {
            vm.setCreationTimestamp(provider.parseTimestamp(attr.getFirstChild().getNodeValue().trim()));
        } else if (nodeName.equalsIgnoreCase("ExpirationTime") && attr.hasChildNodes()) {
            // what exactly is expiration time?
        } else if (nodeName.equalsIgnoreCase("PrimaryIP") && attr.hasChildNodes()) {
            String ipAddress = parseAddress(attr);
            boolean isPublic = isPublicIpAddress(ipAddress);
            if (isPublic) {
                vm.setPublicIpAddresses(addAddress(vm.getPublicIpAddresses(), ipAddress));
            } else {
                vm.setPrivateIpAddresses(addAddress(vm.getPrivateIpAddresses(), ipAddress));
            }
        } else if (nodeName.equalsIgnoreCase("SecondaryIP") && attr.hasChildNodes()) {
            String ipAddress = parseAddress(attr);
            boolean isPublic = isPublicIpAddress(ipAddress);
            if (isPublic) {
                vm.setPublicIpAddresses(addAddress(vm.getPublicIpAddresses(), ipAddress));
            } else {
                vm.setPrivateIpAddresses(addAddress(vm.getPrivateIpAddresses(), ipAddress));
            }
        } else if (nodeName.equalsIgnoreCase("Volume") && attr.hasChildNodes()) {
            // volume
        } else if (nodeName.equalsIgnoreCase("Vlan") && attr.hasChildNodes()) {
            NodeList items = attr.getChildNodes();

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

                if (item.getNodeName().equalsIgnoreCase("ID") && item.hasChildNodes()) {
                    vm.setProviderVlanId(item.getFirstChild().getNodeValue().trim());
                }
            }
        } else if (nodeName.equalsIgnoreCase("Software") && attr.hasChildNodes()) {
            NodeList software = attr.getChildNodes();

            for (int j = 0; j < software.getLength(); j++) {
                Node snode = software.item(j);
                String type = null;
                String name = null;

                if (snode.hasChildNodes()) {
                    NodeList sattrs = snode.getChildNodes();

                    for (int k = 0; k < sattrs.getLength(); k++) {
                        Node sattr = sattrs.item(k);

                        if (sattr.getNodeName().equalsIgnoreCase("Name") && sattr.hasChildNodes()) {
                            name = sattr.getFirstChild().getNodeValue().trim();
                        } else if (sattr.getNodeName().equalsIgnoreCase("Type") && sattr.hasChildNodes()) {
                            type = sattr.getFirstChild().getNodeValue().trim();
                        }
                    }
                }
                if (name != null && type != null && type.equalsIgnoreCase("OS")) {
                    vm.setPlatform(Platform.guess(name));
                }
            }
        }
    }
    if (vm.getProviderVirtualMachineId() == null) {
        return null;
    }
    if (vm.getProviderRegionId() == null || !vm.getProviderRegionId().equals(ctx.getRegionId())) {
        return null;
    }
    if (vm.getName() == null) {
        vm.setName(vm.getProviderVirtualMachineId());
    }
    if (vm.getDescription() == null) {
        vm.setDescription(vm.getName());
    }
    vm.setProviderDataCenterId(vm.getProviderRegionId());
    vm.setLastBootTimestamp(vm.getCreationTimestamp());
    return vm;
}

From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java

@Override
public final ScribeCommandObject getObjects(final ScribeCommandObject cADCommandObject) throws Exception {
    logger.debug("----Inside getObjects");

    /* Check if all record types are to be searched */
    if (cADCommandObject.getObjectType().trim().equalsIgnoreCase(HTTPConstants.anyObject)) {

        return this.searchAllTypeOfObjects(cADCommandObject, null, null, null);
    } else {/*from   w w  w .j a  v a2  s  .co  m*/
        GetMethod getMethod = null;
        try {

            String serviceURL = null;
            String serviceProtocol = null;
            String userId = null;
            String password = null;
            String crmPort = "80";

            /* Check if agent is present in request */
            if (cADCommandObject.getCrmUserId() != null) {

                /* Get agent from session manager */
                final ScribeCacheObject cacheObject = zDCRMSessionManager
                        .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

                /* Get CRM information from agent */
                serviceURL = cacheObject.getScribeMetaObject().getCrmServiceURL();
                serviceProtocol = cacheObject.getScribeMetaObject().getCrmServiceProtocol();
                userId = cacheObject.getScribeMetaObject().getCrmUserId();
                password = cacheObject.getScribeMetaObject().getCrmPassword();
                crmPort = cacheObject.getScribeMetaObject().getCrmPort();
            }

            /* Create Zen desk URL */
            final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/"
                    + cADCommandObject.getObjectType() + "s.xml";

            logger.debug("----Inside getObjects zenDeskURL: " + zenDeskURL);

            /* Instantiate get method */
            getMethod = new GetMethod(zenDeskURL);

            /* Set request content type */
            getMethod.addRequestHeader("Content-Type", "application/xml");
            getMethod.addRequestHeader("accept", "application/xml");

            final HttpClient httpclient = new HttpClient();

            /* Set credentials */
            httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)),
                    new UsernamePasswordCredentials(userId, password));

            /* Execute method */
            int result = httpclient.executeMethod(getMethod);
            logger.debug("----Inside getObjects response code: " + result + " & body: "
                    + getMethod.getResponseBodyAsString());

            if (result == HttpStatus.SC_OK) {

                final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                final DocumentBuilder builder = factory.newDocumentBuilder();
                final Document document = builder.parse(getMethod.getResponseBodyAsStream());

                /* Create new XPath object to query XML document */
                final XPath xpath = XPathFactory.newInstance().newXPath();

                /* XPath Query for showing all nodes value */
                final XPathExpression expr = xpath.compile(
                        "/" + cADCommandObject.getObjectType() + "s/" + cADCommandObject.getObjectType());

                /* Get node list from response document */
                final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

                /* Create new Scribe object list */
                final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>();

                /* Iterate over node list */
                for (int i = 0; i < nodeList.getLength(); i++) {

                    /* Create list of elements */
                    final List<Element> elementList = new ArrayList<Element>();

                    /* Get node from node list */
                    final Node node = nodeList.item(i);

                    /* Create new Scribe object */
                    final ScribeObject cADbject = new ScribeObject();

                    /* Check if node has child nodes */
                    if (node.hasChildNodes()) {

                        final NodeList subNodeList = node.getChildNodes();

                        /* Iterate over sub node list and create elements */
                        for (int j = 0; j < subNodeList.getLength(); j++) {

                            final Node subNode = subNodeList.item(j);

                            /* This trick is to avoid empty nodes */
                            if (!subNode.getNodeName().contains("#text")) {

                                /* Create element from response */
                                final Element element = ZDCRMMessageFormatUtils
                                        .createMessageElement(subNode.getNodeName(), subNode.getTextContent());

                                /* Add element in list */
                                elementList.add(element);
                            }
                        }
                    }
                    /* Add all CRM fields */
                    cADbject.setXmlContent(elementList);

                    /* Add Scribe object in list */
                    cADbjectList.add(cADbject);
                }

                /* Check if no record found */
                if (cADbjectList.size() == 0) {
                    throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zendesk");
                }

                /* Set the final object in command object */
                cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()]));
            } else if (result == HttpStatus.SC_FORBIDDEN) {

                throw new ScribeException(ScribeResponseCodes._1020 + "Query is forbidden by Zendesk CRM");
            } else if (result == HttpStatus.SC_BAD_REQUEST) {

                throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content");
            } else if (result == HttpStatus.SC_UNAUTHORIZED) {

                throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
            } else if (result == HttpStatus.SC_NOT_FOUND) {

                throw new ScribeException(
                        ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM");
            }
        } catch (final ScribeException exception) {

            throw exception;
        } catch (final ParserConfigurationException exception) {

            throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                    exception);
        } catch (final SAXException exception) {

            throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                    exception);
        } catch (final IOException exception) {

            throw new ScribeException(
                    ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                    exception);
        } finally {

            /* Release connection socket */
            if (getMethod != null) {
                getMethod.releaseConnection();
            }
        }
        return cADCommandObject;
    }
}

From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java

/**
 * /*  w ww .jav  a 2s . co  m*/
 * @param cADCommandObject
 * @param query
 * @param select
 * @param order
 * @return
 * @throws Exception
 */
private final ScribeCommandObject searchAllTypeOfObjects(final ScribeCommandObject cADCommandObject,
        final String query, final String select, final String order) throws Exception {
    logger.debug("----Inside searchAllTypeOfObjects query: " + query + " & select: " + select + " & order: "
            + order);
    GetMethod getMethod = null;
    try {

        String serviceURL = null;
        String serviceProtocol = null;
        String userId = null;
        String password = null;
        String sessionId = null;
        String crmPort = "80";

        /* Check if CrmUserId is present in request */
        if (cADCommandObject.getCrmUserId() != null) {

            /* Get agent from session manager */
            final ScribeCacheObject agent = zDCRMSessionManager
                    .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

            /* Get CRM information from agent */
            serviceURL = agent.getScribeMetaObject().getCrmServiceURL();
            serviceProtocol = agent.getScribeMetaObject().getCrmServiceProtocol();
            userId = agent.getScribeMetaObject().getCrmUserId();
            password = agent.getScribeMetaObject().getCrmPassword();
            sessionId = agent.getScribeMetaObject().getCrmSessionId();
            crmPort = agent.getScribeMetaObject().getCrmPort();
        }

        /* Create Zen desk URL */
        final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/search.xml";

        logger.debug(
                "----Inside searchAllTypeOfObjects zenDeskURL: " + zenDeskURL + " & sessionId: " + sessionId);

        /* Instantiate get method */
        getMethod = new GetMethod(zenDeskURL);

        /* Set request content type */
        getMethod.addRequestHeader("Content-Type", "application/xml");

        /* Cookie is required to be set in case of search */
        getMethod.addRequestHeader("Cookie", sessionId);

        final HttpClient httpclient = new HttpClient();

        /* Set credentials */
        httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)),
                new UsernamePasswordCredentials(userId, password));

        /* Check if user has not provided a valid query */
        if (ZDCRMMessageFormatUtils.validateQuery(query)) {
            getMethod.setQueryString(new NameValuePair[] {
                    new NameValuePair("query", ZDCRMMessageFormatUtils.createZDQuery(query)) });
        }

        /* Execute method */
        int result = httpclient.executeMethod(getMethod);
        logger.debug("----Inside searchAllTypeOfObjects response code: " + result + " & body: "
                + getMethod.getResponseBodyAsString());

        if (result == HttpStatus.SC_OK) {
            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final Document document = builder.parse(getMethod.getResponseBodyAsStream());

            /* Create new XPath object to query XML document */
            final XPath xpath = XPathFactory.newInstance().newXPath();

            /* XPath Query for showing all nodes value */
            final XPathExpression expr = xpath.compile("/records/record");

            /* Get node list from resposne document */
            final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

            final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>();

            /* Get select field list */
            List<String> selectFieldList = null;

            /* Check if user is asking for all fields */
            if (select != null && !select.equalsIgnoreCase(HTTPConstants.allCRMObjectFields)) {
                selectFieldList = ZDCRMMessageFormatUtils.createSelectFieldList(select);
            }

            /* Iterate over node list */
            for (int i = 0; i < nodeList.getLength(); i++) {

                /* Get node from node list */
                final Node node = nodeList.item(i);

                /* Create new Scribe object */
                final ScribeObject cADbject = new ScribeObject();

                /* Check if node has child nodes */
                if (node.hasChildNodes()) {

                    final NodeList subNodeList = node.getChildNodes();

                    /* Create list of elements */
                    final List<Element> elementList = new ArrayList<Element>();

                    for (int j = 0; j < subNodeList.getLength(); j++) {

                        /* Get all subnodes */
                        final Node subNode = subNodeList.item(j);

                        /* This trick is to avoid empty nodes */
                        if (!subNode.getNodeName().contains("#text")) {
                            if (selectFieldList != null) {
                                /* Add only user requested fields */
                                if (selectFieldList.contains(subNode.getNodeName().trim().toUpperCase())) {
                                    /* Create element from response */
                                    final Element element = ZDCRMMessageFormatUtils.createMessageElement(
                                            subNode.getNodeName(), subNode.getTextContent());

                                    /* Add element in list */
                                    elementList.add(element);
                                }
                            } else {
                                /* Create element from response */
                                final Element element = ZDCRMMessageFormatUtils
                                        .createMessageElement(subNode.getNodeName(), subNode.getTextContent());

                                /* Add element in list */
                                elementList.add(element);
                            }
                        }
                    }

                    /* Add all CRM fields */
                    cADbject.setXmlContent(elementList);

                    /* Add Scribe object in list */
                    cADbjectList.add(cADbject);
                }
            }
            /* Check if no record found */
            if (cADbjectList.size() == 0) {
                throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zendesk");
            }

            /* Set the final object in command object */
            cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()]));
        } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED
                || result == HttpStatus.SC_NOT_ACCEPTABLE) {
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : "
                    + ZDCRMMessageFormatUtils.getErrorFromResponse(getMethod.getResponseBodyAsStream()));
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM");
        } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {
            throw new ScribeException(ScribeResponseCodes._1004
                    + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct");
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final ParserConfigurationException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final SAXException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } catch (final Exception e) {
        throw new ScribeException(ScribeResponseCodes._1000 + "Problem while communicating with Zendesk CRM",
                e);
    } finally {
        /* Release connection socket */
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}