List of usage examples for javax.xml.parsers DocumentBuilderFactory setValidating
public void setValidating(boolean validating)
From source file:integration.AbstractTest.java
/** * Parses the specified file and returns the document. * //from w w w . j av a 2 s . c om * @param file The file to parse. * @param schema The schema used to validate the specified file. * @return * @throws Exception Thrown if an error occurred. */ protected Document parseFile(File file, File schema) throws Exception { if (file == null) throw new IllegalArgumentException("No file to parse."); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); if (schema != null) { dbf.setValidating(true); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); // Set the schema file dbf.setAttribute(JAXP_SCHEMA_SOURCE, schema); } DocumentBuilder builder = dbf.newDocumentBuilder(); return builder.parse(file); }
From source file:com.l2jfree.gameserver.datatables.AugmentationData.java
@SuppressWarnings("unchecked") private final void load() { // Load the skillmap // Note: the skillmap data is only used when generating new augmentations // the client expects a different id in order to display the skill in the // items description... try {/* w ww .j a va2s .c o m*/ int badAugmantData = 0; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setIgnoringComments(true); File file = new File(Config.DATAPACK_ROOT + "/data/stats/augmentation/augmentation_skillmap.xml"); if (!file.exists()) { _log.warn("The augmentation skillmap file is missing."); 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 ("augmentation".equalsIgnoreCase(d.getNodeName())) { NamedNodeMap attrs = d.getAttributes(); int skillId = 0, augmentationId = Integer.parseInt(attrs.getNamedItem("id").getNodeValue()); int skillLvL = 0; String type = "blue"; for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) { if ("skillId".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); skillId = Integer.parseInt(attrs.getNamedItem("val").getNodeValue()); } else if ("skillLevel".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); skillLvL = Integer.parseInt(attrs.getNamedItem("val").getNodeValue()); } else if ("type".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); type = attrs.getNamedItem("val").getNodeValue(); } } if (skillId == 0) { _log.warn("Bad skillId in augmentation_skillmap.xml in the augmentationId:" + augmentationId); badAugmantData++; continue; } else if (skillLvL == 0) { _log.warn("Bad skillLevel in augmentation_skillmap.xml in the augmentationId:" + augmentationId); badAugmantData++; continue; } int k = (augmentationId - BLUE_START) / SKILLS_BLOCKSIZE; if (type.equalsIgnoreCase("blue")) ((ArrayList<Integer>) _blueSkills[k]).add(augmentationId); else if (type.equalsIgnoreCase("purple")) ((ArrayList<Integer>) _purpleSkills[k]).add(augmentationId); else ((ArrayList<Integer>) _redSkills[k]).add(augmentationId); _allSkills.put(augmentationId, new augmentationSkill(skillId, skillLvL)); } } } } if (badAugmantData != 0) _log.info("AugmentationData: " + badAugmantData + " bad skill(s) were skipped."); } catch (Exception e) { _log.error("Error parsing augmentation_skillmap.xml.", e); return; } // Load the stats from xml for (int i = 1; i < 5; i++) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); File file = new File( Config.DATAPACK_ROOT + "/data/stats/augmentation/augmentation_stats" + i + ".xml"); if (!file.exists()) { _log.warn("The augmentation stat data file " + i + " is missing."); 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 ("stat".equalsIgnoreCase(d.getNodeName())) { NamedNodeMap attrs = d.getAttributes(); String statName = attrs.getNamedItem("name").getNodeValue(); float soloValues[] = null, combinedValues[] = null; for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) { if ("table".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); String tableName = attrs.getNamedItem("name").getNodeValue(); StringTokenizer data = new StringTokenizer( cd.getFirstChild().getNodeValue()); FastList<Float> array = new FastList<Float>(); while (data.hasMoreTokens()) array.add(Float.parseFloat(data.nextToken())); if (tableName.equalsIgnoreCase("#soloValues")) { soloValues = new float[array.size()]; int x = 0; for (float value : array) soloValues[x++] = value; } else { combinedValues = new float[array.size()]; int x = 0; for (float value : array) combinedValues[x++] = value; } } } // store this stat ((ArrayList<augmentationStat>) _augStats[(i - 1)]).add(new augmentationStat( Stats.valueOfXml(statName), soloValues, combinedValues)); } } } } } catch (Exception e) { _log.error("Error parsing augmentation_stats" + i + ".xml.", e); return; } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); File file = new File( Config.DATAPACK_ROOT + "/data/stats/augmentation/augmentation_jewel_stats" + i + ".xml"); if (!file.exists()) { _log.warn("The jewel augmentation stat data file " + i + " is missing."); 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 ("stat".equalsIgnoreCase(d.getNodeName())) { NamedNodeMap attrs = d.getAttributes(); String statName = attrs.getNamedItem("name").getNodeValue(); float soloValues[] = null, combinedValues[] = null; for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) { if ("table".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); String tableName = attrs.getNamedItem("name").getNodeValue(); StringTokenizer data = new StringTokenizer( cd.getFirstChild().getNodeValue()); FastList<Float> array = new FastList<Float>(); while (data.hasMoreTokens()) array.add(Float.parseFloat(data.nextToken())); if (tableName.equalsIgnoreCase("#soloValues")) { soloValues = new float[array.size()]; int x = 0; for (float value : array) soloValues[x++] = value; } else { combinedValues = new float[array.size()]; int x = 0; for (float value : array) combinedValues[x++] = value; } } } // store this stat ((ArrayList<augmentationStat>) _augAccStats[(i - 1)]).add(new augmentationStat( Stats.valueOfXml(statName), soloValues, combinedValues)); } } } } } catch (Exception e) { _log.error("Error parsing jewel augmentation_stats" + i + ".xml.", e); return; } } }
From source file:lineage2.gameserver.Config.java
/** * Method loadGMAccess.//from ww w . ja v a 2s . c o m * @param file File */ public static void loadGMAccess(File file) { try { Field fld; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); Document doc = factory.newDocumentBuilder().parse(file); for (Node z = doc.getFirstChild(); z != null; z = z.getNextSibling()) { for (Node n = z.getFirstChild(); n != null; n = n.getNextSibling()) { if (!n.getNodeName().equalsIgnoreCase("char")) { continue; } PlayerAccess pa = new PlayerAccess(); for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) { Class<?> cls = pa.getClass(); String node = d.getNodeName(); if (node.equalsIgnoreCase("#text")) { continue; } try { fld = cls.getField(node); } catch (NoSuchFieldException e) { _log.info("Not found desclarate ACCESS name: " + node + " in XML Player access Object"); continue; } if (fld.getType().getName().equalsIgnoreCase("boolean")) { fld.setBoolean(pa, Boolean.parseBoolean(d.getAttributes().getNamedItem("set").getNodeValue())); } else if (fld.getType().getName().equalsIgnoreCase("int")) { fld.setInt(pa, Integer.valueOf(d.getAttributes().getNamedItem("set").getNodeValue())); } } gmlist.put(pa.PlayerID, pa); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:ambit.data.qmrf.QMRFObject.java
protected Document buildDocument() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);//from ww w . j a v a 2 s . c om factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new SimpleErrorHandler(builder.getClass().getName())); Document doc = builder.newDocument(); Element e = toXML(doc); doc.appendChild(e); return doc; }
From source file:com.fluidops.iwb.provider.XMLProvider.java
/** * Constructs a w3c DOM from an InputStream. Depending on whether the InputStream is constructed from * an html or xml file, it will used JTidy for clean-up and constructing the document DOM. * @param in any input stream that contains (x)html/xml data * @return the DOM of an HTML or XML constructed from any InputStream * @throws SAXException/*from w ww.j av a 2 s . c o m*/ * @throws IOException * @throws ParserConfigurationException */ protected Document getDocument(InputStream in) throws SAXException, IOException, ParserConfigurationException { Tidy tidy = new Tidy(); tidy.setHideComments(true); tidy.setTidyMark(false); tidy.setQuiet(true); tidy.setShowErrors(1); tidy.setShowWarnings(false); if (StringUtil.isNotNullNorEmpty(config.inputEncoding)) { tidy.setInputEncoding(config.inputEncoding); } tidy.setOutputEncoding("UTF-8"); tidy.setMakeClean(true); Document doc = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); DocumentBuilder db = factory.newDocumentBuilder(); // we assume that xml is provided, if no file extension .htm(l) is provided if (!config.xmlfile.toLowerCase().endsWith(".htm") && !config.xmlfile.toLowerCase().endsWith("html")) { // let jtidy know that it needs to handle xml, instead of html tidy.setXmlOut(true); tidy.setXmlTags(true); // need to have another (re)rewrite of the DOM in order to gain a clean w3c.dom ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); InputStream is = null; try { doc = tidy.parseDOM(in, outputStream); is = new ByteArrayInputStream(outputStream.toByteArray()); doc = db.parse(is); } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(is); } } else { doc = tidy.parseDOM(in, null); } return doc; }
From source file:edu.washington.shibboleth.attribute.resolver.provider.dataConnector.RwsDataConnector.java
/** * Initializes the connector and prepares it for use. *///from w w w. j a va 2 s . c om public void initialize() { initialized = true; initializeConnectionManager(); try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); domFactory.setValidating(false); String feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; domFactory.setFeature(feature, false); documentBuilder = domFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("javax.xml.parsers.ParserConfigurationException: " + e); } for (int i = 0; i < rwsAttributes.size(); i++) { RwsAttribute attr = rwsAttributes.get(i); try { XPath xpath = XPathFactory.newInstance().newXPath(); log.debug("xpath for {} is {}", attr.name, attr.xPath); attr.xpathExpression = xpath.compile(attr.xPath); } catch (XPathExpressionException e) { log.error("xpath expr: " + e); } } activators = new Vector<String>(configuredActivators); refreshActivators(); registerTemplate(); initializeCache(); }
From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java
/** * Validate xml.//from w w w . j av a 2 s . c om * * @param inSchemas the in schemas * @param inXml the in xml * @param schemaLanguage the schema language * * @return the xML error handler * * @throws MotuException the motu exception */ public static XMLErrorHandler validateXML(String[] inSchemas, String inXml, String schemaLanguage) throws MotuException { XMLErrorHandler errorHandler = new XMLErrorHandler(); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!! try { documentBuilderFactory.setXIncludeAware(true); } catch (Exception e) { // Do Nothing } documentBuilderFactory.setExpandEntityReferences(true); documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_LANGUAGE, schemaLanguage); // final String[] srcSchemas = // {"http://schemas.opengis.net/iso/19139/20060504/srv/serviceMetadata.xsd", // }; // final String[] srcSchemas = // {"http://opendap.aviso.oceanobs.com/data/ISO_19139/srv/serviceMetadata.xsd", // "http://opendap.aviso.oceanobs.com/data/ISO_19139/gco/gco.xsd", }; // C:\Documents and Settings\dearith\Mes documents\Atoll\SchemaIso\gml // final String[] srcSchemas = // {"C:/Documents and Settings/us/userocuments/Atoll/SchemaIso/srv/serviceMetadata.xsd", // }; // final String[] srcSchemas = {"schema/iso/srv/serviceMetadata.xsd", // }; documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_SOURCE, inSchemas); // URL url = Organizer.findResource("schema/iso/srv/srv.xsd"); // URL url = Organizer.findResource("iso/19139/20070417/srv/serviceMetadata.xsd"); // documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", // url.toString()); documentBuilderFactory.setValidating(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); // document = documentBuilder.parse(new File(xmlUrl.toURI())); documentBuilder.setErrorHandler(errorHandler); documentBuilder.parse(inXml); } catch (Exception e) { throw new MotuException(e); // instance document is invalid! } return errorHandler; }
From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java
/** * Validate xml./*from w w w . j av a2 s. com*/ * * @param inSchemas the in schemas * @param inXml the in xml * @param schemaLanguage the schema language * * @return the xML error handler * * @throws MotuException the motu exception */ public static XMLErrorHandler validateXML(String[] inSchemas, InputStream inXml, String schemaLanguage) throws MotuException { XMLErrorHandler errorHandler = new XMLErrorHandler(); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!! try { documentBuilderFactory.setXIncludeAware(true); } catch (Exception e) { // Do Nothing } // documentBuilderFactory.setExpandEntityReferences(true); documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_LANGUAGE, schemaLanguage); // final String[] srcSchemas = // {"http://schemas.opengis.net/iso/19139/20060504/srv/serviceMetadata.xsd", // }; // final String[] srcSchemas = // {"http://opendap.aviso.oceanobs.com/data/ISO_19139/srv/serviceMetadata.xsd", // "http://opendap.aviso.oceanobs.com/data/ISO_19139/gco/gco.xsd", }; // C:\Documents and Settings\dearith\Mes documents\Atoll\SchemaIso\gml // final String[] srcSchemas = // {"C:/Documents and Settings/users documents/Atoll/SchemaIso/srv/serviceMetadata.xsd", // }; // final String[] srcSchemas = {"schema/iso/srv/serviceMetadata.xsd", // }; documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_SOURCE, inSchemas); // URL url = Organizer.findResource("schema/iso/srv/srv.xsd"); // URL url = Organizer.findResource("iso/19139/20070417/srv/serviceMetadata.xsd"); // documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", // url.toString()); documentBuilderFactory.setValidating(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); // document = documentBuilder.parse(new File(xmlUrl.toURI())); documentBuilder.setErrorHandler(errorHandler); documentBuilder.parse(inXml); } catch (Exception e) { throw new MotuException(e); // instance document is invalid! } return errorHandler; }
From source file:com.l2jfree.gameserver.datatables.RecipeTable.java
private void loadFromXML() throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setIgnoringComments(true);//from w w w . j a va2 s.c o m File file = new File(Config.DATAPACK_ROOT, "data/" + RECIPES_FILE); if (file.exists()) { Document doc = factory.newDocumentBuilder().parse(file); List<L2RecipeInstance> recipePartList = new FastList<L2RecipeInstance>(); List<L2RecipeStatInstance> recipeStatUseList = new FastList<L2RecipeStatInstance>(); List<L2RecipeStatInstance> recipeAltStatChangeList = new FastList<L2RecipeStatInstance>(); for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { if ("list".equalsIgnoreCase(n.getNodeName())) { recipesFile: for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) { if ("item".equalsIgnoreCase(d.getNodeName())) { recipePartList.clear(); recipeStatUseList.clear(); recipeAltStatChangeList.clear(); NamedNodeMap attrs = d.getAttributes(); Node att; int id = -1; boolean haveRare = false; StatsSet set = new StatsSet(); att = attrs.getNamedItem("id"); if (att == null) { _log.fatal("Missing id for recipe item, skipping"); continue; } id = Integer.parseInt(att.getNodeValue()); set.set("id", id); att = attrs.getNamedItem("recipeId"); if (att == null) { _log.fatal("Missing recipeId for recipe item id: " + id + ", skipping"); continue; } set.set("recipeId", Integer.parseInt(att.getNodeValue())); att = attrs.getNamedItem("name"); if (att == null) { _log.fatal("Missing name for recipe item id: " + id + ", skipping"); continue; } set.set("recipeName", att.getNodeValue()); att = attrs.getNamedItem("craftLevel"); if (att == null) { _log.fatal("Missing level for recipe item id: " + id + ", skipping"); continue; } set.set("craftLevel", Integer.parseInt(att.getNodeValue())); att = attrs.getNamedItem("type"); if (att == null) { _log.fatal("Missing type for recipe item id: " + id + ", skipping"); continue; } set.set("isDwarvenRecipe", att.getNodeValue().equalsIgnoreCase("dwarven")); att = attrs.getNamedItem("successRate"); if (att == null) { _log.fatal("Missing successRate for recipe item id: " + id + ", skipping"); continue; } set.set("successRate", Integer.parseInt(att.getNodeValue())); for (Node c = d.getFirstChild(); c != null; c = c.getNextSibling()) { if ("statUse".equalsIgnoreCase(c.getNodeName())) { String statName = c.getAttributes().getNamedItem("name").getNodeValue(); int value = Integer .parseInt(c.getAttributes().getNamedItem("value").getNodeValue()); try { recipeStatUseList.add(new L2RecipeStatInstance(statName, value)); } catch (Exception e) { _log.fatal("Error in StatUse parameter for recipe item id: " + id + ", skipping", e); continue recipesFile; } } else if ("altStatChange".equalsIgnoreCase(c.getNodeName())) { String statName = c.getAttributes().getNamedItem("name").getNodeValue(); int value = Integer .parseInt(c.getAttributes().getNamedItem("value").getNodeValue()); try { recipeAltStatChangeList.add(new L2RecipeStatInstance(statName, value)); } catch (Exception e) { _log.fatal("Error in AltStatChange parameter for recipe item id: " + id + ", skipping", e); continue recipesFile; } } else if ("ingredient".equalsIgnoreCase(c.getNodeName())) { int ingId = Integer .parseInt(c.getAttributes().getNamedItem("id").getNodeValue()); int ingCount = Integer .parseInt(c.getAttributes().getNamedItem("count").getNodeValue()); recipePartList.add(new L2RecipeInstance(ingId, ingCount)); } else if ("production".equalsIgnoreCase(c.getNodeName())) { set.set("itemId", Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue())); set.set("count", Integer .parseInt(c.getAttributes().getNamedItem("count").getNodeValue())); } else if ("productionRare".equalsIgnoreCase(c.getNodeName())) { set.set("rareItemId", Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue())); set.set("rareCount", Integer .parseInt(c.getAttributes().getNamedItem("count").getNodeValue())); set.set("rarity", Integer .parseInt(c.getAttributes().getNamedItem("rarity").getNodeValue())); haveRare = true; } } L2RecipeList recipeList = new L2RecipeList(set, haveRare); for (L2RecipeInstance recipePart : recipePartList) recipeList.addRecipe(recipePart); for (L2RecipeStatInstance recipeStatUse : recipeStatUseList) recipeList.addStatUse(recipeStatUse); for (L2RecipeStatInstance recipeAltStatChange : recipeAltStatChangeList) recipeList.addAltStatChange(recipeAltStatChange); _lists.put(recipeList.getId(), recipeList); } } } } } else { _log.fatal("Recipes file (" + file.getAbsolutePath() + ") doesnt exists."); } }
From source file:com.connexta.arbitro.ConfigurationStore.java
/** * Private helper that parses the file and sets up the DOM tree. *//*from w w w. j av a 2 s.c o m*/ private Node getRootNode(File configFile) throws ParsingException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setIgnoringComments(true); dbFactory.setNamespaceAware(false); dbFactory.setValidating(false); DocumentBuilder db = null; try { db = dbFactory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { throw new ParsingException("couldn't get a document builder", pce); } Document doc = null; InputStream stream = null; try { stream = new FileInputStream(configFile); doc = db.parse(stream); } catch (IOException ioe) { throw new ParsingException("failed to load the file ", ioe); } catch (SAXException saxe) { throw new ParsingException("error parsing the XML tree", saxe); } catch (IllegalArgumentException iae) { throw new ParsingException("no data to parse", iae); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { logger.error("Error while closing input stream"); } } } Element root = doc.getDocumentElement(); if (!root.getTagName().equals("config")) throw new ParsingException("unknown document type: " + root.getTagName()); return root; }