/** * Non-validating * * @param path path to input file * @param _class class of xml root object * @return root object */ public static Object retrieveJAXB(String path, Class _class) { Object obj = null; /* Block parser from reaching out externally see: https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#SAXTransformerFactory */ try { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://xml.org/sax/features/external-general-entities", false); spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(), new InputSource(new FileReader(new File(path)))); JAXBContext jc = JAXBContext.newInstance(_class); Unmarshaller um = jc.createUnmarshaller(); obj = um.unmarshal(xmlSource); } catch (JAXBException | FileNotFoundException | SAXException | ParserConfigurationException e) { e.printStackTrace(); } return obj; }
public void xsltprocess(String[] args) throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException { // 1. Instantiate a TransformerFactory. SAXTransformerFactory tFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); // 2. Use the TransformerFactory to process the stylesheet Source and // generate a Transformer. InputStream is = getClass().getResourceAsStream("xmg2pol.xsl"); Transformer transformer = tFactory.newTransformer (new StreamSource(is)); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "polarities.dtd,xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); // 3. Use the Transformer to transform an XML Source and send the // output to a Result object. try { String input = args[0]; String output= args[1]; SAXSource saxs = new SAXSource(new InputSource(input)); XMLReader saxReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); saxReader.setEntityResolver(new MyEntityResolver()); saxs.setXMLReader(saxReader); transformer.transform(saxs, new StreamResult(new OutputStreamWriter(new FileOutputStream(output), "utf-8"))); } catch (Exception e) { e.printStackTrace(); } }
/** * Saves the xml, contained by the specified input with the custom indentation. * If the input is the result of jaxb marshalling, make sure to set * Marshaller.JAXB_FORMATTED_OUTPUT to false in order for this method to work * properly. * * @param input * @param fos * @param indentation */ public static void saveWithCustomIndetation(ByteArrayInputStream input, FileOutputStream fos, int indentation) { try { Transformer transformer = SAXTransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indentation)); Source xmlSource = new SAXSource(new org.xml.sax.InputSource(input)); StreamResult res = new StreamResult(fos); transformer.transform(xmlSource, res); fos.flush(); fos.close(); } catch (TransformerFactoryConfigurationError | TransformerException | IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } }
/** * Returns a Source for reading the XML value designated by this SQLXML * instance. <p> * * @param sourceClass The class of the source, or null. If null, then a * DOMSource is returned. * @return a Source for reading the XML value. * @throws SQLException if there is an error processing the XML value * or if the given <tt>sourceClass</tt> is not supported. */ protected <T extends Source>T getSourceImpl( Class<T> sourceClass) throws SQLException { if (JAXBSource.class.isAssignableFrom(sourceClass)) { // Must go first presently, since JAXBSource extends SAXSource // (purely as an implementation detail) and it's not possible // to instantiate a valid JAXBSource with a Zero-Args // constructor(or any subclass thereof, due to the finality of // its private marshaller and context object attributes) // FALL THROUGH... will throw an exception } else if (StreamSource.class.isAssignableFrom(sourceClass)) { return createStreamSource(sourceClass); } else if ((sourceClass == null) || DOMSource.class.isAssignableFrom(sourceClass)) { return createDOMSource(sourceClass); } else if (SAXSource.class.isAssignableFrom(sourceClass)) { return createSAXSource(sourceClass); } else if (StAXSource.class.isAssignableFrom(sourceClass)) { return createStAXSource(sourceClass); } throw JDBCUtil.invalidArgument("sourceClass: " + sourceClass); }
/** * Returns a Source for reading the XML value designated by this SQLXML * instance. <p> * * @param sourceClass The class of the source, or null. If null, then a * DOMSource is returned. * @return a Source for reading the XML value. * @throws SQLException if there is an error processing the XML value * or if the given <tt>sourceClass</tt> is not supported. */ protected <T extends Source>T getSourceImpl( Class<T> sourceClass) throws SQLException { if (JAXBSource.class.isAssignableFrom(sourceClass)) { // Must go first presently, since JAXBSource extends SAXSource // (purely as an implmentation detail) and it's not possible // to instantiate a valid JAXBSource with a Zero-Args // constructor(or any subclass thereof, due to the finality of // its private marshaller and context object attrbutes) // FALL THROUGH... will throw an exception } else if (StreamSource.class.isAssignableFrom(sourceClass)) { return createStreamSource(sourceClass); } else if ((sourceClass == null) || DOMSource.class.isAssignableFrom(sourceClass)) { return createDOMSource(sourceClass); } else if (SAXSource.class.isAssignableFrom(sourceClass)) { return createSAXSource(sourceClass); } else if (StAXSource.class.isAssignableFrom(sourceClass)) { return createStAXSource(sourceClass); } throw Util.invalidArgument("sourceClass: " + sourceClass); }
protected Source processSource(Source source) { if (source instanceof StreamSource) { StreamSource streamSource = (StreamSource) source; InputSource inputSource = new InputSource(streamSource.getInputStream()); try { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); String featureName = "http://xml.org/sax/features/external-general-entities"; xmlReader.setFeature(featureName, isProcessExternalEntities()); if (!isProcessExternalEntities()) { xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER); } return new SAXSource(xmlReader, inputSource); } catch (SAXException ex) { logger.warn("Processing of external entities could not be disabled", ex); return source; } } else { return source; } }
@Override @SuppressWarnings("unchecked") protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { InputStream body = inputMessage.getBody(); if (DOMSource.class.equals(clazz)) { return (T) readDOMSource(body); } else if (SAXSource.class.equals(clazz)) { return (T) readSAXSource(body); } else if (StAXSource.class.equals(clazz)) { return (T) readStAXSource(body); } else if (StreamSource.class.equals(clazz) || Source.class.equals(clazz)) { return (T) readStreamSource(body); } else { throw new HttpMessageConversionException("Could not read class [" + clazz + "]. Only DOMSource, SAXSource, StAXSource, and StreamSource are supported."); } }
/** * Returns a Source for reading the XML value designated by this SQLXML * instance. <p> * * @param sourceClass The class of the source, or null. If null, then a * DOMSource is returned. * @return a Source for reading the XML value. * @throws SQLException if there is an error processing the XML value * or if the given <tt>sourceClass</tt> is not supported. */ protected <T extends Source>T getSourceImpl( Class<T> sourceClass) throws SQLException { if (JAXBSource.class.isAssignableFrom(sourceClass)) { // Must go first presently, since JAXBSource extends SAXSource // (purely as an implmentation detail) and it's not possible // to instantiate a valid JAXBSource with a Zero-Args // constructor(or any subclass thereof, due to the finality of // its private marshaller and context object attrbutes) // FALL THROUGH... will throw an exception } else if (StreamSource.class.isAssignableFrom(sourceClass)) { return createStreamSource(sourceClass); } else if ((sourceClass == null) || DOMSource.class.isAssignableFrom(sourceClass)) { return createDOMSource(sourceClass); } else if (SAXSource.class.isAssignableFrom(sourceClass)) { return createSAXSource(sourceClass); } else if (StAXSource.class.isAssignableFrom(sourceClass)) { return createStAXSource(sourceClass); } throw JDBCUtil.invalidArgument("sourceClass: " + sourceClass); }
@Override public String format(String response) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(response.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray()).trim(); } catch (Exception e) { e.printStackTrace(); Logger.e(TAG, e.getMessage(), e); return response; } }
@Test public void testTransformer() throws TransformerException { String xml = "<?xml version='1.0'?><root/>"; ReaderStub.used = false; TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); InputSource in = new InputSource(new StringReader(xml)); SAXSource source = new SAXSource(in); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); assertTrue(ReaderStub.used); }
@Override public <T> JAXBElement<T> unmarshal( Source source, Class<T> expectedType ) throws JAXBException { if (source instanceof SAXSource) { SAXSource ss = (SAXSource) source; XMLReader locReader = ss.getXMLReader(); if (locReader == null) { locReader = getXMLReader(); } return unmarshal(locReader, ss.getInputSource(), expectedType); } if (source instanceof StreamSource) { return unmarshal(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType); } if (source instanceof DOMSource) { return unmarshal(((DOMSource) source).getNode(), expectedType); } // we don't handle other types of Source throw new IllegalArgumentException(); }
public Object unmarshal0( Source source, JaxBeanInfo expectedType ) throws JAXBException { if (source instanceof SAXSource) { SAXSource ss = (SAXSource) source; XMLReader locReader = ss.getXMLReader(); if (locReader == null) { locReader = getXMLReader(); } return unmarshal0(locReader, ss.getInputSource(), expectedType); } if (source instanceof StreamSource) { return unmarshal0(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType); } if (source instanceof DOMSource) { return unmarshal0(((DOMSource) source).getNode(), expectedType); } // we don't handle other types of Source throw new IllegalArgumentException(); }
public Object unmarshal( Source source ) throws JAXBException { if( source == null ) { throw new IllegalArgumentException( Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) ); } if(source instanceof SAXSource) return unmarshal( (SAXSource)source ); if(source instanceof StreamSource) return unmarshal( streamSourceToInputSource((StreamSource)source)); if(source instanceof DOMSource) return unmarshal( ((DOMSource)source).getNode() ); // we don't handle other types of Source throw new IllegalArgumentException(); }
@Test public void testSAXTransformerFactory() throws TransformerConfigurationException { final String xsl = "<?xml version='1.0'?>\n" + "<xsl:stylesheet" + " xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" + " version='1.0'>\n" + " <xsl:template match='/'>Hello World!</xsl:template>\n" + "</xsl:stylesheet>\n"; ReaderStub.used = false; TransformerFactory transFactory = TransformerFactory.newInstance(); assertTrue(transFactory.getFeature(SAXTransformerFactory.FEATURE)); InputSource in = new InputSource(new StringReader(xsl)); SAXSource source = new SAXSource(in); transFactory.newTransformer(source); assertTrue(ReaderStub.used); }
/** * Loads the document and updates build-time (latency) statistics */ public void loadDocument(String uri) { try { final long stamp = System.currentTimeMillis(); _dom = (DOMEnhancedForDTM)_dtmManager.getDTM( new SAXSource(_reader, new InputSource(uri)), false, null, true, false); _dom.setDocumentURI(uri); // The build time can be used for statistics for a better // priority algorithm (currently round robin). final long thisTime = System.currentTimeMillis() - stamp; if (_buildTime > 0) _buildTime = (_buildTime + thisTime) >>> 1; else _buildTime = thisTime; } catch (Exception e) { _dom = null; } }
/** * This method returns the SAX2 parser to use with the InputSource * obtained from this URI. * It may return null if any SAX2-conformant XML parser can be used, * or if getInputSource() will also return null. The parser must * be free for use (i.e., not currently in use for another parse(). * After use of the parser is completed, the releaseXMLReader(XMLReader) * must be called. * * @param inputSource The value returned from the URIResolver. * @return a SAX2 XMLReader to use to resolve the inputSource argument. * * @return non-null XMLReader reference ready to parse. */ synchronized public XMLReader getXMLReader(Source inputSource) { try { XMLReader reader = (inputSource instanceof SAXSource) ? ((SAXSource) inputSource).getXMLReader() : null; // If user did not supply a reader, ask for one from the reader manager if (null == reader) { if (m_readerManager == null) { m_readerManager = XMLReaderManager.getInstance(super.useServicesMechnism()); } reader = m_readerManager.getXMLReader(); } return reader; } catch (SAXException se) { throw new DTMException(se.getMessage(), se); } }
/** * Generates XML and writes it to the given <code>PrintWriter</code> */ private void generate(PrintWriter pw) { // Use JAXP's transformation API to turn SAX events into pretty // XML text try { Source src = new SAXSource(this, new InputSource()); Result res = new StreamResult(pw); TransformerFactory xFactory = TransformerFactory.newInstance(); Transformer xform = xFactory.newTransformer(); xform.setOutputProperty(OutputKeys.METHOD, "xml"); xform.setOutputProperty(OutputKeys.INDENT, "yes"); xform.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, SYSTEM_ID); xform.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, PUBLIC_ID); xform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); xform.transform(src, res); pw.flush(); } catch (Exception ex) { RuntimeException ex2 = new RuntimeException( LocalizedStrings.ManagedEntityConfigXmlGenerator_EXCEPTION_THROWN_WHILE_GENERATING_XML .toLocalizedString()); ex2.initCause(ex); throw ex2; } }
@Test public void test() throws Exception { SAXParserFactory fac = SAXParserFactory.newInstance(); fac.setNamespaceAware(true); SAXParser saxParser = fac.newSAXParser(); StreamSource sr = new StreamSource(this.getClass().getResourceAsStream("SAX2DOMTest.xml")); InputSource is = SAXSource.sourceToInputSource(sr); RejectDoctypeSaxFilter rf = new RejectDoctypeSaxFilter(saxParser); SAXSource src = new SAXSource(rf, is); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); transformer.transform(src, result); Document doc = (Document) result.getNode(); System.out.println("Name" + doc.getDocumentElement().getLocalName()); String id = "XWSSGID-11605791027261938254268"; Element selement = doc.getElementById(id); if (selement == null) { System.out.println("getElementById returned null"); } }
@Test public void test01() { String xml = "<?xml version='1.0'?><root/>"; ReaderStub.used = false; setSystemProperty("org.xml.sax.driver", ""); // Don't set 'org.xml.sax.driver' here, just use default try { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); InputSource in = new InputSource(new StringReader(xml)); SAXSource source = new SAXSource(in); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); Assert.assertTrue(!printWasReaderStubCreated()); } catch (Exception ex) { Assert.fail(ex.getMessage()); } }
@Test public void test02() { String xml = "<?xml version='1.0'?><root/>"; ReaderStub.used = false; setSystemProperty("org.xml.sax.driver", ReaderStub.class.getName()); try { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); InputSource in = new InputSource(new StringReader(xml)); SAXSource source = new SAXSource(in); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); Assert.assertTrue(printWasReaderStubCreated()); } catch (Exception ex) { Assert.fail(ex.getMessage()); } }
@DataProvider(name = "data_ValidatorA") public Object[][] getDataValidator() { DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog); SAXSource ss = new SAXSource(new InputSource(xml_val_test)); ss.setSystemId(xml_val_test_id); StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog); StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog); StreamSource source = new StreamSource(new File(xml_val_test)); return new Object[][]{ // use catalog {true, false, true, ds, null, null, xml_catalog, null}, {false, true, true, ds, null, null, null, xml_catalog}, {true, false, true, ss, null, null, xml_catalog, null}, {false, true, true, ss, null, null, null, xml_catalog}, {true, false, true, stax, null, null, xml_catalog, xml_catalog}, {false, true, true, stax1, null, null, xml_catalog, xml_catalog}, {true, false, true, source, null, null, xml_catalog, null}, {false, true, true, source, null, null, null, xml_catalog}, }; }
@DataProvider(name = "data_XSLA") public Object[][] getDataXSL() { // XSLInclude.xsl has one import XSLImport_html.xsl and two includes, // XSLInclude_header.xsl and XSLInclude_footer.xsl; SAXSource xslSourceDTD = new SAXSource(new InputSource(new StringReader(xsl_includeDTD))); StreamSource xmlSourceDTD = new StreamSource(new StringReader(xml_xslDTD)); SAXSource xslDocSource = new SAXSource(new InputSource(new File(xsl_doc).toURI().toASCIIString())); StreamSource xmlDocSource = new StreamSource(new File(xml_doc)); return new Object[][]{ // for resolving DTD, import and include in xsl {true, true, xml_catalog, xslSourceDTD, xmlSourceDTD, null, ""}, // for resolving reference by the document function {true, true, xml_catalog, xslDocSource, xmlDocSource, null, "Resolved by a catalog"}, }; }
@Test public void testValidation_SAX_withServiceMech() { System.out.println("Validation using SAX Source. Using service mechnism (by default) to find SAX Impl:"); InputSource is = new InputSource(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml")); SAXSource ss = new SAXSource(is); setSystemProperty(SAX_FACTORY_ID, "MySAXFactoryImpl"); long start = System.currentTimeMillis(); try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(_xsd)); Validator validator = schema.newValidator(); validator.validate(ss, null); Assert.fail("User impl MySAXFactoryImpl should be used."); } catch (Exception e) { String error = e.getMessage(); if (error.indexOf("javax.xml.parsers.FactoryConfigurationError: Provider MySAXFactoryImpl not found") > 0) { // expected } // System.out.println(e.getMessage()); } long end = System.currentTimeMillis(); double elapsedTime = ((end - start)); System.out.println("Time elapsed: " + elapsedTime); clearSystemProperty(SAX_FACTORY_ID); }
@DataProvider(name = "supportLSResourceResolver1") public Object[][] supportLSResourceResolver1() throws Exception { URI catalogFile = getClass().getResource("CatalogSupport.xml").toURI(); URI catalogFileUri = getClass().getResource("CatalogSupport_uri.xml").toURI(); /* * val_test.xml has a reference to system.dtd and val_test.xsd */ SAXSource ss = new SAXSource(new InputSource(xml_val_test)); ss.setSystemId(xml_val_test_id); return new Object[][]{ {catalogFile, ss}, {catalogFileUri, ss}, }; }
@DataProvider(name = "supportURIResolver") public Object[][] supportURIResolver() throws Exception { URI catalogFile = getClass().getResource("CatalogSupport.xml").toURI(); URI catalogFileUri = getClass().getResource("CatalogSupport_uri.xml").toURI(); SAXSource xslSource = new SAXSource(new InputSource(new File(xsl_doc).toURI().toASCIIString())); /* * val_test.xml has a reference to system.dtd and val_test.xsd */ SAXSource ss = new SAXSource(new InputSource(xml_val_test)); ss.setSystemId(xml_val_test_id); return new Object[][]{ {catalogFile, new SAXSource(new InputSource(new File(xsl_doc).toURI().toASCIIString())), new StreamSource(new File(xml_doc)), "Resolved by a catalog"}, {catalogFileUri, new SAXSource(new InputSource(new StringReader(xsl_include))), new StreamSource(new StringReader(xml_xsl)), null}, }; }
@DataProvider(name = "data_ValidatorC") public Object[][] getDataValidator() { DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog); SAXSource ss = new SAXSource(new InputSource(xml_val_test)); ss.setSystemId(xml_val_test_id); StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog); StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog); StreamSource source = new StreamSource(new File(xml_val_test)); return new Object[][]{ // use catalog {false, false, true, ds, null, null, xml_catalog, null}, {false, false, true, ds, null, null, null, xml_catalog}, {false, false, true, ss, null, null, xml_catalog, null}, {false, false, true, ss, null, null, null, xml_catalog}, {false, false, true, stax, null, null, xml_catalog, null}, {false, false, true, stax1, null, null, null, xml_catalog}, {false, false, true, source, null, null, xml_catalog, null}, {false, false, true, source, null, null, null, xml_catalog}, }; }
private String runTransform(SAXParser sp) throws Exception { // Run identity transform using SAX parser SAXSource src = new SAXSource(sp.getXMLReader(), new InputSource(new StringReader(TESTXML))); Transformer transformer = TransformerFactory.newInstance().newTransformer(); StringWriter sw = new StringWriter(); transformer.transform(src, new StreamResult(sw)); String result = sw.getBuffer().toString(); // System.out.println(result); return result; }
@DataProvider(name = "emptySources") public Object[][] getSources() throws URISyntaxException { return new Object[][]{ {new DOMSource()}, {new DOMSource(getDocument())}, {new SAXSource()}, {new SAXSource(new InputSource(new StringReader("")))}, {new SAXSource(getXMLReader(), new InputSource(new StringReader("")))}, {new StreamSource()}, {new StreamSource(new ByteArrayInputStream("".getBytes()))}, {new StreamSource(new StringReader(""))}, {new StreamSource(new StringReader(""), null)}, {new StreamSource((String) null)} }; }
public static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray()); } catch (Exception e) { return xml; } }
@Override public XmlScriptType getHtmlAsXml() { try { XMLReader htmlParser = new Parser(); htmlParser.setFeature(Parser.namespacesFeature, false); htmlParser.setFeature(Parser.namespacePrefixesFeature, false); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); transformer.transform(new SAXSource(htmlParser, new InputSource(new StringReader(getAsText()))), result); Node node = result.getNode(); if( node.getNodeType() == Node.DOCUMENT_NODE ) { node = node.getFirstChild(); } return new PropBagWrapper(new PropBagEx(node)); } catch( Exception ex ) { throw new RuntimeException("Response received from external URL could not be tidied into XML", ex); } }
private SAXSource readSAXSource(InputStream body) throws IOException { try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities()); byte[] bytes = StreamUtils.copyToByteArray(body); if (!isProcessExternalEntities()) { reader.setEntityResolver(NO_OP_ENTITY_RESOLVER); } return new SAXSource(reader, new InputSource(new ByteArrayInputStream(bytes))); } catch (SAXException ex) { throw new HttpMessageNotReadableException("Could not parse document: " + ex.getMessage(), ex); } }
public SourceUtils(Source src) { if(src instanceof StreamSource){ srcType = streamSource; }else if(src instanceof DOMSource){ srcType = domSource; }else if(src instanceof SAXSource){ srcType = saxSource; } }
public Source getContent() throws SOAPException { if (source != null) { InputStream bis = null; if (source instanceof JAXMStreamSource) { StreamSource streamSource = (StreamSource)source; bis = streamSource.getInputStream(); } else if (FastInfosetReflection.isFastInfosetSource(source)) { // FastInfosetSource inherits from SAXSource SAXSource saxSource = (SAXSource)source; bis = saxSource.getInputSource().getByteStream(); } if (bis != null) { try { bis.reset(); } catch (IOException e) { /* This exception will never be thrown. * * The setContent method will modify the source * if StreamSource to JAXMStreamSource, that uses * a ByteInputStream, and for a FastInfosetSource will * replace the InputStream with a ByteInputStream. */ } } return source; } return ((Envelope) getEnvelope()).getContent(); }
/** * convert an array of {@link InputSource InputSource} into an * array of {@link Source Source} * * @param schemas array of {@link InputSource InputSource} * @return array of {@link Source Source} */ private static Source[] getSchemaSource(InputSource[] schemas, EntityResolver entityResolver) throws SAXException { SAXSource[] sources = new SAXSource[schemas.length]; for (int i = 0; i < schemas.length; i++) { sources[i] = new SAXSource(schemas[i]); // sources[i].getXMLReader().setEntityResolver(entityResolver); } return sources; }
@Test public void testValidation_SAX_withSM() throws Exception { if(System.getSecurityManager() == null) return; System.out.println("Validation using SAX Source with security manager:"); InputSource is = new InputSource(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml")); SAXSource ss = new SAXSource(is); setSystemProperty(SAX_FACTORY_ID, "MySAXFactoryImpl"); long start = System.currentTimeMillis(); try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, false); Schema schema = factory.newSchema(new StreamSource(_xsd)); Validator validator = schema.newValidator(); validator.validate(ss, null); } catch (Exception e) { String error = e.getMessage(); if (error.indexOf("javax.xml.parsers.FactoryConfigurationError: Provider MySAXFactoryImpl not found") > 0) { Assert.fail(e.getMessage()); } else { System.out.println("Default impl is used"); } // System.out.println(e.getMessage()); } finally { clearSystemProperty(SAX_FACTORY_ID); } long end = System.currentTimeMillis(); double elapsedTime = ((end - start)); System.out.println("Time elapsed: " + elapsedTime); }