private XMLReader createReader() throws SAXException { try { SAXParserFactory pfactory = SAXParserFactory.newInstance(); pfactory.setValidating(true); pfactory.setNamespaceAware(true); // Enable schema validation SchemaFactory sfactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); InputStream stream = Parser.class.getResourceAsStream("graphdocument.xsd"); pfactory.setSchema(sfactory.newSchema(new Source[]{new StreamSource(stream)})); return pfactory.newSAXParser().getXMLReader(); } catch (ParserConfigurationException ex) { throw new SAXException(ex); } }
/** * xml 格式化 * * @param xml 要格式化的 xml 字符串 * @return 格式化后的新字符串 */ public static String xmlFormat(String xml) { if (TextUtils.isEmpty(xml)) { return "Empty/Null xml content"; } String message; try { Source xmlInput = new StreamSource(new StringReader(xml)); StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, xmlOutput); message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n"); } catch (TransformerException e) { message = xml; } return message; }
@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; } }
Object toReturnValue(Packet response) { try { Unmarshaller unmarshaller = jaxbcontext.createUnmarshaller(); Message msg = response.getMessage(); switch (mode) { case PAYLOAD: return msg.<Object>readPayloadAsJAXB(unmarshaller); case MESSAGE: Source result = msg.readEnvelopeAsSource(); return unmarshaller.unmarshal(result); default: throw new WebServiceException("Unrecognized dispatch mode"); } } catch (JAXBException e) { throw new WebServiceException(e); } }
/** * Reads document description with a given doi from the Scopus API. * * * * */ public Source resolve(String href, String base) throws TransformerException { String doi = href.substring(href.indexOf(":") + 1); LOGGER.debug("Reading MCRContent with DOI " + doi); ScopusConnector connection = new ScopusConnector(); try { MCRContent content = connection.getPublicationByDOI(doi); if (content == null) { return null; } MCRXSL2XMLTransformer transformer = new MCRXSL2XMLTransformer("xsl/scopus2mods.xsl"); MCRContent mods = transformer.transform(content); LOGGER.debug("end resolving " + href); return mods.getSource(); } catch (IOException e) { throw new TransformerException(e); } }
/** * Transforms the XML content to XHTML/HTML format string with the XSL. * * @param payload the XML payload to convert * @param xsltFile the XML stylesheet file * @return the transformed XHTML/HTML format string * @throws AlipayApiException problem converting XML to HTML */ public static String xmlToHtml(String payload, File xsltFile) throws AlipayApiException { String result = null; try { Source template = new StreamSource(xsltFile); Transformer transformer = TransformerFactory.newInstance().newTransformer(template); Properties props = transformer.getOutputProperties(); props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES); transformer.setOutputProperties(props); StreamSource source = new StreamSource(new StringReader(payload)); StreamResult sr = new StreamResult(new StringWriter()); transformer.transform(source, sr); result = sr.getWriter().toString(); } catch (TransformerException e) { throw new AlipayApiException("XML_TRANSFORM_ERROR", e); } return result; }
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()); }
/** * 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); }
public static String formatXml(String xml) { String formatted = null; if (xml == null || xml.trim().length() == 0) { return formatted; } try { Source xmlInput = new StreamSource(new StringReader(xml)); StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(XML_INDENT)); transformer.transform(xmlInput, xmlOutput); formatted = xmlOutput.getWriter().toString().replaceFirst(">", ">" + XPrinter.lineSeparator); } catch (Exception e) { } return formatted; }
/** * Write an XML document to a Writer */ public static void writeDocument(Document doc, Writer writer) throws IOException { final Source source = new DOMSource(doc); // Prepare the output file final Result result = new StreamResult(writer); // Write the DOM document to the file try { final Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$ xformer.transform(source, result); } catch (TransformerException e) { // FIXME: switch to IOException(Throwable) ctor in Java 1.6 throw (IOException) new IOException().initCause(e); } }
public static String formatXml(String xml) { String formatted = null; if (xml == null || xml.trim().length() == 0) { return formatted; } try { Source xmlInput = new StreamSource(new StringReader(xml)); StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(XML_INDENT)); transformer.transform(xmlInput, xmlOutput); formatted = xmlOutput.getWriter().toString().replaceFirst(">", ">" + XPrinter.lineSeparator); } catch (Exception e) { e.printStackTrace(); } return formatted; }
/** * Transforms the XML content to XHTML/HTML format string with the XSL. * * @param payload the XML payload to convert * @param xsltFile the XML stylesheet file * @return the transformed XHTML/HTML format string * @throws AlipayApiException problem converting XML to HTML */ public static String xmlToHtml(String payload, File xsltFile) throws AlipayApiException { String result = null; try { Source template = new StreamSource(xsltFile); Transformer transformer = TransformerFactory.newInstance() .newTransformer(template); Properties props = transformer.getOutputProperties(); props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES); transformer.setOutputProperties(props); StreamSource source = new StreamSource(new StringReader(payload)); StreamResult sr = new StreamResult(new StringWriter()); transformer.transform(source, sr); result = sr.getWriter().toString(); } catch (TransformerException e) { throw new AlipayApiException("XML_TRANSFORM_ERROR", e); } return result; }
/** * Put the source tree root node in the document cache. * TODO: This function needs to be a LOT more sophisticated. * * @param n The node to cache. * @param source The Source object to cache. */ public void putDocumentInCache(int n, Source source) { int cachedNode = getNode(source); if (DTM.NULL != cachedNode) { if (!(cachedNode == n)) throw new RuntimeException( "Programmer's Error! " + "putDocumentInCache found reparse of doc: " + source.getSystemId()); return; } if (null != source.getSystemId()) { m_sourceTree.addElement(new SourceTree(n, source.getSystemId())); } }
/** * Gets the SOAP message pretty printed as escaped xml for displaying in * browser * * @param msg * @return */ private String soapMessage2String(SOAPMessage msg) { if (msg == null) return ""; try (ByteArrayOutputStream streamOut = new ByteArrayOutputStream();) { Transformer transformer = TransformerFactory.newInstance() .newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "2"); Source sc = msg.getSOAPPart().getContent(); StreamResult result = new StreamResult(streamOut); transformer.transform(sc, result); String strMessage = streamOut.toString(); return escapeXmlString(strMessage); } catch (Exception e) { System.out.println("Exception in printing SOAP message: " + e.getMessage()); return ""; } }
@Test public void test() { try { Source source = new StreamSource(util.BOMInputStream.createStream("UTF-16BE", this.getClass().getResourceAsStream("Hello.wsdl.data")), this.getClass().getResource("Hello.wsdl.data").toExternalForm()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.transform(source, new StreamResult(baos)); System.out.println(new String(baos.toByteArray())); ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray()); InputSource inSource = new InputSource(bis); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(inSource.getSystemId(), inSource.getByteStream()); while (reader.hasNext()) { reader.next(); } } catch (Exception ex) { ex.printStackTrace(System.err); Assert.fail("Exception occured: " + ex.getMessage()); } }
/** * Reads document description from the CrossRef API. * * * @author Eike Spielberg * */ public Source resolve(String href, String base) throws TransformerException { String id = href.substring(href.indexOf(":") + 1); MCRContent content = null; CrossRefConnector connection = new CrossRefConnector(); try { MCRContent crossRefExport = connection.getPublicationByDOI(id); content = new MCRStringContent(XML.toString(new JSONObject(crossRefExport.asString()), "content")); LOGGER.debug("Reading MCRContent with DOI " + id); MCRXSL2XMLTransformer transformer = new MCRXSL2XMLTransformer("xsl/CrossRef2mods.xsl"); MCRContent mods = transformer.transform(content); connection.close(); return mods.getSource(); } catch (Exception e) { throw new TransformerException(e); } }
private void validate(final String xsdFile, final Source src, final Result result) throws Exception { try { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new File(ValidatorTest.class.getResource(xsdFile).toURI())); // Get a Validator which can be used to validate instance document // against this grammar. Validator validator = schema.newValidator(); ErrorHandler eh = new ErrorHandlerImpl(); validator.setErrorHandler(eh); // Validate this instance document against the // Instance document supplied validator.validate(src, result); } catch (Exception ex) { throw ex; } }
@Test public void testValidatorTest() throws Exception { try { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); String file = getClass().getResource("types.xsd").getFile(); Source[] sources = new Source[] { new StreamSource(new FileInputStream(file), file) }; Schema schema = sf.newSchema(sources); validator = schema.newValidator(); validate(); } catch (Exception e) { Node node = (Node) validator.getProperty("http://apache.org/xml/properties/dom/current-element-node"); if (node != null) { System.out.println("Node: " + node.getLocalName()); } else Assert.fail("No node returned"); } }
/** * Parses the WSDL and gives WSDLModel. If wsdl parameter is null, then wsdlLoc is used to get the WSDL. If the WSDL * document could not be obtained then {@link MetadataResolverFactory} is tried to get the WSDL document, if not found * then as last option, if the wsdlLoc has no '?wsdl' as query parameter then it is tried by appending '?wsdl'. * * @param wsdlLoc * Either this or {@code wsdl} parameter must be given. * Null location means the system won't be able to resolve relative references in the WSDL, */ public static WSDLModel parse(@Nullable URL wsdlLoc, @NotNull Source wsdlSource, @NotNull EntityResolver resolver, boolean isClientSide, Container container, Class serviceClass, @NotNull PolicyResolver policyResolver, boolean isUseStreamFromEntityResolverWrapper, WSDLParserExtension... extensions) throws IOException, XMLStreamException, SAXException { assert resolver != null; RuntimeWSDLParser wsdlParser = new RuntimeWSDLParser(wsdlSource.getSystemId(), new EntityResolverWrapper(resolver, isUseStreamFromEntityResolverWrapper), isClientSide, container, policyResolver, extensions); Parser parser; try{ parser = wsdlParser.resolveWSDL(wsdlLoc, wsdlSource, serviceClass); if(!hasWSDLDefinitions(parser.parser)){ throw new XMLStreamException(ClientMessages.RUNTIME_WSDLPARSER_INVALID_WSDL(parser.systemId, WSDLConstants.QNAME_DEFINITIONS, parser.parser.getName(), parser.parser.getLocation())); } }catch(XMLStreamException e){ //Try MEX if there is WSDLLoc available if(wsdlLoc == null) throw e; return tryWithMex(wsdlParser, wsdlLoc, resolver, isClientSide, container, e, serviceClass, policyResolver, extensions); }catch(IOException e){ //Try MEX if there is WSDLLoc available if(wsdlLoc == null) throw e; return tryWithMex(wsdlParser, wsdlLoc, resolver, isClientSide, container, e, serviceClass, policyResolver, extensions); } wsdlParser.extensionFacade.start(wsdlParser.context); wsdlParser.parseWSDL(parser, false); wsdlParser.wsdlDoc.freeze(); wsdlParser.extensionFacade.finished(wsdlParser.context); wsdlParser.extensionFacade.postFinished(wsdlParser.context); if(wsdlParser.wsdlDoc.getServices().isEmpty()) throw new WebServiceException(ClientMessages.WSDL_CONTAINS_NO_SERVICE(wsdlLoc)); return wsdlParser.wsdlDoc; }
@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; String[] hrefs = {"XSLImport_html.xsl", "XSLInclude_header.xsl", "XSLInclude_footer.xsl"}; Source[] returnValues = {new StreamSource(xsl_import_html), new StreamSource(xsl_include_header), new StreamSource(xsl_include_footer)}; URIResolver resolver = new XslResolver(hrefs, returnValues); SAXSource xslSourceDTD = new SAXSource(new InputSource(new StringReader(xsl_includeDTD))); StreamSource xmlSourceDTD = new StreamSource(new StringReader(xml_xslDTD)); String[] hrefs1 = {"pathto/DocFunc2.xml"}; Source[] returnValues1 = {new StreamSource(xml_doc2)}; URIResolver docResolver = new XslResolver(hrefs1, returnValues1); 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 {false, true, xml_catalog, xslSourceDTD, xmlSourceDTD, null, ""}, {false, true, xml_bogus_catalog, new SAXSource(new InputSource(new StringReader(xsl_include))), new StreamSource(new StringReader(xml_xsl)), resolver, ""}, {true, true, xml_bogus_catalog, new SAXSource(new InputSource(new StringReader(xsl_include))), new StreamSource(new StringReader(xml_xsl)), resolver, ""}, // for resolving reference by the document function {false, true, xml_catalog, xslDocSource, xmlDocSource, null, "Resolved by a catalog"}, {false, true, xml_bogus_catalog, xslDocSource, xmlDocSource, docResolver, "Resolved by a resolver"}, {true, true, xml_bogus_catalog, xslDocSource, xmlDocSource, docResolver, "Resolved by a resolver"} }; }
public static InputStream FastInfosetSource_getInputStream(Source source) throws Exception { if (fiFastInfosetSource_getInputStream == null) { throw new RuntimeException("Unable to locate Fast Infoset implementation"); } return (InputStream) fiFastInfosetSource_getInputStream.invoke(source, (Object[])null); }
private static String elementToString(Element e) throws IOException { try { Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "no"); // NOI18N t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // NOI18N Source source = new DOMSource(e); StringWriter w = new StringWriter(); Result result = new StreamResult(w); t.transform(source, result); return w.toString(); } catch (Exception x) { throw (IOException)new IOException(x.toString()).initCause(x); } }
/** * Writes the generator's state to pw */ 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"); if (!useSchema) { // set the doctype system and public ids from version for older DTDs. xform.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, version.getSystemId()); xform.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, version.getPublicId()); } xform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); xform.transform(src, res); pw.flush(); } catch (Exception ex) { RuntimeException ex2 = new RuntimeException( LocalizedStrings.CacheXmlGenerator_AN_EXCEPTION_WAS_THROWN_WHILE_GENERATING_XML .toLocalizedString()); ex2.initCause(ex); throw ex2; } }
/** Create new XMLDataObject * * @param fo the primary file object * @param loader loader of this data object */ public XMLDataObject (final FileObject fo, MultiFileLoader loader) throws DataObjectExistsException { super (fo, loader, false); CookieSet set = getCookieSet(); set.add (cookieManager = new DataObjectCookieManager (this, set)); editorSupportFactory = TextEditorSupport.findEditorSupportFactory (this, null); editorSupportFactory.registerCookies (set); CookieSet.Factory viewCookieFactory = new ViewCookieFactory(); set.add (ViewCookie.class, viewCookieFactory); InputSource is = DataObjectAdapters.inputSource (this); //enable "Save As" set.assign( SaveAsCapable.class, new SaveAsCapable() { public void saveAs(FileObject folder, String fileName) throws IOException { editorSupportFactory.createEditor().saveAs( folder, fileName ); } }); // add check and validate cookies set.add (new CheckXMLSupport (is)); set.add (new ValidateXMLSupport (is)); // add TransformableCookie Source source = DataObjectAdapters.source (this); set.add (new TransformableSupport (source)); new CookieManager (this, set, XMLCookieFactoryCreator.class); this.addPropertyChangeListener (this); //??? - strange be aware of firing cycles }
/** * Transformeer een {@link Source} naar een {@link Node}. * @param source de {@link Source} * @return de {@link Node} * @throws TransformerException bij een transformatiefout */ public static Node initializeNode(final Source source) throws TransformerException { final Transformer t = TRANSFORMER_FACTORY.newTransformer(); final DOMResult domResult = new DOMResult(); t.transform(source, domResult); return domResult.getNode().getFirstChild(); }
private static Envelope parseEnvelopeStax(Source src, SOAPPartImpl soapPart) throws SOAPException { XMLStreamReader streamReader = null; if (src instanceof StAXSource) { streamReader = ((StAXSource) src).getXMLStreamReader(); } try { if (streamReader == null) { if (xmlInputFactory == null) xmlInputFactory = XMLInputFactory.newInstance(); streamReader = xmlInputFactory.createXMLStreamReader(src); } // SaajStaxWriter saajWriter = new SaajStaxWriter(soapPart.message, soapPart.document); // XMLStreamReaderToXMLStreamWriter readerWriterBridge = new XMLStreamReaderToXMLStreamWriter( // streamReader, saajWriter, soapPart.getSOAPNamespace()); StaxBridge readerWriterBridge = new StaxReaderBridge(streamReader, soapPart); //bridge will stop reading at body element, and parse upon request, so save it //on the envelope readerWriterBridge.bridgeEnvelopeAndHeaders(); Envelope env = (Envelope) soapPart.getEnvelope(); env.setStaxBridge(readerWriterBridge); return env; } catch (Exception e) { throw new SOAPException(e); } }
public EndpointReference readEndpointReference(final Source eprInfoset) { try { Unmarshaller unmarshaller = eprjc.get().createUnmarshaller(); return (EndpointReference) unmarshaller.unmarshal(eprInfoset); } catch (JAXBException e) { throw new WebServiceException("Error creating Marshaller or marshalling.", e); } }
@Test public void testSAX2SAX() { try { Source input = saxUtil.prepareSource(this.getClass().getResourceAsStream(XML_FILE)); SAXResult saxResult = (SAXResult) saxUtil.prepareResult(); idTransform.transform(input, saxResult); saxUtil.checkResult(saxResult, EXPECTED_VERSION, "UTF-8"); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception occured: " + e.getMessage()); } }
private boolean isKnownReadableSource(Source wsdlSource) { if (wsdlSource instanceof StreamSource) { return (((StreamSource) wsdlSource).getInputStream() != null || ((StreamSource) wsdlSource).getReader() != null); } else { return false; } }
@SuppressWarnings("deprecation") public AllEncompassingFormHttpMessageConverter() { addPartConverter(new SourceHttpMessageConverter<Source>()); if (jaxb2Present) { addPartConverter(new Jaxb2RootElementHttpMessageConverter()); } if (jackson2Present) { addPartConverter(new MappingJackson2HttpMessageConverter()); } else if (jacksonPresent) { addPartConverter(new org.springframework.http.converter.json.MappingJacksonHttpMessageConverter()); } }
@Test(dataProvider = "input-provider") public void testTransform(Supplier<Source> src, Supplier<Result> res, Transformer transformer) throws Throwable { try { transformer.transform(src.get(), res.get()); } catch (WrapperException e) { throw e.getCause(); } }
protected Source getXMLSource(final Map<QName, Object> model) { if (!model.containsKey(ROOT_NAMESPACE)) { return null; } final Object o = model.get(ROOT_NAMESPACE); if (!(o instanceof Document)) { throw new IllegalArgumentException("expected root namespace object to be a " + Document.class.getName() + ". found a " + o.getClass().getName()); } return new DOMSource((Document) o); }
@Test public void testStAXEvent2DOM() { try { Source input = staxUtil.prepareSource(this.getClass().getResourceAsStream(XML10_FILE)); DOMResult domResult = (DOMResult) domUtil.prepareResult(); idTransform.transform(input, domResult); domUtil.checkResult(domResult, "1.0"); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception occured: " + e.getMessage()); } }
void addSchema(Source schema) { assert schema.getSystemId() != null; String systemId = schema.getSystemId(); try { XMLStreamBufferResult xsbr = XmlUtil.identityTransform(schema, new XMLStreamBufferResult()); SDDocumentSource sds = SDDocumentSource.create(new URL(systemId), xsbr.getXMLStreamBuffer()); SDDocument sdoc = SDDocumentImpl.create(sds, new QName(""), new QName("")); docs.put(systemId, sdoc); nsMapping.put(((SDDocument.Schema)sdoc).getTargetNamespace(), sdoc); } catch(Exception ex) { LOGGER.log(Level.WARNING, "Exception in adding schemas to resolver", ex); } }
private static void printXml(String tag, String xml, String headString) { if (TextUtils.isEmpty(tag)) { tag = TAG; } if (xml != null) { try { Source xmlInput = new StreamSource(new StringReader(xml)); StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, xmlOutput); xml = xmlOutput.getWriter().toString().replaceFirst(">", ">\n"); } catch (Exception e) { e.printStackTrace(); } xml = headString + "\n" + xml; } else { xml = headString + "Log with null object"; } printLine(tag, true); String[] lines = xml.split(LINE_SEPARATOR); for (String line : lines) { if (!TextUtils.isEmpty(line)) { Log.d(tag, "|" + line); } } printLine(tag, false); }
/** * Try to create a DOM source tree from the input source. * * @param source The Source object that identifies the source node. * @param locator The location of the caller, for diagnostic purposes. * * @return non-null reference to node identified by the source argument. * * @throws TransformerException if the source argument can not be resolved * to a source node. */ public int parseToNode(Source source, SourceLocator locator, XPathContext xctxt) throws TransformerException { try { Object xowner = xctxt.getOwnerObject(); DTM dtm; if(null != xowner && xowner instanceof com.sun.org.apache.xml.internal.dtm.DTMWSFilter) { dtm = xctxt.getDTM(source, false, (com.sun.org.apache.xml.internal.dtm.DTMWSFilter)xowner, false, true); } else { dtm = xctxt.getDTM(source, false, null, false, true); } return dtm.getDocument(); } catch (Exception e) { //e.printStackTrace(); throw new TransformerException(e.getMessage(), locator, e); } }
static ProviderArgumentsBuilder create(ProviderEndpointModel model, SOAPVersion soapVersion) { if (model.mode == Service.Mode.PAYLOAD) { return new PayloadSource(soapVersion); } else { if(model.datatype==Source.class) return new MessageSource(soapVersion); if(model.datatype==SOAPMessage.class) return new SOAPMessageParameter(soapVersion); if(model.datatype==Message.class) return new MessageProviderArgumentBuilder(soapVersion); throw new WebServiceException(ServerMessages.PROVIDER_INVALID_PARAMETER_TYPE(model.implClass,model.datatype)); } }
/** * Trims the sourceWSDL based on the excludedFields that are declared for the graphClass associated with the input WebService implementation class. * The targetWSDL will be generated as a result. * @param sourceWSDL a source WSDL. * @param targetWSDLToGenerate the WSDL to generate. * @param webServiceImplementationClassName the WebService implementation class that may have an annotation declaring the need for WSDL trimming. */ public static void trim(File sourceWSDL, File targetWSDLToGenerate, String webServiceImplementationClassName) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException, ClassNotFoundException { Map<Class, Collection<String>> excludedFields = getExcludedFields(webServiceImplementationClassName); if (excludedFields != null && excludedFields.size() > 0) { if (log.isDebugEnabled()) log.debug("Trimming '" + sourceWSDL + "' by excluding " + excludedFields); //Parse the source WSDL DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(sourceWSDL); //Trim the source WSDL trim(document.getDocumentElement(), excludedFields); //Generate the target WSDL if (log.isDebugEnabled()) log.debug("Generating: " + targetWSDLToGenerate); Source source = new DOMSource(document); Result result = new StreamResult(targetWSDLToGenerate); TransformerFactory transformerFactory = TransformerFactory.newInstance(); //transformerFactory.setAttribute("indent-number", 2); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); } else if (!sourceWSDL.equals(targetWSDLToGenerate)) { if (log.isDebugEnabled()) log.debug("None of the fields are excluded. '" + targetWSDLToGenerate + "' will be created as a copy of '" + sourceWSDL + '\''); copy(sourceWSDL, targetWSDLToGenerate); } }
/** * Creates a XML transformer with the following properties:<br /> * <br /> * character encoding: UTF-8<br /> * output method: xml<br /> * output version: 1.0 */ public static Transformer newTransformer(Source source) throws TransformerConfigurationException { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(source); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.VERSION, "1.0"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); return transformer; }
@Test public void serialize() throws Exception { // given ResellerRevenueShareResult result = resellerShareAssembler.build( RESELLER_KEY, PERIOD_START_TIME, PERIOD_END_TIME); result.calculateAllShares(); // when JAXBContext jc = JAXBContext .newInstance(ResellerRevenueShareResult.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); ByteArrayOutputStream bos = new ByteArrayOutputStream(); marshaller.marshal(result, bos); assertNotNull(bos.toByteArray()); printXml(bos); final List<String> fragments = new ArrayList<String>(); fragments.add(new String(bos.toByteArray(), "UTF-8")); byte[] xmlBytes = XMLConverter.combine("RevenueSharesResults", fragments, ResellerRevenueShareResult.SCHEMA); ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); bos1.write(xmlBytes); System.out.println(new String(bos1.toByteArray())); SchemaFactory schemaFactory = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaUrl = BillingServiceBean.class.getResource("/" + "ResellerRevenueShareResult.xsd"); Schema schema = schemaFactory.newSchema(schemaUrl); Source xmlFile = new StreamSource(new ByteArrayInputStream(xmlBytes)); Validator validator = schema.newValidator(); validator.validate(xmlFile); }