001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common Development
008: * and Distribution License("CDDL") (collectively, the "License"). You
009: * may not use this file except in compliance with the License. You can obtain
010: * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011: * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
012: * language governing permissions and limitations under the License.
013: *
014: * When distributing the software, include this License Header Notice in each
015: * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016: * Sun designates this particular file as subject to the "Classpath" exception
017: * as provided by Sun in the GPL Version 2 section of the License file that
018: * accompanied this code. If applicable, add the following below the License
019: * Header, with the fields enclosed by brackets [] replaced by your own
020: * identifying information: "Portions Copyrighted [year]
021: * [name of copyright owner]"
022: *
023: * Contributor(s):
024: *
025: * If you wish your version of this file to be governed by only the CDDL or
026: * only the GPL Version 2, indicate your decision by adding "[Contributor]
027: * elects to include this software in this distribution under the [CDDL or GPL
028: * Version 2] license." If you don't indicate a single choice of license, a
029: * recipient has the option to distribute your version of this file under
030: * either the CDDL, the GPL Version 2 or to extend the choice of license to
031: * its licensees as provided above. However, if you add GPL Version 2 code
032: * and therefore, elected the GPL Version 2 license, then the option applies
033: * only if the new code is made subject to such option by the copyright
034: * holder.
035: */
036:
037: package org.jvnet.staxex;
038:
039: import javax.activation.DataHandler;
040: import javax.activation.DataSource;
041: import java.io.InputStream;
042: import java.io.IOException;
043: import java.io.ByteArrayInputStream;
044: import java.io.OutputStream;
045:
046: /**
047: * Binary data represented as base64-encoded string
048: * in XML.
049: *
050: * <p>
051: * Used in conjunction with {@link XMLStreamReaderEx}
052: * and {@link XMLStreamWriterEx}.
053: *
054: * @author Kohsuke Kawaguchi
055: */
056: public class Base64Data implements CharSequence, Cloneable {
057:
058: // either dataHandler or (data,dataLen,mimeType?) must be present
059: // (note that having both is allowed)
060:
061: private DataHandler dataHandler;
062:
063: private byte[] data;
064: /**
065: * Length of the valid data in {@link #data}.
066: */
067: private int dataLen;
068: /**
069: * True if {@link #data} can be cloned by reference
070: * if Base64Data instance is cloned.
071: */
072: private boolean dataCloneByRef;
073: /**
074: * Optional MIME type of {@link #data}.
075: *
076: * Unused when {@link #dataHandler} is set.
077: * Use {@link DataHandler#getContentType()} in that case.
078: */
079: private String mimeType;
080:
081: /**
082: * Default constructor
083: */
084: public Base64Data() {
085: }
086:
087: /**
088: * Clone constructor
089: * @param that needs to be cloned
090: */
091: public Base64Data(Base64Data that) {
092: that.get();
093: if (that.dataCloneByRef) {
094: this .data = that.data;
095: } else {
096: this .data = new byte[that.dataLen];
097: System.arraycopy(that.data, 0, this .data, 0, that.dataLen);
098: }
099:
100: this .dataCloneByRef = true;
101: this .dataLen = that.dataLen;
102: this .dataHandler = null;
103: this .mimeType = that.mimeType;
104: }
105:
106: /**
107: * Fills in the data object by a portion of the byte[].
108: *
109: * @param data actual data
110: * @param len
111: * data[0] to data[len-1] are treated as the data.
112: * @param mimeType MIME type
113: * @param cloneByRef
114: * true if data[] can be cloned by reference
115: */
116: public void set(byte[] data, int len, String mimeType,
117: boolean cloneByRef) {
118: this .data = data;
119: this .dataLen = len;
120: this .dataCloneByRef = cloneByRef;
121: this .dataHandler = null;
122: this .mimeType = mimeType;
123: }
124:
125: /**
126: * Fills in the data object by a portion of the byte[].
127: *
128: * @param data actual data bytes
129: * @param len
130: * data[0] to data[len-1] are treated as the data.
131: * @param mimeType MIME type
132: */
133: public void set(byte[] data, int len, String mimeType) {
134: set(data, len, mimeType, false);
135: }
136:
137: /**
138: * Fills in the data object by the byte[] of the exact length.
139: *
140: * @param data
141: * this buffer may be owned directly by the unmarshaleld JAXB object.
142: * @param mimeType MIME type
143: */
144: public void set(byte[] data, String mimeType) {
145: set(data, data.length, mimeType, false);
146: }
147:
148: /**
149: * Fills in the data object by a {@link DataHandler}.
150: *
151: * @param data DataHandler for the data
152: */
153: public void set(DataHandler data) {
154: assert data != null;
155: this .dataHandler = data;
156: this .data = null;
157: }
158:
159: /**
160: * Gets the raw data. If the returned DataHandler is {@link StreamingDataHandler},
161: * callees may need to downcast to take advantage of its capabilities.
162: *
163: * @see StreamingDataHandler
164: * @return DataHandler for the data
165: */
166: public DataHandler getDataHandler() {
167: if (dataHandler == null) {
168: dataHandler = new DataHandler(new DataSource() {
169: public String getContentType() {
170: return getMimeType();
171: }
172:
173: public InputStream getInputStream() {
174: return new ByteArrayInputStream(data, 0, dataLen);
175: }
176:
177: public String getName() {
178: return null;
179: }
180:
181: public OutputStream getOutputStream() {
182: throw new UnsupportedOperationException();
183: }
184: });
185: }
186: return dataHandler;
187: }
188:
189: /**
190: * Gets the byte[] of the exact length.
191: *
192: * @return byte[] for data
193: */
194: public byte[] getExact() {
195: get();
196: if (dataLen != data.length) {
197: byte[] buf = new byte[dataLen];
198: System.arraycopy(data, 0, buf, 0, dataLen);
199: data = buf;
200: }
201: return data;
202: }
203:
204: /**
205: * Gets the data as an {@link InputStream}.
206: *
207: * @return data as InputStream
208: * @throws IOException if i/o error occurs
209: */
210: public InputStream getInputStream() throws IOException {
211: if (dataHandler != null)
212: return dataHandler.getInputStream();
213: else
214: return new ByteArrayInputStream(data, 0, dataLen);
215: }
216:
217: /**
218: * Returns false if this object only has {@link DataHandler} and therefore
219: * {@link #get()} operation is likely going to be expensive.
220: *
221: * @return false if it has only DataHandler
222: */
223: public boolean hasData() {
224: return data != null;
225: }
226:
227: /**
228: * Gets the raw data. The size of the byte array maybe larger than the actual length.
229: *
230: * @return data as byte[], the array may be larger
231: */
232: public byte[] get() {
233: if (data == null) {
234: try {
235: ByteArrayOutputStreamEx baos = new ByteArrayOutputStreamEx(
236: 1024);
237: InputStream is = dataHandler.getDataSource()
238: .getInputStream();
239: baos.readFrom(is);
240: is.close();
241: data = baos.getBuffer();
242: dataLen = baos.size();
243: dataCloneByRef = true;
244: } catch (IOException e) {
245: // TODO: report the error to the unmarshaller
246: dataLen = 0; // recover by assuming length-0 data
247: }
248: }
249: return data;
250: }
251:
252: /**
253: * Gets the length of the binary data counted in bytes.
254: *
255: * Note that if this object encapsulates {@link DataHandler},
256: * this method would have to read the whole thing into {@code byte[]}
257: * just to count the length, because {@link DataHandler}
258: * doesn't easily expose the length.
259: *
260: * @return no of bytes
261: */
262: public int getDataLen() {
263: get();
264: return dataLen;
265: }
266:
267: public String getMimeType() {
268: if (mimeType == null)
269: return "application/octet-stream";
270: return mimeType;
271: }
272:
273: /**
274: * Gets the number of characters needed to represent
275: * this binary data in the base64 encoding.
276: */
277: public int length() {
278: // for each 3 bytes you use 4 chars
279: // if the remainder is 1 or 2 there will be 4 more
280: get(); // fill in the buffer if necessary
281: return ((dataLen + 2) / 3) * 4;
282: }
283:
284: /**
285: * Encode this binary data in the base64 encoding
286: * and returns the character at the specified position.
287: */
288: public char charAt(int index) {
289: // we assume that the length() method is called before this method
290: // (otherwise how would the caller know that the index is valid?)
291: // so we assume that the byte[] is already populated
292:
293: int offset = index % 4;
294: int base = (index / 4) * 3;
295:
296: byte b1, b2;
297:
298: switch (offset) {
299: case 0:
300: return Base64Encoder.encode(data[base] >> 2);
301: case 1:
302: if (base + 1 < dataLen)
303: b1 = data[base + 1];
304: else
305: b1 = 0;
306: return Base64Encoder.encode(((data[base] & 0x3) << 4)
307: | ((b1 >> 4) & 0xF));
308: case 2:
309: if (base + 1 < dataLen) {
310: b1 = data[base + 1];
311: if (base + 2 < dataLen)
312: b2 = data[base + 2];
313: else
314: b2 = 0;
315:
316: return Base64Encoder.encode(((b1 & 0xF) << 2)
317: | ((b2 >> 6) & 0x3));
318: } else
319: return '=';
320: case 3:
321: if (base + 2 < dataLen)
322: return Base64Encoder.encode(data[base + 2] & 0x3F);
323: else
324: return '=';
325: }
326:
327: throw new IllegalStateException();
328: }
329:
330: /**
331: * Internally this is only used to split a text to a list,
332: * which doesn't happen that much for base64.
333: * So this method should be smaller than faster.
334: */
335: public CharSequence subSequence(int start, int end) {
336: StringBuilder buf = new StringBuilder();
337: get(); // fill in the buffer if we haven't done so
338: for (int i = start; i < end; i++)
339: buf.append(charAt(i));
340: return buf;
341: }
342:
343: /**
344: * Returns the base64 encoded string of this data.
345: */
346: public String toString() {
347: get(); // fill in the buffer
348: return Base64Encoder.print(data, 0, dataLen);
349: }
350:
351: public void writeTo(char[] buf, int start) {
352: get();
353: Base64Encoder.print(data, 0, dataLen, buf, start);
354: }
355:
356: public Base64Data clone() {
357: return new Base64Data(this);
358: }
359: }
|