package org.jboss.axis.components.encoding;
import org.jboss.axis.utils.Messages;
import java.io.UnsupportedEncodingException;
public abstract class AbstractXMLEncoder implements XMLEncoder
{
private static final byte[] AMP = "&".getBytes();
private static final byte[] QUOTE = """.getBytes();
private static final byte[] LESS = "<".getBytes();
private static final byte[] GREATER = ">".getBytes();
private static final byte[] LF = "\n".getBytes();
private static final byte[] CR = "\r".getBytes();
private static final byte[] TAB = "\t".getBytes();
public String encode(String xmlString)
{
if (xmlString == null)
{
return "";
}
char[] characters = xmlString.toCharArray();
EncodedByteArray out = null;
char character;
for (int i = 0; i < characters.length; i++)
{
character = characters[i];
switch (character)
{
case '&':
if (out == null)
{
out = getInitialByteArray(xmlString, i);
}
out.append(AMP);
break;
case '"':
if (out == null)
{
out = getInitialByteArray(xmlString, i);
}
out.append(QUOTE);
break;
case '<':
if (out == null)
{
out = getInitialByteArray(xmlString, i);
}
out.append(LESS);
break;
case '>':
if (out == null)
{
out = getInitialByteArray(xmlString, i);
}
out.append(GREATER);
break;
case '\n':
if (out == null)
{
out = getInitialByteArray(xmlString, i);
}
out.append(LF);
break;
case '\r':
if (out == null)
{
out = getInitialByteArray(xmlString, i);
}
out.append(CR);
break;
case '\t':
if (out == null)
{
out = getInitialByteArray(xmlString, i);
}
out.append(TAB);
break;
default:
if (character < 0x20)
{
throw new IllegalArgumentException(Messages.getMessage("invalidXmlCharacter00", Integer.toHexString(character), xmlString));
}
else if (needsEncoding(character))
{
if (out == null)
{
out = getInitialByteArray(xmlString, i);
}
appendEncoded(out, character);
}
else
{
if (out != null)
{
out.append(character);
}
}
break;
}
}
if (out == null)
{
return xmlString;
}
try
{
return out.toString(getEncoding());
}
catch (UnsupportedEncodingException e)
{
throw new IllegalStateException(Messages.getMessage("encodingDisappeared00", getEncoding()));
}
}
public abstract String getEncoding();
public abstract boolean needsEncoding(char c);
public abstract void appendEncoded(EncodedByteArray out, char c);
private EncodedByteArray getInitialByteArray(String aXmlString, int pos)
{
try
{
return new EncodedByteArray(aXmlString.getBytes(getEncoding()), 0, pos);
}
catch (UnsupportedEncodingException e)
{
throw new IllegalStateException(Messages.getMessage("encodingDisappeared00", getEncoding()));
}
}
}