下面列出了javax.xml.transform.stream.StreamSource#setSystemId ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* This is to test the URIResolver.resolve() method when there is an error
* in the file.
*
* @throws Exception If any errors occur.
*/
@Test
public static void docResolver01() throws Exception {
try (FileInputStream fis = new FileInputStream(XML_DIR + "doctest.xsl")) {
URIResolverTest resolver = new URIResolverTest("temp/colors.xml", SYSTEM_ID);
StreamSource streamSource = new StreamSource(fis);
streamSource.setSystemId(SYSTEM_ID);
Transformer transformer = TransformerFactory.newInstance().newTransformer(streamSource);
transformer.setURIResolver(resolver);
File f = new File(XML_DIR + "myFake.xml");
Document document = DocumentBuilderFactory.newInstance().
newDocumentBuilder().parse(f);
// Use a Transformer for output
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.err);
// No exception is expected because resolver resolve wrong URI.
transformer.transform(source, result);
}
}
/**
* This test is related to problem reported as [WSTX-182], inability
* to use SystemId alone as source.
*/
public void testCreateUsingSystemId()
throws IOException, XMLStreamException
{
File tmpF = File.createTempFile("staxtest", ".xml");
tmpF.deleteOnExit();
// First, need to write contents to the file
Writer w = new OutputStreamWriter(new FileOutputStream(tmpF), "UTF-8");
w.write("<root />");
w.close();
XMLInputFactory f = getInputFactory();
StreamSource src = new StreamSource();
src.setSystemId(tmpF);
XMLStreamReader sr = f.createXMLStreamReader(src);
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(END_ELEMENT, sr.next());
sr.close();
}
/**
* Makes a list of templates from a series of xsltProcessors that applies those xsltProcessors
* in order.
* @param templateList The series of xsltProcessors used to construct the
* filter.
* @throws BuildException If no xsltProcessors are specified.
*/
List<Templates> makeTemplates(List<CCGBankTaskTemplates> templateList)
throws FileNotFoundException,TransformerConfigurationException {
List<Templates> l = new ArrayList<Templates>();
for(CCGBankTaskTemplates taskTemplates : templateList) {
for(File f : taskTemplates) {
StreamSource ss = new StreamSource(
new BufferedInputStream(new FileInputStream(f)));
ss.setSystemId(f);
l.add(transformerFactory.newTemplates(ss));
}
}
return Collections.unmodifiableList(l);
}
private static Transformer getTransformer(String stylesheet) throws IOException, TransformerConfigurationException {
try (InputStream in = XSLTransformation.class.getResourceAsStream(stylesheet);
InputStream xslStream = new BufferedInputStream(in)) {
StreamSource src = new StreamSource(xslStream);
src.setSystemId(stylesheet);
return TransformerFactory.newInstance().newTransformer(src);
}
}
public ValidatorHandler newValidator() {
if (schema==null) {
synchronized (this) {
if (schema == null) {
ResourceResolver resourceResolver = null;
try (InputStream is = clazz.getResourceAsStream(resourceName)) {
StreamSource source = new StreamSource(is);
source.setSystemId(resourceName);
// do not disable secure processing - these are well-known schemas
SchemaFactory sf = XmlFactory.createSchemaFactory(XMLConstants.W3C_XML_SCHEMA_NS_URI, false);
SchemaFactory schemaFactory = allowExternalAccess(sf, "file", false);
if (createResolver) {
resourceResolver = new ResourceResolver(clazz);
schemaFactory.setResourceResolver(resourceResolver);
}
schema = schemaFactory.newSchema(source);
} catch (IOException | SAXException e) {
InternalError ie = new InternalError(e.getMessage());
ie.initCause(e);
throw ie;
} finally {
if (resourceResolver != null) resourceResolver.closeStreams();
}
}
}
}
return schema.newValidatorHandler();
}
/**
* This is to test the URIResolver.resolve() method when a transformer is
* created using StreamSource. style-sheet file has xsl:include in it.
*
* @throws Exception If any errors occur.
*/
@Test
public static void resolver01() throws Exception {
try (FileInputStream fis = new FileInputStream(XSL_INCLUDE_FILE)) {
TransformerFactory tfactory = TransformerFactory.newInstance();
URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID);
tfactory.setURIResolver(resolver);
StreamSource streamSource = new StreamSource(fis);
streamSource.setSystemId(SYSTEM_ID);
assertNotNull(tfactory.newTransformer(streamSource));
}
}
/**
* This is to test the URIResolver.resolve() method when a transformer is
* created using StreamSource. style-sheet file has xsl:import in it.
*
* @throws Exception If any errors occur.
*/
@Test
public static void resolver04() throws Exception {
try (FileInputStream fis = new FileInputStream(XSL_IMPORT_FILE)) {
URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID);
TransformerFactory tfactory = TransformerFactory.newInstance();
tfactory.setURIResolver(resolver);
StreamSource streamSource = new StreamSource(fis);
streamSource.setSystemId(SYSTEM_ID);
assertNotNull(tfactory.newTransformer(streamSource));
}
}
public Source resolve(String href, String base) throws TransformerException {
if ("http://astro.com/stylesheets/topleveltemplate".equals(href)) {
StreamSource ss = new StreamSource(TOPTEMPLINCXSL);
ss.setSystemId(filenameToURL(TOPTEMPLINCXSL));
return ss;
} else {
return null;
}
}
/**
* URI Resolver that resolves XSL document() or xsl:include calls.
*
* @see javax.xml.transform.URIResolver
*/
public Source resolve(String href, String base) throws TransformerException {
if (LOGGER.isDebugEnabled()) {
if (base != null) {
LOGGER.debug("Including {} from {}", href, base);
addDebugInfo(href, base);
} else {
LOGGER.debug("Including {}", href);
addDebugInfo(href, null);
}
}
if (!href.contains(":")) {
return tryResolveXSL(href, base);
}
String scheme = getScheme(href, base);
URIResolver uriResolver = SUPPORTED_SCHEMES.get(scheme);
if (uriResolver != null) {
return uriResolver.resolve(href, base);
} else { // try to handle as URL, use default resolver for file:// and
try {
InputSource entity = MCREntityResolver.instance().resolveEntity(null, href);
if (entity != null) {
LOGGER.debug("Resolved via EntityResolver: {}", entity.getSystemId());
return new MCRLazyStreamSource(entity::getByteStream, entity.getSystemId());
}
} catch (IOException e) {
LOGGER.debug("Error while resolving uri: {}", href);
}
// http://
if (href.endsWith("/") && scheme.equals("file")) {
//cannot stream directories
return null;
}
StreamSource streamSource = new StreamSource();
streamSource.setSystemId(href);
return streamSource;
}
}
/**
* Show simple transformation from input stream to output stream. Taken from
* Saxon samples (slightly modified)
*
* @param sourceID
* file name of the source file
* @param xslFileResource
* file name of the stylesheet file
* @param result
* the path where the generated file should be written to
*/
public static Result transform(Document sourceXML, String xslFileResource, Result result, Map<String, Object> params)
throws TransformerException, FileNotFoundException {
// Create a transform factory instance. specify saxon for XSLT 2.0 support
TransformerFactory tfactory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", null);
InputStream is = XslTransformer.class.getClassLoader().getResourceAsStream(xslFileResource);
// InputStream xslIS = new BufferedInputStream(new FileInputStream(xslID));
InputStream xslIS = new BufferedInputStream(is);
StreamSource xslSource = new StreamSource(xslIS);
// Create a transformer for the stylesheet.
DOMSource dom = new DOMSource(sourceXML);
xslSource.setSystemId(xslFileResource);
// this method MAY return null although the JavaDoc says it doesn't!
// That can happen when an XSLT 2.0 conformant XSL file is given. To work around this,
// Saxon is specified as impl above which can handle such files
javax.xml.transform.Transformer transformer = tfactory.newTransformer(xslSource);
logger.debug("Transformer impl = " + (transformer == null ? "null" : transformer.getClass().getCanonicalName()));
if(params != null && !params.entrySet().isEmpty()){
for(Entry<String, Object> e : params.entrySet()){
transformer.setParameter(e.getKey(), e.getValue());
}
}
transformer.transform(dom, result);
return result;
}
public static File transformTei(Mets mets) throws JAXBException, FileNotFoundException, TransformerException {
if(mets == null){
throw new IllegalArgumentException("An argument is null!");
}
StreamSource mySrc = new StreamSource();
mySrc.setInputStream(new ByteArrayInputStream(JaxbUtils.marshalToBytes(mets, TrpDocMetadata.class)));
//necessary to use the relative paths in the xslt
mySrc.setSystemId(docPath);
InputStream is = XslTransformer.class.getClassLoader().getResourceAsStream(PAGE_TO_TEI_XSLT);
// InputStream xslIS = new BufferedInputStream(new FileInputStream(xslID));
InputStream xslIS = new BufferedInputStream(is);
StreamSource xslSource = new StreamSource(xslIS);
// das Factory-Pattern unterstützt verschiedene XSLT-Prozessoren
TransformerFactory transFact =
TransformerFactory.newInstance();
Transformer trans;
// try {
trans = transFact.newTransformer(xslSource);
File teiFile = new File(new File(docPath).getParentFile().getAbsolutePath()+"/gh_tei.xml");
trans.transform(mySrc, new StreamResult(new FileOutputStream(teiFile)));
return teiFile;
// } catch (TransformerConfigurationException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (TransformerException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
@Override
public void finish() {
try {
BugCollection bugCollection = getBugCollection();
bugCollection.setWithMessages(true);
// Decorate the XML with messages to display
Document document = bugCollection.toDocument();
// new AddMessages(bugCollection, document).execute();
// Get the stylesheet as a StreamSource.
// First, try to load the stylesheet from the filesystem.
// If that fails, try loading it as a resource.
InputStream xslInputStream = getStylesheetStream(stylesheet);
StreamSource xsl = new StreamSource(xslInputStream);
xsl.setSystemId(stylesheet);
// Create a transformer using the stylesheet
TransformerFactory factory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", null);
Transformer transformer = factory.newTransformer(xsl);
// Source document is the XML generated from the BugCollection
DocumentSource source = new DocumentSource(document);
// Write result to output stream
StreamResult result = new StreamResult(outputStream);
// Do the transformation
transformer.transform(source, result);
} catch (Exception e) {
logError("Could not generate HTML output", e);
fatalException = e;
if (FindBugs.DEBUG) {
e.printStackTrace();
}
}
outputStream.close();
}
public static int detectXsltVersion(URL xsltUrl) throws TransformerConfigurationException {
try {
TransformerPool tpVersion = XmlUtils.getDetectXsltVersionTransformerPool();
StreamSource stylesource = new StreamSource(xsltUrl.openStream());
stylesource.setSystemId(ClassUtils.getCleanedFilePath(xsltUrl.toExternalForm()));
return interpretXsltVersion(tpVersion.transform(stylesource));
} catch (Exception e) {
throw new TransformerConfigurationException(e);
}
}
public File transformTei(Mets mets, String workDir, String exportFilename) throws JAXBException, TransformerException, IOException, SAXException, ParserConfigurationException {
if(mets == null){
throw new IllegalArgumentException("An argument is null!");
}
File teiFile = new File(exportFilename);
try (
InputStream metsIs = new ByteArrayInputStream(JaxbUtils.marshalToBytes(mets, TrpDocMetadata.class));
InputStream xslIS = new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream(PAGE_TO_TEI_XSLT));
OutputStream teiOs = new FileOutputStream(teiFile);
) {
StreamSource mySrc = new StreamSource(metsIs);
//necessary to use the relative paths of the mets in the xslt
mySrc.setSystemId(workDir);
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
dFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
InputSource xslInputSource = new InputSource(xslIS);
Document xslDoc = dBuilder.parse(xslInputSource);
DOMSource xslDomSource = new DOMSource(xslDoc);
TransformerFactory transFact = TransformerFactory.newInstance();
//may? this is the only way to dynamically include a xsl in the xsl-source
transFact.setURIResolver(new MyURIResolver(dBuilder));
//would be the short way from MyURIResolver: lambda expression -> brought some .NullPointerException, I/O error reported by XML parser
// transFact.setURIResolver((href, base) -> {
// final InputStream s = DocExporter.class.getClassLoader().getResourceAsStream("xslt/" + href);
// return new StreamSource(s);
// });
Transformer trans = transFact.newTransformer(xslDomSource);
trans.transform(mySrc, new StreamResult(teiOs));
}
return teiFile;
}
public static Transformer createTransformer(URL url, int xsltVersion) throws TransformerConfigurationException, IOException {
StreamSource stylesource = new StreamSource(url.openStream());
stylesource.setSystemId(ClassUtils.getCleanedFilePath(url.toExternalForm()));
return createTransformer(stylesource, xsltVersion);
}