Does anyone know how to get XML from the Tuscany model objects thats nicely
formatted?

As a quick hack I came up with this but it seems like theres probably
something better and I'm not sure that org.apache.xml.serialize.OutputFormat
and org.apache.xml.serialize.XMLSerializer are going to be there by default
in all runtimes:

public class PrettyPrintTestCase {

    @Test
    public void testReadWriteComposite() throws Exception {
        DefaultExtensionPointRegistry extensionPointRegistry = new
DefaultExtensionPointRegistry();
        Composite model = new DefaultAssemblyFactory().createComposite();
        model.setName(new QName("myNs","myName"));
        model.setLocal(true);
        model.setAutowire(false);
        model.getIncludes().add(model);
        String xml = modelToXML(model, true, extensionPointRegistry);
        System.out.println(xml);
    }

    /**
     * Helper method to get the XML string for a model object.
     */
    public static String modelToXML(Base model, boolean pretty,
ExtensionPointRegistry extensionPointRegistry) {
        try {
            StAXHelper stAXHelper =
StAXHelper.getInstance(extensionPointRegistry);
            StAXArtifactProcessorExtensionPoint staxProcessors =
extensionPointRegistry.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class);
            ExtensibleStAXArtifactProcessor staxProcessor = new
ExtensibleStAXArtifactProcessor(staxProcessors, null,
stAXHelper.getOutputFactory());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            staxProcessor.write(model, bos, new
ProcessorContext(extensionPointRegistry));
            bos.close();

            if (!pretty) {
                return bos.toString();
            }

            DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
            DocumentBuilder parser = factory.newDocumentBuilder();
            Document document = parser.parse(new
ByteArrayInputStream(bos.toByteArray()));

            bos = new ByteArrayOutputStream();
            OutputFormat format = new OutputFormat(document);
            format.setLineWidth(65);
            format.setIndenting(true);
            format.setIndent(2);
            XMLSerializer serializer = new XMLSerializer(bos, format);
            serializer.serialize(document);
            return bos.toString();

        } catch (ContributionWriteException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }
}

   ...ant

Reply via email to