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.instancemanager.ZoneManager.java

protected int parseDocument(Document doc) {
    int zoneCount = 0;

    // Get the world regions
    L2WorldRegion[][] worldRegions = L2World.getInstance().getAllWorldRegions();
    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 ("zone".equalsIgnoreCase(d.getNodeName())) {
                    final L2Zone zone = L2Zone.parseZone(d);
                    if (zone == null)
                        continue;
                    Integer id = zone.getQuestZoneId();
                    if (_uniqueZones.containsKey(id)) {
                        _log.warn("Zone " + zone.getName() + " doesn't specify a valid unique ID, ignored!");
                        continue;
                    } else if (id > 0)
                        _uniqueZones.put(id, zone);

                    if (_zones[zone.getType().ordinal()] == null)
                        _zones[zone.getType().ordinal()] = new L2Zone[] { zone };
                    else
                        _zones[zone.getType().ordinal()] = ArrayUtils.add(_zones[zone.getType().ordinal()],
                                zone);/* w w  w.  jav  a  2s .co  m*/

                    // Register the zone to any intersecting world region
                    int ax, ay, bx, by;
                    for (int x = 0; x < worldRegions.length; x++) {
                        for (int y = 0; y < worldRegions[x].length; y++) {
                            ax = (x - L2World.OFFSET_X) << L2World.SHIFT_BY;
                            bx = ((x + 1) - L2World.OFFSET_X) << L2World.SHIFT_BY;
                            ay = (y - L2World.OFFSET_Y) << L2World.SHIFT_BY;
                            by = ((y + 1) - L2World.OFFSET_Y) << L2World.SHIFT_BY;

                            if (zone.intersectsRectangle(ax, bx, ay, by)) {
                                worldRegions[x][y].addZone(zone);
                            }
                        }
                    }
                    zoneCount++;
                }
            }
        }
    }
    return zoneCount;
}

From source file:net.sourceforge.eclipsetrader.core.internal.TradingSystemRepository.java

public TradingSystemRepository(XMLRepository repository) {
    this.repository = repository;

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

            Node firstNode = document.getFirstChild();
            tsNextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$
            tsGroupNextId = new Integer(firstNode.getAttributes().getNamedItem("nextGroupId").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 obj = loadSystem(item.getChildNodes());
                    obj.setRepository(this.repository);
                } else if (nodeName.equalsIgnoreCase("group")) //$NON-NLS-1$
                {
                    TradingSystemGroup group = (TradingSystemGroup) loadGroup(item.getChildNodes());
                    group.setRepository(this.repository);
                }
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }
}

From source file:org.gvnix.web.menu.roo.addon.MenuEntryConverter.java

/**
 * Get all values//from w  w w  .  j a v  a  2s.  c om
 * 
 * @param completions
 * @param requiredType
 * @param existingData
 * @param optionContext
 * @param target
 */
public boolean getAllPossibleValues(List<Completion> completions, Class<?> requiredType, String existingData,
        String optionContext, MethodTarget target) {
    Document document = operations.getMenuDocument();

    // make the root element of the menu the one with the menu identifier
    // allowing for different decorations of menu
    Element rootElement = XmlUtils.findFirstElement("//*[@id='_menu']", (Element) document.getFirstChild());

    List<Element> elements = null;

    if (MenuEntryOperations.CATEGORY_MENU_ITEM_PREFIX.equals(optionContext)) {
        elements = XmlUtils.findElements(
                "//*[starts-with(@id, '".concat(MenuEntryOperations.CATEGORY_MENU_ITEM_PREFIX).concat("')]"),
                rootElement);
    }
    // Get all elements that have the id attribute
    else {
        elements = XmlUtils.findElements("//*[@id]", rootElement);
    }

    for (Element element : elements) {
        completions.add(new Completion(element.getAttribute("id")));
    }

    return false;
}

From source file:DOM2SAX.java

/**
 * Writes the given document using the given ContentHandler.
 * @param doc DOM document// ww  w .j  ava  2s . co m
 * @param fragment if false no startDocument() and endDocument() calls are issued.
 * @throws SAXException In case of a problem while writing XML
 */
public void writeDocument(Document doc, boolean fragment) throws SAXException {
    if (!fragment) {
        contentHandler.startDocument();
    }
    for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        writeNode(n);
    }
    if (!fragment) {
        contentHandler.endDocument();
    }
}

From source file:com.mnxfst.testing.plan.exec.TestSaturationExec.java

public void testExecClient()
        throws ClientProtocolException, IOException, SAXException, ParserConfigurationException {

    HttpGet getMethod = new HttpGet(
            "/?execute=1&threads=4&recurrences=1&recurrencetype=times&testplan=AddressIntTestPlan.xml&scenarioId=sec1");
    HttpHost host = new HttpHost("localhost", 9090);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(host, getMethod);
    InputStream s = response.getEntity().getContent();

    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(s);
    s.close();/*from w w  w. j  ava  2 s .  c o  m*/
    Node rootNode = doc.getFirstChild();
    System.out.println(rootNode.getNodeName());
    NodeList childs = rootNode.getChildNodes();
    for (int i = 0; i < childs.getLength(); i++) {
        System.out.println(childs.item(i));
    }
}

From source file:org.bigtester.ate.model.data.TestDatabaseInitializer.java

/**
 * Combine init xml files.// www .  j  a v  a2 s  . c o  m
 *
 * @return the input stream
 */
private InputStream combineInitXmlFiles() {
    if (getInitXmlFiles().isEmpty()) {
        throw GlobalUtils.createNotInitializedException("xml data files are not populated");
    } else {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder dbuilder;
        try {
            dbuilder = dbf.newDocumentBuilder();

            Document retDoc = dbuilder.newDocument();
            Document doc0;

            doc0 = dbuilder.parse(getInitXmlFiles().get(0));

            Node firstDataset = retDoc.importNode(doc0.getFirstChild(), true);
            retDoc.appendChild(firstDataset);
            for (int i = 1; i < getInitXmlFiles().size(); i++) {
                Document doc2 = dbuilder.parse(getInitXmlFiles().get(i));
                Node root = doc2.getFirstChild();
                NodeList list = root.getChildNodes();
                for (int index = 0; index < list.getLength(); index++) {
                    Node copiedNode = retDoc.importNode(list.item(index), true);
                    retDoc.getDocumentElement().appendChild(copiedNode);
                }
            }

            DOMSource source = new DOMSource(retDoc);
            StringWriter xmlAsWriter = new StringWriter();

            StreamResult result = new StreamResult(xmlAsWriter);

            TransformerFactory.newInstance().newTransformer().transform(source, result);

            // write changes
            return new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8"));

        } catch (SAXException | IOException | ParserConfigurationException e) {
            throw GlobalUtils.createNotInitializedException("xml data files are not correctly populated", e);
        } catch (TransformerException | TransformerFactoryConfigurationError transE) {
            throw GlobalUtils.createInternalError("xml transformer error!", transE);
        }

    }
}

From source file:com.prowidesoftware.swift.model.mx.AbstractMX.java

public Element element() {
    final HashMap<String, String> properties = new HashMap<String, String>();
    // it didn't work as expected
    // properties.put(JAXBRIContext.DEFAULT_NAMESPACE_REMAP, namespace);
    try {/*  w w  w . ja va2  s.com*/
        JAXBContext context = JAXBContext.newInstance(getClasses(), properties);

        DOMResult res = new DOMResult();
        context.createMarshaller().marshal(this, res);
        Document doc = (Document) res.getNode();

        return (Element) doc.getFirstChild();
    } catch (Exception e) {
        log.log(Level.WARNING, "Error creating XML Document for MX", e);
        return null;
    }
}

From source file:com.adaptris.core.services.jdbc.XmlPayloadTranslatorImpl.java

protected List<Element> createListFromResultSet(DocumentBuilder builder, Document doc, JdbcResultSet rs)
        throws SQLException {
    List<Element> results = new ArrayList<Element>();

    List<String> elementNames = new ArrayList<>();
    boolean firstRecord = true;
    for (JdbcResultRow row : rs.getRows()) {
        Element elementRow = doc.createElement(getColumnNameStyle().format(ELEMENT_NAME_ROW));
        // let's go through and build up the element names we need once.
        if (firstRecord) {
            firstRecord = false;/*from www .ja  v a  2  s  .  c  o  m*/
            elementNames = createElementNames(row);
        }
        for (int i = 0; i < row.getFieldCount(); i++) {
            String columnName = row.getFieldName(i);
            String value = toString(row, i);

            Element node = doc.createElement(elementNames.get(i));
            if (isXmlColumn(columnName)) {
                try {
                    Document xmlColumn = null;
                    xmlColumn = builder.parse(createInputSource(value));
                    node.appendChild(doc.importNode(xmlColumn.getFirstChild(), true));
                } catch (Exception e) {
                    if (isDisplayColumnErrors()) {
                        log.warn("Failed to parse column {} as an XML Document, treating as text.", columnName);
                        log.trace("Failed to parse column {} as an XML Document", columnName, e);
                    }
                    node.appendChild(createTextNode(doc, value, isCdataColumn(columnName)));
                }
            } else {
                node.appendChild(createTextNode(doc, value, isCdataColumn(columnName)));
            }
            elementRow.appendChild(node);
        }
        results.add(elementRow);
    }
    return results;
}

From source file:com.prowidesoftware.swift.model.mx.BusinessHeader.java

/**
 * Gets the header as an Element object.
 *  // w  w w  . j  a  va  2  s .c o m
 * @return Element this header parsed into Element or null if header is null
 * @since 7.8
 */
public Element element() {
    Object header = null;
    if (this.businessApplicationHeader != null) {
        header = this.businessApplicationHeader;
    } else if (this.applicationHeader != null) {
        header = this.applicationHeader;
    } else {
        return null;
    }
    try {
        JAXBContext context = JAXBContext.newInstance(header.getClass());
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        DOMResult res = new DOMResult();
        marshaller.marshal(_element(header), res);
        Document doc = (Document) res.getNode();
        return (Element) doc.getFirstChild();

    } catch (JAXBException e) {
        log.log(Level.SEVERE, "Error writing XML:" + e + "\n for header: " + header);
    }
    return null;
}

From source file:com.freedomotic.plugins.devices.ipx800.Ipx800.java

private void evaluateDiffs(Document doc, Board board) {
    //parses xml/*  ww  w . j a va  2 s . c o m*/
    if (doc != null && board != null) {
        Node n = doc.getFirstChild();
        NodeList nl = n.getChildNodes();
        valueTag(doc, board, board.getRelayNumber(), board.getLedTag(), 0);
        valueTag(doc, board, board.getDigitalInputNumber(), board.getDigitalInputTag(), 0);
        valueTag(doc, board, board.getAnalogInputNumber(), board.getAnalogInputTag(), 0);
    }
}