Example usage for javax.xml.parsers DocumentBuilderFactory setValidating

List of usage examples for javax.xml.parsers DocumentBuilderFactory setValidating

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setValidating.

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

From source file:de.interactive_instruments.ShapeChange.Target.Metadata.ApplicationSchemaMetadata.java

@Override
public void initialise(PackageInfo p, Model m, Options o, ShapeChangeResult r, boolean diagOnly)
        throws ShapeChangeAbortException {

    schemaPi = p;/*from   w  w  w  . j  av a  2  s.  c  om*/
    schemaTargetNamespace = p.targetNamespace();

    model = m;
    options = o;
    result = r;
    diagnosticsOnly = diagOnly;

    result.addDebug(this, 1, schemaPi.name());

    if (!initialised) {
        initialised = true;

        outputDirectory = options.parameter(this.getClass().getName(), "outputDirectory");
        if (outputDirectory == null)
            outputDirectory = options.parameter("outputDirectory");
        if (outputDirectory == null)
            outputDirectory = options.parameter(".");

        outputFilename = "schema_metadata.xml";

        // Check if we can use the output directory; create it if it
        // does not exist
        outputDirectoryFile = new File(outputDirectory);
        boolean exi = outputDirectoryFile.exists();
        if (!exi) {
            try {
                FileUtils.forceMkdir(outputDirectoryFile);
            } catch (IOException e) {
                result.addError(null, 600, e.getMessage());
                e.printStackTrace(System.err);
            }
            exi = outputDirectoryFile.exists();
        }
        boolean dir = outputDirectoryFile.isDirectory();
        boolean wrt = outputDirectoryFile.canWrite();
        boolean rea = outputDirectoryFile.canRead();
        if (!exi || !dir || !wrt || !rea) {
            result.addFatalError(null, 601, outputDirectory);
            throw new ShapeChangeAbortException();
        }

        File outputFile = new File(outputDirectoryFile, outputFilename);

        // check if output file already exists - if so, attempt to delete it
        exi = outputFile.exists();
        if (exi) {

            result.addInfo(this, 3, outputFilename, outputDirectory);

            try {
                FileUtils.forceDelete(outputFile);
                result.addInfo(this, 4);
            } catch (IOException e) {
                result.addInfo(null, 600, e.getMessage());
                e.printStackTrace(System.err);
            }
        }

        // identify map entries defined in the target configuration
        List<ProcessMapEntry> mapEntries = options.getCurrentProcessConfig().getMapEntries();

        if (mapEntries != null) {

            for (ProcessMapEntry pme : mapEntries) {
                mapEntryByType.put(pme.getType(), pme);
            }
        }

        // reset processed flags on all classes in the schema
        for (Iterator<ClassInfo> k = model.classes(schemaPi).iterator(); k.hasNext();) {
            ClassInfo ci = k.next();
            ci.processed(getTargetID(), false);
        }

        // ======================================
        // Parse configuration parameters
        // ======================================

        // nothing to do at present

        // ======================================
        // Set up the document and create root
        // ======================================

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        dbf.setAttribute(Options.JAXP_SCHEMA_LANGUAGE, Options.W3C_XML_SCHEMA);
        DocumentBuilder db;
        try {
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            result.addFatalError(null, 2);
            throw new ShapeChangeAbortException();
        }
        document = db.newDocument();

        root = document.createElementNS(NS, "ApplicationSchemaMetadata");
        document.appendChild(root);

        addAttribute(root, "xmlns", NS);

        hook = document.createComment("Created by ShapeChange - http://shapechange.net/");
        root.appendChild(hook);
    }

    // create elements documenting the application schema
    Element e_name = document.createElement("name");
    e_name.setTextContent(schemaPi.name());
    Element e_tns = document.createElement("targetNamespace");
    e_tns.setTextContent(schemaPi.targetNamespace());

    Element e_as = document.createElement("ApplicationSchema");
    e_as.appendChild(e_name);
    e_as.appendChild(e_tns);

    Element e_schema = document.createElement("schema");
    e_schema.appendChild(e_as);

    root.appendChild(e_schema);

    /*
     * Now compute relevant metadata.
     */
    processMetadata(e_as);
}

From source file:com.firegnom.valkyrie.map.tiled.TiledZoneLoader.java

@Override
public Zone load(String name) {
    long startTime, stopTime;
    try {/*from   w  ww . j av a  2s. c  o m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                return new InputSource(new ByteArrayInputStream(new byte[0]));
            }
        });
        startTime = System.currentTimeMillis();

        // map version
        JSONObject obj;
        int version = 0;
        try {
            obj = new JSONObject(convertStreamToString(rl.getResourceAsStreamDownload(name + ".json")));
            version = obj.getInt("version");
        } catch (JSONException e) {
            throw new ValkyrieRuntimeException(e);
        }

        InputStream inputStream = new GZIPInputStream(
                rl.getResourceAsStream(name + "-ver_" + version + ".tmx.gz", true));

        Document doc = builder.parse(inputStream);
        Element docElement = doc.getDocumentElement();
        stopTime = System.currentTimeMillis();
        Log.d(TAG, "Loaded Zone tmx file in  in :" + ((stopTime - startTime) / 1000) + " secondsand "
                + ((stopTime - startTime) % 1000) + " miliseconds");
        System.gc();
        String orient = docElement.getAttribute("orientation");
        if (!orient.equals("orthogonal")) {
            throw new TiledLoaderException("Only orthogonal maps supported, found: " + orient);
        }

        int width = Integer.parseInt(docElement.getAttribute("width"));
        int height = Integer.parseInt(docElement.getAttribute("height"));
        int tileWidth = Integer.parseInt(docElement.getAttribute("tilewidth"));
        int tileHeight = Integer.parseInt(docElement.getAttribute("tileheight"));

        Zone zone = new Zone(name, width, height, tileWidth, tileHeight);
        // now read the map properties
        startTime = System.currentTimeMillis();
        getZoneProperties(zone, docElement);
        stopTime = System.currentTimeMillis();
        Log.d(TAG, "Loaded Zone Properties  in  in :" + ((stopTime - startTime) / 1000) + " secondsand "
                + ((stopTime - startTime) % 1000) + " miliseconds");
        System.gc();
        startTime = System.currentTimeMillis();

        StringTileSet tileSet = null;
        NodeList setNodes = docElement.getElementsByTagName("tileset");
        int i;
        for (i = 0; i < setNodes.getLength(); i++) {
            Element current = (Element) setNodes.item(i);

            tileSet = getTileSet(zone, current, c);
            tileSet.index = i;
            Log.d(TAG, "Adding tileset to zone tilestets firstGID =" + tileSet.firstGID + ",lastGID="
                    + tileSet.lastGID + ", name=" + tileSet.imageName);
            zone.tileSets.add(tileSet.firstGID, tileSet.lastGID, tileSet);
        }
        stopTime = System.currentTimeMillis();
        Log.d("performance", "Loaded Zone tilesets in  in :" + ((stopTime - startTime) / 1000) + " secondsand "
                + ((stopTime - startTime) % 1000) + " miliseconds");
        System.gc();
        startTime = System.currentTimeMillis();
        NodeList layerNodes = docElement.getElementsByTagName("layer");
        Element current;
        for (i = 0; i < layerNodes.getLength(); i++) {
            current = (Element) layerNodes.item(i);
            Layer layer = getLayer(zone, current);
            layer.index = i;
            zone.layers.add(layer);

        }

        stopTime = System.currentTimeMillis();
        Log.d(TAG, "Loaded Zone Layers in  in :" + ((stopTime - startTime) / 1000) + " secondsand "
                + ((stopTime - startTime) % 1000) + " miliseconds");
        NodeList objectGroupNodes = docElement.getElementsByTagName("objectgroup");
        for (i = 0; i < objectGroupNodes.getLength(); i++) {
            current = (Element) objectGroupNodes.item(i);
            if (current.getAttribute("name").equals("_ContextActions")) {
                zone.contextActions = getActionIndex(current);
            } else {
                appendMapObjects(current, zone.mapObjects);
            }
        }
        System.gc();
        return zone;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

From source file:org.openmeetings.app.sip.xmlrpc.OpenXGHttpClient.java

/**
 * /*from ww w  . j av a  2s  .co m*/
 * @param inputStream
 * @return
 */
public OpenXGReturnObject parseOpenXGReturnBody(InputStream inputStream) {
    try {

        OpenXGReturnObject openXGReturnObject = new OpenXGReturnObject();

        // log.debug("parseReturnBody "+inputStream);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(false);

        // get a builder to create a DOM document
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document document = builder.parse(inputStream);

        NodeList members = document.getElementsByTagName("member");

        // log.debug("members LENGTH "+members.getLength());

        for (int i = 0; i < members.getLength(); i++) {
            Element member = (Element) members.item(i);

            NodeList name = member.getElementsByTagName("name");

            // log.debug("Name "+name.item(0).getNodeName());

            Node nameTextNode = name.item(0).getFirstChild();

            log.debug("getNodeValue " + nameTextNode.getNodeValue());

            if (nameTextNode.getNodeValue().equals("status_code")) {

                NodeList string = member.getElementsByTagName("string");

                // log.debug("Value "+string.item(0).getNodeName());

                Node valueTextNode = string.item(0).getFirstChild();

                // log.debug("Value "+valueTextNode.getNodeValue());

                openXGReturnObject.setStatus_code(valueTextNode.getNodeValue());

            } else if (nameTextNode.getNodeValue().equals("status_string")) {

                NodeList string = member.getElementsByTagName("string");

                // log.debug("Value "+string.item(0).getNodeName());

                Node valueTextNode = string.item(0).getFirstChild();

                // log.debug("Value "+valueTextNode.getNodeValue());

                openXGReturnObject.setStatus_string(valueTextNode.getNodeValue());

            } else if (nameTextNode.getNodeValue().equals("conference_number")) {

                NodeList string = member.getElementsByTagName("string");

                // log.debug("Value "+string.item(0).getNodeName());

                Node valueTextNode = string.item(0).getFirstChild();

                // log.debug("Value "+valueTextNode.getNodeValue());

                openXGReturnObject.setConferenceNumber(valueTextNode.getNodeValue());

            } else if (nameTextNode.getNodeValue().equals("conference_pin")) {

                NodeList string = member.getElementsByTagName("string");

                // log.debug("Value "+string.item(0).getNodeName());

                Node valueTextNode = string.item(0).getFirstChild();

                // log.debug("Value "+valueTextNode.getNodeValue());

                openXGReturnObject.setConferencePin(valueTextNode.getNodeValue());

            }

        }

        return openXGReturnObject;

    } catch (Exception err) {

        log.error("[parseOpenXGReturnBody]", err);

    }
    return null;
}

From source file:org.openmrs.web.controller.report.CohortReportFormController.java

/**
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */// w ww. jav  a  2 s. c o  m
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object commandObj,
        BindException errors) throws Exception {
    CommandObject command = (CommandObject) commandObj;

    // do simpleframework serialization of everything but 'rows', and add those via handcoded xml, since
    // serializing them is not reversible

    ReportSchema rs = new ReportSchema();
    rs.setReportSchemaId(command.getReportId());
    rs.setName(command.getName());
    rs.setDescription(command.getDescription());
    rs.setReportParameters(command.getParameters());
    rs.setDataSetDefinitions(new ArrayList<DataSetDefinition>());
    Serializer serializer = OpenmrsUtil.getSerializer();
    StringWriter sw = new StringWriter();
    serializer.write(rs, sw);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document xml = db.parse(new InputSource(
            new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + sw.toString())));
    Node node = findChild(xml, "reportSchema");
    node = findChild(node, "dataSets");
    Element dsd = xml.createElement("dataSetDefinition");
    dsd.setAttribute("name", "cohorts");
    dsd.setAttribute("class", "org.openmrs.report.CohortDataSetDefinition");
    node.appendChild(dsd);
    Element strategies = xml.createElement("strategies");
    strategies.setAttribute("class", "java.util.LinkedHashMap");
    dsd.appendChild(strategies);
    Element descriptions = xml.createElement("descriptions");
    descriptions.setAttribute("class", "java.util.LinkedHashMap");
    dsd.appendChild(descriptions);
    for (CohortReportRow row : command.getRows()) {
        if (StringUtils.hasText(row.getQuery())) {
            Element entry = xml.createElement("entry");
            strategies.appendChild(entry);
            Element nameEl = xml.createElement("string");
            Text val = xml.createTextNode(row.getName());
            val.setNodeValue(row.getName());
            nameEl.appendChild(val);
            entry.appendChild(nameEl);
            Element cohort = xml.createElement("cohort");
            entry.appendChild(cohort);
            cohort.setAttribute("class", "org.openmrs.reporting.PatientSearch");
            Element strategyEl = xml.createElement("specification");
            val = xml.createTextNode(row.getQuery());
            val.setNodeValue(row.getQuery());
            strategyEl.appendChild(val);
            cohort.appendChild(strategyEl);
        }
        if (StringUtils.hasText(row.getDescription())) {
            Element entry = xml.createElement("entry");
            descriptions.appendChild(entry);
            Element el = xml.createElement("string");
            Text val = xml.createTextNode(row.getName());
            val.setNodeValue(row.getName());
            el.appendChild(val);
            entry.appendChild(el);
            el = xml.createElement("string");
            val = xml.createTextNode(row.getDescription());
            val.setNodeValue(row.getDescription());
            el.appendChild(val);
            entry.appendChild(el);
        }
    }

    // now turn this into an xml string
    System.setProperty("javax.xml.transform.TransformerFactory",
            "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.METHOD, "xml");
    StringWriter out = new StringWriter();
    StreamResult result = new StreamResult(out);
    DOMSource source = new DOMSource(xml);
    trans.transform(source, result);
    String schemaXml = out.toString();

    ReportSchemaXml rsx = new ReportSchemaXml();
    rsx.populateFromReportSchema(rs);
    rsx.setXml(schemaXml);
    rsx.updateXmlFromAttributes();
    rsx.setUuid(request.getParameter("parentUUID"));

    ReportService rptSvc = (ReportService) Context.getService(ReportService.class);
    if (rsx.getReportSchemaId() != null) {
        rptSvc.saveReportSchemaXml(rsx);
    } else {
        rptSvc.saveReportSchemaXml(rsx);
    }

    return new ModelAndView(new RedirectView(getSuccessView() + "?reportId=" + rsx.getReportSchemaId()));
}

From source file:it.greenvulcano.gvesb.api.controller.GvConfigurationControllerRest.java

public GvConfigurationControllerRest() throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setValidating(true);
    documentBuilderFactory.setFeature("http://xml.org/sax/features/namespaces", false);
    documentBuilderFactory.setFeature("http://xml.org/sax/features/validation", false);
    documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    documentBuilder = documentBuilderFactory.newDocumentBuilder();
}

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

private void parse() {
    for (File f : Util.getDatapackFiles("multisell", ".xml")) {
        try {/* w ww  .j  a v  a  2 s . co  m*/
            int id = Integer.parseInt(f.getName().replaceAll(".xml", ""));
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);
            Document doc = factory.newDocumentBuilder().parse(f);

            MultiSellListContainer list = parseDocument(doc);
            list.setListId(id);
            _entries.put(id, list);
        } catch (Exception e) {
            _log.fatal("Error in file " + f.getAbsolutePath(), e);
        }
    }
}

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

/**
 * Method load./*  w  ww . j a v a  2s.  c  om*/
 */
private void load() {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        File file = new File(Config.DATAPACK_ROOT, "data/xml/other/cursed_weapons.xml");
        if (!file.exists()) {
            return;
        }
        Document doc = factory.newDocumentBuilder().parse(file);
        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 ("item".equalsIgnoreCase(d.getNodeName())) {
                        NamedNodeMap attrs = d.getAttributes();
                        int id = Integer.parseInt(attrs.getNamedItem("id").getNodeValue());
                        int skillId = Integer.parseInt(attrs.getNamedItem("skillId").getNodeValue());
                        String name = "Unknown cursed weapon";
                        if (attrs.getNamedItem("name") != null) {
                            name = attrs.getNamedItem("name").getNodeValue();
                        } else if (ItemHolder.getInstance().getTemplate(id) != null) {
                            name = ItemHolder.getInstance().getTemplate(id).getName();
                        }
                        if (id == 0) {
                            continue;
                        }
                        CursedWeapon cw = new CursedWeapon(id, skillId, name);
                        for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) {
                            if ("dropRate".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setDropRate(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("duration".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                cw.setDurationMin(Integer.parseInt(attrs.getNamedItem("min").getNodeValue()));
                                cw.setDurationMax(Integer.parseInt(attrs.getNamedItem("max").getNodeValue()));
                            } else if ("durationLost".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setDurationLost(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("disapearChance".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setDisapearChance(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("stageKills".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setStageKills(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("transformationId".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setTransformationId(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("transformationTemplateId".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setTransformationTemplateId(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("transformationName".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setTransformationName(cd.getAttributes().getNamedItem("val").getNodeValue());
                            }
                        }
                        _cursedWeaponsMap.put(id, cw);
                    }
                }
            }
        }
        _cursedWeapons = _cursedWeaponsMap.values(new CursedWeapon[_cursedWeaponsMap.size()]);
    } catch (Exception e) {
        _log.error("CursedWeaponsManager: Error parsing cursed_weapons file. " + e);
    }
}

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

/**
 * Method getHellboundSpawn.//from   ww  w  .j  a  v a2s.  co 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.panet.imeta.job.entries.dtdvalidator.JobEntryDTDValidator.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);/*  w  w w  .  j  a v a  2s  . c  o m*/

    String realxmlfilename = getRealxmlfilename();
    String realDTDfilename = getRealDTDfilename();

    FileObject xmlfile = null;
    FileObject DTDfile = null;

    try

    {

        if (xmlfilename != null && ((dtdfilename != null && !dtdintern) || (dtdintern))) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename);

            if (xmlfile.exists())

            {

                //URL xmlFile = new URL (KettleVFS.getFilename(xmlfile));
                URL xmlFile = new File(KettleVFS.getFilename(xmlfile)).toURI().toURL();

                // open XML File
                BufferedReader xmlBufferedReader = new BufferedReader(
                        new InputStreamReader(xmlFile.openStream()));
                StringBuffer xmlStringbuffer = new StringBuffer("");

                char[] buffertXML = new char[1024];
                int LenXML = -1;
                while ((LenXML = xmlBufferedReader.read(buffertXML)) != -1)
                    xmlStringbuffer.append(buffertXML, 0, LenXML);

                // Prepare parsing ...
                DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance();
                Document xmlDocDTD = null;
                DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder();

                // Let's try to get XML document encoding
                DocBuilderFactory.setValidating(false);
                xmlDocDTD = DocBuilder
                        .parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes("UTF-8")));

                String encoding = null;
                if (xmlDocDTD.getXmlEncoding() == null) {
                    encoding = "UTF-8";
                } else {
                    encoding = xmlDocDTD.getXmlEncoding();
                }

                int xmlStartDTD = xmlStringbuffer.indexOf("<!DOCTYPE");

                if (dtdintern) {
                    // DTD find in the XML document
                    if (xmlStartDTD != -1) {
                        if (log.isBasic())
                            log.logBasic(toString(), Messages
                                    .getString("JobEntryDTDValidator.ERRORDTDFound.Label", realxmlfilename));
                    } else {
                        if (log.isBasic())
                            log.logBasic(toString(), Messages
                                    .getString("JobEntryDTDValidator.ERRORDTDNotFound.Label", realxmlfilename));
                    }

                } else {
                    // DTD in external document
                    // If we find an intern declaration, we remove it
                    DTDfile = KettleVFS.getFileObject(realDTDfilename);

                    if (DTDfile.exists()) {
                        if (xmlStartDTD != -1) {
                            int EndDTD = xmlStringbuffer.indexOf(">", xmlStartDTD);
                            //String DocTypeDTD = xmlStringbuffer.substring(xmlStartDTD, EndDTD + 1);
                            xmlStringbuffer.replace(xmlStartDTD, EndDTD + 1, "");

                        }

                        String xmlRootnodeDTD = xmlDocDTD.getDocumentElement().getNodeName();

                        String RefDTD = "<?xml version='" + xmlDocDTD.getXmlVersion() + "' encoding='"
                                + encoding + "'?>\n<!DOCTYPE " + xmlRootnodeDTD + " SYSTEM '"
                                + KettleVFS.getFilename(DTDfile) + "'>\n";

                        int xmloffsetDTD = xmlStringbuffer.indexOf("<" + xmlRootnodeDTD);
                        xmlStringbuffer.replace(0, xmloffsetDTD, RefDTD);
                    } else {
                        log.logError(Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Subject"),
                                Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Msg",
                                        realDTDfilename));
                    }
                }

                if ((dtdintern && xmlStartDTD == -1 || (!dtdintern && !DTDfile.exists()))) {
                    result.setResult(false);
                    result.setNrErrors(1);
                } else {
                    DocBuilderFactory.setValidating(true);

                    // Let's parse now ...

                    xmlDocDTD = DocBuilder
                            .parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes(encoding)));
                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Subject"),
                                Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Label",
                                        realxmlfilename));

                    // Everything is OK
                    result.setResult(true);
                }

            } else {

                if (!xmlfile.exists()) {
                    log.logError(toString(),
                            Messages.getString("JobEntryDTDValidator.FileDoesNotExist.Label", realxmlfilename));
                }

                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            log.logError(toString(), Messages.getString("JobEntryDTDValidator.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }

    }

    catch (Exception e) {
        log.logError(Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Subject"),
                Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Label", realxmlfilename,
                        realDTDfilename, e.getMessage()));

        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null)
                xmlfile.close();

            if (DTDfile != null)
                DTDfile.close();

        } catch (IOException e) {
        }
    }

    return result;
}

From source file:de.knowwe.defi.usermanager.XMLUserDatabase.java

private void buildDOM() {
    // Read DOM//ww w .  j a  va 2 s .  co m
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    factory.setExpandEntityReferences(false);
    factory.setIgnoringComments(true);
    factory.setNamespaceAware(false);
    try {
        c_dom = factory.newDocumentBuilder().parse(c_file);
        Log.fine("Database successfully initialized");
        c_lastModified = c_file.lastModified();
        c_lastCheck = System.currentTimeMillis();
    } catch (ParserConfigurationException e) {
        Log.severe("Configuration error: " + e.getMessage());
    } catch (SAXException e) {
        Log.severe("SAX error: " + e.getMessage());
    } catch (FileNotFoundException e) {
        Log.info("User database not found; creating from scratch...");
    } catch (IOException e) {
        Log.severe("IO error: " + e.getMessage());
    }
    if (c_dom == null) {
        try {
            //
            //  Create the DOM from scratch
            //
            c_dom = factory.newDocumentBuilder().newDocument();
            c_dom.appendChild(c_dom.createElement("users"));
        } catch (ParserConfigurationException e) {
            Log.severe("Could not create in-memory DOM");
        }
    }
}