gpt4 book ai didi

osgi - 如何从 OSGi Bundle 中使用 Java 扩展执行 XSLT 转换

转载 作者:行者123 更新时间:2023-12-05 01:37:01 25 4
gpt4 key购买 nike

我们正在将现有代码转换为 OSGi 环境。在我们的一个(尚未成为)OSGi 包中,我们有执行 XSLT 转换的代码。一段 XSLT 包括一个 java 扩展函数来创建一个唯一的数值。 Java 类也驻留在包中。这是样式表的片段:

<xsl:template match="m:property">
<xsl:variable name="uniqueDataStreamName" select="concat(../@id,'/',@name)" />
<xsl:variable name="uniqueDataStreamId"
select="java:com.xyz.TransformationUtils.makeDataStreamIdFromUniqueName($uniqueDataStreamName)" />
<data id="{number($uniqueDataStreamId)}">
<tag>
<xsl:value-of select="$uniqueDataStreamName" />
</tag>
<current_value>
<xsl:value-of select="@value" />
</current_value>
</data>

作为引用,这是转换的设置和调用方式:

protected Templates createTemplates(Source xsltSource) {
try {
TransformerFactory tf = TransformerFactory.newInstance();
Templates templates = tf.newTemplates(xsltSource);
return templates;
} catch (TransformerException e) {
throw new RuntimeException(e);
}
}


protected byte[] transform(byte[] input) throws TransformerException {
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
templates.newTransformer().transform(
new StreamSource(new ByteArrayInputStream(input)),
new StreamResult(out));
return out.toByteArray();
}

在非 OSGi 环境中运行时,它可以工作。当在 OSGi 框架中运行时,它会失败,因为无法编译样式表,因为找不到类 TransformationUtils。我有点理解——加载 jaxp 转换器实现的类加载器在我们的包中看不到扩展类。但是,我很难找到解决方案。我试过使用 OSGi:fied Xalan 和 Xerces 包,但无济于事。

我的问题是:如何解决这个问题?可以吗?

最佳答案

答案取决于 XSLT 处理器如何查找扩展类。您可能需要阅读源代码和/或通过调试器运行它才能找到答案。

例如,如果 XSLT 处理器使用线程上下文类加载器 (TCCL),那么这通常会失败,因为 TCCL 在 OSGi 中未定义。您可以通过在调用 XSLT 处理器期间显式设置 TCCL 来解决此问题,例如:

ClassLoader orig = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(MyClass.class.getClassLoader());
try {
// invoke XSLT processor
} finally {
Thread.currentThread.setContextClassLoader(orig);
}

其中 MyClass 是您的包中的一个类,并且具有扩展类的可见性。

在最坏的情况下,处理器可能会使用自己的类加载器查找扩展,即通过简单调用 Class.forName()。在这里做的最好的事情就是痛打图书馆的开发者,因为他们太愚蠢了。完成后,您可以使用片段将扩展类附加到处理器包……这是一个令人讨厌的 hack,但比其他一些可能的令人讨厌的 hack 更好。

关于osgi - 如何从 OSGi Bundle 中使用 Java 扩展执行 XSLT 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7380753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com