List of usage examples for org.xml.sax.helpers XMLReaderFactory createXMLReader
public static XMLReader createXMLReader() throws SAXException
From source file:Examples.java
/** * Show the Transformer using SAX events in and DOM nodes out. */// w ww. j a v a 2 s. c o m public static void exampleContentHandler2DOM(String sourceID, String xslID) throws TransformerException, TransformerConfigurationException, SAXException, IOException, ParserConfigurationException { TransformerFactory tfactory = TransformerFactory.newInstance(); // Make sure the transformer factory we obtained supports both // DOM and SAX. if (tfactory.getFeature(SAXSource.FEATURE) && tfactory.getFeature(DOMSource.FEATURE)) { // We can now safely cast to a SAXTransformerFactory. SAXTransformerFactory sfactory = (SAXTransformerFactory) tfactory; // Create an Document node as the root for the output. DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); org.w3c.dom.Document outNode = docBuilder.newDocument(); // Create a ContentHandler that can liston to SAX events // and transform the output to DOM nodes. TransformerHandler handler = sfactory.newTransformerHandler(new StreamSource(xslID)); handler.setResult(new DOMResult(outNode)); // Create a reader and set it's ContentHandler to be the // transformer. XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2) { } if (reader == null) reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); // Send the SAX events from the parser to the transformer, // and thus to the DOM tree. reader.parse(sourceID); // Serialize the node for diagnosis. exampleSerializeNode(outNode); } else { System.out.println( "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory"); } }
From source file:com.hubrick.vertx.s3.client.S3Client.java
private static SAXSource convertToSaxSource(byte[] payload) throws SAXException { //Create an XMLReader to use with our filter final XMLReader reader = XMLReaderFactory.createXMLReader(); //Create the filter to remove all namespaces and set the xmlReader as its parent. final NamespaceFilter inFilter = new NamespaceFilter(null, false); inFilter.setParent(reader);/*from ww w . j av a 2 s . c om*/ final InputSource inputSource = new InputSource(new ByteArrayInputStream(payload)); //Create a SAXSource specifying the filter return new SAXSource(inFilter, inputSource); }
From source file:de.juwimm.cms.remote.ViewServiceSpringImpl.java
@Override protected ViewComponentValue handleImportViewComponent(Integer parentId, InputStream xmlFile, boolean withMedia, boolean withChildren, Integer unitId, boolean useNewIds, Integer siteId, Integer fulldeploy) throws Exception { String tmpFileName = ""; try {//from ww w.j a v a2s .co m tmpFileName = this.storeSiteFile(xmlFile); if (log.isInfoEnabled()) log.info("-------------->importFile saved."); } catch (IOException e) { log.warn("Unable to copy received inputstream: " + e.getMessage(), e); } ViewComponentHbm parent = getViewComponentHbmDao().load(parentId); ViewComponentHbm firstChild = parent.getFirstChild(); File preparsedXMLfile = null; XMLFilter filter = new XMLFilterImpl(XMLReaderFactory.createXMLReader()); preparsedXMLfile = File.createTempFile("edition_import_preparsed_", ".xml"); if (log.isDebugEnabled()) log.debug("preparsedXMLfile: " + preparsedXMLfile.getAbsolutePath()); XMLWriter xmlWriter = new XMLWriter(new OutputStreamWriter(new FileOutputStream(preparsedXMLfile))); filter.setContentHandler(new de.juwimm.cms.util.EditionBlobContentHandler(xmlWriter, preparsedXMLfile)); InputSource saxIn = null; try { try { saxIn = new InputSource(new GZIPInputStream(new FileInputStream(tmpFileName))); } catch (Exception exe) { saxIn = new InputSource(new BufferedReader(new FileReader(tmpFileName))); } } catch (FileNotFoundException exe) { if (log.isDebugEnabled()) log.error("Error at creating InputSource in paste"); } filter.parse(saxIn); xmlWriter.flush(); xmlWriter = null; filter = null; System.gc(); InputSource domIn = new InputSource(new BufferedInputStream(new FileInputStream(preparsedXMLfile))); org.w3c.dom.Document doc = XercesHelper.inputSource2Dom(domIn); Hashtable<Integer, Integer> picIds = null; Hashtable<Integer, Integer> docIds = null; if (withMedia) { picIds = importPictures(unitId, doc, preparsedXMLfile, useNewIds); docIds = importDocuments(unitId, doc, preparsedXMLfile, useNewIds); } /**import persons */ mappingPersons = new Hashtable<Long, Long>(); Iterator it = XercesHelper.findNodes(doc, "//viewcomponent"); while (it.hasNext()) { Node nodeViewComponent = (Node) it.next(); Integer oldunitId = new Integer(((Element) nodeViewComponent).getAttribute("unitId")); if (oldunitId.intValue() != unitId.intValue()) { importPersons(unitId, doc, useNewIds, picIds); /**import only if not in the same unit*/ } } ViewComponentHbm viewComponent = createViewComponentFromXml(parentId, doc, withChildren, picIds, docIds, useNewIds, siteId, fulldeploy, unitId); //importRealmsForViewComponent(doc, viewComponent, 1); /**import realms*/ parent.addChild(viewComponent); viewComponent.setParent(parent); if (firstChild != null) { viewComponent.setNextNode(firstChild); firstChild.setPrevNode(viewComponent); parent.setFirstChild(viewComponent); } else { parent.setFirstChild(viewComponent); } return viewComponent.getDao(); }
From source file:nl.armatiek.xslweb.serializer.RequestSerializer.java
private XMLReader getFilteredXMLReader() throws SAXException { if (this.xmlReader == null) { XMLFilterImpl filter = new BodyFilter(); filter.setContentHandler(new ContentHandlerToXMLStreamWriter(xsw)); this.xmlReader = XMLReaderFactory.createXMLReader(); this.xmlReader.setFeature("http://xml.org/sax/features/validation", false); this.xmlReader.setFeature("http://xml.org/sax/features/namespaces", true); this.xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); if (Context.getInstance().getParserHardening()) { this.xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false); this.xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); this.xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); this.xmlReader.setEntityResolver(new EntityResolver() { @Override/*from ww w .j ava 2 s .c o m*/ public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return null; } }); this.xmlReader.setProperty("http://apache.org/xml/properties/security-manager", "org.apache.xerces.util.SecurityManager"); } this.xmlReader.setContentHandler(filter); } return this.xmlReader; }
From source file:nl.nn.adapterframework.pipes.BytesOutputPipe.java
public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException { Object result = null;/*from www . j a v a 2s .c o m*/ Variant in = new Variant(input); try { XMLReader parser = XMLReaderFactory.createXMLReader(); FieldsContentHandler fieldsContentHandler = new FieldsContentHandler(); parser.setContentHandler(fieldsContentHandler); parser.parse(in.asXmlInputSource()); result = fieldsContentHandler.getResult(); } catch (SAXException e) { throw new PipeRunException(this, "SAXException", e); } catch (IOException e) { throw new PipeRunException(this, "IOException", e); } return new PipeRunResult(getForward(), result); }
From source file:nl.nn.adapterframework.util.XmlUtils.java
static private XMLReader getParser() throws SAXException { XMLReader parser = null;/*from w w w. jav a2 s . co m*/ parser = XMLReaderFactory.createXMLReader(); return parser; }
From source file:org.apache.synapse.mediators.transform.PayloadFactoryMediator.java
private boolean isWellFormedXML(String value) { try {//w ww. j ava 2s. c o m XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setErrorHandler(null); InputSource source = new InputSource(new ByteArrayInputStream(value.getBytes())); parser.parse(source); } catch (SAXException e) { return false; } catch (IOException e) { return false; } return true; }
From source file:org.apache.synapse.mediators.validate.ValidateMediator.java
public boolean mediate(MessageContext synCtx) { log.debug("ValidateMediator - Validate mediator mediate()"); ByteArrayInputStream baisFromSource = null; boolean shouldTrace = shouldTrace(synCtx.getTracingState()); if (shouldTrace) { trace.trace("Start : Validate mediator"); }/* w ww . jav a 2 s . com*/ try { // create a byte array output stream and serialize the source node into it ByteArrayOutputStream baosForSource = new ByteArrayOutputStream(); XMLStreamWriter xsWriterForSource = XMLOutputFactory.newInstance().createXMLStreamWriter(baosForSource); // serialize the validation target and get an input stream into it OMNode validateSource = getValidateSource(synCtx); if (shouldTrace) { trace.trace("Validate Source : " + validateSource.toString()); } validateSource.serialize(xsWriterForSource); baisFromSource = new ByteArrayInputStream(baosForSource.toByteArray()); } catch (Exception e) { handleException("Error accessing source element for validation : " + source, e); } try { XMLReader reader = XMLReaderFactory.createXMLReader(); SAXSource saxSrc = new SAXSource(reader, new InputSource(baisFromSource)); synchronized (validatorLock) { // initialize schemas/Validator if required initialize(synCtx); // perform actual validation validator.validate(saxSrc); if (errorHandler.isValidationError()) { if (log.isDebugEnabled()) { log.debug("Validation of element returned by XPath : " + source + " failed against the given schemas with Message : " + errorHandler.getSaxParseException().getMessage() + " Executing 'on-fail' sequence"); log.debug("Failed message envelope : " + synCtx.getEnvelope()); } // super.mediate() invokes the "on-fail" sequence of mediators if (shouldTrace) { trace.trace("Validation failed. Invoking the \"on-fail\" " + "sequence of mediators"); } return super.mediate(synCtx); } } } catch (SAXException e) { handleException("Error validating " + source + " element" + e.getMessage(), e); } catch (IOException e) { handleException("Error validating " + source + " element" + e.getMessage(), e); } log.debug("validation of element returned by the XPath expression : " + source + " succeeded against the given schemas and the current message"); if (shouldTrace) { trace.trace("End : Validate mediator"); } return true; }
From source file:org.apache.vxquery.xtest.util.DiskPerformance.java
public Pair<XMLReader, SAXContentHandler> getNewParser() { XMLReader parser;//w ww . ja va 2s . c om SAXContentHandler handler; try { parser = XMLReaderFactory.createXMLReader(); List<SequenceType> childSeq = new ArrayList<SequenceType>(); NameTest nt = new NameTest(createUTF8String(""), createUTF8String("data")); childSeq.add(SequenceType.create(new ElementType(nt, AnyType.INSTANCE, false), Quantifier.QUANT_ONE)); handler = new SAXContentHandler(false, new TreeNodeIdProvider((short) 0), null, null, childSeq); parser.setContentHandler(handler); parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler); return new Pair<XMLReader, SAXContentHandler>(parser, handler); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.apromore.canoniser.yawl.YAWL22Canoniser.java
private JAXBElement<OrgDataType> unmarshalOrgDataFormat(final InputStream organisationalData) throws JAXBException, SAXException { final NamespaceFilter namespaceFilter = new NamespaceFilter(YAWL_ORGDATA_URI, true); // Create an XMLReader to use with our filter final XMLReader reader = XMLReaderFactory.createXMLReader(); namespaceFilter.setParent(reader);/*from w ww . j a v a 2 s. c o m*/ // Prepare the input, in this case a java.io.File (output) final InputSource is = new InputSource(organisationalData); // Create a SAXSource specifying the filter final SAXSource source = new SAXSource(namespaceFilter, is); return YAWLOrgDataSchema.unmarshalYAWLOrgDataFormat(source, false); }