Example usage for org.w3c.dom Element getNodeName

List of usage examples for org.w3c.dom Element getNodeName

Introduction

In this page you can find the example usage for org.w3c.dom Element getNodeName.

Prototype

public String getNodeName();

Source Link

Document

The name of this node, depending on its type; see the table above.

Usage

From source file:org.apache.myfaces.shared_impl.webapp.webxml.WebXmlParser.java

private void readFilter(Element filterElem) {
    String filterName = null;/*from  w ww. ja  v a 2s  .c om*/
    String filterClass = null;
    NodeList nodeList = filterElem.getChildNodes();
    for (int i = 0, len = nodeList.getLength(); i < len; i++) {
        Node n = nodeList.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            if (n.getNodeName().equals("filter-name")) {
                filterName = XmlUtils.getElementText((Element) n).trim();
            } else if (n.getNodeName().equals("filter-class")) {
                filterClass = org.apache.myfaces.shared_impl.util.xml.XmlUtils.getElementText((Element) n)
                        .trim();
            } else if (n.getNodeName().equals("description") || n.getNodeName().equals("init-param")) {
                //ignore
            } else {
                if (log.isDebugEnabled())
                    log.debug("Ignored element '" + n.getNodeName() + "' as child of '"
                            + filterElem.getNodeName() + "'.");
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Ignored node '" + n.getNodeName() + "' of type " + n.getNodeType());
        }
    }
    _webXml.addFilter(filterName, filterClass);
}

From source file:org.apache.myfaces.shared_impl.webapp.webxml.WebXmlParser.java

private void readFilterMapping(Element filterMappingElem) {
    String filterName = null;//from w  w w  .ja v a  2 s.co m
    String urlPattern = null;
    NodeList nodeList = filterMappingElem.getChildNodes();
    for (int i = 0, len = nodeList.getLength(); i < len; i++) {
        Node n = nodeList.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            if (n.getNodeName().equals("filter-name")) {
                filterName = org.apache.myfaces.shared_impl.util.xml.XmlUtils.getElementText((Element) n)
                        .trim();
            } else if (n.getNodeName().equals("url-pattern")) {
                urlPattern = org.apache.myfaces.shared_impl.util.xml.XmlUtils.getElementText((Element) n)
                        .trim();
            } else if (n.getNodeName().equals("servlet-name")) {
                // we are not interested in servlet-name based mapping - for now
            } else if (n.getNodeName().equals("dispatcher")) {
                // we are not interested in dispatcher instructions
            } else {
                if (log.isWarnEnabled())
                    log.warn("Ignored element '" + n.getNodeName() + "' as child of '"
                            + filterMappingElem.getNodeName() + "'.");
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Ignored node '" + n.getNodeName() + "' of type " + n.getNodeType());
        }
    }
    _webXml.addFilterMapping(filterName, urlPattern);
}

From source file:org.apache.nifi.authorization.FlowParser.java

/**
 * Finds child elements with the given tagName.
 *
 * @param element the parent element//from   ww w.  ja  v a  2  s.  c  om
 * @param tagName the child element name to find
 * @return a list of matching child elements
 */
private static List<Element> getChildrenByTagName(final Element element, final String tagName) {
    final List<Element> matches = new ArrayList<>();
    final NodeList nodeList = element.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node node = nodeList.item(i);
        if (!(node instanceof Element)) {
            continue;
        }

        final Element child = (Element) nodeList.item(i);
        if (child.getNodeName().equals(tagName)) {
            matches.add(child);
        }
    }

    return matches;
}

From source file:org.apache.nifi.controller.StandardFlowSynchronizer.java

private static List<Element> getChildrenByTagName(final Element element, final String tagName) {
    final List<Element> matches = new ArrayList<>();
    final NodeList nodeList = element.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node node = nodeList.item(i);
        if (!(node instanceof Element)) {
            continue;
        }/*w ww  .  java  2  s  .c  om*/

        final Element child = (Element) nodeList.item(i);
        if (child.getNodeName().equals(tagName)) {
            matches.add(child);
        }
    }

    return matches;
}

From source file:org.apache.nifi.minifi.FlowParser.java

/**
 * Finds child elements with the given tagName.
 *
 * @param element the parent element/*  ww  w  . j  a v  a 2 s.com*/
 * @param tagName the child element name to find
 * @return a list of matching child elements
 */
public static List<Element> getChildrenByTagName(final Element element, final String tagName) {
    final List<Element> matches = new ArrayList<>();
    final NodeList nodeList = element.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node node = nodeList.item(i);
        if (!(node instanceof Element)) {
            continue;
        }
        final Element child = (Element) nodeList.item(i);
        if (child.getNodeName().equals(tagName)) {
            matches.add(child);
        }
    }
    return matches;
}

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java

public Object[] parseFault(PartnerRoleMessageExchange odeMex, HttpMethod method) {
    Operation opDef = odeMex.getOperation();
    BindingOperation opBinding = binding.getBindingOperation(opDef.getName(), opDef.getInput().getName(),
            opDef.getOutput().getName());

    final String body;
    try {/*w  w w  .jav  a2 s.  co m*/
        body = method.getResponseBodyAsString();
    } catch (IOException e) {
        throw new RuntimeException("Unable to get the request body : " + e.getMessage(), e);
    }
    Header h = method.getResponseHeader("Content-Type");
    String receivedType = h != null ? h.getValue() : null;
    if (opDef.getFaults().isEmpty()) {
        throw new RuntimeException("Operation [" + opDef.getName() + "] has no fault. This "
                + method.getStatusCode() + " error will be considered as a failure.");
    } else if (opBinding.getBindingFaults().isEmpty()) {
        throw new RuntimeException(
                "No fault binding. This " + method.getStatusCode() + " error will be considered as a failure.");
    } else if (StringUtils.isEmpty(body)) {
        throw new RuntimeException("No body in the response. This " + method.getStatusCode()
                + " error will be considered as a failure.");
    } else if (receivedType != null && !HttpUtils.isXml(receivedType)) {
        throw new RuntimeException("Response Content-Type [" + receivedType
                + "] does not describe XML entities. Faults must be XML. This " + method.getStatusCode()
                + " error will be considered as a failure.");
    } else {

        if (receivedType == null) {
            if (log.isWarnEnabled())
                log.warn("[Service: " + serviceName + ", Port: " + portName + ", Operation: " + opDef.getName()
                        + "] Received Response with a body but no 'Content-Type' header! Will try to parse nevertheless.");
        }

        // try to parse body
        final Element bodyElement;
        try {
            bodyElement = DOMUtils.stringToDOM(body);
        } catch (Exception e) {
            throw new RuntimeException("Unable to parse the response body as xml. This "
                    + method.getStatusCode() + " error will be considered as a failure.", e);
        }

        // Guess which fault it is
        QName bodyName = new QName(bodyElement.getNamespaceURI(), bodyElement.getNodeName());
        Fault faultDef = WsdlUtils.inferFault(opDef, bodyName);

        if (faultDef == null) {
            throw new RuntimeException("Unknown Fault Type [" + bodyName + "] This " + method.getStatusCode()
                    + " error will be considered as a failure.");
        } else if (!WsdlUtils.isOdeFault(opBinding.getBindingFault(faultDef.getName()))) {
            // is this fault bound with ODE extension?
            throw new RuntimeException("Fault [" + bodyName + "] is not bound with "
                    + new QName(Namespaces.ODE_HTTP_EXTENSION_NS, "fault") + ". This " + method.getStatusCode()
                    + " error will be considered as a failure.");
        } else {
            // a fault has only one part
            Part partDef = (Part) faultDef.getMessage().getParts().values().iterator().next();

            QName faultName = new QName(definition.getTargetNamespace(), faultDef.getName());
            QName faultType = faultDef.getMessage().getQName();

            // create the ODE Message now that we know the fault
            org.apache.ode.bpel.iapi.Message response = odeMex.createMessage(faultType);

            // build the element to be sent back
            Element partElement = createPartElement(partDef, bodyElement);
            response.setPart(partDef.getName(), partElement);

            // extract and set headers
            extractHttpResponseHeaders(response, method, opDef);
            return new Object[] { faultName, response };
        }
    }
}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

private static Document sendUspsRequest(String requestType, Document requestDocument, Delegator delegator,
        String shipmentGatewayConfigId, String resource, Locale locale) throws UspsRequestException {
    String conUrl = null;// w w w.  j ava  2 s . c om
    List<String> labelRequestTypes = UtilMisc.toList("PriorityMailIntl", "PriorityMailIntlCertify");
    if (labelRequestTypes.contains(requestType)) {
        conUrl = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "connectUrlLabels", resource,
                "shipment.usps.connect.url.labels");
    } else {
        conUrl = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "connectUrl", resource,
                "shipment.usps.connect.url");
    }
    if (UtilValidate.isEmpty(conUrl)) {
        throw new UspsRequestException(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsConnectUrlIncomplete", locale));
    }

    OutputStream os = new ByteArrayOutputStream();

    try {
        UtilXml.writeXmlDocument(requestDocument, os, "UTF-8", true, false, 0);
    } catch (TransformerException e) {
        throw new UspsRequestException(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsSerializingError", UtilMisc.toMap("errorString", e.getMessage()), locale));
    }

    String xmlString = os.toString();

    Debug.logInfo("USPS XML request string: " + xmlString, module);

    String timeOutStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "connectTimeout",
            resource, "shipment.usps.connect.timeout", "60");
    int timeout = 60;
    try {
        timeout = Integer.parseInt(timeOutStr);
    } catch (NumberFormatException e) {
        Debug.logError(e, "Unable to set timeout to " + timeOutStr + " using default " + timeout);
    }

    HttpClient http = new HttpClient(conUrl);
    http.setTimeout(timeout * 1000);
    http.setParameter("API", requestType);
    http.setParameter("XML", xmlString);

    String responseString = null;
    try {
        responseString = http.get();
    } catch (HttpClientException e) {
        throw new UspsRequestException(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsConnectionProblem", UtilMisc.toMap("errorString", e), locale));
    }

    Debug.logInfo("USPS response: " + responseString, module);

    if (UtilValidate.isEmpty(responseString)) {
        return null;
    }

    Document responseDocument = null;
    try {
        responseDocument = UtilXml.readXmlDocument(responseString, false);
    } catch (Exception e) {
        throw new UspsRequestException(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsResponseError", UtilMisc.toMap("errorString", e.getMessage()), locale));
    }

    // If a top-level error document is returned, throw exception
    // Other request-level errors should be handled by the caller
    Element responseElement = responseDocument.getDocumentElement();
    if ("Error".equals(responseElement.getNodeName())) {
        throw new UspsRequestException(UtilXml.childElementValue(responseElement, "Description"));
    }

    return responseDocument;
}

From source file:org.apache.ofbiz.testtools.ModelTestSuite.java

public ModelTestSuite(Element mainElement, String testCase) {
    this.suiteName = mainElement.getAttribute("suite-name");

    this.originalDelegatorName = mainElement.getAttribute("delegator-name");
    if (UtilValidate.isEmpty(this.originalDelegatorName))
        this.originalDelegatorName = "test";

    this.originalDispatcherName = mainElement.getAttribute("dispatcher-name");
    if (UtilValidate.isEmpty(this.originalDispatcherName))
        this.originalDispatcherName = "test-dispatcher";

    String uniqueSuffix = "-" + RandomStringUtils.randomAlphanumeric(10);

    this.delegator = DelegatorFactory.getDelegator(this.originalDelegatorName)
            .makeTestDelegator(this.originalDelegatorName + uniqueSuffix);
    this.dispatcher = ServiceContainer.getLocalDispatcher(originalDispatcherName + uniqueSuffix, delegator);

    for (Element testCaseElement : UtilXml.childElementList(mainElement,
            UtilMisc.toSet("test-case", "test-group"))) {
        String caseName = testCaseElement.getAttribute("case-name");
        String nodeName = testCaseElement.getNodeName();
        if (testCase == null || caseName.equals(testCase)) {
            if (nodeName.equals("test-case")) {
                parseTestElement(caseName, UtilXml.firstChildElement(testCaseElement));
            } else if (nodeName.equals("test-group")) {
                int i = 0;
                for (Element childElement : UtilXml.childElementList(testCaseElement)) {
                    parseTestElement(caseName + '-' + i, childElement);
                    i++;//from w ww. j ava2 s  . com
                }
            }
        }
    }
}

From source file:org.apache.ofbiz.testtools.ModelTestSuite.java

private void parseTestElement(String caseName, Element testElement) {
    String nodeName = testElement.getNodeName();
    if ("junit-test-suite".equals(nodeName)) {
        String className = testElement.getAttribute("class-name");

        try {/*from   ww w .  j  a  v a  2s  .  co  m*/
            @SuppressWarnings("unchecked")
            Class<? extends TestCase> clz = (Class<? extends TestCase>) ObjectType.loadClass(className);
            TestSuite suite = new TestSuite();
            suite.addTestSuite(clz);
            Enumeration<?> testEnum = suite.tests();
            int testsAdded = 0;
            int casesAdded = 0;
            while (testEnum.hasMoreElements()) {
                Test tst = (Test) testEnum.nextElement();
                this.testList.add(tst);
                casesAdded += tst.countTestCases();
                testsAdded++;
            }
            Debug.logInfo(
                    "Added " + testsAdded + " tests [" + casesAdded + " cases] from the class: " + className,
                    module);
        } catch (Exception e) {
            String errMsg = "Unable to load test suite class : " + className;
            Debug.logError(e, errMsg, module);
        }
    } else if ("service-test".equals(nodeName)) {
        this.testList.add(new ServiceTest(caseName, testElement));
    } else if ("simple-method-test".equals(nodeName)) {
        if (UtilValidate.isNotEmpty(testElement.getAttribute("name"))) {
            this.testList.add(new SimpleMethodTest(caseName, testElement));
        } else {
            String methodLocation = testElement.getAttribute("location");
            List<SimpleMethod> simpleMethods;
            try {
                simpleMethods = SimpleMethod.getSimpleMethodsList(methodLocation, null);
                for (SimpleMethod simpleMethod : simpleMethods) {
                    String methodName = simpleMethod.getMethodName();
                    if (methodName.startsWith("test")) {
                        this.testList.add(
                                new SimpleMethodTest(caseName + "." + methodName, methodLocation, methodName));
                    }
                }
            } catch (MiniLangException e) {
                Debug.logError(e, module);
            }
        }
    } else if ("webdriver-test".equals(nodeName)) {
        try {
            String className = "org.apache.ofbiz.testtools.WebDriverTest";
            Class<?> cl;
            cl = Class.forName(className);
            Constructor<?> con = cl.getConstructor(String.class, Element.class);
            this.testList.add((Test) con.newInstance(caseName, testElement));
        } catch (Exception e) {
            Debug.logError(e, module);
        }
    } else if ("entity-xml".equals(nodeName)) {
        this.testList.add(new EntityXmlAssertTest(caseName, testElement));
    } else if ("entity-xml-assert".equals(nodeName)) {
        // this is the old, deprecated name for the element, changed because it now does assert or load
        this.testList.add(new EntityXmlAssertTest(caseName, testElement));
    }
}

From source file:org.apache.openaz.xacml.pdp.policy.dom.DOMVariableDefinition.java

public static boolean repair(Node nodeVariableDefinition) throws DOMStructureException {
    Element elementVariableDefinition = DOMUtil.getElement(nodeVariableDefinition);
    boolean result = false;

    Element elementExpression = DOMUtil.getFirstChildElement(elementVariableDefinition);
    if (elementExpression != null) {
        if (DOMExpression.isExpression(elementExpression)) {
            result = result || DOMExpression.repair(elementExpression);
        } else {//from  ww  w .  j  av  a2  s  .c  o  m
            logger.warn("Unexpected element " + elementExpression.getNodeName());
            elementVariableDefinition.removeChild(elementExpression);
            result = true;
        }
    } else {
        throw DOMUtil.newMissingElementException(elementVariableDefinition, XACML3.XMLNS,
                XACML3.ELEMENT_EXPRESSION);
    }

    result = result || DOMUtil.repairStringAttribute(elementVariableDefinition, XACML3.ATTRIBUTE_VARIABLEID,
            "variable", logger);
    return result;
}