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:org.gvnix.service.roo.addon.addon.security.SecurityServiceImpl.java

/**
 * Adds Apache wss4j dependency to application pom.
 *//*  ww  w .  j  a va  2  s.  c  o m*/
protected void addDependencies() {

    annotationsService.addAddonDependency();
    InputStream templateInputStream = FileUtils.getInputStream(getClass(), DEPENDENCIES_FILE);
    Validate.notNull(templateInputStream, "Can't adquire dependencies file ".concat(DEPENDENCIES_FILE));

    Document dependencyDoc;
    try {

        dependencyDoc = XmlUtils.getDocumentBuilder().parse(templateInputStream);
    } catch (Exception e) {

        throw new IllegalStateException(e);
    }

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

    List<Element> dependecyElementList = XmlUtils.findElements("/dependencies/dependency", dependencies);
    List<Dependency> dependencyList = new ArrayList<Dependency>();

    for (Element element : dependecyElementList) {
        dependencyList.add(new Dependency(element));
    }
    projectOperations.addDependencies(projectOperations.getFocusedModuleName(), dependencyList);
}

From source file:lineage2.gameserver.instancemanager.HellboundManager.java

/**
 * Method getHellboundSpawn.//from   ww  w . j  a  va2s .c o m
 */
private void getHellboundSpawn() {
    _list = new ArrayList<>();
    _spawnList = new ArrayList<>();
    try {
        File file = new File(Config.DATAPACK_ROOT + "/data/xml/other/hellbound_spawnlist.xml");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        Document doc1 = factory.newDocumentBuilder().parse(file);
        int counter = 0;
        for (Node n1 = doc1.getFirstChild(); n1 != null; n1 = n1.getNextSibling()) {
            if ("list".equalsIgnoreCase(n1.getNodeName())) {
                for (Node d1 = n1.getFirstChild(); d1 != null; d1 = d1.getNextSibling()) {
                    if ("data".equalsIgnoreCase(d1.getNodeName())) {
                        counter++;
                        int npcId = Integer.parseInt(d1.getAttributes().getNamedItem("npc_id").getNodeValue());
                        Location spawnLoc = null;
                        if (d1.getAttributes().getNamedItem("loc") != null) {
                            spawnLoc = Location.parseLoc(d1.getAttributes().getNamedItem("loc").getNodeValue());
                        }
                        int count = 1;
                        if (d1.getAttributes().getNamedItem("count") != null) {
                            count = Integer.parseInt(d1.getAttributes().getNamedItem("count").getNodeValue());
                        }
                        int respawn = 60;
                        if (d1.getAttributes().getNamedItem("respawn") != null) {
                            respawn = Integer
                                    .parseInt(d1.getAttributes().getNamedItem("respawn").getNodeValue());
                        }
                        int respawnRnd = 0;
                        if (d1.getAttributes().getNamedItem("respawn_rnd") != null) {
                            respawnRnd = Integer
                                    .parseInt(d1.getAttributes().getNamedItem("respawn_rnd").getNodeValue());
                        }
                        Node att = d1.getAttributes().getNamedItem("stage");
                        StringTokenizer st = new StringTokenizer(att.getNodeValue(), ";");
                        int tokenCount = st.countTokens();
                        int[] stages = new int[tokenCount];
                        for (int i = 0; i < tokenCount; i++) {
                            Integer value = Integer.decode(st.nextToken().trim());
                            stages[i] = value;
                        }
                        Territory territory = null;
                        for (Node s1 = d1.getFirstChild(); s1 != null; s1 = s1.getNextSibling()) {
                            if ("territory".equalsIgnoreCase(s1.getNodeName())) {
                                Polygon poly = new Polygon();
                                for (Node s2 = s1.getFirstChild(); s2 != null; s2 = s2.getNextSibling()) {
                                    if ("add".equalsIgnoreCase(s2.getNodeName())) {
                                        int x = Integer
                                                .parseInt(s2.getAttributes().getNamedItem("x").getNodeValue());
                                        int y = Integer
                                                .parseInt(s2.getAttributes().getNamedItem("y").getNodeValue());
                                        int minZ = Integer.parseInt(
                                                s2.getAttributes().getNamedItem("zmin").getNodeValue());
                                        int maxZ = Integer.parseInt(
                                                s2.getAttributes().getNamedItem("zmax").getNodeValue());
                                        poly.add(x, y).setZmin(minZ).setZmax(maxZ);
                                    }
                                }
                                territory = new Territory().add(poly);
                                if (!poly.validate()) {
                                    _log.error("HellboundManager: Invalid spawn territory : " + poly + "!");
                                    continue;
                                }
                            }
                        }
                        if ((spawnLoc == null) && (territory == null)) {
                            _log.error("HellboundManager: no spawn data for npc id : " + npcId + "!");
                            continue;
                        }
                        HellboundSpawn hbs = new HellboundSpawn(npcId, spawnLoc, count, territory, respawn,
                                respawnRnd, stages);
                        _list.add(hbs);
                    }
                }
            }
        }
        _log.info("HellboundManager: Loaded " + counter + " spawn entries.");
    } catch (Exception e) {
        _log.warn("HellboundManager: Spawn table could not be initialized.");
        e.printStackTrace();
    }
}

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

private MultiSellListContainer parseDocument(Document doc) {
    MultiSellListContainer list = new MultiSellListContainer();

    int entryId = 1;
    for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("list".equalsIgnoreCase(n.getNodeName())) {
            if (n.getAttributes() != null) {
                Node attribute;/*from  ww w.j  a v  a  2  s.  c  o m*/
                attribute = n.getAttributes().getNamedItem("applyTaxes");
                if (attribute == null)
                    list.setApplyTaxes(false);
                else
                    list.setApplyTaxes(Boolean.parseBoolean(attribute.getNodeValue()));
                attribute = n.getAttributes().getNamedItem("maintainEnchantment");
                if (attribute == null)
                    list.setMaintainEnchantment(false);
                else
                    list.setMaintainEnchantment(Boolean.parseBoolean(attribute.getNodeValue()));
            }

            for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                if ("item".equalsIgnoreCase(d.getNodeName())) {
                    MultiSellEntry e = parseEntry(d, entryId++);
                    list.addEntry(e);
                }
            }
        }
    }

    return list;
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

@Override
public CommitRequest parseCommitRequest(String content) {
    try {/*from   ww w  .  j a  v  a 2  s  . c  o m*/
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS lsImpl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSParser requestConfigParser = lsImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

        // Set options on the parser
        DOMConfiguration config = requestConfigParser.getDomConfig();
        config.setParameter("validate", Boolean.TRUE);
        config.setParameter("element-content-whitespace", Boolean.FALSE);
        config.setParameter("comments", Boolean.FALSE);
        requestConfigParser.setFilter(new LSParserFilter() {
            @Override
            public short startElement(Element elementArg) {
                return LSParserFilter.FILTER_ACCEPT;
            }

            @Override
            public short acceptNode(Node nodeArg) {
                return StringUtils.isBlank(nodeArg.getTextContent()) ? LSParserFilter.FILTER_REJECT
                        : LSParserFilter.FILTER_ACCEPT;
            }

            @Override
            public int getWhatToShow() {
                return NodeFilter.SHOW_TEXT;
            }
        });
        LSInput lsInput = lsImpl.createLSInput();
        lsInput.setStringData(content);
        Document commitRequestDoc = requestConfigParser.parse(lsInput);
        Node rootNode = commitRequestDoc.getFirstChild();
        if (!"CommitRequest".equals(rootNode.getNodeName()))
            throw new IllegalArgumentException("Not a CommitRequest xml passed: " + rootNode.getNodeName());

        CommitRequest result = new CommitRequest();

        NodeList children = rootNode.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            String childNodeName = child.getNodeName();
            if ("commitInstances".equals(childNodeName)) {
                NodeList entitiesNodeList = child.getChildNodes();

                Set<String> commitIds = new HashSet<>(entitiesNodeList.getLength());
                for (int j = 0; j < entitiesNodeList.getLength(); j++) {
                    Node idNode = entitiesNodeList.item(j).getAttributes().getNamedItem("id");
                    if (idNode == null)
                        continue;

                    String id = idNode.getTextContent();
                    if (id.startsWith("NEW-"))
                        id = id.substring(id.indexOf('-') + 1);
                    commitIds.add(id);
                }

                result.setCommitIds(commitIds);
                result.setCommitInstances(parseNodeList(result, entitiesNodeList));
            } else if ("removeInstances".equals(childNodeName)) {
                NodeList entitiesNodeList = child.getChildNodes();

                List removeInstances = parseNodeList(result, entitiesNodeList);
                result.setRemoveInstances(removeInstances);
            } else if ("softDeletion".equals(childNodeName)) {
                result.setSoftDeletion(Boolean.parseBoolean(child.getTextContent()));
            }
        }
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:it.unibo.alchemist.language.EnvironmentBuilder.java

/**
 * Actually builds the environment given the AST built in the constructor.
 * /*from w w w .java2s  . c  o  m*/
 * @throws InstantiationException
 *             malformed XML
 * @throws IllegalAccessException
 *             malformed XML
 * @throws InvocationTargetException
 *             malformed XML
 * @throws ClassNotFoundException
 *             your classpath does not include all the classes you are using
 * @throws IOException
 *             if there is an error reading the file
 * @throws SAXException
 *             if the XML is not correctly formatted
 * @throws ParserConfigurationException
 *             should not happen.
 */
private void buildEnvironment()
        throws InstantiationException, IllegalAccessException, InvocationTargetException,
        ClassNotFoundException, SAXException, IOException, ParserConfigurationException {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.parse(xmlFile);
    L.debug("Starting processing");
    random = null;
    final Node root = doc.getFirstChild();
    if (root.getNodeName().equals("environment") && doc.getChildNodes().getLength() == 1) {
        final NamedNodeMap atts = root.getAttributes();
        String type = atts.getNamedItem(TYPE).getNodeValue();
        type = type.contains(".") ? type : "it.unibo.alchemist.model.implementations.environments." + type;
        result = coreOperations(new ConcurrentHashMap<String, Object>(), root, type, null);
        synchronized (result) {
            final Node nameNode = atts.getNamedItem(NAME);
            final String name = nameNode == null ? "" : nameNode.getNodeValue();
            final Map<String, Object> env = new ConcurrentHashMap<String, Object>();
            env.put("ENV", result);
            if (!name.equals("")) {
                env.put(name, result);
            }
            final NodeList children = root.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                final Node son = children.item(i);
                final String kind = son.getNodeName();
                L.debug(kind);
                if (!kind.equals(TEXT)) {
                    final Node sonNameAttr = son.getAttributes().getNamedItem(NAME);
                    final String sonName = sonNameAttr == null ? "" : sonNameAttr.getNodeValue();
                    Object sonInstance = null;
                    if (kind.equals("molecule")) {
                        sonInstance = buildMolecule(son, env);
                    } else if (kind.equals("concentration")) {
                        if (concentrationClass == null) {
                            setConcentration(son);
                        }
                    } else if (kind.equals("position")) {
                        if (positionClass == null) {
                            setPosition(son);
                        }
                    } else if (kind.equals("random")) {
                        setRandom(son, env);
                    } else if (kind.equals("linkingrule")) {
                        result.setLinkingRule(buildLinkingRule(son, env));
                    } else if (kind.equals("condition")) {
                        sonInstance = buildCondition(son, env);
                    } else if (kind.equals("action")) {
                        sonInstance = buildAction(son, env);
                    } else if (kind.equals("reaction")) {
                        sonInstance = buildReaction(son, env);
                    } else if (kind.equals("node")) {
                        final it.unibo.alchemist.model.interfaces.Node<T> node = buildNode(son, env);
                        final Position pos = buildPosition(son, env);
                        sonInstance = node;
                        result.addNode(node, pos);
                    } else if (kind.equals("time")) {
                        sonInstance = buildTime(son, env);
                    }
                    if (sonInstance != null) {
                        env.put(sonName, sonInstance);
                    }
                }
            }
            /*
             * This operation forces a reset to the random generator. It
             * ensures that if the user reloads the same random seed she
             * passed in the specification, the simulation will still be
             * reproducible.
             */
            random.setSeed(seed);
        }
    } else {
        L.error("XML does not contain one and one only environment.");
    }
}

From source file:eu.apenet.dpt.standalone.gui.hgcreation.LevelTreeActions.java

public File createXML(TreeModel model, HashMap<String, String> paramMap, String countryCode,
        String globalIdentifier) {
    CLevelTreeObject obj = (CLevelTreeObject) ((DefaultMutableTreeNode) model.getRoot()).getUserObject();
    try {/*from   w  w w.  j a v a2s  .  co m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation domImplementation = builder.getDOMImplementation();
        Document doc = domImplementation.createDocument(null, null, null);

        Element root = createArchdesc(doc, model, model.getRoot(), paramMap, obj.getId(), obj.getName());

        doc.appendChild(root);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer output = tf.newTransformer();
        output.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
        output.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
        output.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        output.transform(new DOMSource(doc.getFirstChild()),
                new StreamResult(new File(Utilities.TEMP_DIR + ".hg_creation.xml")));

        File outputFile = new File(Utilities.TEMP_DIR + "temp_HG.xml");
        File finalFile = new File(
                Utilities.TEMP_DIR + "Holdings_Guide_" + globalIdentifier + "_" + obj.getId() + ".xml");
        finalFile.deleteOnExit();

        FileUtils.writeStringToFile(outputFile, HoldingsGuideCreationUtils.eadDeclaration(obj.getName(),
                obj.getId(), countryCode, globalIdentifier, DataPreparationToolGUI.VERSION_NB), "UTF-8");
        fileUtil.writeToFile(fileUtil.readFileAsString_linebreak(Utilities.TEMP_DIR + ".hg_creation.xml"),
                Utilities.TEMP_DIR + outputFile.getName(), true);
        fileUtil.writeToFile(HoldingsGuideCreationUtils.endDeclaration(),
                Utilities.TEMP_DIR + outputFile.getName(), true);

        TransformationTool.createTransformation(fileUtil.readFileAsInputStream(outputFile), finalFile,
                Utilities.BEFORE_XSL_FILE, null, true, true, null, true, null);
        outputFile.delete();

        return finalFile;
    } catch (Exception e) {
        LOG.error("Error", e);
    }
    return null;
}

From source file:com.l2jfree.gameserver.instancemanager.MapRegionManager.java

private void parseDocument(Document doc) throws Exception {
    final Map<Integer, L2MapRegionRestart> restarts = new FastMap<Integer, L2MapRegionRestart>();

    final List<L2MapRegion> specialMapRegions = new ArrayList<L2MapRegion>();
    final List<L2MapArea> mapAreas = new ArrayList<L2MapArea>();

    final Set<Integer> restartAreas = new HashSet<Integer>();

    for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("mapregion".equalsIgnoreCase(n.getNodeName())) {
            for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                if ("regions".equalsIgnoreCase(d.getNodeName())) {
                    for (Node f = d.getFirstChild(); f != null; f = f.getNextSibling()) {
                        if ("region".equalsIgnoreCase(f.getNodeName())) {
                            specialMapRegions.add(new L2SpecialMapRegion(f));
                        }// w  w  w. jav a  2 s.  c  om
                    }
                } else if ("restartpoints".equalsIgnoreCase(d.getNodeName())) {
                    for (Node f = d.getFirstChild(); f != null; f = f.getNextSibling()) {
                        if ("restartpoint".equalsIgnoreCase(f.getNodeName())) {
                            L2MapRegionRestart restart = new L2MapRegionRestart(f);

                            if (!restarts.containsKey(restart.getRestartId()))
                                restarts.put(restart.getRestartId(), restart);
                            else
                                throw new Exception(
                                        "Duplicate restartpointId: " + restart.getRestartId() + ".");
                        }
                    }
                } else if ("restartareas".equalsIgnoreCase(d.getNodeName())) {
                    for (Node f = d.getFirstChild(); f != null; f = f.getNextSibling()) {
                        if ("restartarea".equalsIgnoreCase(f.getNodeName())) {
                            final int restartId = Integer
                                    .parseInt(f.getAttributes().getNamedItem("restartId").getNodeValue());

                            restartAreas.add(restartId);

                            for (Node r = f.getFirstChild(); r != null; r = r.getNextSibling()) {
                                if ("map".equalsIgnoreCase(r.getNodeName())) {
                                    int X = Integer
                                            .parseInt(r.getAttributes().getNamedItem("X").getNodeValue());
                                    int Y = Integer
                                            .parseInt(r.getAttributes().getNamedItem("Y").getNodeValue());

                                    mapAreas.add(new L2MapArea(restartId, X, Y));
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    final L2WorldRegion[][] worldRegions = L2World.getInstance().getAllWorldRegions();

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

                if (mapregion.intersectsRectangle(ax, bx, ay, by))
                    worldRegions[x][y].addMapRegion(mapregion);
            }
        }
    }

    _mapRegionRestart.clear(false);

    for (Map.Entry<Integer, L2MapRegionRestart> entry : restarts.entrySet())
        _mapRegionRestart.set(entry.getKey(), entry.getValue());

    int redirectCount = 0;

    for (L2MapRegionRestart restart : _mapRegionRestart) {
        if (restart.getBannedRace() != null)
            redirectCount++;
    }

    _log.info("MapRegionManager: Loaded " + _mapRegionRestart.size() + " restartpoint(s).");
    _log.info("MapRegionManager: Loaded " + restartAreas.size() + " restartareas with " + mapAreas.size()
            + " arearegion(s).");
    _log.info("MapRegionManager: Loaded " + specialMapRegions.size() + " zoneregion(s).");
    _log.info("MapRegionManager: Loaded " + redirectCount + " race depending redirects.");
}

From source file:playground.jbischoff.carsharing.data.VBBRouteCatcher.java

private void run(Coord from, Coord to, long departureTime) {

    Locale locale = new Locale("en", "UK");
    String pattern = "###.000000";

    DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(locale);
    df.applyPattern(pattern);/*  ww w  .j av  a2 s .c om*/

    // Construct data
    //X&Y coordinates must be exactly 8 digits, otherwise no proper result is given. They are swapped (x = long, y = lat)

    //Verbindungen 1-n bekommen; Laufweg, Reisezeit & Umstiege ermitteln
    String text = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"
            + "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"
            + "<ReqC accessId=\"JBischoff2486b558356fa9b81b1rzum\" ver=\"1.1\" requestId=\"7\" prod=\"SPA\" lang=\"DE\">"
            + "<ConReq>" + "<ReqT date=\"" + VBBDAY.format(departureTime) + "\" time=\""
            + VBBTIME.format(departureTime) + "\">" + "</ReqT>" + "<RFlags b=\"0\" f=\"1\" >" + "</RFlags>"
            + "<Start>" + "<Coord name=\"START\" x=\"" + df.format(from.getY()).replace(".", "") + "\" y=\""
            + df.format(from.getX()).replace(".", "") + "\" type=\"WGS84\"/>"
            + "<Prod  prod=\"1111000000000000\" direct=\"0\" sleeper=\"0\" couchette=\"0\" bike=\"0\"/>"
            + "</Start>" + "<Dest>" + "<Coord name=\"ZIEL\" x=\"" + df.format(to.getY()).replace(".", "")
            + "\" y=\"" + df.format(to.getX()).replace(".", "") + "\" type=\"WGS84\"/>" + "</Dest>"
            + "</ConReq>" + "</ReqC>";
    PostMethod post = new PostMethod("http://demo.hafas.de/bin/pub/vbb/extxml.exe/");
    post.setRequestBody(text);
    post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
    HttpClient httpclient = new HttpClient();
    try {

        int result = httpclient.executeMethod(post);

        // Display status code
        //                     System.out.println("Response status code: " + result);

        // Display response
        //                     System.out.println("Response body: ");
        //                     System.out.println(post.getResponseBodyAsString());

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(post.getResponseBodyAsStream());

        if (writeOutput) {
            BufferedWriter writer = IOUtils.getBufferedWriter(filename);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            //initialize StreamResult with File object to save to file
            StreamResult res = new StreamResult(writer);
            DOMSource source = new DOMSource(document);
            transformer.transform(source, res);
            writer.flush();
            writer.close();

        }

        Node connectionList = document.getFirstChild().getFirstChild().getFirstChild();
        NodeList connections = connectionList.getChildNodes();
        int amount = connections.getLength();
        for (int i = 0; i < amount; i++) {
            Node connection = connections.item(i);
            Node overview = connection.getFirstChild();
            ;

            while (!overview.getNodeName().equals("Overview")) {
                overview = overview.getNextSibling();
            }

            System.out.println(overview.getChildNodes().item(3).getTextContent());
            int transfers = Integer.parseInt(overview.getChildNodes().item(3).getTextContent());
            String time = overview.getChildNodes().item(4).getFirstChild().getTextContent().substring(3);
            System.out.println(time);
            Date rideTime = VBBDATE.parse(time);
            int seconds = rideTime.getHours() * 3600 + rideTime.getMinutes() * 60 + rideTime.getSeconds();
            System.out.println(seconds + "s; transfers: " + transfers);
            if (seconds < this.bestRideTime) {
                this.bestRideTime = seconds;
                this.bestTransfers = transfers;
            }
        }
    } catch (Exception e) {
        this.bestRideTime = -1;
        this.bestTransfers = -1;
    }

    finally {
        // Release current connection to the connection pool 
        // once you are done
        post.releaseConnection();
        post.abort();

    }

}

From source file:com.l2jfree.gameserver.instancemanager.DimensionalRiftManager.java

public void load() {
    int countGood = 0, countBad = 0;
    try {//from  www.  j av a2s .  c  o m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setIgnoringComments(true);

        File file = new File(Config.DATAPACK_ROOT, "data/dimensionalRift.xml");
        if (!file.exists())
            throw new IOException();

        Document doc = factory.newDocumentBuilder().parse(file);
        NamedNodeMap attrs;
        byte type, roomId;
        int mobId, x, y, z, delay, count;
        L2Spawn spawnDat;
        L2NpcTemplate template;
        int xMin = 0, xMax = 0, yMin = 0, yMax = 0, zMin = 0, zMax = 0, xT = 0, yT = 0, zT = 0;
        boolean isBossRoom;

        for (Node rift = doc.getFirstChild(); rift != null; rift = rift.getNextSibling()) {
            if ("rift".equalsIgnoreCase(rift.getNodeName())) {
                for (Node area = rift.getFirstChild(); area != null; area = area.getNextSibling()) {
                    if ("area".equalsIgnoreCase(area.getNodeName())) {
                        attrs = area.getAttributes();
                        type = Byte.parseByte(attrs.getNamedItem("type").getNodeValue());

                        for (Node room = area.getFirstChild(); room != null; room = room.getNextSibling()) {
                            if ("room".equalsIgnoreCase(room.getNodeName())) {
                                attrs = room.getAttributes();
                                roomId = Byte.parseByte(attrs.getNamedItem("id").getNodeValue());
                                Node boss = attrs.getNamedItem("isBossRoom");
                                isBossRoom = boss != null && Boolean.parseBoolean(boss.getNodeValue());

                                for (Node coord = room.getFirstChild(); coord != null; coord = coord
                                        .getNextSibling()) {
                                    if ("teleport".equalsIgnoreCase(coord.getNodeName())) {
                                        attrs = coord.getAttributes();
                                        xT = Integer.parseInt(attrs.getNamedItem("x").getNodeValue());
                                        yT = Integer.parseInt(attrs.getNamedItem("y").getNodeValue());
                                        zT = Integer.parseInt(attrs.getNamedItem("z").getNodeValue());
                                    } else if ("zone".equalsIgnoreCase(coord.getNodeName())) {
                                        attrs = coord.getAttributes();
                                        xMin = Integer.parseInt(attrs.getNamedItem("xMin").getNodeValue());
                                        xMax = Integer.parseInt(attrs.getNamedItem("xMax").getNodeValue());
                                        yMin = Integer.parseInt(attrs.getNamedItem("yMin").getNodeValue());
                                        yMax = Integer.parseInt(attrs.getNamedItem("yMax").getNodeValue());
                                        zMin = Integer.parseInt(attrs.getNamedItem("zMin").getNodeValue());
                                        zMax = Integer.parseInt(attrs.getNamedItem("zMax").getNodeValue());
                                    }
                                }

                                if (!_rooms.containsKey(type))
                                    _rooms.put(type, new FastMap<Byte, DimensionalRiftRoom>());

                                _rooms.get(type).put(roomId, new DimensionalRiftRoom(type, roomId, xMin, xMax,
                                        yMin, yMax, zMin, zMax, xT, yT, zT, isBossRoom));

                                for (Node spawn = room.getFirstChild(); spawn != null; spawn = spawn
                                        .getNextSibling()) {
                                    if ("spawn".equalsIgnoreCase(spawn.getNodeName())) {
                                        attrs = spawn.getAttributes();
                                        mobId = Integer.parseInt(attrs.getNamedItem("mobId").getNodeValue());
                                        delay = Integer.parseInt(attrs.getNamedItem("delay").getNodeValue());
                                        count = Integer.parseInt(attrs.getNamedItem("count").getNodeValue());

                                        template = NpcTable.getInstance().getTemplate(mobId);
                                        if (template == null) {
                                            _log.warn("Template " + mobId + " not found!");
                                        }
                                        if (!_rooms.containsKey(type)) {
                                            _log.warn("Type " + type + " not found!");
                                        } else if (!_rooms.get(type).containsKey(roomId)) {
                                            _log.warn("Room " + roomId + " in Type " + type + " not found!");
                                        }

                                        for (int i = 0; i < count; i++) {
                                            DimensionalRiftRoom riftRoom = _rooms.get(type).get(roomId);
                                            x = riftRoom.getRandomX();
                                            y = riftRoom.getRandomY();
                                            z = riftRoom.getTeleportCoords()[2];

                                            if (template != null && _rooms.containsKey(type)
                                                    && _rooms.get(type).containsKey(roomId)) {
                                                spawnDat = new L2Spawn(template);
                                                spawnDat.setAmount(1);
                                                spawnDat.setLocx(x);
                                                spawnDat.setLocy(y);
                                                spawnDat.setLocz(z);
                                                spawnDat.setHeading(-1);
                                                spawnDat.setRespawnDelay(delay);
                                                SpawnTable.getInstance().addNewSpawn(spawnDat, false);
                                                _rooms.get(type).get(roomId).getSpawns().add(spawnDat);
                                                countGood++;
                                            } else {
                                                countBad++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        _log.warn("Error on loading dimensional rift spawns: ", e);
    }
    int typeSize = _rooms.keySet().size();
    int roomSize = 0;

    for (Byte b : _rooms.keySet())
        roomSize += _rooms.get(b).keySet().size();

    _log.info("DimensionalRiftManager: Loaded " + typeSize + " room types with " + roomSize + " rooms.");
    _log.info("DimensionalRiftManager: Loaded " + countGood + " dimensional rift spawns, " + countBad
            + " errors.");
}

From source file:com.marklogic.client.functionaltest.TestBulkSearchWithStrucQueryDef.java

@Test
public void testExtractDocumentData3() throws Exception {
    String head = "<search:search xmlns:search=\"http://marklogic.com/appservices/search\">";
    String tail = "</search:search>";
    String qtext4 = "<search:qtext>71 OR dog14</search:qtext>";
    DocumentManager docMgr = client.newDocumentManager();
    QueryManager queryMgr = client.newQueryManager();
    String options = "<search:options>" + "<search:extract-document-data selected=\"include-with-ancestors\">"
            + "<search:extract-path>//foo</search:extract-path>"
            + "<search:extract-path>//says</search:extract-path>" + "</search:extract-document-data>"
            + "</search:options>";
    // test XML response with extracted XML and JSON matches
    String combinedSearch = head + qtext4 + options + tail;
    RawCombinedQueryDefinition rawCombinedQueryDefinition = queryMgr
            .newRawCombinedQueryDefinition(new StringHandle(combinedSearch).withMimetype("application/xml"));
    SearchHandle results = queryMgr.search(rawCombinedQueryDefinition, new SearchHandle());
    MatchDocumentSummary[] summaries = results.getMatchResults();
    assertNotNull(summaries);//from   ww w. j  a  v a  2s  .  co  m
    assertEquals(2, summaries.length);
    for (MatchDocumentSummary summary : summaries) {
        ExtractedResult extracted = summary.getExtracted();
        if (Format.XML == summary.getFormat()) {
            // we don't test for kind because it isn't sent in this case
            assertEquals(1, extracted.size());
            Document item1 = extracted.next().getAs(Document.class);
            assertEquals("This is so foo with a bar 71", item1.getFirstChild().getTextContent());
            continue;
        } else if (Format.JSON == summary.getFormat()) {
            // we don't test for kind because it isn't sent in this case
            assertEquals(1, extracted.size());
            for (ExtractedItem item : extracted) {
                String stringJsonItem = item.getAs(String.class);
                JsonNode nodeJsonItem = item.getAs(JsonNode.class);
                if (nodeJsonItem.has("says")) {
                    assertEquals("{\"says\":\"woof\"}", stringJsonItem);
                    continue;
                }
                fail("unexpected extracted item:" + stringJsonItem);
            }
            continue;
        }
        fail("unexpected search result:" + summary.getUri());
    }
}