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 transient 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      */
 166     public byte[] getBytes(long pos, int length) throws SerialException {
 167         if (isFree == true) {
 168             throw new SerialException(
 169                     "Unsupported operation. SerialBlob cannot "
 170                             + "get bytes when it has already been freed with free()");
 171          }
 172 
 173         if (length > len) {
 174             length = (int)len;
 175         }
 176 
 177         if (pos < 1 || len - pos < 0 ) {
 178             throw new SerialException("Invalid arguments: position cannot be "
 179                     + "less than 1 or greater than the length of the SerialBlob");
 180         }
 181 
 182         pos--; // correct pos to array index
 183 
 184         byte[] b = new byte[length];
 185 
 186         for (int i = 0; i < length; i++) {
 187             b[i] = this.buf[(int)pos];
 188             pos++;
 189         }
 190         return b;
 191     }
 192 
 193     /**
 194      * Retrieves the number of bytes in this <code>SerialBlob</code>
 195      * object's array of bytes.
 196      *
 197      * @return a <code>long</code> indicating the length in bytes of this
 198      *         <code>SerialBlob</code> object's array of bytes
 199      * @throws SerialException if an error occurs
 200      */
 201     public long length() throws SerialException {
 202         return len;
 203     }
 204 
 205     /**
 206      * Returns this <code>SerialBlob</code> object as an input stream.
 207      * Unlike the related method, <code>setBinaryStream</code>,
 208      * a stream is produced regardless of whether the <code>SerialBlob</code>
 209      * was created with a <code>Blob</code> object or a <code>byte</code> array.
 210      *
 211      * @return a <code>java.io.InputStream</code> object that contains
 212      *         this <code>SerialBlob</code> object's array of bytes
 213      * @throws SerialException if an error occurs
 214      * @see #setBinaryStream
 215      */
 216     public java.io.InputStream getBinaryStream() throws SerialException {
 217          if (isFree == true) {
 218             throw new SerialException(
 219                     "Unsupported operation. SerialBlob cannot "
 220                             + "return a binary stream when it has already been freed with free()");
 221          }
 222 
 223          InputStream stream = new ByteArrayInputStream(buf);
 224          return stream;
 225     }
 226 
 227     /**
 228      * Returns the position in this <code>SerialBlob</code> object where
 229      * the given pattern of bytes begins, starting the search at the
 230      * specified position.
 231      *
 232      * @param pattern the pattern of bytes for which to search
 233      * @param start the position of the byte in this
 234      *              <code>SerialBlob</code> object from which to begin
 235      *              the search; the first position is <code>1</code>;
 236      *              must not be less than <code>1</code> nor greater than
 237      *              the length of this <code>SerialBlob</code> object
 238      * @return the position in this <code>SerialBlob</code> object
 239      *         where the given pattern begins, starting at the specified
 240      *         position; <code>-1</code> if the pattern is not found
 241      *         or the given starting position is out of bounds; position
 242      *         numbering for the return value starts at <code>1</code>
 243      * @throws SerialException if an error occurs when serializing the blob
 244      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 245      *         value from the database
 246      */
 247     public long position(byte[] pattern, long start)
 248                 throws SerialException, SQLException {
 249         if (isFree == true) {
 250             throw new SerialException(
 251                     "Unsupported operation. SerialBlob has already been freed ");
 252         }
 253 
 254         if (start < 1 || start > len) {
 255             return -1;
 256         }
 257 
 258         int pos = (int)start-1; // internally Blobs are stored as arrays.
 259         int i = 0;
 260         long patlen = pattern.length;
 261 
 262         while (pos < len) {
 263             if (pattern[i] == buf[pos]) {
 264                 if (i + 1 == patlen) {
 265                     return (pos + 1) - (patlen - 1);
 266                 }
 267                 i++; pos++; // increment pos, and i
 268             } else if (pattern[i] != buf[pos]) {
 269                 pos++; // increment pos only
 270             }
 271         }
 272         return -1; // not found
 273     }
 274 
 275     /**
 276      * Returns the position in this <code>SerialBlob</code> object where
 277      * the given <code>Blob</code> object begins, starting the search at the
 278      * specified position.
 279      *
 280      * @param pattern the <code>Blob</code> object for which to search;
 281      * @param start the position of the byte in this
 282      *              <code>SerialBlob</code> object from which to begin
 283      *              the search; the first position is <code>1</code>;
 284      *              must not be less than <code>1</code> nor greater than
 285      *              the length of this <code>SerialBlob</code> object
 286      * @return the position in this <code>SerialBlob</code> object
 287      *         where the given <code>Blob</code> object begins, starting
 288      *         at the specified position; <code>-1</code> if the pattern is
 289      *         not found or the given starting position is out of bounds;
 290      *         position numbering for the return value starts at <code>1</code>
 291      * @throws SerialException if an error occurs when serializing the blob
 292      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 293      *         value from the database
 294      */
 295     public long position(Blob pattern, long start)
 296        throws SerialException, SQLException {
 297         return position(pattern.getBytes(1, (int)(pattern.length())), start);
 298     }
 299 
 300     /**
 301      * Writes the given array of bytes to the <code>BLOB</code> value that
 302      * this <code>Blob</code> object represents, starting at position
 303      * <code>pos</code>, and returns the number of bytes written.
 304      *
 305      * @param pos the position in the SQL <code>BLOB</code> value at which
 306      *     to start writing. The first position is <code>1</code>;
 307      *     must not be less than <code>1</code> nor greater than
 308      *     the length of this <code>SerialBlob</code> object.
 309      * @param bytes the array of bytes to be written to the <code>BLOB</code>
 310      *        value that this <code>Blob</code> object represents
 311      * @return the number of bytes written
 312      * @throws SerialException if there is an error accessing the
 313      *     <code>BLOB</code> value; or if an invalid position is set; if an
 314      *     invalid offset value is set
 315      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 316      *         value from the database
 317      * @see #getBytes
 318      */
 319     public int setBytes(long pos, byte[] bytes)
 320         throws SerialException, SQLException {
 321         return (setBytes(pos, bytes, 0, bytes.length));
 322     }
 323 
 324     /**
 325      * Writes all or part of the given <code>byte</code> array to the
 326      * <code>BLOB</code> value that this <code>Blob</code> object represents
 327      * and returns the number of bytes written.
 328      * Writing starts at position <code>pos</code> in the <code>BLOB</code>
 329      * value; <i>len</i> bytes from the given byte array are written.
 330      *
 331      * @param pos the position in the <code>BLOB</code> object at which
 332      *     to start writing. The first position is <code>1</code>;
 333      *     must not be less than <code>1</code> nor greater than
 334      *     the length of this <code>SerialBlob</code> object.
 335      * @param bytes the array of bytes to be written to the <code>BLOB</code>
 336      *     value
 337      * @param offset the offset in the <code>byte</code> array at which
 338      *     to start reading the bytes. The first offset position is
 339      *     <code>0</code>; must not be less than <code>0</code> nor greater
 340      *     than the length of the <code>byte</code> array
 341      * @param length the number of bytes to be written to the
 342      *     <code>BLOB</code> value from the array of bytes <i>bytes</i>.
 343      *
 344      * @return the number of bytes written
 345      * @throws SerialException if there is an error accessing the
 346      *     <code>BLOB</code> value; if an invalid position is set; if an
 347      *     invalid offset value is set; if number of bytes to be written
 348      *     is greater than the <code>SerialBlob</code> length; or the combined
 349      *     values of the length and offset is greater than the Blob buffer
 350      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 351      *         value from the database.
 352      * @see #getBytes
 353      */
 354     public int setBytes(long pos, byte[] bytes, int offset, int length)
 355         throws SerialException, SQLException {
 356         if (isFree == true) {
 357             throw new SerialException(
 358                     "Unsupported operation. SerialBlob cannot "
 359                             + "set a binary stream when it has already been freed with free()");
 360          }
 361 
 362         if (offset < 0 || offset > bytes.length) {
 363             throw new SerialException("Invalid offset in byte array set");
 364         }
 365 
 366         if (pos < 1 || pos > this.length()) {
 367             throw new SerialException("Invalid position in BLOB object set");
 368         }
 369 
 370         if ((long)(length) > origLen) {
 371             throw new SerialException("Buffer is not sufficient to hold the value");
 372         }
 373 
 374         if ((length + offset) > bytes.length) {
 375             throw new SerialException("Invalid OffSet. Cannot have combined offset " +
 376                 "and length that is greater that the Blob buffer");
 377         }
 378 
 379         int i = 0;
 380         pos--; // correct to array indexing
 381         while ( i < length || (offset + i +1) < (bytes.length-offset) ) {
 382             this.buf[(int)pos + i] = bytes[offset + i ];
 383             i++;
 384         }
 385         return i;
 386     }
 387 
 388     /**
 389      * Retrieves a stream that can be used to write to the <code>BLOB</code>
 390      * value that this <code>Blob</code> object represents.  The stream begins
 391      * at position <code>pos</code>. This method forwards the
 392      * <code>setBinaryStream()</code> call to the underlying <code>Blob</code> in
 393      * the event that this <code>SerialBlob</code> object is instantiated with a
 394      * <code>Blob</code>. If this <code>SerialBlob</code> is instantiated with
 395      * a <code>byte</code> array, a <code>SerialException</code> is thrown.
 396      *
 397      * @param pos the position in the <code>BLOB</code> value at which
 398      *        to start writing
 399      * @return a <code>java.io.OutputStream</code> object to which data can
 400      *         be written
 401      * @throws SQLException if there is an error accessing the
 402      *            <code>BLOB</code> value
 403      * @throws SerialException if the SerialBlob in not instantiated with a
 404      *     <code>Blob</code> object that supports <code>setBinaryStream()</code>
 405      * @see #getBinaryStream
 406      */
 407     public java.io.OutputStream setBinaryStream(long pos)
 408         throws SerialException, SQLException {
 409         if (this.blob != null) {
 410             return this.blob.setBinaryStream(pos);
 411         } else {
 412             throw new SerialException("Unsupported operation. SerialBlob cannot " +
 413                 "return a writable binary stream, unless instantiated with a Blob object " +
 414                 "that provides a setBinaryStream() implementation");
 415         }
 416     }
 417 
 418     /**
 419      * Truncates the <code>BLOB</code> value that this <code>Blob</code>
 420      * object represents to be <code>len</code> bytes in length.
 421      *
 422      * @param length the length, in bytes, to which the <code>BLOB</code>
 423      *        value that this <code>Blob</code> object represents should be
 424      *        truncated
 425      * @throws SerialException if there is an error accessing the Blob value;
 426      *     or the length to truncate is greater that the SerialBlob length
 427      */
 428     public void truncate(long length) throws SerialException {
 429         if (isFree == true) {
 430             throw new SerialException(
 431                     "Unsupported operation. SerialBlob cannot "
 432                             + "truncate a SerialBlob when it has already been freed with free()");
 433          }
 434 
 435          if (length > len) {
 436             throw new SerialException
 437                ("Length more than what can be truncated");
 438          } else if((int)length == 0) {
 439               buf = new byte[0];
 440               len = length;
 441          } else {
 442               len = length;
 443               buf = this.getBytes(1, (int)len);
 444          }
 445     }
 446 
 447 
 448     /**
 449      * Returns an <code>InputStream</code> object that contains a partial <code>Blob</code> value,
 450      * starting  with the byte specified by pos, which is length bytes in length.
 451      *
 452      * @param pos the offset to the first byte of the partial value to be retrieved.
 453      *  The first byte in the <code>Blob</code> is at position 1
 454      * @param length the length in bytes of the partial value to be retrieved
 455      * @return <code>InputStream</code> through which the partial <code>Blob</code> value can be read.
 456      * @throws SQLException if pos is less than 1 or if pos is greater than the number of bytes
 457      * in the <code>Blob</code> or if pos + length is greater than the number of bytes
 458      * in the <code>Blob</code>
 459      *
 460      * @since 1.6
 461      */
 462     public InputStream getBinaryStream(long pos,long length) throws SQLException {
 463         if (isFree == true) {
 464             throw new SerialException(
 465                     "Unsupported operation. SerialBlob cannot "
 466                             + "return a binary stream when it has already been freed with free()");
 467          }
 468 
 469         if (pos < 1 || pos > len || length > len - pos + 1) {
 470             throw new SerialException("Invalid pos in getBinaryStream");
 471         }
 472         if (length > len - pos + 1) {
 473             throw new SerialException("pos + length greater than total number of bytes");
 474         }
 475         return new ByteArrayInputStream(buf, (int) pos - 1, (int) length);
 476     }
 477 
 478 
 479     /**
 480      * This method frees the <code>Blob</code> object and releases the resources that it holds.
 481      * <code>Blob</code> object. The object is invalid once the <code>free</code>
 482      * method is called. If <code>free</code> is called multiple times, the subsequent
 483      * calls to <code>free</code> are treated as a no-op.
 484      *
 485      * @throws SQLException if an error occurs releasing
 486      * the Blob's resources
 487      * @since 1.6
 488      */
 489     public void free() throws SQLException {
 490         if (isFree == false) {
 491             len = -1;
 492             origLen = -1;
 493             buf = null;
 494             blob = null;
 495 
 496             isFree = true;
 497         }
 498     }
 499     /**
 500          * The identifier that assists in the serialization of this <code>SerialBlob</code>
 501      * object.
 502      */
 503 
 504     static final long serialVersionUID = -8144641928112860441L;
 505 }