Example usage for org.w3c.dom Node getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:org.dasein.cloud.opsource.OpSourceMethod.java

public String getRequestResultId(String action, Document doc, String resultTag, String resultDetailTag)
        throws CloudException, InternalException {
    if (wire.isDebugEnabled()) {
        wire.debug(provider.convertDomToString(doc));
    }//from   ww  w  .ja  v a 2  s .  co m

    String sNS = "";
    try {
        sNS = doc.getDocumentElement().getTagName().substring(0,
                doc.getDocumentElement().getTagName().indexOf(":") + 1);
    } catch (IndexOutOfBoundsException ex) {
    }
    NodeList blocks = doc.getElementsByTagName(sNS + resultTag);

    if (blocks != null) {
        for (int i = 0; i < blocks.getLength(); i++) {
            Node attr = blocks.item(i);
            if (attr.getFirstChild().getNodeValue().equals(OpSource.RESPONSE_RESULT_SUCCESS_VALUE)) {
                blocks = doc.getElementsByTagName(sNS + resultDetailTag);
                if (blocks == null) {
                    throw new CloudException(action + "  fails " + "without explaination !!!");
                } else {
                    String result = blocks.item(0).getFirstChild().getNodeValue().toLowerCase();
                    return result.split("id:")[1].substring(0, result.split("id:")[1].indexOf(")")).trim();
                }
            }
            if (attr.getFirstChild().getNodeValue().equals(OpSource.RESPONSE_RESULT_ERROR_VALUE)) {
                blocks = doc.getElementsByTagName(sNS + OpSource.RESPONSE_RESULT_DETAIL_TAG);
                if (blocks == null) {
                    logger.error(action + "  fails " + "without explaination !!!");
                    throw new CloudException(action + "  fails " + "without explaination !!!");
                } else {
                    logger.error(blocks.item(0).getFirstChild().getNodeValue());
                    throw new CloudException(blocks.item(0).getFirstChild().getNodeValue());
                }
            }
        }
    }
    return null;
}

From source file:com.marklogic.client.test.SPARQLManagerTest.java

@Test
public void testDescribe() {
    // verify base has expected effect
    String relativeConstruct = "DESCRIBE <http://example.org/s1>";
    SPARQLQueryDefinition qdef = smgr.newQueryDefinition(relativeConstruct);
    Document rdf = smgr.executeConstruct(qdef, new DOMHandle()).get();

    Node description = rdf.getFirstChild().getFirstChild();
    assertNotNull(description.getAttributes());
    assertEquals("subject", "http://example.org/s1", description.getAttributes().item(0).getTextContent());
    assertNotNull(description.getFirstChild());
    assertEquals("predicate", "p1", description.getFirstChild().getNodeName());
    assertEquals("predicate namespace", "http://example.org/", description.getFirstChild().getNamespaceURI());
    NamedNodeMap attrs = description.getFirstChild().getAttributes();
    assertNotNull(attrs);//from w w  w  . j av  a 2s.c om
    assertNotNull(attrs.getNamedItemNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "resource"));
    assertEquals("object", "http://example.org/o1",
            attrs.getNamedItemNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "resource").getTextContent());
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

private String getRefId(Node refNode) {
    Node childNode = refNode.getFirstChild();
    do {//from w w  w.  ja  v  a2  s .c o m
        if (ELEMENT_REF.equals(childNode.getNodeName())) {
            Node idNode = childNode.getAttributes().getNamedItem(ATTR_ID);
            return idNode != null ? idNode.getTextContent() : null;
        }
        childNode = childNode.getNextSibling();
    } while (childNode != null);
    return null;
}

From source file:net.sourceforge.eclipsetrader.core.CurrencyConverter.java

CurrencyConverter() {
    File file = new File(Platform.getLocation().toFile(), "currencies.xml"); //$NON-NLS-1$
    if (file.exists() == true) {
        try {/*www.  j a v a  2s  .  co m*/
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(file);

            Node firstNode = document.getFirstChild();

            NodeList childNodes = firstNode.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node item = childNodes.item(i);
                String nodeName = item.getNodeName();

                if (nodeName.equalsIgnoreCase("currency")) //$NON-NLS-1$
                {
                    Node valueNode = item.getFirstChild();
                    if (valueNode != null)
                        currencies.add(valueNode.getNodeValue());
                } else if (nodeName.equalsIgnoreCase("conversion")) //$NON-NLS-1$
                {
                    String symbol = (item).getAttributes().getNamedItem("symbol").getNodeValue(); //$NON-NLS-1$

                    Node valueNode = null;
                    if ((item).getAttributes().getNamedItem("ratio") != null) //$NON-NLS-1$
                        valueNode = (item).getAttributes().getNamedItem("ratio"); //$NON-NLS-1$
                    if (valueNode == null)
                        valueNode = item.getFirstChild();
                    if (valueNode != null) {
                        Double value = new Double(Double.parseDouble(valueNode.getNodeValue()));
                        map.put(symbol, value);
                    }
                    readHistory(symbol, item.getChildNodes());
                }
            }
        } catch (Exception e) {
            logger.error(e, e);
        }
    }
}

From source file:esg.security.yadis.XrdsDoc.java

public List parse(String input, Set targetTypes) throws XrdsParseException {
    Document document = parseXmlInput(input);

    NodeList XRDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_XRD);
    Node lastXRD;/*w w w . ja  v  a 2s  .  com*/
    if (XRDs.getLength() < 1 || (lastXRD = XRDs.item(XRDs.getLength() - 1)) == null)
        throw new XrdsParseException("No XRD elements found.");

    // get the canonical ID, if any (needed for XRIs)
    String canonicalId = null;
    Node canonicalIdNode;
    NodeList canonicalIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_CANONICALID);
    for (int i = 0; i < canonicalIDs.getLength(); i++) {
        canonicalIdNode = canonicalIDs.item(i);
        if (canonicalIdNode.getParentNode() != lastXRD)
            continue;
        if (canonicalId != null)
            throw new XrdsParseException("More than one Canonical ID found.");
        canonicalId = canonicalIdNode.getFirstChild() != null
                && canonicalIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE
                        ? canonicalIdNode.getFirstChild().getNodeValue()
                        : null;
    }

    // extract the services that match the specified target types
    NodeList types = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_TYPE);
    Map serviceTypes = new HashMap();
    Set selectedServices = new HashSet();
    Node typeNode, serviceNode;
    for (int i = 0; i < types.getLength(); i++) {
        typeNode = types.item(i);
        String type = typeNode != null && typeNode.getFirstChild() != null
                && typeNode.getFirstChild().getNodeType() == Node.TEXT_NODE
                        ? typeNode.getFirstChild().getNodeValue()
                        : null;
        if (type == null)
            continue;

        serviceNode = typeNode.getParentNode();

        if (targetTypes == null)
            selectedServices.add(serviceNode);

        else if (targetTypes.contains(type))
            selectedServices.add(serviceNode);

        addServiceType(serviceTypes, serviceNode, type);
    }

    // extract local IDs
    Map serviceLocalIDs = extractElementsByParent(XRD_NS, XRD_ELEM_LOCALID, selectedServices, document);
    Map serviceDelegates = extractElementsByParent(OPENID_NS, OPENID_ELEM_DELEGATE, selectedServices, document);

    // build XrdsServiceEndpoints for all URIs in the found services
    List result = new ArrayList();
    NodeList uris = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_URI);
    Node uriNode;
    for (int i = 0; i < uris.getLength(); i++) {
        uriNode = uris.item(i);
        if (uriNode == null || !selectedServices.contains(uriNode.getParentNode()))
            continue;

        String uri = uriNode.getFirstChild() != null && uriNode.getFirstChild().getNodeType() == Node.TEXT_NODE
                ? uriNode.getFirstChild().getNodeValue()
                : null;

        serviceNode = uriNode.getParentNode();
        Set typeSet = (Set) serviceTypes.get(serviceNode);

        String localId = (String) serviceLocalIDs.get(serviceNode);
        String delegate = (String) serviceDelegates.get(serviceNode);

        XrdsServiceElem endpoint = new XrdsServiceElem(uri, typeSet, getPriority(serviceNode),
                getPriority(uriNode), localId, delegate, canonicalId);
        result.add(endpoint);
    }

    Collections.sort(result);
    return result;
}

From source file:com.zoho.creator.jframework.XMLParser.java

private static void parseAndSetRecords(ZCView zcView, Node recordsNode) {
    NodeList recordsList = recordsNode.getChildNodes();
    List<ZCRecord> records = new ArrayList<ZCRecord>();
    List<ZCGroup> zcGroups = zcView.getGroups();
    ZCGroup zcGroup = null;//from   w ww  .  j  a  v  a2 s  . co  m
    if (zcGroups.size() > 0) { // setting the previous set's last group
        zcGroup = zcGroups.get(zcGroups.size() - 1);
    }
    boolean isViewGrouped = false;
    boolean isFirstRecordInGroup = false;
    List<String> groupHeaderValues = null;
    for (int k = 0; k < recordsList.getLength(); k++) {
        Node recordNode = recordsList.item(k);
        if (recordNode.getNodeName().equals("group")) {
            isFirstRecordInGroup = true;
            if (!isViewGrouped) {
                isViewGrouped = true;
            }
            groupHeaderValues = new ArrayList<String>();
            NodeList columnList = recordNode.getChildNodes();
            for (int l = 0; l < columnList.getLength(); l++) {
                Node columnNode = columnList.item(l);
                Node valueNode = columnNode.getFirstChild();
                groupHeaderValues.add(getDecodedString(getStringValue(valueNode, "")));
            }
        } else if (recordNode.getNodeName().equals("record")) {
            ZCRecord record = parseAndSetRecord(zcView, recordNode, null);
            records.add(record);
            if (isViewGrouped) {
                if (isFirstRecordInGroup
                        && (zcGroup == null || !zcGroup.getGroupHeaderValues().equals(groupHeaderValues))) {// To check if it's not the same group of the previous set's last group
                    zcGroup = new ZCGroup(groupHeaderValues);
                    zcGroups.add(zcGroup);
                    isFirstRecordInGroup = false;
                    groupHeaderValues = null;
                }
                zcGroup.addRecord(record);
            }
        }
    }

    zcView.addRecords(records);
    zcView.setGrouped(isViewGrouped);
}

From source file:com.konakart.actions.gateways.WorldPayXMLRedirectAction.java

public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    // Create these outside of try / catch since they are needed in the case of a general
    // exception/*from w  w w .  j  a  va 2  s.c  o  m*/
    IpnHistoryIf ipnHistory = new IpnHistory();
    ipnHistory.setModuleCode(WorldPayXMLRedirect.WP_XML_REDIRECT_GATEWAY_CODE);
    KKAppEng kkAppEng = null;

    try {
        int custId;

        kkAppEng = this.getKKAppEng(request, response);

        custId = this.loggedIn(request, response, kkAppEng, "Checkout");

        // Check to see whether the user is logged in
        if (custId < 0) {
            return KKLOGIN;
        }

        // Set the customer id for the IPN history object
        ipnHistory.setCustomerId(custId);

        // Ensure we are using the correct protocol. Redirect if not.
        String redirForward = checkSSL(kkAppEng, request, custId, /* forceSSL */false);
        if (redirForward != null) {
            setupResponseForSSLRedirect(response, redirForward);
            return null;
        }

        // Get the order
        OrderIf order = kkAppEng.getOrderMgr().getCheckoutOrder();
        validateOrder(order, WorldPayXMLRedirect.WP_XML_REDIRECT_GATEWAY_CODE);

        // Set the order id for the ipnHistory object
        ipnHistory.setOrderId(order.getId());

        PaymentDetailsIf pd = order.getPaymentDetails();

        // Do the post
        String gatewayResp = null;
        try {
            gatewayResp = postData(pd, null);
        } catch (Exception e) {
            if (log.isWarnEnabled()) {
                log.warn("Problem posting data to WorldPay: " + e.getMessage());
                e.printStackTrace();
            }

            // Save the ipnHistory
            ipnHistory.setGatewayFullResponse(e.getMessage());
            ipnHistory.setKonakartResultDescription(
                    getResultDescription("Problem posting data to WorldPay: " + e.getMessage()));
            ipnHistory.setKonakartResultId(RET4);
            kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory);

            // Redirect the user to an error screen
            return "CheckoutError";
        }

        gatewayResp = URLDecoder.decode(gatewayResp, "UTF-8");
        if (log.isDebugEnabled()) {
            log.debug("Unformatted GatewayResp = \n" + gatewayResp);
        }

        // Should look similar to:

        // <?xml version="1.0" encoding="UTF-8"?>
        // <!DOCTYPE paymentService PUBLIC "-//WorldPay//DTD WorldPay PaymentService v1//EN"
        // "http://dtd.worldpay.com/paymentService_v1.dtd">
        // <paymentService version="1.4" merchantCode="MERCHANT">
        // <reply>
        // <orderStatus orderCode="1315239998049">
        // <reference id="123678374">
        // https://secure-test.worldpay.com/jsp/shopper/SelectPaymentMethod.jsp?OrderKey=MERCHANT^1315239998049
        // </reference>
        // </orderStatus>
        // </reply>
        // </paymentService>

        // Now process the XML response
        String redirectUrl = null;

        try {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            ByteArrayInputStream bais = new ByteArrayInputStream(gatewayResp.getBytes());
            Document doc = builder.parse(bais);

            // get all elements
            NodeList list = doc.getElementsByTagName("*");
            for (int i = 0; i < list.getLength(); i++) {
                Node node = list.item(i);
                String name = node.getNodeName();
                if (name.equals("reference")) {
                    Text textnode = (Text) node.getFirstChild();
                    String value = "";
                    if (textnode != null) {
                        value = textnode.getNodeValue();
                    }
                    redirectUrl = value;
                    break;
                } else if (name.equals("error")) {
                    String errorCode = "";
                    NamedNodeMap map = node.getAttributes();
                    Node attrNode = map.getNamedItem("code");
                    if (attrNode != null) {
                        errorCode = attrNode.getNodeValue();
                    }

                    Text textnode = (Text) node.getFirstChild();
                    String errorDesc = "";
                    if (textnode != null) {
                        errorDesc = textnode.getNodeValue();
                    }

                    // Save the ipnHistory
                    ipnHistory.setGatewayFullResponse(gatewayResp);
                    ipnHistory.setKonakartResultDescription(getResultDescription(
                            "Error from WorldPay: Code = " + errorCode + " Desc = " + errorDesc));
                    ipnHistory.setKonakartResultId(RET4);
                    kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory);

                    // Redirect the user to an error screen
                    return "CheckoutError";
                }
            }

            if (redirectUrl != null) {
                HashMap<String, String> hp = hashParameters(pd, null);

                StringBuffer redirectUrlSb = new StringBuffer(redirectUrl);
                CustomerIf cust = kkAppEng.getCustomerMgr().getCurrentCustomer();
                if (log.isDebugEnabled()) {
                    log.debug("Customer Locale = " + cust.getLocale());
                }
                if (cust.getLocale() != null && cust.getLocale().length() > 3
                        && cust.getLocale().charAt(2) == '_') {
                    String langCode = cust.getLocale().substring(0, 2);
                    redirectUrlSb.append("&language=");
                    redirectUrlSb.append(langCode);
                }

                kkAppEng.getCustomerMgr().populateCurrentCustomerAddresses(/* force */false);
                if (cust.getAddresses() != null && cust.getAddresses().length > 0) {
                    int countryId = cust.getAddresses()[0].getCountryId();
                    CountryIf country = kkAppEng.getEng().getCountry(countryId);
                    if (country != null && country.getIsoCode2() != null) {
                        redirectUrlSb.append("&country=");
                        redirectUrlSb.append(country.getIsoCode2());
                    }
                }

                redirectUrlSb.append("&successURL=");
                redirectUrlSb.append(hp.get("responseUrl") + "?retCode=success");
                redirectUrlSb.append("&pendingURL=");
                redirectUrlSb.append(hp.get("responseUrl") + "?retCode=pending");
                redirectUrlSb.append("&failureURL=");
                redirectUrlSb.append(hp.get("responseUrl") + "?retCode=failure");

                if (log.isDebugEnabled()) {
                    log.debug("Redirecting customer to : " + redirectUrlSb.toString());
                }

                this.url = redirectUrlSb.toString();
                return "redirect";
            }
            throw new KKAppException("Redirect URL is null");

        } catch (Exception e) {
            // Problems parsing the XML

            if (log.isWarnEnabled()) {
                log.warn("Problem parsing the XML WorldPay response: "
                        + ((gatewayResp != null) ? gatewayResp : "null"));
                e.printStackTrace();
            }

            // Save the ipnHistory
            ipnHistory.setGatewayFullResponse(gatewayResp);
            ipnHistory.setKonakartResultDescription(
                    getResultDescription("Problem parsing the XML WorldPay response: " + e.getMessage()));
            ipnHistory.setKonakartResultId(RET4);
            kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory);

            // Redirect the user to an error screen
            return "CheckoutError";
        }

    } catch (Exception e) {
        try {
            ipnHistory.setKonakartResultDescription(getResultDescription(RET4_DESC + e.getMessage()));
            ipnHistory.setKonakartResultId(RET4);
            if (kkAppEng != null) {
                kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory);
            }
        } catch (KKException e1) {
            return super.handleException(request, e1);
        }
        return super.handleException(request, e);
    }
}

From source file:com.connexta.arbitro.AbstractPolicy.java

/**
 * There used to be multiple things in the defaults type, but now there's just the one string
 * that must be a certain value, so it doesn't seem all that useful to have a class for
 * this...we could always bring it back, however, if it started to do more
 * @param root/*from ww  w.ja  va  2 s.  c  o m*/
 * @throws ParsingException
 */
private void handleDefaults(Node root) throws ParsingException {
    defaultVersion = null;
    NodeList nodes = root.getChildNodes();

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (DOMHelper.getLocalName(node).equals("XPathVersion")) {
            defaultVersion = node.getFirstChild().getNodeValue();
        }
    }
}

From source file:com.fujitsu.dc.client.DavCollection.java

/**
 * This method fetches the list of resource for the box/collection as specified in the path URL.
 * @param folder value/* w ww. j av  a 2  s  .  c  o m*/
 * @return List of resources
 * @throws DaoException Exception thrown
 */
private String[] getResourceList(boolean folder) throws DaoException {
    ArrayList<String> folderList = new ArrayList<String>();
    ArrayList<String> fileList = new ArrayList<String>();
    RestAdapter rest = (RestAdapter) RestAdapterFactory.create(this.accessor);
    DcResponse res = rest.propfind(this.url.toString());
    Document doc = res.bodyAsXml();
    NodeList nl = doc.getElementsByTagName("response");
    String name;
    for (int i = 1; i < nl.getLength(); i++) {
        Element elm = (Element) nl.item(i);
        Node href = elm.getElementsByTagName("href").item(0);
        name = href.getFirstChild().getNodeValue();
        NodeList col = elm.getElementsByTagName("collection");
        if (col.getLength() > 0) {
            folderList.add(name);
        } else {
            fileList.add(name);
        }
    }
    if (folder) {
        return folderList.toArray(new String[0]);
    } else {
        return fileList.toArray(new String[0]);
    }
}

From source file:io.personium.client.DavCollection.java

/**
 * This method fetches the list of resource for the box/collection as specified in the path URL.
 * @param folder value//from w  w w .  ja  va2 s.c om
 * @return List of resources
 * @throws DaoException Exception thrown
 */
private String[] getResourceList(boolean folder) throws DaoException {
    ArrayList<String> folderList = new ArrayList<String>();
    ArrayList<String> fileList = new ArrayList<String>();
    RestAdapter rest = (RestAdapter) RestAdapterFactory.create(this.accessor);
    PersoniumResponse res = rest.propfind(this.url.toString());
    Document doc = res.bodyAsXml();
    NodeList nl = doc.getElementsByTagName("response");
    String name;
    for (int i = 1; i < nl.getLength(); i++) {
        Element elm = (Element) nl.item(i);
        Node href = elm.getElementsByTagName("href").item(0);
        name = href.getFirstChild().getNodeValue();
        NodeList col = elm.getElementsByTagName("collection");
        if (col.getLength() > 0) {
            folderList.add(name);
        } else {
            fileList.add(name);
        }
    }
    if (folder) {
        return folderList.toArray(new String[0]);
    } else {
        return fileList.toArray(new String[0]);
    }
}