Example usage for org.w3c.dom Document getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:com.l2jfree.gameserver.datatables.EnchantHPBonusData.java

private EnchantHPBonusData() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);// w w w.j  ava 2s.  c  o m
    factory.setIgnoringComments(true);
    File file = new File(Config.DATAPACK_ROOT, "data/enchantHPBonus.xml");
    Document doc = null;

    try {
        doc = factory.newDocumentBuilder().parse(file);
    } catch (Exception e) {
        _log.warn("", e);
        return;
    }

    for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("list".equalsIgnoreCase(n.getNodeName())) {
            for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                if ("enchantHP".equalsIgnoreCase(d.getNodeName())) {
                    NamedNodeMap attrs = d.getAttributes();
                    Node att;
                    boolean fullArmor;

                    att = attrs.getNamedItem("grade");
                    if (att == null) {
                        _log.warn("[EnchantHPBonusData] Missing grade, skipping");
                        continue;
                    }

                    int grade = Integer.parseInt(att.getNodeValue());

                    att = attrs.getNamedItem("fullArmor");
                    if (att == null) {
                        _log.warn("[EnchantHPBonusData] Missing fullArmor, skipping");
                        continue;
                    }
                    fullArmor = Boolean.valueOf(att.getNodeValue());

                    att = attrs.getNamedItem("values");
                    if (att == null) {
                        _log.warn("[EnchantHPBonusData] Missing bonus id: " + grade + ", skipping");
                        continue;
                    }
                    StringTokenizer st = new StringTokenizer(att.getNodeValue(), ",");
                    int tokenCount = st.countTokens();
                    Integer[] bonus = new Integer[tokenCount];
                    for (int i = 0; i < tokenCount; i++) {
                        Integer value = Integer.decode(st.nextToken().trim());
                        if (value == null) {
                            _log.warn("[EnchantHPBonusData] Bad Hp value!! grade: " + grade + " FullArmor? "
                                    + fullArmor + " token: " + i);
                            value = 0;
                        }
                        bonus[i] = value;
                    }
                    if (fullArmor)
                        _fullArmorHPBonus.set(grade, bonus);
                    else
                        _singleArmorHPBonus.set(grade, bonus);
                }
            }
        }
    }

    if (_fullArmorHPBonus.isEmpty() && _singleArmorHPBonus.isEmpty())
        return;

    int count = 0;

    for (L2Item item0 : ItemTable.getInstance().getAllTemplates()) {
        if (!(item0 instanceof L2Equip))
            continue;

        final L2Equip item = (L2Equip) item0;

        if (item.getCrystalType() == L2Item.CRYSTAL_NONE)
            continue;

        boolean shouldAdd = false;

        // normally for armors
        if (item instanceof L2Armor) {
            switch (item.getBodyPart()) {
            case L2Item.SLOT_CHEST:
            case L2Item.SLOT_FEET:
            case L2Item.SLOT_GLOVES:
            case L2Item.SLOT_HEAD:
            case L2Item.SLOT_LEGS:
            case L2Item.SLOT_BACK:
            case L2Item.SLOT_FULL_ARMOR:
            case L2Item.SLOT_UNDERWEAR:
            case L2Item.SLOT_L_HAND:
                shouldAdd = true;
                break;
            }
        }
        // shields in the weapons table
        else if (item instanceof L2Weapon) {
            switch (item.getBodyPart()) {
            case L2Item.SLOT_L_HAND:
                shouldAdd = true;
                break;
            }
        }

        if (shouldAdd) {
            count++;
            item.attach(new FuncTemplate(null, "EnchantHp", Stats.MAX_HP, 0x60, 0));
        }
    }

    _log.info("Enchant HP Bonus registered for " + count + " items!");
}

From source file:net.java.sen.StringTagger.java

/**
 * Read configuration file.//  w  w  w.  j a v  a 2s .  c  o m
 * 
 * @param confFile
 *            configuration file
 */
private void readConfig(String confFile) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        File cf = new File(confFile);
        String parent = cf.getParentFile().getParent();
        if (parent == null)
            parent = ".";
        Document doc = builder.parse(new InputSource(confFile));
        NodeList nl = doc.getFirstChild().getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            org.w3c.dom.Node n = nl.item(i);
            if (n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                String nn = n.getNodeName();
                String value = n.getFirstChild().getNodeValue();

                if (nn.equals("charset")) {
                    charset = value;
                } else if (nn.equals("unknown-pos")) {
                    unknownPos = value;
                } else if (nn.equals("tokenizer")) {
                    tokenizerClass = value;
                }

                if (nn.equals("dictionary")) {
                    // read nested tag in <dictinary>
                    NodeList dnl = n.getChildNodes();
                    for (int j = 0; j < dnl.getLength(); j++) {
                        org.w3c.dom.Node dn = dnl.item(j);
                        if (dn.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {

                            String dnn = dn.getNodeName();
                            if (dn.getFirstChild() == null) {
                                throw new IllegalArgumentException("element '" + dnn + "' is empty");
                            }
                            String dvalue = dn.getFirstChild().getNodeValue();

                            if (dnn.equals("connection-cost")) {
                                connectFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("double-array-trie")) {
                                doubleArrayFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("token")) {
                                tokenFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("pos-info")) {
                                posInfoFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("compound")) {
                                // do nothing
                            } else {
                                throw new IllegalArgumentException("element '" + dnn + "' is invalid");
                            }
                        }
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        throw new IllegalArgumentException(e.getMessage());
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException(e.getMessage());
    } catch (SAXException e) {
        throw new IllegalArgumentException(e.getMessage());
    } catch (IOException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}

From source file:net.sourceforge.eclipsetrader.ats.Repository.java

public void load() {
    File file = new File(Platform.getLocation().toFile(), "systems.xml"); //$NON-NLS-1$
    if (file.exists() == true) {
        log.info("Loading trading systems");
        try {//from w ww  .  j  a  va2s .co m
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setErrorHandler(errorHandler);
            Document document = builder.parse(file);

            Node firstNode = document.getFirstChild();
            nextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$

            NodeList childNodes = firstNode.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node item = childNodes.item(i);
                String nodeName = item.getNodeName();
                if (nodeName.equalsIgnoreCase("system")) //$NON-NLS-1$
                {
                    TradingSystem system = loadTradingSystem(item.getChildNodes());
                    if (system != null)
                        systems.add(system);
                }
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }
}

From source file:com.freedomotic.plugins.devices.ethrly.DevantechEthRly.java

private void evaluateDiffs(Document doc, Board board) {
    //parses xml//from   w w w  .  ja v  a2  s . com
    if (doc != null && board != null) {
        Node n = doc.getFirstChild();
        NodeList nl = n.getChildNodes();
        valueTag(doc, board, board.getRelayNumber(), "led", 0);
    }
}

From source file:com.viadee.acceptancetests.roo.addon.AcceptanceTestsOperations.java

protected List<Element> loadDependencies() {
    InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "dependencies.xml");
    Assert.notNull(templateInputStream, "Could not acquire dependencies.xml file");
    Document dependencyDoc;
    try {//  w w w . j a v  a 2s  . c o m
        dependencyDoc = XmlUtils.getDocumentBuilder().parse(templateInputStream);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    Element dependenciesElement = (Element) dependencyDoc.getFirstChild();

    return XmlUtils.findElements("/dependencies/acceptanceTests/dependency", dependenciesElement);
}

From source file:com.gargoylesoftware.htmlunit.xml.XmlPage.java

/**
 * Creates an instance./*from  ww w  . ja v  a  2s .c om*/
 * A warning is logged if an exception is thrown while parsing the XML content
 * (for instance when the content is not a valid XML and can't be parsed).
 *
 * @param webResponse the response from the server
 * @param enclosingWindow the window that holds the page
 * @param ignoreSAXException Whether to ignore {@link SAXException} or throw it as {@link IOException}
 * @param handleXHTMLAsHTML if true elements from the XHTML namespace are handled as HTML elements instead of
 *     DOM elements
 * @throws IOException if the page could not be created
 */
public XmlPage(final WebResponse webResponse, final WebWindow enclosingWindow, final boolean ignoreSAXException,
        final boolean handleXHTMLAsHTML) throws IOException {
    super(webResponse, enclosingWindow);

    try {
        try {
            final Document document = XmlUtil.buildDocument(webResponse);
            node_ = document.getFirstChild();
        } catch (final SAXException e) {
            LOG.warn("Failed parsing XML document " + webResponse.getWebRequest().getUrl() + ": "
                    + e.getMessage());
            if (!ignoreSAXException) {
                throw new IOException(e.getMessage());
            }
        }
    } catch (final ParserConfigurationException e) {
        if (null == webResponse) {
            LOG.warn("Failed parsing XML empty document: " + e.getMessage());
        } else {
            LOG.warn("Failed parsing XML empty document " + webResponse.getWebRequest().getUrl() + ": "
                    + e.getMessage());
        }
    }

    Node node = node_;
    while (node != null) {
        XmlUtil.appendChild(this, this, node, handleXHTMLAsHTML);
        node = node.getNextSibling();
    }
}

From source file:org.apache.camel.component.social.providers.twitter.AbstractTwitterPath.java

public SocialData updateData(Object data, Map<String, Object> headers) throws SocialDataFetchError {
    String status = data.toString();

    String url = normalizeURL(getCommandPath());

    Map<String, Object> params = new HashMap<String, Object>();

    Object inReplyTo = headers.get(TwitterProvider.IN_REPLY_TO);
    if (inReplyTo != null) {
        params.put(TwitterProvider.IN_REPLY_TO, inReplyTo);
    }/*from   w  w w  .j a  v a  2  s . co m*/

    Object lat = headers.get(TwitterProvider.LATITUDE);
    if (lat != null) {
        params.put(TwitterProvider.LATITUDE, lat);
    }

    Object _long = headers.get(TwitterProvider.LONGITUDE);
    if (_long != null) {
        params.put(TwitterProvider.LONGITUDE, _long);
    }

    Object place_id = headers.get(TwitterProvider.PLACE_ID);
    if (place_id != null) {
        params.put(TwitterProvider.PLACE_ID, place_id);
    }

    Object trim_user = headers.get(TwitterProvider.TRIM_USER);
    params.put(TwitterProvider.TRIM_USER, trim_user == null ? "1" : trim_user);
    params.put(TwitterProvider.STATUS, status);

    HttpPost post = new HttpPost(url);
    HttpResponse response;
    response = callHttpMethod(params, post);

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        try {
            log.warn("Could not update Twitter status: " + response.getStatusLine() + "\n"
                    + EntityUtils.toString(response.getEntity()));
        } catch (ParseException e) {
        } catch (IOException e) {
        }
        return null;
    }

    String body;
    try {
        body = EntityUtils.toString(response.getEntity());

        DocumentBuilder db = domFac.newDocumentBuilder();

        InputSource source = new InputSource();
        source.setCharacterStream(new StringReader(body));
        Document doc = db.parse(source);

        DefaultSocialData socialData = parseStatus(doc.getFirstChild());
        return socialData;
    } catch (Exception e) {
        throw new SocialDataFetchError(e);
    }
}

From source file:com.hygenics.parser.ManualReplacement.java

private void transform() {
    log.info("Transforming");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    for (String fpath : fpaths) {
        log.info("FILE: " + fpath);
        try {/*  ww  w .  j  av a  2 s.  c om*/
            // TRANSFORM
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File(fpath));
            Node root = doc.getFirstChild();
            XPathFactory xfactory = XPathFactory.newInstance();
            XPath xpath = xfactory.newXPath();
            String database = null;
            String path = "//transformation/connection";

            log.info("Removing");
            for (String dbname : remove) {
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                if (conn != null) {
                    root.removeChild(conn);
                }
            }

            log.info("Transforming");
            for (String key : databaseAttributes.keySet()) {
                database = key;
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);

                if (conn != null) {
                    if (remove.contains(key)) {
                        root.removeChild(conn);
                    } else {
                        Map<String, String> attrs = databaseAttributes.get(database);
                        NodeList nl = conn.getChildNodes();
                        Set<String> keys = databaseAttributes.get(key).keySet();

                        for (int i = 0; i < nl.getLength(); i++) {
                            org.w3c.dom.Node n = nl.item(i);

                            if (keys.contains(n.getNodeName().trim())) {
                                n.setNodeValue(attrs.get(n.getNodeName()));
                            }
                        }
                    }
                }

                if (!this.log_to_table || (this.log_to_table && this.loggingTables != null)) {
                    log.info("Logging Manipulation");
                    log.info("PERFORMING LOGGING MANIPULATION: " + (!this.log_to_table) != null
                            ? "Removing Logging Data"
                            : "Adding Logging data");
                    String[] sections = new String[] { "trans-log-table", "perf-log-table", "channel-log-table",
                            "step-log-table", "metrics-log-table" };
                    for (String section : sections) {
                        log.info("Changing Settings for " + section);
                        xepr = xpath.compile("//" + section + "/field/enabled");
                        NodeList nodes = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET);
                        log.info("Nodes Found: " + Integer.toString(nodes.getLength()));
                        for (int i = 0; i < nodes.getLength(); i++) {
                            if (!this.log_to_table) {
                                nodes.item(i).setNodeValue("N");
                            } else {
                                nodes.item(i).setNodeValue("Y");
                            }
                        }

                        for (String nodeName : new String[] { "schema", "connection", "table",
                                "size_limit_lines", "interval", "timeout_days" }) {
                            if (!this.log_to_table) {
                                log.info("Changing Settings for Node: " + nodeName);
                                xepr = xpath.compile("//" + section + "/" + nodeName);
                                Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                                if (node != null) {
                                    if (!this.log_to_table) {
                                        node.setNodeValue(null);
                                    } else if (this.loggingTables.containsKey(section)
                                            && this.loggingTables.get(section).containsKey(nodeName)) {
                                        node.setNodeValue(this.loggingTables.get(section).get(nodeName));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // SET MAIN CONNECTION
            if (mainConnection != null) {
                XPathExpression xepr = xpath.compile(path);
                NodeList conns = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); // NodeSet is not a part of
                // org.w3c it is
                // actually a NodeList
                for (int i = 0; i < conns.getLength(); i++) {
                    if (!conns.item(i).hasChildNodes()) {// only connection
                        // elements
                        // without child
                        // nodes have
                        // text content
                        conns.item(i).setNodeValue(mainConnection);
                    }
                }
            }

            if (this.replacements != null) {
                for (String key : this.replacements.keySet()) {
                    XPathExpression xepr = xpath.compile(key);
                    Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                    if (node != null) {
                        for (String attrVal : this.replacements.get(key).keySet()) {
                            log.info("Replacing Information at " + key + "at " + attrVal);
                            log.info("Replacement Will Be: "
                                    + StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));

                            if (attrVal.toLowerCase().trim().equals("text")) {
                                node.setNodeValue(
                                        StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));
                                if (node.getNodeValue() == null) {
                                    node.setTextContent(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                }

                            } else {
                                NamedNodeMap nattrs = node.getAttributes();
                                Node n = nattrs.getNamedItem(attrVal);
                                if (n != null) {
                                    n.setNodeValue(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                } else {
                                    log.warn("Attribute Not Found " + attrVal);
                                }
                            }
                        }
                    } else {
                        log.warn("Node not found for " + key);
                    }
                }
            }

            // WRITE TO FILE
            log.info("Writing to File");
            TransformerFactory tfact = TransformerFactory.newInstance();
            Transformer transformer = tfact.newTransformer();
            DOMSource source = new DOMSource(doc);
            try (FileOutputStream stream = new FileOutputStream(new File(fpath))) {
                StreamResult result = new StreamResult(stream);
                transformer.transform(source, result);
                stream.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.sourceforge.eclipsetrader.yahoo.FrenchNewsProvider.java

private void update() {
    Job job = new Job(NEWS_NAME) {
        @Override/*from   w w  w. j ava 2s  . c  om*/
        protected IStatus run(IProgressMonitor monitor) {
            IPreferenceStore store = YahooPlugin.getDefault().getPreferenceStore();

            List urls = new ArrayList();
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document document = builder.parse(FileLocator.openStream(YahooPlugin.getDefault().getBundle(),
                        new Path(NEWS_CONFIG_FILE), false));

                NodeList childNodes = document.getFirstChild().getChildNodes();
                for (int i = 0; i < childNodes.getLength(); i++) {
                    Node node = childNodes.item(i);
                    String nodeName = node.getNodeName();
                    if (nodeName.equalsIgnoreCase("category")) //$NON-NLS-1$
                    {
                        String id = (node).getAttributes().getNamedItem("id").getNodeValue(); //$NON-NLS-1$

                        NodeList list = node.getChildNodes();
                        for (int x = 0; x < list.getLength(); x++) {
                            Node item = list.item(x);
                            nodeName = item.getNodeName();
                            Node value = item.getFirstChild();
                            if (value != null) {
                                if (nodeName.equalsIgnoreCase("url")) //$NON-NLS-1$
                                {
                                    if (store.getBoolean(id))
                                        urls.add(value.getNodeValue());
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            //                List securities = CorePlugin.getRepository().allSecurities();
            //                monitor.beginTask("Fetching" + NEWS_NAME, securities.size() + urls.size());
            //
            //                for (Iterator iter = securities.iterator(); iter.hasNext(); )
            //                {
            //                    Security security = (Security) iter.next();
            //                    try {
            //                        String url = NEWS_SECURITY_URL_BASE + security.getCode().toLowerCase();
            //                        monitor.subTask(url);
            //                        update(new URL(url), security);
            //                    } catch(Exception e) {
            //                        CorePlugin.logException(e);
            //                    }
            //                    monitor.worked(1);
            //                }
            for (Iterator iter = urls.iterator(); iter.hasNext();) {
                String url = (String) iter.next();
                try {
                    monitor.subTask(url);
                    update(new URL(url));
                } catch (Exception e) {
                    CorePlugin.logException(e);
                }
                monitor.worked(1);
            }

            monitor.done();
            return Status.OK_STATUS;
        }
    };
    job.setUser(false);
    job.schedule();
}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

public static void prettyPrintDOMWithEncoding(Document doc, String defaultEncoding, Result result) {
    Node firstChild = doc.getFirstChild();
    boolean omitXMLDeclaration = false;
    String encoding = defaultEncoding; // default Encoding char set if non
    // is found in the PI

    if ((firstChild.getNodeType() == Document.PROCESSING_INSTRUCTION_NODE)
            && (firstChild.getNodeName().equals("xml"))) {
        omitXMLDeclaration = true;//from   w ww  .java 2  s  .com
        String piValue = firstChild.getNodeValue();
        // extract from PI the encoding Char Set
        int encodingOffset = piValue.indexOf("encoding=\"");
        if (encodingOffset != -1) {
            encoding = piValue.substring(encodingOffset + 10);
            // remove the last "
            encoding = encoding.substring(0, encoding.length() - 1);
        }
    }

    try {
        Transformer t = getNewTransformer();
        t.setOutputProperty(OutputKeys.ENCODING, encoding);
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html, text
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration ? "yes" : "no");
        t.transform(new DOMSource(doc), result);
    } catch (Exception e) {
        Engine.logEngine.error("Unexpected exception while pretty print DOM", e);
    }
}