Java Code Examples for javax.xml.transform.Source

The following are top voted examples for showing how to use javax.xml.transform.Source. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: JaxpIssue49.java   Source Code and License 7 votes vote down vote up
@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");
    }
}
 
Example 2
Project: openjdk-jdk10   File: Parser.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 3
Project: MVVMArms   File: CharacterHandler.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Project: AndroidSnooper   File: XmlFormatter.java   Source Code and License 6 votes vote down vote up
@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;
  }
}
 
Example 5
Project: OpenJSharp   File: JAXBDispatch.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 6
Project: bibliometrics   File: MCRScopusDOIresolver.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 7
Project: framework   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 8
Project: sstore-soft   File: JDBCSQLXML.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 9
Project: 19porn   File: LogFormat.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 10
Project: VASSAL-src   File: Builder.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example 11
Project: Renrentou   File: LogFormat.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 12
Project: pay   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
/**
    * 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;
   }
 
Example 13
Project: openjdk-jdk10   File: SourceTreeManager.java   Source Code and License 6 votes vote down vote up
/**
 * 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()));
  }
}
 
Example 14
Project: oscm   File: VersionHandler.java   Source Code and License 6 votes vote down vote up
/**
 * 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 "";
    }

}
 
Example 15
Project: openjdk-jdk10   File: Bug6388460.java   Source Code and License 6 votes vote down vote up
@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());
    }
}
 
Example 16
Project: bibliometrics   File: MCRCrossRefResolver.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 17
Project: openjdk-jdk10   File: ValidatorTest.java   Source Code and License 6 votes vote down vote up
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;
    }
}
 
Example 18
Project: openjdk-jdk10   File: RuntimeWSDLParser.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 19
Project: openjdk-jdk10   File: CatalogSupport.java   Source Code and License 5 votes vote down vote up
@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"}
    };
}
 
Example 20
Project: openjdk-jdk10   File: FastInfosetReflection.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 21
Project: incubator-netbeans   File: Arch.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 22
Project: monarch   File: CacheXmlGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
  }
}
 
Example 23
Project: incubator-netbeans   File: XMLDataObject.java   Source Code and License 5 votes vote down vote up
/** 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
}
 
Example 24
Project: OperatieBRP   File: TransformerUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
}
 
Example 25
Project: openjdk-jdk10   File: EnvelopeFactory.java   Source Code and License 5 votes vote down vote up
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);
        }
    }
 
Example 26
Project: openjdk-jdk10   File: ProviderImpl.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 27
Project: openjdk-jdk10   File: Bug4892774.java   Source Code and License 5 votes vote down vote up
@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());
    }
}
 
Example 28
Project: openjdk-jdk10   File: RuntimeWSDLParser.java   Source Code and License 5 votes vote down vote up
private boolean isKnownReadableSource(Source wsdlSource) {
        if (wsdlSource instanceof StreamSource) {
                return (((StreamSource) wsdlSource).getInputStream() != null ||
                                ((StreamSource) wsdlSource).getReader() != null);
        } else {
                return false;
        }
}
 
Example 29
Project: lams   File: AllEncompassingFormHttpMessageConverter.java   Source Code and License 5 votes vote down vote up
@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());
	}
}
 
Example 30
Project: jdk8u-jdk   File: Test.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 31
Project: openjdk-jdk10   File: TransformTest.java   Source Code and License 5 votes vote down vote up
@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();
    }
}
 
Example 32
Project: alfresco-repository   File: XSLTProcessor.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 33
Project: openjdk-jdk10   File: Bug4892774.java   Source Code and License 5 votes vote down vote up
@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());
    }
}
 
Example 34
Project: OpenJSharp   File: AbstractSchemaValidationTube.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 35
Project: AndroidBasicLibs   File: JLog.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 36
Project: openjdk-jdk10   File: SourceTreeManager.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
  }

}
 
Example 37
Project: openjdk-jdk10   File: SOAPProviderArgumentBuilder.java   Source Code and License 5 votes vote down vote up
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));
    }
}
 
Example 38
Project: jaffa-framework   File: WSDLTrimmer.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 39
Project: oscm   File: Transformers.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 40
Project: oscm   File: ResellerShareResultAssemblerTest.java   Source Code and License 5 votes vote down vote up
@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);

}