下面列出了怎么用javax.xml.transform.Source的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Create a Transformer object that from the input stylesheet
* Uses the com.sun.org.apache.xalan.internal.processor.TransformerFactory.
* @param source the stylesheet.
* @return A Transformer object.
*/
public Transformer newTransformer(Source source) throws
TransformerConfigurationException
{
if (_xalanFactory == null) {
createXalanTransformerFactory();
}
if (_errorlistener != null) {
_xalanFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xalanFactory.setURIResolver(_uriresolver);
}
_currFactory = _xalanFactory;
return _currFactory.newTransformer(source);
}
private void createMessagePartInfo(OperationInfo oi, Class<?> type, QName qname, Method m,
boolean input) {
if (type == void.class || Source.class.isAssignableFrom(type)) {
return;
}
if (InjectionUtils.isPrimitive(type) || Response.class == type) {
return;
}
QName mName = new QName(qname.getNamespaceURI(),
(input ? "in" : "out") + m.getName());
MessageInfo ms = oi.createMessage(mName,
input ? MessageInfo.Type.INPUT : MessageInfo.Type.OUTPUT);
if (input) {
oi.setInput("in", ms);
} else {
oi.setOutput("out", ms);
}
QName mpQName = JAXRSUtils.getClassQName(type);
MessagePartInfo mpi = ms.addMessagePart(mpQName);
mpi.setConcreteName(mpQName);
mpi.setTypeQName(mpQName);
mpi.setTypeClass(type);
}
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 void transform(File inputXml, File phrasesFile, File outputXml)
throws TransformerException {
final File parentFile = outputXml.getParentFile();
if (parentFile != null) {
parentFile.mkdirs();
}
final Source xmlSource = new javax.xml.transform.stream.StreamSource(inputXml);
final InputStream xsltFile =
getClass().getClassLoader().getResourceAsStream("xsl/unified2orchestra.xslt");
final Source xsltSource = new javax.xml.transform.stream.StreamSource(xsltFile);
final Result result = new javax.xml.transform.stream.StreamResult(outputXml);
final TransformerFactory transFact = new TransformerFactoryImpl();
final Transformer trans = transFact.newTransformer(xsltSource);
trans.setParameter("phrases-file", phrasesFile.toURI().toString());
trans.transform(xmlSource, result);
}
public static String prettyFormat(String input, String indent) {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", indent);
transformer.transform(xmlInput, new StreamResult(stringWriter));
return stringWriter.toString().trim();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void testConcurrentTransformations() throws Exception {
final TransformerFactory tf = TransformerFactory.newInstance();
final Source xslsrc = new StreamSource(new StringReader(XSL));
final Templates tmpl = tf.newTemplates(xslsrc);
concurrentTestPassed.set(true);
// Execute multiple TestWorker tasks
for (int id = 0; id < THREADS_COUNT; id++) {
EXECUTOR.execute(new TransformerThread(tmpl.newTransformer(), id));
}
// Initiate shutdown of previously submitted task
EXECUTOR.shutdown();
// Wait for termination of submitted tasks
if (!EXECUTOR.awaitTermination(THREADS_COUNT, TimeUnit.SECONDS)) {
// If not all tasks terminates during the time out force them to shutdown
EXECUTOR.shutdownNow();
}
// Check if all transformation threads generated the correct namespace prefix
assertTrue(concurrentTestPassed.get());
}
public static void transform(String stylesheet,
Source src,
Result res,
HashMap<String, String> params) throws Exception {
Transformer transformer = getTransformer(stylesheet);
transformer.clearParameters();
if (params != null && params.size() > 0) {
Iterator<String> itKeys = params.keySet().iterator();
while (itKeys.hasNext()) {
String key = itKeys.next();
String value = params.get(key);
transformer.setParameter(key,
value);
}
}
transformer.transform(src,
res);
}
public static String getSourceAsString(Source s) throws Exception {
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
try (Writer out = new StringWriter()) {
StreamResult streamResult = new StreamResult();
streamResult.setWriter(out);
transformer.transform(s, streamResult);
return streamResult.getWriter().toString();
}
} catch (TransformerException te) {
if ("javax.xml.transform.stax.StAXSource".equals(s.getClass().getName())) {
//on java6, we will get this class if "stax" is configured
//for the preferred type. However, older xalans don't know about it
//we'll manually do it
XMLStreamReader r = (XMLStreamReader)s.getClass().getMethod("getXMLStreamReader").invoke(s);
return StaxUtils.toString(StaxUtils.read(r).getDocumentElement());
}
throw te;
}
}
/**
* Checks the correctness of the XML Schema documents and return true
* if it's OK.
*
* <p>
* This method performs a weaker version of the tests where error messages
* are provided without line number information. So whenever possible
* use {@link SchemaConstraintChecker}.
*
* @see SchemaConstraintChecker
*/
public boolean checkSchemaCorrectness(ErrorReceiver errorHandler) {
try {
boolean disableXmlSecurity = false;
if (options != null) {
disableXmlSecurity = options.disableXmlSecurity;
}
SchemaFactory sf = XmlFactory.createSchemaFactory(W3C_XML_SCHEMA_NS_URI, disableXmlSecurity);
ErrorReceiverFilter filter = new ErrorReceiverFilter(errorHandler);
sf.setErrorHandler(filter);
Set<String> roots = getRootDocuments();
Source[] sources = new Source[roots.size()];
int i=0;
for (String root : roots) {
sources[i++] = new DOMSource(get(root),root);
}
sf.newSchema(sources);
return !filter.hadError();
} catch (SAXException e) {
// the errors should have been reported
return false;
}
}
private String getSourceAsString(Source s) {
String result = "";
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
OutputStream out = new ByteArrayOutputStream();
StreamResult streamResult = new StreamResult();
streamResult.setOutputStream(out);
transformer.transform(s, streamResult);
return streamResult.getOutputStream().toString();
} catch (Exception e) {
//do nothing
}
return result;
}
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();
}
/**
* Get the source tree from the a base URL and a URL string.
*
* @param base The base URI to use if the urlString is relative.
* @param urlString An absolute or relative URL string.
* @param locator The location of the caller, for diagnostic purposes.
*
* @return should be a non-null reference to the node identified by the
* base and urlString.
*
* @throws TransformerException If the URL can not resolve to a node.
*/
public int getSourceTree(
String base, String urlString, SourceLocator locator, XPathContext xctxt)
throws TransformerException
{
// System.out.println("getSourceTree");
try
{
Source source = this.resolveURI(base, urlString, locator);
// System.out.println("getSourceTree - base: "+base+", urlString: "+urlString+", source: "+source.getSystemId());
return getSourceTree(source, locator, xctxt);
}
catch (IOException ioe)
{
throw new TransformerException(ioe.getMessage(), locator, ioe);
}
/* catch (TransformerException te)
{
throw new TransformerException(te.getMessage(), locator, te);
}*/
}
@Override
protected void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Templates templates = this.cachedTemplates;
if (templates == null) {
templates = loadTemplates();
}
Transformer transformer = createTransformer(templates);
configureTransformer(model, response, transformer);
configureResponse(model, response, transformer);
Source source = null;
try {
source = locateSource(model);
if (source == null) {
throw new IllegalArgumentException("Unable to locate Source object in model: " + model);
}
transformer.transform(source, createResult(response));
}
finally {
closeSourceIfNecessary(source);
}
}
public static void convertSourceToObject(Message message) {
List<Object> content = CastUtils.cast(message.getContent(List.class));
if (content == null || content.isEmpty()) {
// nothing to convert
return;
}
// only supporting the wrapped style for now (one pojo <-> one source)
Source source = (Source)content.get(0);
DataReader<XMLStreamReader> reader =
message.getExchange().getService().getDataBinding().createReader(XMLStreamReader.class);
MessagePartInfo mpi = getMessageInfo(message).getMessagePart(0);
XMLStreamReader streamReader = null;
Object wrappedObject = null;
try {
streamReader = StaxUtils.createXMLStreamReader(source);
wrappedObject = reader.read(mpi, streamReader);
} finally {
try {
StaxUtils.close(streamReader);
} catch (XMLStreamException e) {
// Ignore
}
}
MessageContentsList parameters = new MessageContentsList();
parameters.put(mpi, wrappedObject);
message.setContent(List.class, parameters);
}
/**
* Build instance of MCRSourceContent by resolving via {@link MCRURIResolver}
*
* @throws TransformerException
* thrown by {@link MCRURIResolver#resolve(String, String)}
*/
public static MCRSourceContent getInstance(String uri) throws TransformerException {
Source source = URI_RESOLVER.resolve(uri, null);
if (source == null) {
return null;
}
return new MCRSourceContent(source);
}
private static String toString(Source response) throws TransformerException, IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(response, new StreamResult(bos));
bos.close();
return new String(bos.toByteArray());
}
public SAX2RTFDTM(DTMManager mgr, Source source, int dtmIdentity,
DTMWSFilter whiteSpaceFilter,
XMLStringFactory xstringfactory,
boolean doIndexing)
{
super(mgr, source, dtmIdentity, whiteSpaceFilter,
xstringfactory, doIndexing);
// NEVER track source locators for RTFs; they aren't meaningful. I think.
// (If we did track them, we'd need to tail-prune these too.)
//com.sun.org.apache.xalan.internal.processor.TransformerFactoryImpl.m_source_location;
m_useSourceLocationProperty=false;
m_sourceSystemId = (m_useSourceLocationProperty) ? new StringVector()
: null;
m_sourceLine = (m_useSourceLocationProperty) ? new IntVector() : null;
m_sourceColumn = (m_useSourceLocationProperty) ? new IntVector() : null;
// Record initial sizes of fields that are pushed and restored
// for RTF tail-pruning. More entries can be popped than pushed, so
// we need this to mark the primordial state of the DTM.
m_emptyNodeCount = m_size;
m_emptyNSDeclSetCount = (m_namespaceDeclSets == null)
? 0 : m_namespaceDeclSets.size();
m_emptyNSDeclSetElemsCount = (m_namespaceDeclSetElements == null)
? 0 : m_namespaceDeclSetElements.size();
m_emptyDataCount = m_data.size();
m_emptyCharsCount = m_chars.size();
m_emptyDataQNCount = m_dataOrQName.size();
}
/**
* Test case for multiple tags.
* @exception Exception
* test failed
*/
@Test
public void testMultipleTags() throws Exception {
final TransformerFactory factory = TransformerFactory.newInstance();
final Transformer transformer = factory.newTransformer();
final InputStream in =
TestSmlInterpretationExtractor.class.getResourceAsStream(
"sml-multiple-tags.xml");
final Source source = new StreamSource(in);
final SmlInterpretationExtractor extractor =
new SmlInterpretationExtractor();
final Result result = new SAXResult(extractor);
transformer.transform(source, result);
Assert.assertEquals("Hello Dirk",
extractor.getUtterance());
Assert.assertEquals(0.6734907, extractor.getConfidence(),
MAX_CONFIDENCE_DIFF);
final List<SmlInterpretation> interpretations =
extractor.getInterpretations();
Assert.assertEquals(2, interpretations.size());
final SmlInterpretation greet = interpretations.get(0);
Assert.assertEquals("greet", greet.getTag());
Assert.assertEquals("general", greet.getValue());
Assert.assertEquals(2.069468E-02f, greet.getConfidence(),
MAX_CONFIDENCE_DIFF);
final SmlInterpretation who = interpretations.get(1);
Assert.assertEquals("who", who.getTag());
Assert.assertEquals("Projectmanager", who.getValue());
Assert.assertEquals(2.069468E-02f, who.getConfidence(),
MAX_CONFIDENCE_DIFF);
Assert.assertEquals("", extractor.getUtteranceTag());
}
private Source getSource(Object payload) {
if (payload instanceof byte[]) {
return new StreamSource(new ByteArrayInputStream((byte[]) payload));
}
else {
return new StreamSource(new StringReader((String) payload));
}
}
/**
* Initializes the filter.
*/
protected void initializeFilter( InputStream filterInput, OutputStream filterOutput)
{
try
{
// Create Transformer object.
Source transform = getTransform();
if( transform == null)
{
throw new IllegalStateException( "No XSLT transform specified");
}
TransformerFactory factory = TransformerFactory.newInstance();
factory.setErrorListener( this);
transformer_ = factory.newTransformer( transform);
transformer_.setErrorListener( this);
if( transformParams_ != null)
{
for( String paramName : transformParams_.keySet())
{
transformer_.setParameter( paramName, transformParams_.get( paramName));
}
}
transformSource_ = new StreamSource( filterInput);
transformResult_ = new StreamResult( filterOutput);
}
catch( Exception e)
{
throw new RuntimeException( "Can't initialize filter", e);
}
}
public Source asSource() {
try {
return new StreamSource(dh.getInputStream());
} catch (IOException e) {
throw new WebServiceException(e);
}
}
/**
* Validate the input file against a schema
* @param configStream
* @throws SAXException
* @throws IOException
*/
public void schemaValidate(InputStream configStream) throws SAXException, IOException
{
Validator validator = schemaValidator();
Source xmlSource = new StreamSource(configStream);
validator.validate(xmlSource);
}
/**
* Convert inputsource to string. Used on InputSourceHandle
*
* @param fileRead
* @return
* @throws IOException
* @throws TransformerException
*/
public String convertInputSourceToString(InputSource fileRead) throws IOException, TransformerException
{
Source saxsrc = new SAXSource(fileRead);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(saxsrc, new StreamResult(writer));
String output = writer.getBuffer().toString();
return output;
}
private void generateXSDForConnector(final File connectorToTransform)
throws URISyntaxException, IOException, TransformerException {
if (xslTemplate == null) {
final TransformerFactory transFact = TransformerFactory.newInstance();
final URL xsltUrl = ConnectorPlugin.getDefault().getBundle().getEntry("transfo/genConnectorsXSD.xsl");
final File xsltFileoriginal = new File(FileLocator.toFileURL(xsltUrl).getFile());
final Source xsltSource = new StreamSource(xsltFileoriginal);
xslTemplate = transFact.newTemplates(xsltSource);
}
//FIXME: this is only a workaround because currently we can't serialize the xml file in a way that both EMF and xslt can handle it correctly
// see http://java.dzone.com/articles/emf-reading-model-xml-%E2%80%93-how
final File connectorToTransformWC = File.createTempFile(connectorToTransform.getName(), "");
FileUtil.copy(connectorToTransform, connectorToTransformWC);
FileUtil.replaceStringInFile(connectorToTransformWC,
"xmlns:definition=\"http://www.bonitasoft.org/ns/connector/definition/6.0\"",
"xmlns=\"http://www.bonitasoft.org/ns/connector/definition/6.0\" xmlns:definition=\"http://www.bonitasoft.org/ns/connector/definition/6.0\"");
final Source xmlSource = new StreamSource(connectorToTransformWC);
final String generatedXsdName = connectorToTransform.getName() + "connectors.xsd";
final File connectorsDefFolder = new File(
destBpmnFile.getParentFile().getAbsolutePath() + File.separator + "connectorDefs");
if (!connectorsDefFolder.exists()) {
connectorsDefFolder.mkdirs();
}
try (final OutputStream stream = new FileOutputStream(
new File(connectorsDefFolder.getAbsolutePath(), generatedXsdName))) {
final Result result = new StreamResult(stream);
final Transformer transformer = xslTemplate.newTransformer();
transformer.setParameter("indent", true);
transformer.transform(xmlSource, result);
} finally {
connectorToTransformWC.delete();
}
}
public Source parse(CharSequence text) throws SAXException {
try {
if(text instanceof Base64Data)
return new DataSourceSource( ((Base64Data)text).getDataHandler() );
else
return new DataSourceSource(new ByteArrayDataSource(decodeBase64(text),
UnmarshallingContext.getInstance().getXMIMEContentType()));
} catch (MimeTypeParseException e) {
UnmarshallingContext.getInstance().handleError(e);
return null;
}
}
private boolean verifyWriterCorrect() throws Exception {
final String IDENTITY_XSLT_WITH_INDENT =
"<xsl:stylesheet version='1.0' " + // NOI18N
"xmlns:xsl='http://www.w3.org/1999/XSL/Transform' " + // NOI18N
"xmlns:xalan='http://xml.apache.org/xslt' " + // NOI18N
"exclude-result-prefixes='xalan'>" + // NOI18N
"<xsl:output method='xml' indent='yes' xalan:indent-amount='4'/>" + // NOI18N
"<xsl:template match='@*|node()'>" + // NOI18N
"<xsl:copy>" + // NOI18N
"<xsl:apply-templates select='@*|node()'/>" + // NOI18N
"</xsl:copy>" + // NOI18N
"</xsl:template>" + // NOI18N
"</xsl:stylesheet>"; // NOI18N
String data = "<root xmlns='root'/>"; // NOI18N
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(data)));
doc.getDocumentElement().appendChild(doc.createElementNS("child", "child")); // NOI18N
Transformer t = TransformerFactory.newInstance().newTransformer(
new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
Source source = new DOMSource(doc);
CharArrayWriter output = new CharArrayWriter();
Result result = new StreamResult(output);
t.transform(source, result);
output.close();
String text = output.toString();
return text.indexOf("\"child\"") != (-1) || text.indexOf("'child'") != (-1); // NOI18N
}
static XMLProviderArgumentBuilder createBuilder(ProviderEndpointModel model, WSBinding binding) {
if (model.mode == Service.Mode.PAYLOAD) {
return new PayloadSource();
} else {
if(model.datatype==Source.class)
return new PayloadSource();
if(model.datatype== DataSource.class)
return new DataSourceParameter(binding);
throw new WebServiceException(ServerMessages.PROVIDER_INVALID_PARAMETER_TYPE(model.implClass,model.datatype));
}
}
private Source getSource(Object payload) {
if (payload instanceof byte[]) {
return new StreamSource(new ByteArrayInputStream((byte[]) payload));
}
else {
return new StreamSource(new StringReader((String) payload));
}
}
/**
* Gets the attachment as a {@link javax.xml.transform.Source}.
* Note that there's no guarantee that the attachment is actually an XML.
*/
public Source asSource() {
try {
return new StreamSource(ap.getRawContent());
} catch (SOAPException e) {
throw new WebServiceException(e);
}
}
/**
* Construct a SAX2DTM2 object using the given block size.
*/
public SAX2DTM2(DTMManager mgr, Source source, int dtmIdentity,
DTMWSFilter whiteSpaceFilter,
XMLStringFactory xstringfactory,
boolean doIndexing,
int blocksize,
boolean usePrevsib,
boolean buildIdIndex,
boolean newNameTable)
{
super(mgr, source, dtmIdentity, whiteSpaceFilter,
xstringfactory, doIndexing, blocksize, usePrevsib, newNameTable);
// Initialize the values of m_SHIFT and m_MASK.
int shift;
for(shift=0; (blocksize>>>=1) != 0; ++shift);
m_blocksize = 1<<shift;
m_SHIFT = shift;
m_MASK = m_blocksize - 1;
m_buildIdIndex = buildIdIndex;
// Some documents do not have attribute nodes. That is why
// we set the initial size of this Vector to be small and set
// the increment to a bigger number.
m_values = new Vector(32, 512);
m_maxNodeIndex = 1 << DTMManager.IDENT_DTM_NODE_BITS;
// Set the map0 values in the constructor.
m_exptype_map0 = m_exptype.getMap0();
m_nextsib_map0 = m_nextsib.getMap0();
m_firstch_map0 = m_firstch.getMap0();
m_parent_map0 = m_parent.getMap0();
}