Thursday, August 21, 2008

oaw Output Postprocessor (Beautifier)

I'm working on a project using oaw to generate java classes, spring definitions, ecore models and a lot more.

There is a pretty nice JavaBeautifier to clean up my generated classes. The problem was the XmlBeautifier, it didn't remove white spaces. This resulted in some pretty ugly xml files.

So I searched the web for some alternative, didn't find one so I modified the original for my own needs.
Here is the code if someone approaches the same problem.

* Copyright (c) 2005-2006 Sven Efftinge ( and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* Contributors:
* Sven Efftinge ( - Initial API and implementation

package com.softmodeler.generator.postprocessor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openarchitectureware.util.EncodingDetector;
import org.openarchitectureware.xpand2.output.FileHandle;
import org.openarchitectureware.xpand2.output.PostProcessor;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

* *
* @author Sven Efftinge (
* @author Bernd Kolb
public class XmlBeautifier implements PostProcessor {

private final Log log = LogFactory.getLog(getClass());

private String[] fileExtensions = new String[] { ".xml", ".xsl", ".xsd", ".wsdd", ".wsdl", ".ecore" };

public void setFileExtensions(final String[] fileExtensions) {
this.fileExtensions = fileExtensions;

public void beforeWriteAndClose(final FileHandle info) {
if (isXmlFile(info.getTargetFile().getAbsolutePath())) {
try {
// TODO this is only a heuristic, but it should work for most cases. This really is the beginning of reimplementing
// the XML parser just because we do RAM rather then file based beautification...
final String bufferedString = info.getBuffer().toString().trim();
final int indEncoding = bufferedString.indexOf("encoding");
final int indEndHeader = bufferedString.indexOf("?>");
String readEncoding = null;
Document doc = null;
if (bufferedString.startsWith(" 0 && indEncoding < readencoding =" info.getFileEncoding();" doc =" parseDocument(bufferedString," doc =" parseDocument(bufferedString," tfactory =" TransformerFactory.newInstance();" threadid="562510&tstart="90" showtopic="788" serializer =" tfactory.newTransformer();" systemvalue =" doc.getDoctype().getSystemId();" publicid =" doc.getDoctype().getPublicId();" bytearrayoutputstream =" new" string =" byteArrayOutputStream.toString(info.getFileEncoding());" nodelist =" node.getChildNodes();" i =" 0;" child =" nodeList.item(i);"> encodingsToTry = new ArrayList();
if (encoding != null) {
} else {
byte[] sampleBytes = bufferedString.substring(0, Math.min(64, bufferedString.length())).getBytes();

Document doc = null;
Exception lastException = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

builder.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
return new InputSource(new StringReader(""));
builder.setErrorHandler(new ErrorHandler() {
public void error(SAXParseException exception) throws SAXException {

public void fatalError(SAXParseException exception) throws SAXException {
if (exception.getMessage() != null && exception.getMessage().startsWith("Invalid byte")) {
// ignore, since we try other encodings
} else {

public void warning(SAXParseException exception) throws SAXException {

for (Iterator it = encodingsToTry.iterator(); it.hasNext();) {
String enc =;
try {
doc = builder.parse(new ByteArrayInputStream(bufferedString.getBytes(enc)));
// if no error exit here
} catch (Exception e) {
lastException = e;
if (doc == null && lastException != null) {
throw lastException;
} else {
return doc;

public boolean isXmlFile(final String absolutePath) {
for (int i = 0; i <>

The only difference to the original Beautifier is the removeWhiteSpaces method and it's call.

If you want to use this class or make your own for any other job, place the class in your generator plug-in and add the following config in your oaw workflow file:

<component class="org.openarchitectureware.xpand2.Generator">
<metaModel id="mm" class="org.eclipse.m2t.type.emf.EmfRegistryMetaModel"/>
<expand value="template::Nls::modelEcoreFile FOR model" />
<outlet path="${model-ecore}">
<postprocessor class="com.softmodeler.generator.postprocessor.XmlBeautifier"/>

1 comment:

Anonymous said...

Yo Flavio,
This is Sung Jin from Delphi.
Do you remember me? How are you?
I thought of you so I just googled you and found your blog haha

Email me at if you remember me.