下面列出了怎么用javax.xml.transform.stream.StreamSource的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES)
@FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_INTEGER_VALUES)
@FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES)
public void shouldTransformGraphMLV2ToV3ViaXSLT() throws Exception {
final InputStream stylesheet = Thread.currentThread().getContextClassLoader().getResourceAsStream("tp2-to-tp3-graphml.xslt");
final InputStream datafile = getResourceAsStream(GraphMLResourceAccess.class, "tinkerpop-classic-tp2.xml");
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final TransformerFactory tFactory = TransformerFactory.newInstance();
final StreamSource stylesource = new StreamSource(stylesheet);
final Transformer transformer = tFactory.newTransformer(stylesource);
final StreamSource source = new StreamSource(datafile);
final StreamResult result = new StreamResult(output);
transformer.transform(source, result);
final GraphReader reader = GraphMLReader.build().create();
reader.readGraph(new ByteArrayInputStream(output.toByteArray()), graph);
assertClassicGraph(graph, false, true);
}
@Test
public final void testTransform() {
try {
StreamSource input = new StreamSource(getClass().getResourceAsStream("PredicateInKeyTest.xml"));
StreamSource stylesheet = new StreamSource(getClass().getResourceAsStream("PredicateInKeyTest.xsl"));
CharArrayWriter buffer = new CharArrayWriter();
StreamResult output = new StreamResult(buffer);
TransformerFactory.newInstance().newTransformer(stylesheet).transform(input, output);
Assert.assertEquals(buffer.toString(), "0|1|2|3", "XSLT xsl:key implementation is broken!");
// expected success
} catch (Exception e) {
// unexpected failure
e.printStackTrace();
Assert.fail(e.toString());
}
}
/**
* Performs identity transformation.
*/
public static <T extends Result>
T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException {
if (src instanceof StreamSource) {
// work around a bug in JAXP in JDK6u4 and earlier where the namespace processing
// is not turned on by default
StreamSource ssrc = (StreamSource) src;
TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler();
th.setResult(result);
XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader();
reader.setContentHandler(th);
reader.setProperty(LEXICAL_HANDLER_PROPERTY, th);
reader.parse(toInputSource(ssrc));
} else {
newTransformer().transform(src, result);
}
return result;
}
public static String formatMetadata(String input, int indent) {
input = input.replace("> <", "><");
try {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
StringWriter sw = new StringWriter();
xmlOutput.setWriter(sw);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", indent);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "" + indent);
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (IllegalArgumentException | TransformerException e) {
return input;
}
}
@Test
public void readWithTypeMismatchException() throws Exception {
MockHttpInputMessage inputMessage = new MockHttpInputMessage(new byte[0]);
Marshaller marshaller = mock(Marshaller.class);
Unmarshaller unmarshaller = mock(Unmarshaller.class);
given(unmarshaller.unmarshal(isA(StreamSource.class))).willReturn(Integer.valueOf(3));
MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller, unmarshaller);
try {
converter.read(String.class, inputMessage);
fail("Should have thrown HttpMessageNotReadableException");
}
catch (HttpMessageNotReadableException ex) {
assertTrue(ex.getCause() instanceof TypeMismatchException);
}
}
private Authorizers loadAuthorizersConfiguration() throws Exception {
final File authorizersConfigurationFile = properties.getAuthorizerConfigurationFile();
// load the authorizers from the specified file
if (authorizersConfigurationFile.exists()) {
try {
// find the schema
final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = schemaFactory.newSchema(Authorizers.class.getResource(AUTHORIZERS_XSD));
// attempt to unmarshal
final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
unmarshaller.setSchema(schema);
final JAXBElement<Authorizers> element = unmarshaller.unmarshal(new StreamSource(authorizersConfigurationFile), Authorizers.class);
return element.getValue();
} catch (SAXException | JAXBException e) {
throw new Exception("Unable to load the authorizer configuration file at: " + authorizersConfigurationFile.getAbsolutePath(), e);
}
} else {
throw new Exception("Unable to find the authorizer configuration file at " + authorizersConfigurationFile.getAbsolutePath());
}
}
private String modsAsFedoraLabel(InputStream xmlIS, String model) throws Exception {
assertNotNull(xmlIS);
StreamSource streamSource = new StreamSource(xmlIS);
Transformers mt = new Transformers();
Map<String, Object> params = new HashMap<String, Object>();
params.put("MODEL", model);
try {
byte[] contents = mt.transformAsBytes(streamSource, Transformers.Format.ModsAsFedoraLabel, params);
assertNotNull(contents);
String label = new String(contents, "UTF-8");
// System.out.println(label);
return label;
} finally {
close(xmlIS);
}
}
public POCDMT000040ClinicalDocument unmarshaller(String xml) throws JAXBException {
long start = 0;
if ( LOGGER.isDebugEnabled() ) {
start = System.currentTimeMillis();
}
POCDMT000040ClinicalDocument result = null;
try {
StringReader reader = new StringReader(xml);
Unmarshaller u = jaxbContext.createUnmarshaller();
result = u.unmarshal(new StreamSource(reader), POCDMT000040ClinicalDocument.class).getValue();
}
catch (JAXBException e) {
LOGGER.error("UnMarshallointi epäonnistui.", e.getMessage());
throw e;
}
if ( LOGGER.isDebugEnabled() ) {
long end = System.currentTimeMillis();
LOGGER.debug("Unmarshalling took " + (end - start) + " ms.");
}
return result;
}
/**
* Remove all namespaces from the XML source into the XML output.
*
* @param xmlSource the XML source
* @throws TransformerException the TransformerException
*/
public static String removeNamespace(String xmlSource) throws TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
InputStream xsltRemoveNamespace = XmlUtils.class.getResourceAsStream("/remove-namespace.xslt");
if (xsltRemoveNamespace == null)
throw new ExceptionInInitializerError(new FileNotFoundException("No XSLT resource is found!"));
Templates transformer = factory.newTemplates(new StreamSource(xsltRemoveNamespace));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
Source src = new StreamSource(new StringReader(xmlSource));
transformer.newTransformer().transform(src, result);
String newXml = baos.toString();
try {
xsltRemoveNamespace.close();
baos.close();
} catch (IOException e) {
//eat it
}
return newXml;
}
Transformer createTransformer() throws Exception {
// Prepare sources for transormation
Source xslsrc = new StreamSource(new StringReader(xsl));
// Create factory and transformer
TransformerFactory tf;
// newTransformer() method doc states that different transformer
// factories can be used concurrently by different Threads.
synchronized (TransformerFactory.class) {
tf = TransformerFactory.newInstance();
}
Transformer t = tf.newTransformer(xslsrc);
// Set URI Resolver to return the newly constructed xml
// stream source object from xml test string
t.setURIResolver((String href, String base) -> new StreamSource(new StringReader(xml)));
return t;
}
@Override
public ValidationResult validate(final String subject, final String input, final ValidationContext validationContext) {
final Tuple<String, ValidationResult> lastResult = this.cachedResult;
if (lastResult != null && lastResult.getKey().equals(input)) {
return lastResult.getValue();
} else {
String error = null;
final File stylesheet = new File(input);
final TransformerFactory tFactory = new net.sf.saxon.TransformerFactoryImpl();
final StreamSource styleSource = new StreamSource(stylesheet);
try {
tFactory.newTransformer(styleSource);
} catch (final Exception e) {
error = e.toString();
}
this.cachedResult = new Tuple<>(input, new ValidationResult.Builder()
.input(input)
.subject(subject)
.valid(error == null)
.explanation(error)
.build());
return this.cachedResult.getValue();
}
}
/**
* Returns a list of QName's which are referenced in the ODE deploy.xml File as invoked service.<br>
*
* @param deployXML a file object of a valid deploy.xml File
* @return a list of QNames which represent the PortTypes used by the BPEL process to invoke operations
* @throws JAXBException if the JAXB parser couldn't work properly
*/
private List<QName> getInvokedDeployXMLPorts(final File deployXML) throws JAXBException {
// http://svn.apache.org/viewvc/ode/trunk/bpel-schemas/src/main/xsd/
// grabbed that and using jaxb
final List<QName> qnames = new LinkedList<>();
final JAXBContext context =
JAXBContext.newInstance("org.apache.ode.schemas.dd._2007._03", this.getClass().getClassLoader());
final Unmarshaller unmarshaller = context.createUnmarshaller();
final TDeployment deploy = unmarshaller.unmarshal(new StreamSource(deployXML), TDeployment.class).getValue();
for (final org.apache.ode.schemas.dd._2007._03.TDeployment.Process process : deploy.getProcess()) {
for (final TInvoke invoke : process.getInvoke()) {
final QName serviceName = invoke.getService().getName();
// add only qnames which aren't from the plan itself
if (!serviceName.getNamespaceURI().equals(process.getName().getNamespaceURI())) {
qnames.add(new QName(serviceName.getNamespaceURI(), invoke.getService().getPort()));
}
}
}
return qnames;
}
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();
}
/**
* Performs identity transformation.
*/
public static <T extends Result>
T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException {
if (src instanceof StreamSource) {
// work around a bug in JAXP in JDK6u4 and earlier where the namespace processing
// is not turned on by default
StreamSource ssrc = (StreamSource) src;
TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler();
th.setResult(result);
XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader();
reader.setContentHandler(th);
reader.setProperty(LEXICAL_HANDLER_PROPERTY, th);
reader.parse(toInputSource(ssrc));
} else {
newTransformer().transform(src, result);
}
return result;
}
@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();
}
@Test
public void shouldGenerateValidOutputSchemasets() throws IOException {
final DataShape output = generator.createShapeFromResponse(json, openApiDoc, operation);
if (output.getKind() != DataShapeKinds.XML_SCHEMA) {
return;
}
final Validator validator = createValidator();
try (InputStream in = UnifiedXmlDataShapeGenerator.class.getResourceAsStream("/openapi/v2/atlas-xml-schemaset-model-v2.xsd")) {
validator.setSchemaSource(new StreamSource(in));
final String outputSpecification = output.getSpecification();
final ValidationResult result = validator.validateInstance(source(outputSpecification));
assertThat(result.isValid())//
.as("Non valid output XML schemaset was generated for specification: %s, operation: %s, errors: %s", specification,
operation.operationId,
StreamSupport.stream(result.getProblems().spliterator(), false).map(ValidationProblem::toString)//
.collect(Collectors.joining("\n")))//
.isTrue();
}
}
@Test
public void testOaiMarcAsMarc() throws Exception {
InputStream goldenIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsMarcXml.xml");
assertNotNull(goldenIS);
InputStream xmlIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsOaiMarc.xml");
assertNotNull(xmlIS);
StreamSource streamSource = new StreamSource(xmlIS);
Transformers mt = new Transformers();
try {
byte[] contents = mt.transformAsBytes(streamSource, Transformers.Format.OaimarcAsMarc21slim);
assertNotNull(contents);
// System.out.println(new String(contents, "UTF-8"));
XMLAssert.assertXMLEqual(new InputSource(goldenIS), new InputSource(new ByteArrayInputStream(contents)));
} finally {
close(xmlIS);
close(goldenIS);
}
}
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();
}
public static void getHelpItems( OutputStream out, Locale locale )
{
try
{
ClassPathResource classPathResource = resolveHelpFileResource( locale );
Source source = new StreamSource( classPathResource.getInputStream(), ENCODING_UTF8 );
Result result = new StreamResult( out );
getTransformer( "helpitems_stylesheet.xsl" ).transform( source, result );
}
catch ( Exception ex )
{
throw new RuntimeException( "Failed to get help content", ex );
}
}
public PropertiesConfig(String configXML) {
if (configXML != null) {
try {
if (m_sp == null) {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(false);
spf.setNamespaceAware(true);
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
InputStream = getClass().getResourceAsStream("/com/openbravo/pos/templates/Schema.Ticket.xsd");
spf.setSchema(schemaFactory.newSchema(new Source[]{new StreamSource(InputStream)}));
m_sp = spf.newSAXParser();
m_sr = m_sp.getXMLReader();
m_sr.setContentHandler(new ConfigurationHandler());
}
m_sp.parse(new InputSource(new StringReader(configXML)), new ConfigurationHandler());
m_sr.parse(new InputSource(new StringReader(configXML)));
} catch (ParserConfigurationException ePC) {
logger.log(Level.WARNING, LocalRes.getIntString("exception.parserconfig"), ePC);
} catch (SAXException eSAX) {
logger.log(Level.WARNING, LocalRes.getIntString("exception.xmlfile"), eSAX);
} catch (IOException eIO) {
logger.log(Level.WARNING, LocalRes.getIntString("exception.iofile"), eIO);
}
}
}
/**
* Attempt to obtain a SAX InputSource object from a Source
* object.
*
* @param source Must be a non-null Source reference.
*
* @return An InputSource, or null if Source can not be converted.
*/
public static InputSource sourceToInputSource(Source source) {
if (source instanceof SAXSource) {
return ((SAXSource) source).getInputSource();
} else if (source instanceof StreamSource) {
StreamSource ss = (StreamSource) source;
InputSource isource = new InputSource(ss.getSystemId());
isource.setByteStream(ss.getInputStream());
isource.setCharacterStream(ss.getReader());
isource.setPublicId(ss.getPublicId());
return isource;
} else {
return null;
}
}
XMLInputSource jaxpSourcetoXMLInputSource(Source source){
if(source instanceof StreamSource){
StreamSource stSource = (StreamSource)source;
String systemId = stSource.getSystemId();
String publicId = stSource.getPublicId();
InputStream istream = stSource.getInputStream();
Reader reader = stSource.getReader();
if(istream != null){
return new XMLInputSource(publicId, systemId, null, istream, null);
}
else if(reader != null){
return new XMLInputSource(publicId, systemId,null, reader, null);
}else{
return new XMLInputSource(publicId, systemId, null);
}
}
throw new UnsupportedOperationException("Cannot create " +
"XMLStreamReader or XMLEventReader from a " +
source.getClass().getName());
}
public static void generateTryit(Source xmlIn, Result result, Map paramMap)
throws TransformerException {
InputStream tryItXSLTStream =
Util.class.getClassLoader().getResourceAsStream(Util.TRYIT_XSL_LOCATION);
Source tryItXSLSource = new StreamSource(tryItXSLTStream);
Util.transform(xmlIn, tryItXSLSource, result, paramMap, new XSLTURIResolver());
}
@Override
Source toReturnValue(Packet response) {
Message msg = response.getMessage();
try {
return new StreamSource(XMLMessage.getDataSource(msg, binding.getFeatures()).getInputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
byte[] getOriginalBytes(InputStream in) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Source source = new StreamSource(in);
Result out = new StreamResult(baos);
TransformerFactory factory = tf;
if (factory == null) {
factory = TransformerFactory.newInstance();
factory.setURIResolver(new URIResolverImpl());
}
Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
transformer.transform(source, out);
in.close();
return baos.toByteArray();
}
private static void cleanUnMarshaller() {
try {
String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><entity-mappings/>";
MODELER_UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xmlStr)));
} catch (JAXBException ex) {
System.err.println(ex);
}
}
@Override
public <T> T deserialize( ModuleDescriptor module, ValueType valueType, Reader state )
{
try
{
DOMResult domResult = new DOMResult();
xmlFactories.normalizationTransformer().transform( new StreamSource( state ), domResult );
Node node = domResult.getNode();
return fromXml( module, valueType, node );
}
catch( TransformerException ex )
{
throw new SerializationException( "Unable to read XML document", ex );
}
}
private ValidatorHandler createValidatorHandler(String xsd) throws SAXException {
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
StringReader reader = new StringReader(xsd);
StreamSource xsdSource = new StreamSource(reader);
Schema schema = schemaFactory.newSchema(xsdSource);
return schema.newValidatorHandler();
}
private Tenants unmarshallTenants() throws JAXBException {
final Unmarshaller unmarshaller = JAXB_TENANTS_CONTEXT.createUnmarshaller();
unmarshaller.setSchema(tenantsSchema);
final JAXBElement<Tenants> element = unmarshaller.unmarshal(new StreamSource(tenantsFile), Tenants.class);
return element.getValue();
}
/**
* Tests conversion of {@link PaymentRequest} from XML file for release payment types.
*/
@Test
public void paymentRequestXmlFromFileReleaseTest() {
File file = new File(this.getClass().getResource(RELEASE_PAYMENT_REQUEST_XML_PATH).getPath());
StreamSource source = new StreamSource(file);
//Convert from XML back to PaymentRequest
PaymentRequest fromXmlRequest = new PaymentRequest().fromXml(source);
checkUnmarshalledReleasePaymentRequest(fromXmlRequest);
}