1 /*
   2  * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javax.sql.rowset.serial;
  27 
  28 import java.sql.*;
  29 import java.io.*;
  30 import java.lang.reflect.*;
  31 
  32 
  33 /**
  34  * A serialized mapping in the Java programming language of an SQL
  35  * <code>BLOB</code> value.
  36  * <P>
  37  * The <code>SerialBlob</code> class provides a constructor for creating
  38  * an instance from a <code>Blob</code> object.  Note that the
  39  * <code>Blob</code>
  40  * object should have brought the SQL <code>BLOB</code> value's data over
  41  * to the client before a <code>SerialBlob</code> object
  42  * is constructed from it.  The data of an SQL <code>BLOB</code> value can
  43  * be materialized on the client as an array of bytes (using the method
  44  * <code>Blob.getBytes</code>) or as a stream of uninterpreted bytes
  45  * (using the method <code>Blob.getBinaryStream</code>).
  46  * <P>
  47  * <code>SerialBlob</code> methods make it possible to make a copy of a
  48  * <code>SerialBlob</code> object as an array of bytes or as a stream.
  49  * They also make it possible to locate a given pattern of bytes or a
  50  * <code>Blob</code> object within a <code>SerialBlob</code> object
  51  * and to update or truncate a <code>Blob</code> object.
  52  *
  53  * @author Jonathan Bruce
  54  */
  55 public class SerialBlob implements Blob, Serializable, Cloneable {
  56 
  57     /**
  58      * A serialized array of uninterpreted bytes representing the
  59      * value of this <code>SerialBlob</code> object.
  60      * @serial
  61      */
  62     private byte buf[];
  63 
  64     /**
  65      * The internal representation of the <code>Blob</code> object on which this
  66      * <code>SerialBlob</code> object is based.
  67      */
  68     private Blob blob;
  69 
  70     /**
  71      * The number of bytes in this <code>SerialBlob</code> object's
  72      * array of bytes.
  73      * @serial
  74      */
  75     private long len;
  76 
  77     /**
  78      * The orginal number of bytes in this <code>SerialBlob</code> object's
  79      * array of bytes when it was first established.
  80      * @serial
  81      */
  82     private long origLen;
  83 
  84     private boolean isFree = false;
  85 
  86     /**
  87      * Constructs a <code>SerialBlob</code> object that is a serialized version of
  88      * the given <code>byte</code> array.
  89      * <p>
  90      * The new <code>SerialBlob</code> object is initialized with the data from the
  91      * <code>byte</code> array, thus allowing disconnected <code>RowSet</code>
  92      * objects to establish serialized <code>Blob</code> objects without
  93      * touching the data source.
  94      *
  95      * @param b the <code>byte</code> array containing the data for the
  96      *        <code>Blob</code> object to be serialized
  97      * @throws SerialException if an error occurs during serialization
  98      * @throws SQLException if a SQL errors occurs
  99      */
 100     public SerialBlob(byte[] b) throws SerialException, SQLException {
 101 
 102         len = b.length;
 103         buf = new byte[(int)len];
 104         for(int i = 0; i < len; i++) {
 105            buf[i] = b[i];
 106         }
 107         origLen = len;
 108     }
 109 
 110 
 111     /**
 112      * Constructs a <code>SerialBlob</code> object that is a serialized
 113      * version of the given <code>Blob</code> object.
 114      * <P>
 115      * The new <code>SerialBlob</code> object is initialized with the
 116      * data from the <code>Blob</code> object; therefore, the
 117      * <code>Blob</code> object should have previously brought the
 118      * SQL <code>BLOB</code> value's data over to the client from
 119      * the database. Otherwise, the new <code>SerialBlob</code> object
 120      * will contain no data.
 121      *
 122      * @param blob the <code>Blob</code> object from which this
 123      *     <code>SerialBlob</code> object is to be constructed;
 124      *     cannot be null.
 125      * @throws SerialException if an error occurs during serialization
 126      * @throws SQLException if the <code>Blob</code> passed to this
 127      *     to this constructor is a <code>null</code>.
 128      * @see java.sql.Blob
 129      */
 130     public SerialBlob (Blob blob) throws SerialException, SQLException {
 131 
 132         if (blob == null) {
 133             throw new SQLException("Cannot instantiate a SerialBlob " +
 134                  "object with a null Blob object");
 135         }
 136 
 137         len = blob.length();
 138         buf = blob.getBytes(1, (int)len );
 139         this.blob = blob;
 140 
 141          //if ( len < 10240000)
 142          // len = 10240000;
 143         origLen = len;
 144     }
 145 
 146     /**
 147      * Copies the specified number of bytes, starting at the given
 148      * position, from this <code>SerialBlob</code> object to
 149      * another array of bytes.
 150      * <P>
 151      * Note that if the given number of bytes to be copied is larger than
 152      * the length of this <code>SerialBlob</code> object's array of
 153      * bytes, the given number will be shortened to the array's length.
 154      *
 155      * @param pos the ordinal position of the first byte in this
 156      *            <code>SerialBlob</code> object to be copied;
 157      *            numbering starts at <code>1</code>; must not be less
 158      *            than <code>1</code> and must be less than or equal
 159      *            to the length of this <code>SerialBlob</code> object
 160      * @param length the number of bytes to be copied
 161      * @return an array of bytes that is a copy of a region of this
 162      *         <code>SerialBlob</code> object, starting at the given
 163      *         position and containing the given number of consecutive bytes
 164      * @throws SerialException if the given starting position is out of bounds
 165      *         or called after free() has been called.
 166      */
 167     public byte[] getBytes(long pos, int length) throws SerialException {
 168         isFreed();
 169 
 170         if (length > len) {
 171             length = (int)len;
 172         }
 173 
 174         if (pos < 1 || len - pos < 0 ) {
 175             throw new SerialException("Invalid arguments: position cannot be "
 176                     + "less than 1 or greater than the length of the SerialBlob");
 177         }
 178 
 179         pos--; // correct pos to array index
 180 
 181         byte[] b = new byte[length];
 182 
 183         for (int i = 0; i < length; i++) {
 184             b[i] = this.buf[(int)pos];
 185             pos++;
 186         }
 187         return b;
 188     }
 189 
 190     /**
 191      * Retrieves the number of bytes in this <code>SerialBlob</code>
 192      * object's array of bytes.
 193      *
 194      * @return a <code>long</code> indicating the length in bytes of this
 195      *         <code>SerialBlob</code> object's array of bytes
 196      * @throws SerialException if an error occurs or called after free() has been called.
 197      */
 198     public long length() throws SerialException {
 199         isFreed();
 200         return len;
 201     }
 202 
 203     /**
 204      * Returns this <code>SerialBlob</code> object as an input stream.
 205      * Unlike the related method, <code>setBinaryStream</code>,
 206      * a stream is produced regardless of whether the <code>SerialBlob</code>
 207      * was created with a <code>Blob</code> object or a <code>byte</code> array.
 208      *
 209      * @return a <code>java.io.InputStream</code> object that contains
 210      *         this <code>SerialBlob</code> object's array of bytes
 211      * @throws SerialException if an error occurs or called after free() has
 212      *         been called.
 213      * @see #setBinaryStream
 214      */
 215     public java.io.InputStream getBinaryStream() throws SerialException {
 216         isFreed();
 217 
 218          InputStream stream = new ByteArrayInputStream(buf);
 219          return stream;
 220     }
 221 
 222     /**
 223      * Returns the position in this <code>SerialBlob</code> object where
 224      * the given pattern of bytes begins, starting the search at the
 225      * specified position.
 226      *
 227      * @param pattern the pattern of bytes for which to search
 228      * @param start the position of the byte in this
 229      *              <code>SerialBlob</code> object from which to begin
 230      *              the search; the first position is <code>1</code>;
 231      *              must not be less than <code>1</code> nor greater than
 232      *              the length of this <code>SerialBlob</code> object
 233      * @return the position in this <code>SerialBlob</code> object
 234      *         where the given pattern begins, starting at the specified
 235      *         position; <code>-1</code> if the pattern is not found
 236      *         or the given starting position is out of bounds; position
 237      *         numbering for the return value starts at <code>1</code>
 238      * @throws SerialException if an error occurs when serializing the blob or
 239      *         called after free() has been called.
 240      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 241      *         value from the database
 242      */
 243     public long position(byte[] pattern, long start)
 244                 throws SerialException, SQLException {
 245         isFreed();
 246 
 247         if (start < 1 || start > len) {
 248             return -1;
 249         }
 250 
 251         int pos = (int)start-1; // internally Blobs are stored as arrays.
 252         int i = 0;
 253         long patlen = pattern.length;
 254 
 255         while (pos < len) {
 256             if (pattern[i] == buf[pos]) {
 257                 if (i + 1 == patlen) {
 258                     return (pos + 1) - (patlen - 1);
 259                 }
 260                 i++; pos++; // increment pos, and i
 261             } else if (pattern[i] != buf[pos]) {
 262                 pos++; // increment pos only
 263             }
 264         }
 265         return -1; // not found
 266     }
 267 
 268     /**
 269      * Returns the position in this <code>SerialBlob</code> object where
 270      * the given <code>Blob</code> object begins, starting the search at the
 271      * specified position.
 272      *
 273      * @param pattern the <code>Blob</code> object for which to search;
 274      * @param start the position of the byte in this
 275      *              <code>SerialBlob</code> object from which to begin
 276      *              the search; the first position is <code>1</code>;
 277      *              must not be less than <code>1</code> nor greater than
 278      *              the length of this <code>SerialBlob</code> object
 279      * @return the position in this <code>SerialBlob</code> object
 280      *         where the given <code>Blob</code> object begins, starting
 281      *         at the specified position; <code>-1</code> if the pattern is
 282      *         not found or the given starting position is out of bounds;
 283      *         position numbering for the return value starts at <code>1</code>
 284      * @throws SerialException if an error occurs when serializing the blob or
 285      *         called after free() has been called.
 286      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 287      *         value from the database
 288      */
 289     public long position(Blob pattern, long start)
 290        throws SerialException, SQLException {
 291         isFreed();
 292         return position(pattern.getBytes(1, (int)(pattern.length())), start);
 293     }
 294 
 295     /**
 296      * Writes the given array of bytes to the <code>BLOB</code> value that
 297      * this <code>Blob</code> object represents, starting at position
 298      * <code>pos</code>, and returns the number of bytes written.
 299      *
 300      * @param pos the position in the SQL <code>BLOB</code> value at which
 301      *     to start writing. The first position is <code>1</code>;
 302      *     must not be less than <code>1</code> nor greater than
 303      *     the length of this <code>SerialBlob</code> object.
 304      * @param bytes the array of bytes to be written to the <code>BLOB</code>
 305      *        value that this <code>Blob</code> object represents
 306      * @return the number of bytes written
 307      * @throws SerialException if there is an error accessing the
 308      *     <code>BLOB</code> value; or if an invalid position is set; if an
 309      *     invalid offset value is set or called after free() has been called.
 310      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 311      *         value from the database
 312      * @see #getBytes
 313      */
 314     public int setBytes(long pos, byte[] bytes)
 315         throws SerialException, SQLException {
 316         isFreed();
 317         return (setBytes(pos, bytes, 0, bytes.length));
 318     }
 319 
 320     /**
 321      * Writes all or part of the given <code>byte</code> array to the
 322      * <code>BLOB</code> value that this <code>Blob</code> object represents
 323      * and returns the number of bytes written.
 324      * Writing starts at position <code>pos</code> in the <code>BLOB</code>
 325      * value; <i>len</i> bytes from the given byte array are written.
 326      *
 327      * @param pos the position in the <code>BLOB</code> object at which
 328      *     to start writing. The first position is <code>1</code>;
 329      *     must not be less than <code>1</code> nor greater than
 330      *     the length of this <code>SerialBlob</code> object.
 331      * @param bytes the array of bytes to be written to the <code>BLOB</code>
 332      *     value
 333      * @param offset the offset in the <code>byte</code> array at which
 334      *     to start reading the bytes. The first offset position is
 335      *     <code>0</code>; must not be less than <code>0</code> nor greater
 336      *     than the length of the <code>byte</code> array
 337      * @param length the number of bytes to be written to the
 338      *     <code>BLOB</code> value from the array of bytes <i>bytes</i>.
 339      *
 340      * @return the number of bytes written
 341      * @throws SerialException if there is an error accessing the
 342      *     <code>BLOB</code> value; if an invalid position is set; if an
 343      *     invalid offset value is set; if number of bytes to be written
 344      *     is greater than the <code>SerialBlob</code> length; or the combined
 345      *     values of the length and offset is greater than the Blob buffer or
 346      *     called after free() has been called.
 347      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 348      *         value from the database.
 349      * @see #getBytes
 350      */
 351     public int setBytes(long pos, byte[] bytes, int offset, int length)
 352         throws SerialException, SQLException {
 353         isFreed();
 354 
 355         if (offset < 0 || offset > bytes.length) {
 356             throw new SerialException("Invalid offset in byte array set");
 357         }
 358 
 359         if (pos < 1 || pos > this.length()) {
 360             throw new SerialException("Invalid position in BLOB object set");
 361         }
 362 
 363         if ((long)(length) > origLen) {
 364             throw new SerialException("Buffer is not sufficient to hold the value");
 365         }
 366 
 367         if ((length + offset) > bytes.length) {
 368             throw new SerialException("Invalid OffSet. Cannot have combined offset " +
 369                 "and length that is greater that the Blob buffer");
 370         }
 371 
 372         int i = 0;
 373         pos--; // correct to array indexing
 374         while ( i < length || (offset + i +1) < (bytes.length-offset) ) {
 375             this.buf[(int)pos + i] = bytes[offset + i ];
 376             i++;
 377         }
 378         return i;
 379     }
 380 
 381     /**
 382      * Retrieves a stream that can be used to write to the <code>BLOB</code>
 383      * value that this <code>Blob</code> object represents.  The stream begins
 384      * at position <code>pos</code>. This method forwards the
 385      * <code>setBinaryStream()</code> call to the underlying <code>Blob</code> in
 386      * the event that this <code>SerialBlob</code> object is instantiated with a
 387      * <code>Blob</code>. If this <code>SerialBlob</code> is instantiated with
 388      * a <code>byte</code> array, a <code>SerialException</code> is thrown.
 389      *
 390      * @param pos the position in the <code>BLOB</code> value at which
 391      *        to start writing
 392      * @return a <code>java.io.OutputStream</code> object to which data can
 393      *         be written
 394      * @throws SQLException if there is an error accessing the
 395      *            <code>BLOB</code> value
 396      * @throws SerialException if the SerialBlob in not instantiated with a
 397      *     <code>Blob</code> object that supports <code>setBinaryStream()</code>
 398      *     or called after free() has been called.
 399      * @see #getBinaryStream
 400      */
 401     public java.io.OutputStream setBinaryStream(long pos)
 402         throws SerialException, SQLException {
 403         isFreed();
 404 
 405         if (this.blob != null) {
 406             return this.blob.setBinaryStream(pos);
 407         } else {
 408             throw new SerialException("Unsupported operation. SerialBlob cannot " +
 409                 "return a writable binary stream, unless instantiated with a Blob object " +
 410                 "that provides a setBinaryStream() implementation");
 411         }
 412     }
 413 
 414     /**
 415      * Truncates the <code>BLOB</code> value that this <code>Blob</code>
 416      * object represents to be <code>len</code> bytes in length.
 417      *
 418      * @param length the length, in bytes, to which the <code>BLOB</code>
 419      *        value that this <code>Blob</code> object represents should be
 420      *        truncated
 421      * @throws SerialException if there is an error accessing the Blob value;
 422      *     or the length to truncate is greater that the SerialBlob length or
 423      *     called after free() has been called.
 424      */
 425     public void truncate(long length) throws SerialException {
 426         isFreed();
 427 
 428          if (length > len) {
 429             throw new SerialException
 430                ("Length more than what can be truncated");
 431          } else if((int)length == 0) {
 432               buf = new byte[0];
 433               len = length;
 434          } else {
 435               len = length;
 436               buf = this.getBytes(1, (int)len);
 437          }
 438     }
 439 
 440 
 441     /**
 442      * Returns an <code>InputStream</code> object that contains a partial <code>Blob</code> value,
 443      * starting  with the byte specified by pos, which is length bytes in length.
 444      *
 445      * @param pos the offset to the first byte of the partial value to be retrieved.
 446      *  The first byte in the <code>Blob</code> is at position 1
 447      * @param length the length in bytes of the partial value to be retrieved
 448      * @return <code>InputStream</code> through which the partial <code>Blob</code> value can be read.
 449      * @throws SerialException if called after free() has been called.
 450      * @throws SQLException if pos is less than 1 or if pos is greater than the number of bytes
 451      * in the <code>Blob</code> or if pos + length is greater than the number of bytes
 452      * in the <code>Blob</code>
 453      *
 454      * @since 1.6
 455      */
 456     public InputStream getBinaryStream(long pos,long length) throws SerialException, SQLException {
 457         isFreed();
 458 
 459         if (pos < 1 || pos > len) {
 460             throw new SerialException("Invalid pos in getBinaryStream");
 461         }
 462         if ((pos - 1) + length > len) {
 463             throw new SerialException(
 464                     "pos + length greater than total number of bytes");
 465         }
 466         return new ByteArrayInputStream(buf, (int) pos - 1, (int) length);
 467     }
 468 
 469 
 470     /**
 471      * This method frees the <code>Blob</code> object and releases the
 472      * resources that it holds. <code>Blob</code> object. The object is
 473      * invalid once the <code>free</code> method is called. After
 474      * <code>free</code> has been called, any attempt to invoke a method
 475      * other than <code>free</code> will result in a
 476      * <code>SerialException</code> being thrown. If <code>free</code> is
 477      * called multiple times, the subsequent calls to <code>free</code>
 478      * are treated as a no-op.
 479      *
 480      * @throws SQLException if an error occurs releasing the Blob's resources
 481      * @since 1.6
 482      */
 483     public void free() throws SQLException {
 484         if (isFree == false) {
 485             len = -1;
 486             origLen = -1;
 487             buf = null;
 488 
 489             if (blob != null) {
 490                 blob.free();
 491                 blob = null;
 492             }
 493 
 494             isFree = true;
 495         }
 496     }
 497 
 498     private void isFreed() throws SerialException {
 499         if (isFree == true) {
 500             throw new SerialException(
 501                     "Unsupported operation. SerialBlob cannot "
 502                             + "execute this operation when it"
 503                             + "has already been freed by free()");
 504         }
 505     }
 506 
 507     /**
 508          * The identifier that assists in the serialization of this <code>SerialBlob</code>
 509      * object.
 510      */
 511 
 512     static final long serialVersionUID = -8144641928112860441L;
 513 }