List of usage examples for javax.xml.parsers SAXParser setProperty
public abstract void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException;
Sets the particular property in the underlying implementation of org.xml.sax.XMLReader .
From source file:Main.java
public static void main(String[] args) throws Exception { String xml = "<!DOCTYPE html><hml><img/></hml>"; SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); InputSource in = new InputSource(new StringReader(xml)); DefaultHandler2 myHandler = new DefaultHandler2() { @Override//w ww .j a va 2 s. c o m public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { System.out.println("Element: " + qName); } @Override public void startDTD(String name, String publicId, String systemId) throws SAXException { System.out.println("DocType: " + name); } }; saxParser.setProperty("http://xml.org/sax/properties/lexical-handler", myHandler); saxParser.parse(in, myHandler); }
From source file:Main.java
public static SAXParser getSAXParser() throws Exception { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(true); saxParserFactory.setNamespaceAware(true); SAXParser saxParser = saxParserFactory.newSAXParser(); saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); return saxParser; }
From source file:Main.java
public static void saxParserValidation(InputStream streamDaValidare, InputStream inputSchema, DefaultHandler handler) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true);//www . j ava 2 s . c o m if (inputSchema != null) { factory.setValidating(true); } else { factory.setValidating(false); } SAXParser parser = factory.newSAXParser(); if (inputSchema != null) { parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); parser.setProperty(JAXP_SCHEMA_SOURCE, inputSchema); } parser.parse(streamDaValidare, handler); }
From source file:Main.java
/** * Constructs a validating secure SAX Parser. * * @param schemaStream the schema to validate the XML against * @return a SAX Parser// w w w . ja v a 2 s .co m * @throws ParserConfigurationException is thrown if there is a parser * configuration exception * @throws SAXNotRecognizedException thrown if there is an unrecognized * feature * @throws SAXNotSupportedException thrown if there is a non-supported * feature * @throws SAXException is thrown if there is a SAXException */ public static SAXParser buildSecureSaxParser(InputStream schemaStream) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException, SAXException { final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); //setting the following unfortunately breaks reading the old suppression files (version 1). //factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); final SAXParser saxParser = factory.newSAXParser(); saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); saxParser.setProperty(JAXP_SCHEMA_SOURCE, schemaStream); return saxParser; }
From source file:net.sf.jasperreports.engine.xml.BaseSaxParserFactory.java
protected void configureParser(SAXParser parser) throws SAXException { List<String> schemaLocations = getSchemaLocations(); parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaLocations.toArray(new String[schemaLocations.size()])); boolean cache = JRPropertiesUtil.getInstance(jasperReportsContext) .getBooleanProperty(PROPERTY_CACHE_SCHEMAS); if (cache) {/*from w w w . j a v a 2 s . c o m*/ enableSchemaCaching(parser); } }
From source file:kmlvalidator.KmlValidatorServlet.java
/** * Handles POST requests for the servlet. *//* w w w.j a v a2 s.com*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // Our response is always JSON. response.setContentType("application/json"); // Create the JSON response objects to be filled in later. JSONObject responseObj = new JSONObject(); JSONArray responseErrors = new JSONArray(); try { // Load XSD files here. Note that the Java runtime should be caching // these files. Object[] schemas = { new URL("http://schemas.opengis.net/kml/2.2.0/atom-author-link.xsd").openConnection() .getInputStream(), new URL("http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd").openConnection().getInputStream(), new URL("http://code.google.com/apis/kml/schema/kml22gx.xsd").openConnection() .getInputStream() }; // Create a SAX parser factory (not a DOM parser, we don't need the // overhead) and set it to validate and be namespace aware, for // we want to validate against multiple XSDs. SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Create a SAX parser and prepare for XSD validation. SAXParser parser = parserFactory.newSAXParser(); parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); parser.setProperty(JAXP_SCHEMA_SOURCE, schemas); // Create a parser handler to trap errors during parse. KmlValidatorParserHandler parserHandler = new KmlValidatorParserHandler(); // Parse the KML and send all errors to our handler. parser.parse(request.getInputStream(), parserHandler); // Check our handler for validation results. if (parserHandler.getErrors().size() > 0) { // There were errors, enumerate through them and create JSON objects // for each one. for (KmlValidationError e : parserHandler.getErrors()) { JSONObject error = new JSONObject(); switch (e.getType()) { case KmlValidationError.VALIDATION_WARNING: error.put("type", "warning"); break; case KmlValidationError.VALIDATION_ERROR: error.put("type", "error"); break; case KmlValidationError.VALIDATION_FATAL_ERROR: error.put("type", "fatal_error"); break; default: error.put("type", "fatal_error"); } // fill in parse exception details SAXParseException innerException = e.getInnerException(); error.put("message", innerException.getMessage()); if (innerException.getLineNumber() >= 0) error.put("line", innerException.getLineNumber()); if (innerException.getColumnNumber() >= 0) error.put("column", innerException.getColumnNumber()); // add this error to the list responseErrors.add(error); } // The KML wasn't valid. responseObj.put("status", "invalid"); } else { // The KML is valid against the XSDs. responseObj.put("status", "valid"); } } catch (SAXException e) { // We should never get here due to regular parse errors. This error // must've been thrown by the schema factory. responseObj.put("status", "internal_error"); JSONObject error = new JSONObject(); error.put("type", "fatal_error"); error.put("message", "Internal error: " + e.getMessage()); responseErrors.add(error); } catch (ParserConfigurationException e) { // Internal error at this point. responseObj.put("status", "internal_error"); JSONObject error = new JSONObject(); error.put("type", "fatal_error"); error.put("message", "Internal parse error."); responseErrors.add(error); } // If there were errors, add them to the final response JSON object. if (responseErrors.size() > 0) { responseObj.put("errors", responseErrors); } // output the JSON object as the HTTP response and append a newline for // prettiness response.getWriter().print(responseObj); response.getWriter().println(); }
From source file:com.centeractive.ws.builder.soap.XmlUtils.java
/** * XmlOptions configuration used in preventing XML Bomb * /* w ww. j a v a 2 s. co m*/ * @return XmlOptions */ public static XmlOptions createDefaultXmlOptions() { XmlOptions xmlOptions; try { SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); SecurityManager securityManager = new SecurityManager(); // Default seems to be 64000! // TODO // securityManager.setEntityExpansionLimit( 16 ); saxParser.setProperty("http://apache.org/xml/properties/security-manager", securityManager); XMLReader xmlReader = saxParser.getXMLReader(); xmlOptions = new XmlOptions().setLoadUseXMLReader(xmlReader); } catch (Exception e) { xmlOptions = new XmlOptions(); log.error("Error creating XmlOptions; " + e.getMessage(), e); } return xmlOptions; }
From source file:eionet.cr.util.xml.XmlAnalysis.java
/** * * @param inputStream/*from w ww . ja va2s . c om*/ * @return * @throws SAXException * @throws ParserConfigurationException * @throws GDEMException * @throws SAXException * @throws IOException */ public void parse(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException { // set up the parser and reader SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); // turn off validation against schema or dtd (we only need the document to be well-formed XML) parserFactory.setValidating(false); reader.setFeature("http://xml.org/sax/features/validation", false); reader.setFeature("http://apache.org/xml/features/validation/schema", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); reader.setFeature("http://xml.org/sax/features/namespaces", true); // turn on dtd handling doctypeReader = new SAXDoctypeReader(); try { parser.setProperty("http://xml.org/sax/properties/lexical-handler", doctypeReader); } catch (SAXNotRecognizedException e) { logger.warn("Installed XML parser does not provide lexical events", e); } catch (SAXNotSupportedException e) { logger.warn("Cannot turn on comment processing here", e); } // set the handler and do the parsing handler = new Handler(); reader.setContentHandler(handler); try { reader.parse(new InputSource(inputStream)); } catch (SAXException e) { Exception ee = e.getException(); if (ee == null || !(ee instanceof CRException)) throw e; } }
From source file:eu.scape_project.planning.xml.PlanParser.java
/** * Imports the XML representation of plans from the given input stream. * /*from ww w . j a v a 2 s . c o m*/ * @param in * the input stream to read from * @return list of read plans * @throws PlatoException * if the plan cannot be parsed */ public List<Plan> importProjects(final InputStream in) throws PlatoException { try { SAXParser parser = validatingParserFactory.getValidatingParser(); parser.setProperty(ValidatingParserFactory.JAXP_SCHEMA_SOURCE, PlanXMLConstants.PLAN_SCHEMAS); Digester digester = new Digester(parser); SchemaResolver schemaResolver = new SchemaResolver(); schemaResolver .addSchemaLocation(PlanXMLConstants.PLATO_SCHEMA_URI, PlanXMLConstants.PLATO_SCHEMA_LOCATION) .addSchemaLocation(PlanXMLConstants.PAP_SCHEMA_URI, PlanXMLConstants.PAP_SCHEMA_LOCATION) .addSchemaLocation(PlanXMLConstants.TAVERNA_SCHEMA_URI, PlanXMLConstants.TAVERNA_SCHEMA_LOCATION); digester.setEntityResolver(schemaResolver); digester.setErrorHandler(new StrictErrorHandler()); digester.setNamespaceAware(true); digester.push(this); PlanParser.addRules(digester); digester.setUseContextClassLoader(true); plans = new ArrayList<Plan>(); // finally parse the XML representation with all created rules digester.parse(in); for (Plan plan : plans) { String projectName = plan.getPlanProperties().getName(); if ((projectName != null) && (!"".equals(projectName))) { /* * establish links from values to scales. For all(!) * alternatives: An alternative could have be discarded * after some measurements have already been added. */ plan.getTree().initValues(plan.getAlternativesDefinition().getAlternatives(), plan.getSampleRecordsDefinition().getRecords().size(), true); /* * establish references of Experiment.uploads */ HashMap<String, SampleObject> records = new HashMap<String, SampleObject>(); for (SampleObject record : plan.getSampleRecordsDefinition().getRecords()) { records.put(record.getShortName(), record); } for (Alternative alt : plan.getAlternativesDefinition().getAlternatives()) { if ((alt.getExperiment() != null) && (alt.getExperiment() instanceof ExperimentWrapper)) { alt.setExperiment(((ExperimentWrapper) alt.getExperiment()).getExperiment(records)); } } // CHECK NUMERIC TRANSFORMER THRESHOLDS for (Leaf l : plan.getTree().getRoot().getAllLeaves()) { eu.scape_project.planning.model.transform.Transformer t = l.getTransformer(); if (t != null && t instanceof NumericTransformer) { NumericTransformer nt = (NumericTransformer) t; if (!nt.checkOrder()) { StringBuffer sb = new StringBuffer("NUMERICTRANSFORMER THRESHOLD ERROR "); sb.append(l.getName()).append("::NUMERICTRANSFORMER:: "); sb.append(nt.getThreshold1()).append(" ").append(nt.getThreshold2()).append(" ") .append(nt.getThreshold3()).append(" ").append(nt.getThreshold4()) .append(" ").append(nt.getThreshold5()); log.error(sb.toString()); } } } /* * establish references to selected alternative */ HashMap<String, Alternative> alternatives = new HashMap<String, Alternative>(); for (Alternative alt : plan.getAlternativesDefinition().getAlternatives()) { alternatives.put(alt.getName(), alt); } if ((plan.getRecommendation() != null) && (plan.getRecommendation() instanceof RecommendationWrapper)) { plan.setRecommendation( ((RecommendationWrapper) plan.getRecommendation()).getRecommendation(alternatives)); } if ((plan.getPlanProperties().getState() == PlanState.ANALYSED) && ((plan.getRecommendation() == null) || (plan.getRecommendation().getAlternative() == null))) { /* * This project is NOT completely analysed */ plan.getPlanProperties().setState(PlanState.valueOf(PlanState.ANALYSED.getValue() - 1)); } } else { throw new PlatoException("Could not find any project data."); } } } catch (Exception e) { throw new PlatoException("Failed to import plans.", e); } return plans; }
From source file:net.sf.jasperreports.engine.xml.BaseSaxParserFactory.java
protected void setGrammarPoolProperty(SAXParser parser, String poolClassName) { try {/*from w w w . j a v a2 s . c o m*/ Object cacheKey = getGrammarPoolCacheKey(); // we're using thread local caches to avoid thread safety problems ThreadLocal<ReferenceMap<Object, Object>> grammarPoolCache = getGrammarPoolCache(); ReferenceMap<Object, Object> cacheMap = grammarPoolCache.get(); if (cacheMap == null) { cacheMap = new ReferenceMap<Object, Object>(ReferenceMap.ReferenceStrength.WEAK, ReferenceMap.ReferenceStrength.SOFT); grammarPoolCache.set(cacheMap); } Object grammarPool = cacheMap.get(cacheKey); if (grammarPool == null) { if (log.isDebugEnabled()) { log.debug("Instantiating grammar pool of type " + poolClassName + " for cache key " + cacheKey); } grammarPool = ClassUtils.instantiateClass(poolClassName, Object.class); cacheMap.put(cacheKey, grammarPool); } parser.setProperty(XERCES_PARSER_PROPERTY_GRAMMAR_POOL, grammarPool); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Error setting Xerces grammar pool of type " + poolClassName, e); } } }