com.hfg.xml.IndentedXMLOutputStream Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of com_hfg Show documentation
Show all versions of com_hfg Show documentation
com.hfg xml, html, svg, and bioinformatics utility library
package com.hfg.xml;
import java.io.FilterOutputStream;
import java.io.OutputStream;
class IndentedXMLOutputStream extends FilterOutputStream
{
private static enum State { IN_START_TAG, IN_END_TAG, IN_CONTENT }
private int mIndentLevel = 0;
private int mIndentSize = 3;
private byte[] mBuffer = new byte[16 * 1024];
private int mBufferPtr = 0;
private char mPreviousChar = (char)-1;
private State mState;
private static byte[] ln = System.getProperty("line.separator").getBytes();
//---------------------------------------------------------------------------
public IndentedXMLOutputStream(OutputStream outputStream)
{
super(outputStream);
}
//---------------------------------------------------------------------------
@Override
public void write(int i) throws java.io.IOException
{
if (mBufferPtr < mBuffer.length)
{
// Just add it to the buffer.
mBuffer[mBufferPtr++] = (byte) i;
}
else
{
flush();
}
}
//---------------------------------------------------------------------------
// TODO: improve this simple implementation
@Override
public void write(byte[] bytes) throws java.io.IOException
{
for (int i = 0; i < bytes.length; i++)
{
write(bytes[i]);
}
}
//---------------------------------------------------------------------------
// TODO: improve this simple implementation
@Override
public void write(byte[] bytes, int i, int i1) throws java.io.IOException
{
for (int index = i; index - i < i1; index++)
{
write(bytes[i]);
}
}
//---------------------------------------------------------------------------
public void flush() throws java.io.IOException
{
for (int i = 0; i < mBufferPtr; i++)
{
if ((char) mBuffer[i] == '>')
{
if (mPreviousChar == '/')
{
// End of an empty tag. Return and indent at the current level
out.write(ln);
for (int j = 0; j < mIndentLevel * mIndentSize; j++) out.write((byte) ' ');
}
else if (mState == State.IN_END_TAG)
{
// End of an end tag. Return and decrease the indent level
out.write(ln);
for (int j = 0; j < mIndentLevel * mIndentSize; j++) out.write((byte) ' ');
}
}
if ((char) mBuffer[i] == '<')
{
mState = State.IN_START_TAG;
}
else if ((char) mBuffer[i] == '/')
{
if (mPreviousChar == '<') mState = State.IN_END_TAG;
}
if (mPreviousChar == '>')
out.write(mBuffer[i]);
mPreviousChar = (char) mBuffer[i];
}
mBufferPtr = 0;
}
//---------------------------------------------------------------------------
public void close() throws java.io.IOException
{
}
}