ohair@286: /*
alanb@368: * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
ohair@286: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
ohair@286: *
ohair@286: * This code is free software; you can redistribute it and/or modify it
ohair@286: * under the terms of the GNU General Public License version 2 only, as
ohair@286: * published by the Free Software Foundation. Oracle designates this
ohair@286: * particular file as subject to the "Classpath" exception as provided
ohair@286: * by Oracle in the LICENSE file that accompanied this code.
ohair@286: *
ohair@286: * This code is distributed in the hope that it will be useful, but WITHOUT
ohair@286: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
ohair@286: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
ohair@286: * version 2 for more details (a copy is included in the LICENSE file that
ohair@286: * accompanied this code).
ohair@286: *
ohair@286: * You should have received a copy of the GNU General Public License version
ohair@286: * 2 along with this work; if not, write to the Free Software Foundation,
ohair@286: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
ohair@286: *
ohair@286: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
ohair@286: * or visit www.oracle.com if you need additional information or have any
ohair@286: * questions.
ohair@286: */
ohair@286:
ohair@286: package javax.xml.bind;
ohair@286:
ohair@286: import java.math.BigDecimal;
ohair@286: import java.math.BigInteger;
ohair@286: import java.util.Calendar;
ohair@286: import java.util.GregorianCalendar;
ohair@286: import java.util.TimeZone;
ohair@286:
ohair@286: import javax.xml.namespace.QName;
ohair@286: import javax.xml.namespace.NamespaceContext;
ohair@286: import javax.xml.datatype.DatatypeFactory;
ohair@286: import javax.xml.datatype.DatatypeConfigurationException;
ohair@286:
ohair@286: /**
ohair@286: * This class is the JAXB RI's default implementation of the
ohair@286: * {@link DatatypeConverterInterface}.
ohair@286: *
ohair@286: *
ohair@286: * When client applications specify the use of the static print/parse
ohair@286: * methods in {@link DatatypeConverter}, it will delegate
ohair@286: * to this class.
ohair@286: *
ohair@286: *
ohair@286: * This class is responsible for whitespace normalization.
ohair@286: *
ohair@286: * @author
- Ryan Shoemaker, Sun Microsystems, Inc.
ohair@286: * @since JAXB2.1
ohair@286: */
ohair@286: final class DatatypeConverterImpl implements DatatypeConverterInterface {
ohair@286:
ohair@286: /**
ohair@286: * To avoid re-creating instances, we cache one instance.
ohair@286: */
ohair@286: public static final DatatypeConverterInterface theInstance = new DatatypeConverterImpl();
ohair@286:
ohair@286: protected DatatypeConverterImpl() {
ohair@286: }
ohair@286:
ohair@286: public String parseString(String lexicalXSDString) {
ohair@286: return lexicalXSDString;
ohair@286: }
ohair@286:
ohair@286: public BigInteger parseInteger(String lexicalXSDInteger) {
ohair@286: return _parseInteger(lexicalXSDInteger);
ohair@286: }
ohair@286:
ohair@286: public static BigInteger _parseInteger(CharSequence s) {
ohair@286: return new BigInteger(removeOptionalPlus(WhiteSpaceProcessor.trim(s)).toString());
ohair@286: }
ohair@286:
ohair@286: public String printInteger(BigInteger val) {
ohair@286: return _printInteger(val);
ohair@286: }
ohair@286:
ohair@286: public static String _printInteger(BigInteger val) {
ohair@286: return val.toString();
ohair@286: }
ohair@286:
ohair@286: public int parseInt(String s) {
ohair@286: return _parseInt(s);
ohair@286: }
ohair@286:
ohair@286: /**
ohair@286: * Faster but less robust String->int conversion.
ohair@286: *
ohair@286: * Note that:
ohair@286: *
ohair@286: * - XML Schema allows '+', but {@link Integer#valueOf(String)} is not.
ohair@286: *
- XML Schema allows leading and trailing (but not in-between) whitespaces.
ohair@286: * {@link Integer#valueOf(String)} doesn't allow any.
ohair@286: *
ohair@286: */
ohair@286: public static int _parseInt(CharSequence s) {
ohair@286: int len = s.length();
ohair@286: int sign = 1;
ohair@286:
ohair@286: int r = 0;
ohair@286:
ohair@286: for (int i = 0; i < len; i++) {
ohair@286: char ch = s.charAt(i);
ohair@286: if (WhiteSpaceProcessor.isWhiteSpace(ch)) {
ohair@286: // skip whitespace
ohair@286: } else if ('0' <= ch && ch <= '9') {
ohair@286: r = r * 10 + (ch - '0');
ohair@286: } else if (ch == '-') {
ohair@286: sign = -1;
ohair@286: } else if (ch == '+') {
ohair@286: // noop
ohair@286: } else {
ohair@286: throw new NumberFormatException("Not a number: " + s);
ohair@286: }
ohair@286: }
ohair@286:
ohair@286: return r * sign;
ohair@286: }
ohair@286:
ohair@286: public long parseLong(String lexicalXSLong) {
ohair@286: return _parseLong(lexicalXSLong);
ohair@286: }
ohair@286:
ohair@286: public static long _parseLong(CharSequence s) {
ohair@286: return Long.valueOf(removeOptionalPlus(WhiteSpaceProcessor.trim(s)).toString());
ohair@286: }
ohair@286:
ohair@286: public short parseShort(String lexicalXSDShort) {
ohair@286: return _parseShort(lexicalXSDShort);
ohair@286: }
ohair@286:
ohair@286: public static short _parseShort(CharSequence s) {
ohair@286: return (short) _parseInt(s);
ohair@286: }
ohair@286:
ohair@286: public String printShort(short val) {
ohair@286: return _printShort(val);
ohair@286: }
ohair@286:
ohair@286: public static String _printShort(short val) {
ohair@286: return String.valueOf(val);
ohair@286: }
ohair@286:
ohair@286: public BigDecimal parseDecimal(String content) {
ohair@286: return _parseDecimal(content);
ohair@286: }
ohair@286:
ohair@286: public static BigDecimal _parseDecimal(CharSequence content) {
ohair@286: content = WhiteSpaceProcessor.trim(content);
ohair@286:
ohair@286: if (content.length() <= 0) {
ohair@286: return null;
ohair@286: }
ohair@286:
ohair@286: return new BigDecimal(content.toString());
ohair@286:
ohair@286: // from purely XML Schema perspective,
ohair@286: // this implementation has a problem, since
ohair@286: // in xs:decimal "1.0" and "1" is equal whereas the above
ohair@286: // code will return different values for those two forms.
ohair@286: //
ohair@286: // the code was originally using com.sun.msv.datatype.xsd.NumberType.load,
ohair@286: // but a profiling showed that the process of normalizing "1.0" into "1"
ohair@286: // could take non-trivial time.
ohair@286: //
ohair@286: // also, from the user's point of view, one might be surprised if
ohair@286: // 1 (not 1.0) is returned from "1.000"
ohair@286: }
ohair@286:
ohair@286: public float parseFloat(String lexicalXSDFloat) {
ohair@286: return _parseFloat(lexicalXSDFloat);
ohair@286: }
ohair@286:
ohair@286: public static float _parseFloat(CharSequence _val) {
ohair@286: String s = WhiteSpaceProcessor.trim(_val).toString();
ohair@286: /* Incompatibilities of XML Schema's float "xfloat" and Java's float "jfloat"
ohair@286:
ohair@286: * jfloat.valueOf ignores leading and trailing whitespaces,
ohair@286: whereas this is not allowed in xfloat.
ohair@286: * jfloat.valueOf allows "float type suffix" (f, F) to be
ohair@286: appended after float literal (e.g., 1.52e-2f), whereare
ohair@286: this is not the case of xfloat.
ohair@286:
ohair@286: gray zone
ohair@286: ---------
ohair@286: * jfloat allows ".523". And there is no clear statement that mentions
ohair@286: this case in xfloat. Although probably this is allowed.
ohair@286: *
ohair@286: */
ohair@286:
ohair@286: if (s.equals("NaN")) {
ohair@286: return Float.NaN;
ohair@286: }
ohair@286: if (s.equals("INF")) {
ohair@286: return Float.POSITIVE_INFINITY;
ohair@286: }
ohair@286: if (s.equals("-INF")) {
ohair@286: return Float.NEGATIVE_INFINITY;
ohair@286: }
ohair@286:
ohair@286: if (s.length() == 0
ohair@286: || !isDigitOrPeriodOrSign(s.charAt(0))
ohair@286: || !isDigitOrPeriodOrSign(s.charAt(s.length() - 1))) {
ohair@286: throw new NumberFormatException();
ohair@286: }
ohair@286:
ohair@286: // these screening process is necessary due to the wobble of Float.valueOf method
ohair@286: return Float.parseFloat(s);
ohair@286: }
ohair@286:
ohair@286: public String printFloat(float v) {
ohair@286: return _printFloat(v);
ohair@286: }
ohair@286:
ohair@286: public static String _printFloat(float v) {
ohair@286: if (Float.isNaN(v)) {
ohair@286: return "NaN";
ohair@286: }
ohair@286: if (v == Float.POSITIVE_INFINITY) {
ohair@286: return "INF";
ohair@286: }
ohair@286: if (v == Float.NEGATIVE_INFINITY) {
ohair@286: return "-INF";
ohair@286: }
ohair@286: return String.valueOf(v);
ohair@286: }
ohair@286:
ohair@286: public double parseDouble(String lexicalXSDDouble) {
ohair@286: return _parseDouble(lexicalXSDDouble);
ohair@286: }
ohair@286:
ohair@286: public static double _parseDouble(CharSequence _val) {
ohair@286: String val = WhiteSpaceProcessor.trim(_val).toString();
ohair@286:
ohair@286: if (val.equals("NaN")) {
ohair@286: return Double.NaN;
ohair@286: }
ohair@286: if (val.equals("INF")) {
ohair@286: return Double.POSITIVE_INFINITY;
ohair@286: }
ohair@286: if (val.equals("-INF")) {
ohair@286: return Double.NEGATIVE_INFINITY;
ohair@286: }
ohair@286:
ohair@286: if (val.length() == 0
ohair@286: || !isDigitOrPeriodOrSign(val.charAt(0))
ohair@286: || !isDigitOrPeriodOrSign(val.charAt(val.length() - 1))) {
ohair@286: throw new NumberFormatException(val);
ohair@286: }
ohair@286:
ohair@286:
ohair@286: // these screening process is necessary due to the wobble of Float.valueOf method
ohair@286: return Double.parseDouble(val);
ohair@286: }
ohair@286:
ohair@286: public boolean parseBoolean(String lexicalXSDBoolean) {
alanb@368: Boolean b = _parseBoolean(lexicalXSDBoolean);
alanb@368: return (b == null) ? false : b.booleanValue();
ohair@286: }
ohair@286:
ohair@286: public static Boolean _parseBoolean(CharSequence literal) {
ohair@286: if (literal == null) {
ohair@286: return null;
ohair@286: }
ohair@286:
ohair@286: int i = 0;
ohair@286: int len = literal.length();
ohair@286: char ch;
ohair@286: boolean value = false;
ohair@286:
ohair@286: if (literal.length() <= 0) {
ohair@286: return null;
ohair@286: }
ohair@286:
ohair@286: do {
ohair@286: ch = literal.charAt(i++);
ohair@286: } while (WhiteSpaceProcessor.isWhiteSpace(ch) && i < len);
ohair@286:
ohair@286: int strIndex = 0;
ohair@286:
ohair@286: switch (ch) {
ohair@286: case '1':
ohair@286: value = true;
ohair@286: break;
ohair@286: case '0':
ohair@286: value = false;
ohair@286: break;
ohair@286: case 't':
ohair@286: String strTrue = "rue";
ohair@286: do {
ohair@286: ch = literal.charAt(i++);
ohair@286: } while ((strTrue.charAt(strIndex++) == ch) && i < len && strIndex < 3);
ohair@286:
ohair@286: if (strIndex == 3) {
ohair@286: value = true;
ohair@286: } else {
ohair@286: return false;
ohair@286: }
ohair@286: // throw new IllegalArgumentException("String \"" + literal + "\" is not valid boolean value.");
ohair@286:
ohair@286: break;
ohair@286: case 'f':
ohair@286: String strFalse = "alse";
ohair@286: do {
ohair@286: ch = literal.charAt(i++);
ohair@286: } while ((strFalse.charAt(strIndex++) == ch) && i < len && strIndex < 4);
ohair@286:
ohair@286:
ohair@286: if (strIndex == 4) {
ohair@286: value = false;
ohair@286: } else {
ohair@286: return false;
ohair@286: }
ohair@286: // throw new IllegalArgumentException("String \"" + literal + "\" is not valid boolean value.");
ohair@286:
ohair@286: break;
ohair@286: }
ohair@286:
ohair@286: if (i < len) {
ohair@286: do {
ohair@286: ch = literal.charAt(i++);
ohair@286: } while (WhiteSpaceProcessor.isWhiteSpace(ch) && i < len);
ohair@286: }
ohair@286:
ohair@286: if (i == len) {
ohair@286: return value;
ohair@286: } else {
ohair@286: return null;
ohair@286: }
ohair@286: // throw new IllegalArgumentException("String \"" + literal + "\" is not valid boolean value.");
ohair@286: }
ohair@286:
ohair@286: public String printBoolean(boolean val) {
ohair@286: return val ? "true" : "false";
ohair@286: }
ohair@286:
ohair@286: public static String _printBoolean(boolean val) {
ohair@286: return val ? "true" : "false";
ohair@286: }
ohair@286:
ohair@286: public byte parseByte(String lexicalXSDByte) {
ohair@286: return _parseByte(lexicalXSDByte);
ohair@286: }
ohair@286:
ohair@286: public static byte _parseByte(CharSequence literal) {
ohair@286: return (byte) _parseInt(literal);
ohair@286: }
ohair@286:
ohair@286: public String printByte(byte val) {
ohair@286: return _printByte(val);
ohair@286: }
ohair@286:
ohair@286: public static String _printByte(byte val) {
ohair@286: return String.valueOf(val);
ohair@286: }
ohair@286:
ohair@286: public QName parseQName(String lexicalXSDQName, NamespaceContext nsc) {
ohair@286: return _parseQName(lexicalXSDQName, nsc);
ohair@286: }
ohair@286:
ohair@286: /**
ohair@286: * @return null if fails to convert.
ohair@286: */
ohair@286: public static QName _parseQName(CharSequence text, NamespaceContext nsc) {
ohair@286: int length = text.length();
ohair@286:
ohair@286: // trim whitespace
ohair@286: int start = 0;
ohair@286: while (start < length && WhiteSpaceProcessor.isWhiteSpace(text.charAt(start))) {
ohair@286: start++;
ohair@286: }
ohair@286:
ohair@286: int end = length;
ohair@286: while (end > start && WhiteSpaceProcessor.isWhiteSpace(text.charAt(end - 1))) {
ohair@286: end--;
ohair@286: }
ohair@286:
ohair@286: if (end == start) {
ohair@286: throw new IllegalArgumentException("input is empty");
ohair@286: }
ohair@286:
ohair@286:
ohair@286: String uri;
ohair@286: String localPart;
ohair@286: String prefix;
ohair@286:
ohair@286: // search ':'
ohair@286: int idx = start + 1; // no point in searching the first char. that's not valid.
ohair@286: while (idx < end && text.charAt(idx) != ':') {
ohair@286: idx++;
ohair@286: }
ohair@286:
ohair@286: if (idx == end) {
ohair@286: uri = nsc.getNamespaceURI("");
ohair@286: localPart = text.subSequence(start, end).toString();
ohair@286: prefix = "";
ohair@286: } else {
ohair@286: // Prefix exists, check everything
ohair@286: prefix = text.subSequence(start, idx).toString();
ohair@286: localPart = text.subSequence(idx + 1, end).toString();
ohair@286: uri = nsc.getNamespaceURI(prefix);
ohair@286: // uri can never be null according to javadoc,
ohair@286: // but some users reported that there are implementations that return null.
ohair@286: if (uri == null || uri.length() == 0) // crap. the NamespaceContext interface is broken.
ohair@286: // error: unbound prefix
ohair@286: {
ohair@286: throw new IllegalArgumentException("prefix " + prefix + " is not bound to a namespace");
ohair@286: }
ohair@286: }
ohair@286:
ohair@286: return new QName(uri, localPart, prefix);
ohair@286: }
ohair@286:
ohair@286: public Calendar parseDateTime(String lexicalXSDDateTime) {
ohair@286: return _parseDateTime(lexicalXSDDateTime);
ohair@286: }
ohair@286:
ohair@286: public static GregorianCalendar _parseDateTime(CharSequence s) {
ohair@286: String val = WhiteSpaceProcessor.trim(s).toString();
ohair@286: return datatypeFactory.newXMLGregorianCalendar(val).toGregorianCalendar();
ohair@286: }
ohair@286:
ohair@286: public String printDateTime(Calendar val) {
ohair@286: return _printDateTime(val);
ohair@286: }
ohair@286:
ohair@286: public static String _printDateTime(Calendar val) {
ohair@286: return CalendarFormatter.doFormat("%Y-%M-%DT%h:%m:%s%z", val);
ohair@286: }
ohair@286:
ohair@286: public byte[] parseBase64Binary(String lexicalXSDBase64Binary) {
ohair@286: return _parseBase64Binary(lexicalXSDBase64Binary);
ohair@286: }
ohair@286:
ohair@286: public byte[] parseHexBinary(String s) {
ohair@286: final int len = s.length();
ohair@286:
ohair@286: // "111" is not a valid hex encoding.
ohair@286: if (len % 2 != 0) {
ohair@286: throw new IllegalArgumentException("hexBinary needs to be even-length: " + s);
ohair@286: }
ohair@286:
ohair@286: byte[] out = new byte[len / 2];
ohair@286:
ohair@286: for (int i = 0; i < len; i += 2) {
ohair@286: int h = hexToBin(s.charAt(i));
ohair@286: int l = hexToBin(s.charAt(i + 1));
ohair@286: if (h == -1 || l == -1) {
ohair@286: throw new IllegalArgumentException("contains illegal character for hexBinary: " + s);
ohair@286: }
ohair@286:
ohair@286: out[i / 2] = (byte) (h * 16 + l);
ohair@286: }
ohair@286:
ohair@286: return out;
ohair@286: }
ohair@286:
ohair@286: private static int hexToBin(char ch) {
ohair@286: if ('0' <= ch && ch <= '9') {
ohair@286: return ch - '0';
ohair@286: }
ohair@286: if ('A' <= ch && ch <= 'F') {
ohair@286: return ch - 'A' + 10;
ohair@286: }
ohair@286: if ('a' <= ch && ch <= 'f') {
ohair@286: return ch - 'a' + 10;
ohair@286: }
ohair@286: return -1;
ohair@286: }
ohair@286: private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
ohair@286:
ohair@286: public String printHexBinary(byte[] data) {
ohair@286: StringBuilder r = new StringBuilder(data.length * 2);
ohair@286: for (byte b : data) {
ohair@286: r.append(hexCode[(b >> 4) & 0xF]);
ohair@286: r.append(hexCode[(b & 0xF)]);
ohair@286: }
ohair@286: return r.toString();
ohair@286: }
ohair@286:
ohair@286: public long parseUnsignedInt(String lexicalXSDUnsignedInt) {
ohair@286: return _parseLong(lexicalXSDUnsignedInt);
ohair@286: }
ohair@286:
ohair@286: public String printUnsignedInt(long val) {
ohair@286: return _printLong(val);
ohair@286: }
ohair@286:
ohair@286: public int parseUnsignedShort(String lexicalXSDUnsignedShort) {
ohair@286: return _parseInt(lexicalXSDUnsignedShort);
ohair@286: }
ohair@286:
ohair@286: public Calendar parseTime(String lexicalXSDTime) {
ohair@286: return datatypeFactory.newXMLGregorianCalendar(lexicalXSDTime).toGregorianCalendar();
ohair@286: }
ohair@286:
ohair@286: public String printTime(Calendar val) {
ohair@286: return CalendarFormatter.doFormat("%h:%m:%s%z", val);
ohair@286: }
ohair@286:
ohair@286: public Calendar parseDate(String lexicalXSDDate) {
ohair@286: return datatypeFactory.newXMLGregorianCalendar(lexicalXSDDate).toGregorianCalendar();
ohair@286: }
ohair@286:
ohair@286: public String printDate(Calendar val) {
ohair@286: return _printDate(val);
ohair@286: }
ohair@286:
ohair@286: public static String _printDate(Calendar val) {
ohair@286: return CalendarFormatter.doFormat((new StringBuilder("%Y-%M-%D").append("%z")).toString(),val);
ohair@286: }
ohair@286:
ohair@286: public String parseAnySimpleType(String lexicalXSDAnySimpleType) {
ohair@286: return lexicalXSDAnySimpleType;
ohair@286: // return (String)SimpleURType.theInstance._createValue( lexicalXSDAnySimpleType, null );
ohair@286: }
ohair@286:
ohair@286: public String printString(String val) {
ohair@286: // return StringType.theInstance.convertToLexicalValue( val, null );
ohair@286: return val;
ohair@286: }
ohair@286:
ohair@286: public String printInt(int val) {
ohair@286: return _printInt(val);
ohair@286: }
ohair@286:
ohair@286: public static String _printInt(int val) {
ohair@286: return String.valueOf(val);
ohair@286: }
ohair@286:
ohair@286: public String printLong(long val) {
ohair@286: return _printLong(val);
ohair@286: }
ohair@286:
ohair@286: public static String _printLong(long val) {
ohair@286: return String.valueOf(val);
ohair@286: }
ohair@286:
ohair@286: public String printDecimal(BigDecimal val) {
ohair@286: return _printDecimal(val);
ohair@286: }
ohair@286:
ohair@286: public static String _printDecimal(BigDecimal val) {
ohair@286: return val.toPlainString();
ohair@286: }
ohair@286:
ohair@286: public String printDouble(double v) {
ohair@286: return _printDouble(v);
ohair@286: }
ohair@286:
ohair@286: public static String _printDouble(double v) {
ohair@286: if (Double.isNaN(v)) {
ohair@286: return "NaN";
ohair@286: }
ohair@286: if (v == Double.POSITIVE_INFINITY) {
ohair@286: return "INF";
ohair@286: }
ohair@286: if (v == Double.NEGATIVE_INFINITY) {
ohair@286: return "-INF";
ohair@286: }
ohair@286: return String.valueOf(v);
ohair@286: }
ohair@286:
ohair@286: public String printQName(QName val, NamespaceContext nsc) {
ohair@286: return _printQName(val, nsc);
ohair@286: }
ohair@286:
ohair@286: public static String _printQName(QName val, NamespaceContext nsc) {
ohair@286: // Double-check
ohair@286: String qname;
ohair@286: String prefix = nsc.getPrefix(val.getNamespaceURI());
ohair@286: String localPart = val.getLocalPart();
ohair@286:
ohair@286: if (prefix == null || prefix.length() == 0) { // be defensive
ohair@286: qname = localPart;
ohair@286: } else {
ohair@286: qname = prefix + ':' + localPart;
ohair@286: }
ohair@286:
ohair@286: return qname;
ohair@286: }
ohair@286:
ohair@286: public String printBase64Binary(byte[] val) {
ohair@286: return _printBase64Binary(val);
ohair@286: }
ohair@286:
ohair@286: public String printUnsignedShort(int val) {
ohair@286: return String.valueOf(val);
ohair@286: }
ohair@286:
ohair@286: public String printAnySimpleType(String val) {
ohair@286: return val;
ohair@286: }
ohair@286:
ohair@286: /**
ohair@286: * Just return the string passed as a parameter but
ohair@286: * installs an instance of this class as the DatatypeConverter
ohair@286: * implementation. Used from static fixed value initializers.
ohair@286: */
ohair@286: public static String installHook(String s) {
ohair@286: DatatypeConverter.setDatatypeConverter(theInstance);
ohair@286: return s;
ohair@286: }
ohair@286: // base64 decoder
ohair@286: private static final byte[] decodeMap = initDecodeMap();
ohair@286: private static final byte PADDING = 127;
ohair@286:
ohair@286: private static byte[] initDecodeMap() {
ohair@286: byte[] map = new byte[128];
ohair@286: int i;
ohair@286: for (i = 0; i < 128; i++) {
ohair@286: map[i] = -1;
ohair@286: }
ohair@286:
ohair@286: for (i = 'A'; i <= 'Z'; i++) {
ohair@286: map[i] = (byte) (i - 'A');
ohair@286: }
ohair@286: for (i = 'a'; i <= 'z'; i++) {
ohair@286: map[i] = (byte) (i - 'a' + 26);
ohair@286: }
ohair@286: for (i = '0'; i <= '9'; i++) {
ohair@286: map[i] = (byte) (i - '0' + 52);
ohair@286: }
ohair@286: map['+'] = 62;
ohair@286: map['/'] = 63;
ohair@286: map['='] = PADDING;
ohair@286:
ohair@286: return map;
ohair@286: }
ohair@286:
ohair@286: /**
ohair@286: * computes the length of binary data speculatively.
ohair@286: *
ohair@286: *
ohair@286: * Our requirement is to create byte[] of the exact length to store the binary data.
ohair@286: * If we do this in a straight-forward way, it takes two passes over the data.
ohair@286: * Experiments show that this is a non-trivial overhead (35% or so is spent on
ohair@286: * the first pass in calculating the length.)
ohair@286: *
ohair@286: *
ohair@286: * So the approach here is that we compute the length speculatively, without looking
ohair@286: * at the whole contents. The obtained speculative value is never less than the
ohair@286: * actual length of the binary data, but it may be bigger. So if the speculation
ohair@286: * goes wrong, we'll pay the cost of reallocation and buffer copying.
ohair@286: *
ohair@286: *
ohair@286: * If the base64 text is tightly packed with no indentation nor illegal char
ohair@286: * (like what most web services produce), then the speculation of this method
ohair@286: * will be correct, so we get the performance benefit.
ohair@286: */
ohair@286: private static int guessLength(String text) {
ohair@286: final int len = text.length();
ohair@286:
ohair@286: // compute the tail '=' chars
ohair@286: int j = len - 1;
ohair@286: for (; j >= 0; j--) {
ohair@286: byte code = decodeMap[text.charAt(j)];
ohair@286: if (code == PADDING) {
ohair@286: continue;
ohair@286: }
ohair@286: if (code == -1) // most likely this base64 text is indented. go with the upper bound
ohair@286: {
ohair@286: return text.length() / 4 * 3;
ohair@286: }
ohair@286: break;
ohair@286: }
ohair@286:
ohair@286: j++; // text.charAt(j) is now at some base64 char, so +1 to make it the size
ohair@286: int padSize = len - j;
ohair@286: if (padSize > 2) // something is wrong with base64. be safe and go with the upper bound
ohair@286: {
ohair@286: return text.length() / 4 * 3;
ohair@286: }
ohair@286:
ohair@286: // so far this base64 looks like it's unindented tightly packed base64.
ohair@286: // take a chance and create an array with the expected size
ohair@286: return text.length() / 4 * 3 - padSize;
ohair@286: }
ohair@286:
ohair@286: /**
ohair@286: * @param text
ohair@286: * base64Binary data is likely to be long, and decoding requires
ohair@286: * each character to be accessed twice (once for counting length, another
ohair@286: * for decoding.)
ohair@286: *
ohair@286: * A benchmark showed that taking {@link String} is faster, presumably
ohair@286: * because JIT can inline a lot of string access (with data of 1K chars, it was twice as fast)
ohair@286: */
ohair@286: public static byte[] _parseBase64Binary(String text) {
ohair@286: final int buflen = guessLength(text);
ohair@286: final byte[] out = new byte[buflen];
ohair@286: int o = 0;
ohair@286:
ohair@286: final int len = text.length();
ohair@286: int i;
ohair@286:
ohair@286: final byte[] quadruplet = new byte[4];
ohair@286: int q = 0;
ohair@286:
ohair@286: // convert each quadruplet to three bytes.
ohair@286: for (i = 0; i < len; i++) {
ohair@286: char ch = text.charAt(i);
ohair@286: byte v = decodeMap[ch];
ohair@286:
ohair@286: if (v != -1) {
ohair@286: quadruplet[q++] = v;
ohair@286: }
ohair@286:
ohair@286: if (q == 4) {
ohair@286: // quadruplet is now filled.
ohair@286: out[o++] = (byte) ((quadruplet[0] << 2) | (quadruplet[1] >> 4));
ohair@286: if (quadruplet[2] != PADDING) {
ohair@286: out[o++] = (byte) ((quadruplet[1] << 4) | (quadruplet[2] >> 2));
ohair@286: }
ohair@286: if (quadruplet[3] != PADDING) {
ohair@286: out[o++] = (byte) ((quadruplet[2] << 6) | (quadruplet[3]));
ohair@286: }
ohair@286: q = 0;
ohair@286: }
ohair@286: }
ohair@286:
ohair@286: if (buflen == o) // speculation worked out to be OK
ohair@286: {
ohair@286: return out;
ohair@286: }
ohair@286:
ohair@286: // we overestimated, so need to create a new buffer
ohair@286: byte[] nb = new byte[o];
ohair@286: System.arraycopy(out, 0, nb, 0, o);
ohair@286: return nb;
ohair@286: }
ohair@286: private static final char[] encodeMap = initEncodeMap();
ohair@286:
ohair@286: private static char[] initEncodeMap() {
ohair@286: char[] map = new char[64];
ohair@286: int i;
ohair@286: for (i = 0; i < 26; i++) {
ohair@286: map[i] = (char) ('A' + i);
ohair@286: }
ohair@286: for (i = 26; i < 52; i++) {
ohair@286: map[i] = (char) ('a' + (i - 26));
ohair@286: }
ohair@286: for (i = 52; i < 62; i++) {
ohair@286: map[i] = (char) ('0' + (i - 52));
ohair@286: }
ohair@286: map[62] = '+';
ohair@286: map[63] = '/';
ohair@286:
ohair@286: return map;
ohair@286: }
ohair@286:
ohair@286: public static char encode(int i) {
ohair@286: return encodeMap[i & 0x3F];
ohair@286: }
ohair@286:
ohair@286: public static byte encodeByte(int i) {
ohair@286: return (byte) encodeMap[i & 0x3F];
ohair@286: }
ohair@286:
ohair@286: public static String _printBase64Binary(byte[] input) {
ohair@286: return _printBase64Binary(input, 0, input.length);
ohair@286: }
ohair@286:
ohair@286: public static String _printBase64Binary(byte[] input, int offset, int len) {
ohair@286: char[] buf = new char[((len + 2) / 3) * 4];
ohair@286: int ptr = _printBase64Binary(input, offset, len, buf, 0);
ohair@286: assert ptr == buf.length;
ohair@286: return new String(buf);
ohair@286: }
ohair@286:
ohair@286: /**
ohair@286: * Encodes a byte array into a char array by doing base64 encoding.
ohair@286: *
ohair@286: * The caller must supply a big enough buffer.
ohair@286: *
ohair@286: * @return
ohair@286: * the value of {@code ptr+((len+2)/3)*4}, which is the new offset
ohair@286: * in the output buffer where the further bytes should be placed.
ohair@286: */
ohair@286: public static int _printBase64Binary(byte[] input, int offset, int len, char[] buf, int ptr) {
ohair@286: // encode elements until only 1 or 2 elements are left to encode
ohair@286: int remaining = len;
ohair@286: int i;
ohair@286: for (i = offset;remaining >= 3; remaining -= 3, i += 3) {
ohair@286: buf[ptr++] = encode(input[i] >> 2);
ohair@286: buf[ptr++] = encode(
ohair@286: ((input[i] & 0x3) << 4)
ohair@286: | ((input[i + 1] >> 4) & 0xF));
ohair@286: buf[ptr++] = encode(
ohair@286: ((input[i + 1] & 0xF) << 2)
ohair@286: | ((input[i + 2] >> 6) & 0x3));
ohair@286: buf[ptr++] = encode(input[i + 2] & 0x3F);
ohair@286: }
ohair@286: // encode when exactly 1 element (left) to encode
ohair@286: if (remaining == 1) {
ohair@286: buf[ptr++] = encode(input[i] >> 2);
ohair@286: buf[ptr++] = encode(((input[i]) & 0x3) << 4);
ohair@286: buf[ptr++] = '=';
ohair@286: buf[ptr++] = '=';
ohair@286: }
ohair@286: // encode when exactly 2 elements (left) to encode
ohair@286: if (remaining == 2) {
ohair@286: buf[ptr++] = encode(input[i] >> 2);
ohair@286: buf[ptr++] = encode(((input[i] & 0x3) << 4)
ohair@286: | ((input[i + 1] >> 4) & 0xF));
ohair@286: buf[ptr++] = encode((input[i + 1] & 0xF) << 2);
ohair@286: buf[ptr++] = '=';
ohair@286: }
ohair@286: return ptr;
ohair@286: }
ohair@286:
ohair@286: /**
ohair@286: * Encodes a byte array into another byte array by first doing base64 encoding
ohair@286: * then encoding the result in ASCII.
ohair@286: *
ohair@286: * The caller must supply a big enough buffer.
ohair@286: *
ohair@286: * @return
ohair@286: * the value of {@code ptr+((len+2)/3)*4}, which is the new offset
ohair@286: * in the output buffer where the further bytes should be placed.
ohair@286: */
ohair@286: public static int _printBase64Binary(byte[] input, int offset, int len, byte[] out, int ptr) {
ohair@286: byte[] buf = out;
ohair@286: int remaining = len;
ohair@286: int i;
ohair@286: for (i=offset; remaining >= 3; remaining -= 3, i += 3 ) {
ohair@286: buf[ptr++] = encodeByte(input[i]>>2);
ohair@286: buf[ptr++] = encodeByte(
ohair@286: ((input[i]&0x3)<<4) |
ohair@286: ((input[i+1]>>4)&0xF));
ohair@286: buf[ptr++] = encodeByte(
ohair@286: ((input[i+1]&0xF)<<2)|
ohair@286: ((input[i+2]>>6)&0x3));
ohair@286: buf[ptr++] = encodeByte(input[i+2]&0x3F);
ohair@286: }
ohair@286: // encode when exactly 1 element (left) to encode
ohair@286: if (remaining == 1) {
ohair@286: buf[ptr++] = encodeByte(input[i]>>2);
ohair@286: buf[ptr++] = encodeByte(((input[i])&0x3)<<4);
ohair@286: buf[ptr++] = '=';
ohair@286: buf[ptr++] = '=';
ohair@286: }
ohair@286: // encode when exactly 2 elements (left) to encode
ohair@286: if (remaining == 2) {
ohair@286: buf[ptr++] = encodeByte(input[i]>>2);
ohair@286: buf[ptr++] = encodeByte(
ohair@286: ((input[i]&0x3)<<4) |
ohair@286: ((input[i+1]>>4)&0xF));
ohair@286: buf[ptr++] = encodeByte((input[i+1]&0xF)<<2);
ohair@286: buf[ptr++] = '=';
ohair@286: }
ohair@286:
ohair@286: return ptr;
ohair@286: }
ohair@286:
ohair@286: private static CharSequence removeOptionalPlus(CharSequence s) {
ohair@286: int len = s.length();
ohair@286:
ohair@286: if (len <= 1 || s.charAt(0) != '+') {
ohair@286: return s;
ohair@286: }
ohair@286:
ohair@286: s = s.subSequence(1, len);
ohair@286: char ch = s.charAt(0);
ohair@286: if ('0' <= ch && ch <= '9') {
ohair@286: return s;
ohair@286: }
ohair@286: if ('.' == ch) {
ohair@286: return s;
ohair@286: }
ohair@286:
ohair@286: throw new NumberFormatException();
ohair@286: }
ohair@286:
ohair@286: private static boolean isDigitOrPeriodOrSign(char ch) {
ohair@286: if ('0' <= ch && ch <= '9') {
ohair@286: return true;
ohair@286: }
ohair@286: if (ch == '+' || ch == '-' || ch == '.') {
ohair@286: return true;
ohair@286: }
ohair@286: return false;
ohair@286: }
ohair@286: private static final DatatypeFactory datatypeFactory;
ohair@286:
ohair@286: static {
ohair@286: try {
ohair@286: datatypeFactory = DatatypeFactory.newInstance();
ohair@286: } catch (DatatypeConfigurationException e) {
ohair@286: throw new Error(e);
ohair@286: }
ohair@286: }
ohair@286:
ohair@286: private static final class CalendarFormatter {
ohair@286:
ohair@286: public static String doFormat(String format, Calendar cal) throws IllegalArgumentException {
ohair@286: int fidx = 0;
ohair@286: int flen = format.length();
ohair@286: StringBuilder buf = new StringBuilder();
ohair@286:
ohair@286: while (fidx < flen) {
ohair@286: char fch = format.charAt(fidx++);
ohair@286:
ohair@286: if (fch != '%') { // not a meta character
ohair@286: buf.append(fch);
ohair@286: continue;
ohair@286: }
ohair@286:
ohair@286: // seen meta character. we don't do error check against the format
ohair@286: switch (format.charAt(fidx++)) {
ohair@286: case 'Y': // year
ohair@286: formatYear(cal, buf);
ohair@286: break;
ohair@286:
ohair@286: case 'M': // month
ohair@286: formatMonth(cal, buf);
ohair@286: break;
ohair@286:
ohair@286: case 'D': // days
ohair@286: formatDays(cal, buf);
ohair@286: break;
ohair@286:
ohair@286: case 'h': // hours
ohair@286: formatHours(cal, buf);
ohair@286: break;
ohair@286:
ohair@286: case 'm': // minutes
ohair@286: formatMinutes(cal, buf);
ohair@286: break;
ohair@286:
ohair@286: case 's': // parse seconds.
ohair@286: formatSeconds(cal, buf);
ohair@286: break;
ohair@286:
ohair@286: case 'z': // time zone
ohair@286: formatTimeZone(cal, buf);
ohair@286: break;
ohair@286:
ohair@286: default:
ohair@286: // illegal meta character. impossible.
ohair@286: throw new InternalError();
ohair@286: }
ohair@286: }
ohair@286:
ohair@286: return buf.toString();
ohair@286: }
ohair@286:
ohair@286: private static void formatYear(Calendar cal, StringBuilder buf) {
ohair@286: int year = cal.get(Calendar.YEAR);
ohair@286:
ohair@286: String s;
ohair@286: if (year <= 0) // negative value
ohair@286: {
ohair@286: s = Integer.toString(1 - year);
ohair@286: } else // positive value
ohair@286: {
ohair@286: s = Integer.toString(year);
ohair@286: }
ohair@286:
ohair@286: while (s.length() < 4) {
ohair@286: s = '0' + s;
ohair@286: }
ohair@286: if (year <= 0) {
ohair@286: s = '-' + s;
ohair@286: }
ohair@286:
ohair@286: buf.append(s);
ohair@286: }
ohair@286:
ohair@286: private static void formatMonth(Calendar cal, StringBuilder buf) {
ohair@286: formatTwoDigits(cal.get(Calendar.MONTH) + 1, buf);
ohair@286: }
ohair@286:
ohair@286: private static void formatDays(Calendar cal, StringBuilder buf) {
ohair@286: formatTwoDigits(cal.get(Calendar.DAY_OF_MONTH), buf);
ohair@286: }
ohair@286:
ohair@286: private static void formatHours(Calendar cal, StringBuilder buf) {
ohair@286: formatTwoDigits(cal.get(Calendar.HOUR_OF_DAY), buf);
ohair@286: }
ohair@286:
ohair@286: private static void formatMinutes(Calendar cal, StringBuilder buf) {
ohair@286: formatTwoDigits(cal.get(Calendar.MINUTE), buf);
ohair@286: }
ohair@286:
ohair@286: private static void formatSeconds(Calendar cal, StringBuilder buf) {
ohair@286: formatTwoDigits(cal.get(Calendar.SECOND), buf);
ohair@286: if (cal.isSet(Calendar.MILLISECOND)) { // milliseconds
ohair@286: int n = cal.get(Calendar.MILLISECOND);
ohair@286: if (n != 0) {
ohair@286: String ms = Integer.toString(n);
ohair@286: while (ms.length() < 3) {
ohair@286: ms = '0' + ms; // left 0 paddings.
ohair@286: }
ohair@286: buf.append('.');
ohair@286: buf.append(ms);
ohair@286: }
ohair@286: }
ohair@286: }
ohair@286:
ohair@286: /** formats time zone specifier. */
ohair@286: private static void formatTimeZone(Calendar cal, StringBuilder buf) {
ohair@286: TimeZone tz = cal.getTimeZone();
ohair@286:
ohair@286: if (tz == null) {
ohair@286: return;
ohair@286: }
ohair@286:
ohair@286: // otherwise print out normally.
ohair@286: int offset = tz.getOffset(cal.getTime().getTime());
ohair@286:
ohair@286: if (offset == 0) {
ohair@286: buf.append('Z');
ohair@286: return;
ohair@286: }
ohair@286:
ohair@286: if (offset >= 0) {
ohair@286: buf.append('+');
ohair@286: } else {
ohair@286: buf.append('-');
ohair@286: offset *= -1;
ohair@286: }
ohair@286:
ohair@286: offset /= 60 * 1000; // offset is in milli-seconds
ohair@286:
ohair@286: formatTwoDigits(offset / 60, buf);
ohair@286: buf.append(':');
ohair@286: formatTwoDigits(offset % 60, buf);
ohair@286: }
ohair@286:
ohair@286: /** formats Integer into two-character-wide string. */
ohair@286: private static void formatTwoDigits(int n, StringBuilder buf) {
ohair@286: // n is always non-negative.
ohair@286: if (n < 10) {
ohair@286: buf.append('0');
ohair@286: }
ohair@286: buf.append(n);
ohair@286: }
ohair@286: }
ohair@286: }