Example usage for org.w3c.dom Element getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:org.apache.impala.yarn.server.resourcemanager.scheduler.fair.AllocationFileLoaderService.java

/**
 * Loads a queue from a queue element in the configuration file
 *///  w ww  . j  a  va 2  s .co m
private void loadQueue(String parentName, Element element, Map<String, Resource> minQueueResources,
        Map<String, Resource> maxQueueResources, Map<String, Resource> maxChildQueueResources,
        Map<String, Integer> queueMaxApps, Map<String, Integer> userMaxApps,
        Map<String, Float> queueMaxAMShares, Map<String, ResourceWeights> queueWeights,
        Map<String, SchedulingPolicy> queuePolicies, Map<String, Long> minSharePreemptionTimeouts,
        Map<String, Long> fairSharePreemptionTimeouts, Map<String, Float> fairSharePreemptionThresholds,
        Map<String, Map<QueueACL, AccessControlList>> queueAcls, Map<FSQueueType, Set<String>> configuredQueues,
        Set<String> nonPreemptableQueues) throws AllocationConfigurationException {
    String queueName = CharMatcher.WHITESPACE.trimFrom(element.getAttribute("name"));

    if (queueName.contains(".")) {
        throw new AllocationConfigurationException("Bad fair scheduler config " + "file: queue name ("
                + queueName + ") shouldn't contain period.");
    }

    if (queueName.isEmpty()) {
        throw new AllocationConfigurationException("Bad fair scheduler config "
                + "file: queue name shouldn't be empty or " + "consist only of whitespace.");
    }

    if (parentName != null) {
        queueName = parentName + "." + queueName;
    }

    Map<QueueACL, AccessControlList> acls = new HashMap<>();
    NodeList fields = element.getChildNodes();
    boolean isLeaf = true;

    for (int j = 0; j < fields.getLength(); j++) {
        Node fieldNode = fields.item(j);
        if (!(fieldNode instanceof Element))
            continue;
        Element field = (Element) fieldNode;
        if ("minResources".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData().trim();
            Resource val = FairSchedulerConfiguration.parseResourceConfigValue(text);
            minQueueResources.put(queueName, val);
        } else if ("maxResources".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData().trim();
            Resource val = FairSchedulerConfiguration.parseResourceConfigValue(text);
            maxQueueResources.put(queueName, val);
        } else if ("maxChildResources".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData().trim();
            Resource val = FairSchedulerConfiguration.parseResourceConfigValue(text);
            maxChildQueueResources.put(queueName, val);
        } else if ("maxRunningApps".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData().trim();
            int val = Integer.parseInt(text);
            queueMaxApps.put(queueName, val);
        } else if ("maxAMShare".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData().trim();
            float val = Float.parseFloat(text);
            val = Math.min(val, 1.0f);
            queueMaxAMShares.put(queueName, val);
        } else if ("weight".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData().trim();
            double val = Double.parseDouble(text);
            queueWeights.put(queueName, new ResourceWeights((float) val));
        } else if ("minSharePreemptionTimeout".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData().trim();
            long val = Long.parseLong(text) * 1000L;
            minSharePreemptionTimeouts.put(queueName, val);
        } else if ("fairSharePreemptionTimeout".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData().trim();
            long val = Long.parseLong(text) * 1000L;
            fairSharePreemptionTimeouts.put(queueName, val);
        } else if ("fairSharePreemptionThreshold".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData().trim();
            float val = Float.parseFloat(text);
            val = Math.max(Math.min(val, 1.0f), 0.0f);
            fairSharePreemptionThresholds.put(queueName, val);
        } else if ("schedulingPolicy".equals(field.getTagName())
                || "schedulingMode".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData().trim();
            SchedulingPolicy policy = SchedulingPolicy.parse(text);
            queuePolicies.put(queueName, policy);
        } else if ("aclSubmitApps".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData();
            acls.put(QueueACL.SUBMIT_APPLICATIONS, new AccessControlList(text));
        } else if ("aclAdministerApps".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData();
            acls.put(QueueACL.ADMINISTER_QUEUE, new AccessControlList(text));
        } else if ("allowPreemptionFrom".equals(field.getTagName())) {
            String text = ((Text) field.getFirstChild()).getData().trim();
            if (!Boolean.parseBoolean(text)) {
                nonPreemptableQueues.add(queueName);
            }
        } else if ("queue".endsWith(field.getTagName()) || "pool".equals(field.getTagName())) {
            loadQueue(queueName, field, minQueueResources, maxQueueResources, maxChildQueueResources,
                    queueMaxApps, userMaxApps, queueMaxAMShares, queueWeights, queuePolicies,
                    minSharePreemptionTimeouts, fairSharePreemptionTimeouts, fairSharePreemptionThresholds,
                    queueAcls, configuredQueues, nonPreemptableQueues);
            configuredQueues.get(FSQueueType.PARENT).add(queueName);
            isLeaf = false;
        }
    }
    if (isLeaf) {
        // if a leaf in the alloc file is marked as type='parent'
        // then store it under 'parent'
        if ("parent".equals(element.getAttribute("type"))) {
            configuredQueues.get(FSQueueType.PARENT).add(queueName);
        } else {
            configuredQueues.get(FSQueueType.LEAF).add(queueName);
        }
    }
    queueAcls.put(queueName, acls);
    if (maxQueueResources.containsKey(queueName) && minQueueResources.containsKey(queueName)
            && !Resources.fitsIn(minQueueResources.get(queueName), maxQueueResources.get(queueName))) {
        LOG.warn(String.format("Queue %s has max resources %s less than " + "min resources %s", queueName,
                maxQueueResources.get(queueName), minQueueResources.get(queueName)));
    }
}

From source file:org.apache.jackrabbit.webdav.client.methods.PropFindMethod.java

public PropFindMethod(String uri, int propfindType, DavPropertyNameSet propNameSet, int depth)
        throws IOException {
    super(uri);/*from   ww  w  .  j  ava2s .co m*/

    DepthHeader dh = new DepthHeader(depth);
    setRequestHeader(dh.getHeaderName(), dh.getHeaderValue());

    // build the request body
    try {
        // create the document and attach the root element
        Document document = DomUtil.createDocument();
        Element propfind = DomUtil.createElement(document, XML_PROPFIND, NAMESPACE);
        document.appendChild(propfind);

        // fill the propfind element
        switch (propfindType) {
        case PROPFIND_ALL_PROP:
            propfind.appendChild(DomUtil.createElement(document, XML_ALLPROP, NAMESPACE));
            break;

        case PROPFIND_PROPERTY_NAMES:
            propfind.appendChild(DomUtil.createElement(document, XML_PROPNAME, NAMESPACE));
            break;

        case PROPFIND_BY_PROPERTY:
            if (propNameSet == null) {
                // name set missing, ask for a property that is known to exist
                Element prop = DomUtil.createElement(document, XML_PROP, NAMESPACE);
                Element resourcetype = DomUtil.createElement(document, PROPERTY_RESOURCETYPE, NAMESPACE);
                prop.appendChild(resourcetype);
                propfind.appendChild(prop);
            } else {
                propfind.appendChild(propNameSet.toXml(document));
            }
            break;

        case PROPFIND_ALL_PROP_INCLUDE:
            propfind.appendChild(DomUtil.createElement(document, XML_ALLPROP, NAMESPACE));
            if (propNameSet != null && !propNameSet.isEmpty()) {
                Element include = DomUtil.createElement(document, XML_INCLUDE, NAMESPACE);
                Element prop = propNameSet.toXml(document);
                for (Node c = prop.getFirstChild(); c != null; c = c.getNextSibling()) {
                    // copy over the children of <prop> to <include> element
                    include.appendChild(c.cloneNode(true));
                }
                propfind.appendChild(include);
            }
            break;

        default:
            throw new IllegalArgumentException("unknown propfind type");
        }

        // set the request body
        setRequestBody(document);
    } catch (ParserConfigurationException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:org.apache.jackrabbit.webdav.server.BindTest.java

private String getUri(Element href) {
    String s = "";
    for (Node c = href.getFirstChild(); c != null; c = c.getNextSibling()) {
        if (c.getNodeType() == Node.TEXT_NODE) {
            s += c.getNodeValue();/*w ww  .  ja  v a 2s  .  c om*/
        }
    }
    return s;
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMHMACSignatureMethod.java

SignatureMethodParameterSpec unmarshalParams(Element paramsElem) throws MarshalException {
    outputLength = Integer.valueOf(paramsElem.getFirstChild().getNodeValue()).intValue();
    outputLengthSet = true;//w w w.j  av a 2s.c o  m
    if (log.isDebugEnabled()) {
        log.debug("unmarshalled outputLength: " + outputLength);
    }
    return new HMACParameterSpec(outputLength);
}

From source file:org.apache.jxtadoop.conf.Configuration.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {/*from   w w  w .j  av  a 2s. c  om*/
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        //ignore all comments inside the xml file
        docBuilderFactory.setIgnoringComments(true);

        //allow includes in the xml file
        docBuilderFactory.setNamespaceAware(true);
        try {
            docBuilderFactory.setXIncludeAware(true);
        } catch (UnsupportedOperationException e) {
            LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e);
        }
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = null;
        Element root = null;

        if (name instanceof URL) { // an URL resource
            URL url = (URL) name;
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof String) { // a CLASSPATH resource
            URL url = getResource((String) name);
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof Path) { // a file resource
            // Can't use FileSystem API or we get an infinite loop
            // since FileSystem uses Configuration API.  Use java.io.File instead.
            File file = new File(((Path) name).toUri().getPath()).getAbsoluteFile();
            if (file.exists()) {
                if (!quiet) {
                    LOG.info("parsing " + file);
                }
                InputStream in = new BufferedInputStream(new FileInputStream(file));
                try {
                    doc = builder.parse(in);
                } finally {
                    in.close();
                }
            }
        } else if (name instanceof InputStream) {
            try {
                doc = builder.parse((InputStream) name);
            } finally {
                ((InputStream) name).close();
            }
        } else if (name instanceof Element) {
            root = (Element) name;
        }

        if (doc == null && root == null) {
            if (quiet)
                return;
            throw new RuntimeException(name + " not found");
        }

        if (root == null) {
            root = doc.getDocumentElement();
        }
        if (!"configuration".equals(root.getTagName()))
            LOG.fatal("bad conf file: top-level element not <configuration>");
        NodeList props = root.getChildNodes();
        for (int i = 0; i < props.getLength(); i++) {
            Node propNode = props.item(i);
            if (!(propNode instanceof Element))
                continue;
            Element prop = (Element) propNode;
            if ("configuration".equals(prop.getTagName())) {
                loadResource(properties, prop, quiet);
                continue;
            }
            if (!"property".equals(prop.getTagName()))
                LOG.warn("bad conf file: element not <property>");
            NodeList fields = prop.getChildNodes();
            String attr = null;
            String value = null;
            boolean finalParameter = false;
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element))
                    continue;
                Element field = (Element) fieldNode;
                if ("name".equals(field.getTagName()) && field.hasChildNodes())
                    attr = ((Text) field.getFirstChild()).getData().trim();
                if ("value".equals(field.getTagName()) && field.hasChildNodes())
                    value = ((Text) field.getFirstChild()).getData();
                if ("final".equals(field.getTagName()) && field.hasChildNodes())
                    finalParameter = "true".equals(((Text) field.getFirstChild()).getData());
            }

            // Ignore this parameter if it has already been marked as 'final'
            if (attr != null && value != null) {
                if (!finalParameters.contains(attr)) {
                    properties.setProperty(attr, value);
                    if (finalParameter)
                        finalParameters.add(attr);
                } else {
                    LOG.warn(name + ":a attempt to override final parameter: " + attr + ";  Ignoring.");
                }
            }
        }

    } catch (IOException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (DOMException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (SAXException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.nutch.net.urlnormalizer.regex.RegexURLNormalizer.java

private List readConfiguration(InputStream is) {
    Perl5Compiler compiler = new Perl5Compiler();
    List rules = new ArrayList();
    try {/*w  w  w.j av a  2  s. co m*/

        // borrowed heavily from code in Configuration.java
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
        Element root = doc.getDocumentElement();
        if ((!"regex-normalize".equals(root.getTagName())) && (LOG.isFatalEnabled())) {
            LOG.fatal("bad conf file: top-level element not <regex-normalize>");
        }
        NodeList regexes = root.getChildNodes();
        for (int i = 0; i < regexes.getLength(); i++) {
            Node regexNode = regexes.item(i);
            if (!(regexNode instanceof Element))
                continue;
            Element regex = (Element) regexNode;
            if ((!"regex".equals(regex.getTagName())) && (LOG.isWarnEnabled())) {
                LOG.warn("bad conf file: element not <regex>");
            }
            NodeList fields = regex.getChildNodes();
            String patternValue = null;
            String subValue = null;
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element))
                    continue;
                Element field = (Element) fieldNode;
                if ("pattern".equals(field.getTagName()) && field.hasChildNodes())
                    patternValue = ((Text) field.getFirstChild()).getData();
                if ("substitution".equals(field.getTagName()) && field.hasChildNodes())
                    subValue = ((Text) field.getFirstChild()).getData();
                if (!field.hasChildNodes())
                    subValue = "";
            }
            if (patternValue != null && subValue != null) {
                Rule rule = new Rule();
                rule.pattern = (Perl5Pattern) compiler.compile(patternValue);
                rule.substitution = subValue;
                rules.add(rule);
            }
        }
    } catch (Exception e) {
        if (LOG.isFatalEnabled()) {
            LOG.fatal("error parsing conf file: " + e);
        }
        return EMPTY_RULES;
    }
    if (rules.size() == 0)
        return EMPTY_RULES;
    return rules;
}

From source file:org.apache.ode.bpel.elang.xpath20.runtime.XPath20ExpressionRuntime.java

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type)
        throws FaultException, EvaluationException {
    try {/* w  ww.ja  va 2s.c  o m*/
        OXPath20ExpressionBPEL20 oxpath20 = ((OXPath20ExpressionBPEL20) cexp);

        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(ctx, oxpath20);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(ctx, oxpath20,
                ((XPathFactoryImpl) _xpf).getConfiguration());
        XPath xpe = _xpf.newXPath();
        xpe.setXPathFunctionResolver(funcResolver);
        xpe.setXPathVariableResolver(varResolver);
        xpe.setNamespaceContext(oxpath20.namespaceCtx);
        String xpath = ((OXPath10Expression) cexp).xpath;
        XPathExpression expr = xpe.compile(xpath);
        Node contextNode = ctx.getRootNode();
        if (contextNode == null) {
            contextNode = DOMUtils.newDocument();
        }
        // Create step nodes in XPath in case it is incompletely instantiated
        if (oxpath20.insertMissingData) {
            XPath20ExpressionModifier modifier = new XPath20ExpressionModifier(oxpath20.namespaceCtx,
                    ((XPathFactoryImpl) _xpf).getConfiguration().getNamePool());

            Node temp = ctx.getRootNode();
            if (temp.getLocalName().equals("message") && temp.getNamespaceURI() == null) {
                int startind = xpath.indexOf('.');
                int endind = xpath.indexOf('/');
                if (startind != -1) {
                    String part = null;
                    if (endind != -1) {
                        part = xpath.substring(startind + 1, endind);
                    } else {
                        part = xpath.substring(startind + 1);
                    }
                    Element partElem = DOMUtils.findChildByName((Element) temp, new QName(null, part));

                    if (partElem != null && partElem.getFirstChild() != null) {
                        temp = partElem.getFirstChild();
                    }
                }
            }

            modifier.insertMissingData(expr, temp);
        }
        Object evalResult = expr.evaluate(contextNode, type);
        if (evalResult != null && __log.isDebugEnabled()) {
            __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (ctx.getRootNode() != null)
                __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
        return evalResult;
    } catch (XPathExpressionException e) {
        // Extracting the real cause from all this wrapping isn't a simple task
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        if (cause instanceof XPathException) {
            Throwable th = ((XPathException) cause).getException();
            if (th != null) {
                cause = th;
                if (cause.getCause() != null)
                    cause = cause.getCause();
            }
        }
        throw new EvaluationException("Error while executing an XPath expression: " + cause.toString(), cause);
    } catch (WrappedResolverException wre) {
        __log.debug("Could not evaluate expression because of ", wre);
        throw (FaultException) wre.getCause();
    } catch (Throwable t) {
        __log.debug("Could not evaluate expression because of ", t);
        throw new EvaluationException("Error while executing an XPath expression: ", t);
    }
}