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:com.l2jfree.gameserver.model.skills.conditions.ConditionParser.java

private Condition parseLogicNot(Node n, Object template) {
    Condition cond = null;/*from   w  ww.j  a  va2s .  c  o m*/
    for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) {
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            if (cond != null)
                throw new IllegalStateException("Full <not> condition");

            cond = parseExistingConditionInsideLogic(n, template);
        }
    }

    if (cond == null)
        throw new IllegalStateException("Empty <not> condition");

    return new ConditionLogicNot(cond);
}

From source file:it.skymedia.idolTunnel.IdolOEMConnection.java

/**
 * Method that catches response node from xml autnresponse
 * //from  w ww . j  a v  a 2s  . co  m
 * @return a XML Document
 */
@WebMethod(operationName = "getQueryResponse")
public String getQueryResponse(String xml) {
    String result = "";
    Document document = getDocumentFrom(xml);

    NodeList response = document.getElementsByTagName("response");
    Node resp = response.item(0);

    result = resp.getFirstChild().getNodeValue();
    return result;
}

From source file:com.amalto.core.history.accessor.ManyFieldAccessor.java

private Element getCollectionItemNode() {
    if (cachedCollectionItemNode != null) {
        return cachedCollectionItemNode;
    }/*  ww  w. j av a2 s .  com*/
    Element collectionItemNode = null;
    Node node = parent.getNode();
    if (node == null) {
        throw new IllegalStateException("Could not find parent node in document.");
    }
    NodeList children = node.getChildNodes();
    if (index > children.getLength()) {
        return null;
    }
    int currentIndex = 0;
    Node current = node.getFirstChild();
    while (current != null) {
        if (fieldName.equals(current.getNodeName())) {
            if (index == currentIndex) {
                collectionItemNode = (Element) current;
                break;
            } else {
                currentIndex++;
            }
        }
        current = current.getNextSibling();
    }
    cachedCollectionItemNode = collectionItemNode;
    return collectionItemNode;
}

From source file:org.dasein.cloud.aws.AWSCloud.java

/**
 * Returns the text from the given node.
 *
 * @param node the node to extract the value from
 * @return the text from the node//from   www.j av  a2  s  . c  o m
 */
static public String getTextValue(Node node) {
    if (node.getChildNodes().getLength() == 0) {
        return null;
    }
    return node.getFirstChild().getNodeValue();
}

From source file:com.l2jfree.gameserver.model.skills.conditions.ConditionParser.java

private Condition parseLogicOr(Node n, Object template) {
    ConditionLogicOr cond = new ConditionLogicOr();
    for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) {
        if (n.getNodeType() == Node.ELEMENT_NODE)
            cond.add(parseExistingConditionInsideLogic(n, template));
    }//  ww w  . ja v a 2 s  . c o  m

    return cond.getCanonicalCondition();
}

From source file:com.l2jfree.gameserver.model.skills.conditions.ConditionParser.java

private Condition parseLogicAnd(Node n, Object template) {
    ConditionLogicAnd cond = new ConditionLogicAnd();
    for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) {
        if (n.getNodeType() == Node.ELEMENT_NODE)
            cond.add(parseExistingConditionInsideLogic(n, template));
    }/*  w ww.ja v  a 2 s  .co  m*/

    return cond.getCanonicalCondition();
}

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderFE.java

private void downloadDatabase(DownloadItem di) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    String url = di.getAddress();
    Log.i(TAG, "Url: " + url);
    HttpGet httpget = new HttpGet(url);
    HttpResponse response;/* w  w  w . j  a v a 2s  .co  m*/
    response = httpclient.execute(httpget);
    Log.i(TAG, "Response: " + response.getStatusLine().toString());
    HttpEntity entity = response.getEntity();

    if (entity == null) {
        throw new Exception("Null entity error");
    }

    InputStream instream = entity.getContent();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = factory.newDocumentBuilder();
    Document doc = documentBuilder.parse(instream);
    NodeList nodes = doc.getElementsByTagName("cardSet");
    nodes = doc.getElementsByTagName("error");

    if (nodes.getLength() > 0) {
        throw new Exception("Invalid ID to retrieve the database!");
    }

    List<Item> itemList = new LinkedList<Item>();
    nodes = doc.getElementsByTagName("flashcard");

    int nodeNumber = nodes.getLength();
    for (int i = 0; i < nodeNumber; i++) {
        Node node = nodes.item(i);
        if (!node.hasChildNodes()) {
            continue;
        }
        NodeList childNodes = node.getChildNodes();

        int childNodeNumber = childNodes.getLength();
        Item item = new Item();
        item.setId(i + 1);
        for (int j = 0; j < childNodeNumber; j++) {
            Node childNode = childNodes.item(j);
            if (childNode.hasChildNodes()) {
                if (childNode.getNodeName().equals("question")) {
                    item.setQuestion(childNode.getFirstChild().getNodeValue());
                } else if (childNode.getNodeName().equals("answer")) {
                    item.setAnswer(childNode.getFirstChild().getNodeValue());
                }
            }
        }
        if (!item.getQuestion().equals("")) {
            itemList.add(item);
        }
    }
    instream.close();
    /* Now create the databased from the itemList */

    String dbname = di.getTitle() + ".db";
    /* Replace illegal characters */
    dbname = dbname.replaceAll("[`~!#@%&*{};:'\"]", "_");
    String dbpath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + getString(R.string.default_dir);
    DatabaseHelper.createEmptyDatabase(dbpath, dbname);
    DatabaseHelper dbHelper = new DatabaseHelper(this, dbpath, dbname);
    dbHelper.insertListItems(itemList);
    dbHelper.close();
}

From source file:ca.brood.softlogger.Softlogger.java

@Override
public boolean configure(Node rootNode) {
    NodeList loggerConfigNodes = rootNode.getChildNodes();
    log.debug("Configuring Logger...");
    for (int i = 0; i < loggerConfigNodes.getLength(); i++) {
        Node configNode = loggerConfigNodes.item(i);
        if ("name".compareToIgnoreCase(configNode.getNodeName()) == 0) {
            //log.debug("Logger Name: "+configNode.getFirstChild().getNodeValue());
            this.loggerName = configNode.getFirstChild().getNodeValue();
        } else if ("defaultScanRate".compareToIgnoreCase(configNode.getNodeName()) == 0) {
            //log.debug("Default scan rate: "+configNode.getFirstChild().getNodeValue());
            try {
                this.defaultScanRate = Integer.parseInt(configNode.getFirstChild().getNodeValue());
            } catch (NumberFormatException e) {
                log.error("Invalid scan rate: " + configNode.getFirstChild().getNodeValue());
                this.defaultScanRate = 0;
            }/*from   ww  w. ja  v a2s. c  om*/
        } else if (("server".compareToIgnoreCase(configNode.getNodeName()) == 0)
                || ("channel".compareToIgnoreCase(configNode.getNodeName()) == 0)
                || ("outputModule".compareToIgnoreCase(configNode.getNodeName()) == 0)
                || ("#comment".compareToIgnoreCase(configNode.getNodeName()) == 0)
                || ("#text".compareToIgnoreCase(configNode.getNodeName()) == 0)) {
            continue;
        } else {
            log.warn("Got unknown node in config: " + configNode.getNodeName());
        }
    }
    if (loggerName.equals("")) {
        log.warn("Softlogger name is blank");
    }
    if (defaultScanRate <= 0) {
        log.warn("Softlogger default scan rate is invalid.  Using default of 5000.");
        defaultScanRate = 5000;
    }

    //Load the data server
    loggerConfigNodes = rootNode.getOwnerDocument().getElementsByTagName("server");
    if (loggerConfigNodes.getLength() == 0) {
        log.fatal("Could not find a server defined in the config file.");
        return false;
    }
    if (loggerConfigNodes.getLength() > 1) {
        log.fatal("Too many servers are defined in the config file");
        return false;
    }
    Node currentConfigNode = loggerConfigNodes.item(0);
    server = new DataServer();
    if (!server.configure(currentConfigNode)) {
        return false;
    }

    //Load the softloggerChannels
    loggerConfigNodes = rootNode.getOwnerDocument().getElementsByTagName("channel");
    boolean workingChannel = false;
    for (int i = 0; i < loggerConfigNodes.getLength(); i++) {
        currentConfigNode = loggerConfigNodes.item(i);
        SoftloggerChannel mc = new SoftloggerChannel();
        if (mc.configure(currentConfigNode)) {
            workingChannel = true;
            softloggerChannels.add(mc);
        }
    }

    if (!workingChannel) {
        log.fatal("No usable softloggerChannels configured");
        return false;
    }

    for (int i = 0; i < softloggerChannels.size(); i++) {
        softloggerChannels.get(i).setDefaultScanRate(this.defaultScanRate);
    }

    ArrayList<Device> devices = new ArrayList<Device>();
    for (SoftloggerChannel channel : softloggerChannels) {
        devices.addAll(channel.getDevices());
    }

    //Load the global output modules
    currentConfigNode = rootNode.getOwnerDocument().getDocumentElement();
    loggerConfigNodes = currentConfigNode.getChildNodes();
    for (int i = 0; i < loggerConfigNodes.getLength(); i++) {
        currentConfigNode = loggerConfigNodes.item(i);
        if ("outputModule".compareToIgnoreCase(currentConfigNode.getNodeName()) != 0) {
            continue;
        }
        try {
            @SuppressWarnings("unchecked")
            Class<? extends OutputModule> outputClass = (Class<? extends OutputModule>) Class
                    .forName(currentConfigNode.getAttributes().getNamedItem("class").getNodeValue());
            OutputModule outputModule = outputClass.newInstance();
            if (outputModule.configure(currentConfigNode)) {
                for (Device d : devices) {
                    d.addOutputModule(outputModule.clone());
                }
            }
        } catch (Exception e) {
            log.error("Got exception while loading output module: ", e);
        }
    }

    this.printAll();

    return true;
}

From source file:com.gargoylesoftware.htmlunit.html.impl.SimpleRange.java

/**
 * {@inheritDoc}//  w  w  w.j  a  v  a 2 s.  c  om
 */
@Override
public void selectNodeContents(final Node node) throws RangeException, DOMException {
    startContainer_ = node.getFirstChild();
    startOffset_ = 0;
    endContainer_ = node.getLastChild();
    endOffset_ = getMaxOffset(node.getLastChild());
}

From source file:de.escidoc.core.common.util.security.helper.InvocationParser.java

/**
 * Gets the {@link StringAttribute} for the provided values.
 *
 * @param arguments         The arguments of the method call.
 * @param isArray           Flag that indicates that the given arguments parameter is an array (<code>true</code>)
 *                          or not (<code>false</code>).
 * @param index             The index of the current object.
 * @param invocationMapping The {@link InvocationMapping} to get the value for.
 * @return Returns a {@link StringAttribute} with the value for the invocation mapping.
 * @throws MissingMethodParameterException
 *                                  Thrown if a mandatory method parameter is not provided.
 * @throws WebserverSystemException Thrown in case of an internal error.
 * @throws de.escidoc.core.common.exceptions.application.invalid.XmlCorruptedException
 *//*from  w w w.j a v  a  2 s. co m*/
private StringAttribute getValueForInvocationMapping(final Object arguments, final boolean isArray,
        final int index, final InvocationMapping invocationMapping)
        throws WebserverSystemException, MissingMethodParameterException, XmlCorruptedException {

    // set the value
    final StringAttribute value;
    if (invocationMapping.getMappingType() == InvocationMapping.VALUE_MAPPING) {
        // fetch the value from inside the invocation mapping
        value = new StringAttribute(invocationMapping.getValue());
    } else {
        // Get the current object addressed by the invocation mapping
        final Object currentObject;
        if (isArray) {
            currentObject = ((Object[]) arguments)[invocationMapping.getPosition()];
        } else {
            if (invocationMapping.getPosition() != 0) {
                throw new WebserverSystemException("Invocation mapping error. Position "
                        + invocationMapping.getPosition() + " invalid for single argument, must be 0. [id="
                        + invocationMapping.getId() + ']');
            }
            currentObject = arguments;
        }

        // assert the addressed object has been provided
        if (currentObject == null) {
            throw new MissingMethodParameterException("The parameter at specified "
                    + "position must be provided" + (invocationMapping.getPosition() + 1));
        }
        if (invocationMapping.getMappingType() == InvocationMapping.SIMPLE_ATTRIBUTE_MAPPING) {
            value = new StringAttribute(currentObject.toString());
        } else if (invocationMapping.getMappingType() == InvocationMapping.XML_ATTRIBUTE_MAPPING
                || invocationMapping.getMappingType() == InvocationMapping.OPTIONAL_XML_ATTRIBUTE_MAPPING) {
            // fetch the value from XML document
            final Document document;
            try {
                document = documentCache.retrieveDocument(currentObject);
            } catch (final SAXException e) {
                throw new XmlCorruptedException(
                        StringUtility.format("Parsing of provided XML data failed. ", e.getMessage()), e);
            } catch (final Exception e) {
                throw new WebserverSystemException("Internal error. Parsing of XML failed.", e);
            }

            String path = invocationMapping.getPath();
            boolean extractObjidNeeded = false;
            if (path.startsWith("extractObjid:")) {
                path = path.substring("extractObjid:".length());
                extractObjidNeeded = true;
            }
            final String xpath = PATTERN_INDEXED.matcher(path).replaceAll("[" + (index + 1) + ']');
            final NodeList nodeList;
            try {
                nodeList = XPathAPI.selectNodeList(document, xpath);
            } catch (final TransformerException e) {
                throw new WebserverSystemException(
                        StringUtility.format("Invocation mapping error. Xpath invalid?", xpath, index,
                                invocationMapping.getId()),
                        e);
            }

            if (nodeList == null || nodeList.getLength() == 0) {
                if (index > 0) {
                    throw new IndexOutOfBoundsException();
                } else if (invocationMapping.getMappingType() == InvocationMapping.XML_ATTRIBUTE_MAPPING) {
                    throw new XmlCorruptedException(
                            StringUtility.format("Expected value not found " + "in provided XML data ", xpath));
                } else {
                    // skip undefined optional attribute by setting
                    // the value to null.
                    value = null;
                }
            } else {
                int length = 1;
                if (invocationMapping.isMultiValue()) {
                    length = nodeList.getLength();
                }
                final Collection<String> values = new HashSet<String>();
                for (int i = 0; i < length; i++) {
                    final Node node = nodeList.item(i);
                    String tmpValue = null;
                    if (node.getFirstChild() != null) {
                        tmpValue = node.getFirstChild().getNodeValue();
                    } else {
                        tmpValue = "";
                    }
                    if (tmpValue != null) {
                        if (extractObjidNeeded) {
                            tmpValue = XmlUtility.getIdFromURI(tmpValue);
                        }
                        values.add(tmpValue.trim());
                    }
                }
                if (values.isEmpty()) {
                    value = null;
                } else {
                    final StringBuilder valueBuf = new StringBuilder("");
                    for (final String val : values) {
                        if (!val.isEmpty()) {
                            if (valueBuf.length() > 0) {
                                valueBuf.append(' ');
                            }
                            valueBuf.append(val);
                        }
                    }
                    value = new StringAttribute(valueBuf.toString());
                }
            }
        } else {
            throw new WebserverSystemException(StringUtility.format("Unsupported invocation mapping type",
                    invocationMapping.getMappingType(), invocationMapping.getId()));
        }
    }
    return value;
}