1 /*
   2  * Copyright (c) 2003, 2012, 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 import java.util.Arrays;
  32 import java.util.Objects;
  33 
  34 
  35 /**
  36  * A serialized mapping in the Java programming language of an SQL
  37  * <code>BLOB</code> value.
  38  * <P>
  39  * The <code>SerialBlob</code> class provides a constructor for creating
  40  * an instance from a <code>Blob</code> object.  Note that the
  41  * <code>Blob</code>
  42  * object should have brought the SQL <code>BLOB</code> value's data over
  43  * to the client before a <code>SerialBlob</code> object
  44  * is constructed from it.  The data of an SQL <code>BLOB</code> value can
  45  * be materialized on the client as an array of bytes (using the method
  46  * <code>Blob.getBytes</code>) or as a stream of uninterpreted bytes
  47  * (using the method <code>Blob.getBinaryStream</code>).
  48  * <P>
  49  * <code>SerialBlob</code> methods make it possible to make a copy of a
  50  * <code>SerialBlob</code> object as an array of bytes or as a stream.
  51  * They also make it possible to locate a given pattern of bytes or a
  52  * <code>Blob</code> object within a <code>SerialBlob</code> object
  53  * and to update or truncate a <code>Blob</code> object.
  54  *
  55  * @author Jonathan Bruce
  56  */
  57 public class SerialBlob implements Blob, Serializable, Cloneable {
  58 
  59     /**
  60      * A serialized array of uninterpreted bytes representing the
  61      * value of this <code>SerialBlob</code> object.
  62      * @serial
  63      */
  64     private byte buf[];
  65 
  66     /**
  67      * The internal representation of the <code>Blob</code> object on which this
  68      * <code>SerialBlob</code> object is based.
  69      */
  70     private Blob blob;
  71 
  72     /**
  73      * The number of bytes in this <code>SerialBlob</code> object's
  74      * array of bytes.
  75      * @serial
  76      */
  77     private long len;
  78 
  79     /**
  80      * The orginal number of bytes in this <code>SerialBlob</code> object's
  81      * array of bytes when it was first established.
  82      * @serial
  83      */
  84     private long origLen;
  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 (length > len) {
 168             length = (int)len;
 169         }
 170 
 171         if (pos < 1 || len - pos < 0 ) {
 172             throw new SerialException("Invalid arguments: position cannot be "
 173                     + "less than 1 or greater than the length of the SerialBlob");
 174         }
 175 
 176         pos--; // correct pos to array index
 177 
 178         byte[] b = new byte[length];
 179 
 180         for (int i = 0; i < length; i++) {
 181             b[i] = this.buf[(int)pos];
 182             pos++;
 183         }
 184         return b;
 185     }
 186 
 187     /**
 188      * Retrieves the number of bytes in this <code>SerialBlob</code>
 189      * object's array of bytes.
 190      *
 191      * @return a <code>long</code> indicating the length in bytes of this
 192      *         <code>SerialBlob</code> object's array of bytes
 193      * @throws SerialException if an error occurs
 194      */
 195     public long length() throws SerialException {
 196         return len;
 197     }
 198 
 199     /**
 200      * Returns this <code>SerialBlob</code> object as an input stream.
 201      * Unlike the related method, <code>setBinaryStream</code>,
 202      * a stream is produced regardless of whether the <code>SerialBlob</code>
 203      * was created with a <code>Blob</code> object or a <code>byte</code> array.
 204      *
 205      * @return a <code>java.io.InputStream</code> object that contains
 206      *         this <code>SerialBlob</code> object's array of bytes
 207      * @throws SerialException if an error occurs
 208      * @see #setBinaryStream
 209      */
 210     public java.io.InputStream getBinaryStream() throws SerialException {
 211          InputStream stream = new ByteArrayInputStream(buf);
 212          return stream;
 213     }
 214 
 215     /**
 216      * Returns the position in this <code>SerialBlob</code> object where
 217      * the given pattern of bytes begins, starting the search at the
 218      * specified position.
 219      *
 220      * @param pattern the pattern of bytes for which to search
 221      * @param start the position of the byte in this
 222      *              <code>SerialBlob</code> object from which to begin
 223      *              the search; the first position is <code>1</code>;
 224      *              must not be less than <code>1</code> nor greater than
 225      *              the length of this <code>SerialBlob</code> object
 226      * @return the position in this <code>SerialBlob</code> object
 227      *         where the given pattern begins, starting at the specified
 228      *         position; <code>-1</code> if the pattern is not found
 229      *         or the given starting position is out of bounds; position
 230      *         numbering for the return value starts at <code>1</code>
 231      * @throws SerialException if an error occurs when serializing the blob
 232      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 233      *         value from the database
 234      */
 235     public long position(byte[] pattern, long start)
 236                 throws SerialException, SQLException {
 237         if (start < 1 || start > len) {
 238             return -1;
 239         }
 240 
 241         int pos = (int)start-1; // internally Blobs are stored as arrays.
 242         int i = 0;
 243         long patlen = pattern.length;
 244 
 245         while (pos < len) {
 246             if (pattern[i] == buf[pos]) {
 247                 if (i + 1 == patlen) {
 248                     return (pos + 1) - (patlen - 1);
 249                 }
 250                 i++; pos++; // increment pos, and i
 251             } else if (pattern[i] != buf[pos]) {
 252                 pos++; // increment pos only
 253             }
 254         }
 255         return -1; // not found
 256     }
 257 
 258     /**
 259      * Returns the position in this <code>SerialBlob</code> object where
 260      * the given <code>Blob</code> object begins, starting the search at the
 261      * specified position.
 262      *
 263      * @param pattern the <code>Blob</code> object for which to search;
 264      * @param start the position of the byte in this
 265      *              <code>SerialBlob</code> object from which to begin
 266      *              the search; the first position is <code>1</code>;
 267      *              must not be less than <code>1</code> nor greater than
 268      *              the length of this <code>SerialBlob</code> object
 269      * @return the position in this <code>SerialBlob</code> object
 270      *         where the given <code>Blob</code> object begins, starting
 271      *         at the specified position; <code>-1</code> if the pattern is
 272      *         not found or the given starting position is out of bounds;
 273      *         position numbering for the return value starts at <code>1</code>
 274      * @throws SerialException if an error occurs when serializing the blob
 275      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 276      *         value from the database
 277      */
 278     public long position(Blob pattern, long start)
 279        throws SerialException, SQLException {
 280         return position(pattern.getBytes(1, (int)(pattern.length())), start);
 281     }
 282 
 283     /**
 284      * Writes the given array of bytes to the <code>BLOB</code> value that
 285      * this <code>Blob</code> object represents, starting at position
 286      * <code>pos</code>, and returns the number of bytes written.
 287      *
 288      * @param pos the position in the SQL <code>BLOB</code> value at which
 289      *     to start writing. The first position is <code>1</code>;
 290      *     must not be less than <code>1</code> nor greater than
 291      *     the length of this <code>SerialBlob</code> object.
 292      * @param bytes the array of bytes to be written to the <code>BLOB</code>
 293      *        value that this <code>Blob</code> object represents
 294      * @return the number of bytes written
 295      * @throws SerialException if there is an error accessing the
 296      *     <code>BLOB</code> value; or if an invalid position is set; if an
 297      *     invalid offset value is set
 298      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 299      *         value from the database
 300      * @see #getBytes
 301      */
 302     public int setBytes(long pos, byte[] bytes)
 303         throws SerialException, SQLException {
 304         return (setBytes(pos, bytes, 0, bytes.length));
 305     }
 306 
 307     /**
 308      * Writes all or part of the given <code>byte</code> array to the
 309      * <code>BLOB</code> value that this <code>Blob</code> object represents
 310      * and returns the number of bytes written.
 311      * Writing starts at position <code>pos</code> in the <code>BLOB</code>
 312      * value; <i>len</i> bytes from the given byte array are written.
 313      *
 314      * @param pos the position in the <code>BLOB</code> object at which
 315      *     to start writing. The first position is <code>1</code>;
 316      *     must not be less than <code>1</code> nor greater than
 317      *     the length of this <code>SerialBlob</code> object.
 318      * @param bytes the array of bytes to be written to the <code>BLOB</code>
 319      *     value
 320      * @param offset the offset in the <code>byte</code> array at which
 321      *     to start reading the bytes. The first offset position is
 322      *     <code>0</code>; must not be less than <code>0</code> nor greater
 323      *     than the length of the <code>byte</code> array
 324      * @param length the number of bytes to be written to the
 325      *     <code>BLOB</code> value from the array of bytes <i>bytes</i>.
 326      *
 327      * @return the number of bytes written
 328      * @throws SerialException if there is an error accessing the
 329      *     <code>BLOB</code> value; if an invalid position is set; if an
 330      *     invalid offset value is set; if number of bytes to be written
 331      *     is greater than the <code>SerialBlob</code> length; or the combined
 332      *     values of the length and offset is greater than the Blob buffer
 333      * @throws SQLException if there is an error accessing the <code>BLOB</code>
 334      *         value from the database.
 335      * @see #getBytes
 336      */
 337     public int setBytes(long pos, byte[] bytes, int offset, int length)
 338         throws SerialException, SQLException {
 339 
 340         if (offset < 0 || offset > bytes.length) {
 341             throw new SerialException("Invalid offset in byte array set");
 342         }
 343 
 344         if (pos < 1 || pos > this.length()) {
 345             throw new SerialException("Invalid position in BLOB object set");
 346         }
 347 
 348         if ((long)(length) > origLen) {
 349             throw new SerialException("Buffer is not sufficient to hold the value");
 350         }
 351 
 352         if ((length + offset) > bytes.length) {
 353             throw new SerialException("Invalid OffSet. Cannot have combined offset " +
 354                 "and length that is greater that the Blob buffer");
 355         }
 356 
 357         int i = 0;
 358         pos--; // correct to array indexing
 359         while ( i < length || (offset + i +1) < (bytes.length-offset) ) {
 360             this.buf[(int)pos + i] = bytes[offset + i ];
 361             i++;
 362         }
 363         return i;
 364     }
 365 
 366     /**
 367      * Retrieves a stream that can be used to write to the <code>BLOB</code>
 368      * value that this <code>Blob</code> object represents.  The stream begins
 369      * at position <code>pos</code>. This method forwards the
 370      * <code>setBinaryStream()</code> call to the underlying <code>Blob</code> in
 371      * the event that this <code>SerialBlob</code> object is instantiated with a
 372      * <code>Blob</code>. If this <code>SerialBlob</code> is instantiated with
 373      * a <code>byte</code> array, a <code>SerialException</code> is thrown.
 374      *
 375      * @param pos the position in the <code>BLOB</code> value at which
 376      *        to start writing
 377      * @return a <code>java.io.OutputStream</code> object to which data can
 378      *         be written
 379      * @throws SQLException if there is an error accessing the
 380      *            <code>BLOB</code> value
 381      * @throws SerialException if the SerialBlob in not instantiated with a
 382      *     <code>Blob</code> object that supports <code>setBinaryStream()</code>
 383      * @see #getBinaryStream
 384      */
 385     public java.io.OutputStream setBinaryStream(long pos)
 386         throws SerialException, SQLException {
 387         if (this.blob != null) {
 388             return this.blob.setBinaryStream(pos);
 389         } else {
 390             throw new SerialException("Unsupported operation. SerialBlob cannot " +
 391                 "return a writable binary stream, unless instantiated with a Blob object " +
 392                 "that provides a setBinaryStream() implementation");
 393         }
 394     }
 395 
 396     /**
 397      * Truncates the <code>BLOB</code> value that this <code>Blob</code>
 398      * object represents to be <code>len</code> bytes in length.
 399      *
 400      * @param length the length, in bytes, to which the <code>BLOB</code>
 401      *        value that this <code>Blob</code> object represents should be
 402      *        truncated
 403      * @throws SerialException if there is an error accessing the Blob value;
 404      *     or the length to truncate is greater that the SerialBlob length
 405      */
 406     public void truncate(long length) throws SerialException {
 407 
 408          if (length > len) {
 409             throw new SerialException
 410                ("Length more than what can be truncated");
 411          } else if((int)length == 0) {
 412               buf = new byte[0];
 413               len = length;
 414          } else {
 415               len = length;
 416               buf = this.getBytes(1, (int)len);
 417          }
 418     }
 419 
 420 
 421     /**
 422      * Returns an <code>InputStream</code> object that contains a partial <code>Blob</code> value,
 423      * starting  with the byte specified by pos, which is length bytes in length.
 424      *
 425      * @param pos the offset to the first byte of the partial value to be retrieved.
 426      *  The first byte in the <code>Blob</code> is at position 1
 427      * @param length the length in bytes of the partial value to be retrieved
 428      * @return <code>InputStream</code> through which the partial <code>Blob</code> value can be read.
 429      * @throws SQLException if pos is less than 1 or if pos is greater than the number of bytes
 430      * in the <code>Blob</code> or if pos + length is greater than the number of bytes
 431      * in the <code>Blob</code>
 432      *
 433      * @since 1.6
 434      */
 435     public InputStream getBinaryStream(long pos,long length) throws SQLException {
 436         throw new java.lang.UnsupportedOperationException("Not supported");
 437     }
 438 
 439 
 440     /**
 441      * This method frees the <code>Blob</code> object and releases the resources that it holds.
 442      * <code>Blob</code> object. The object is invalid once the <code>free</code>
 443      * method is called. If <code>free</code> is called multiple times, the subsequent
 444      * calls to <code>free</code> are treated as a no-op.
 445      *
 446      * @throws SQLException if an error occurs releasing
 447      * the Blob's resources
 448      * @since 1.6
 449      */
 450     public void free() throws SQLException {
 451         throw new java.lang.UnsupportedOperationException("Not supported");
 452     }
 453 
 454    /**
 455      * Compares this SerialBlob to the specified object.  The result is {@code
 456      * true} if and only if the argument is not {@code null} and is a {@code
 457      * SerialBlob} object that represents the same sequence of bytes as this
 458      * object.
 459      *
 460      * @param  obj
 461      *         The object to compare this {@code SerialBlob} against
 462      *  
 463      * @return  {@code true} if the given object represents a {@code SerialBlob}
 464      *          equivalent to this SerialBlob, {@code false} otherwise
 465      *  
 466      */
 467     public boolean equals(Object obj) {
 468         if (this == obj) {
 469             return true;
 470         }
 471         if(obj == null || !(obj instanceof SerialBlob)) {
 472             return false;
 473         }
 474 
 475         SerialBlob sb = (SerialBlob)obj;
 476         if(this.len == sb.len) {
 477             return Arrays.equals(buf, sb.buf);
 478         }
 479         return false;
 480     }
 481 
 482     /**
 483      * Returns a hash code for this {@code SerialBlob}.
 484      * @return  a hash code value for this object.
 485      */
 486     public int hashCode() {
 487        return Objects.hash(buf, len, origLen);
 488     }
 489 
 490     /**
 491      * Returns a clone of this {@code SerialBlob}. The copy will contain a
 492      * reference to a clone of the internal byte array, not a reference
 493      * to the original internal byte array of this {@code SerialBlob} object.
 494      * The internal {@code Blob} field will be set to null.
 495      *  
 496      * @return  a clone of this SerialBlob
 497      */ 
 498     public Object clone() {
 499         SerialBlob sb = null;
 500         try {
 501             sb = (SerialBlob) super.clone();
 502             sb.buf = Arrays.copyOf(buf, (int)len);
 503             sb.blob = null;
 504 
 505         } catch (CloneNotSupportedException ex) {
 506             // this shouldn't happen, since we are Cloneable
 507         }
 508        return sb;
 509     }
 510 
 511     /**
 512      * readObject is called to restore the state of the SerialBlob from
 513      * a stream.
 514      */
 515     private void readObject(ObjectInputStream s)
 516             throws IOException, ClassNotFoundException {
 517         
 518         ObjectInputStream.GetField fields = s.readFields();
 519        byte[] tmp = (byte[])fields.get("buf", null);
 520        if (tmp == null)
 521            throw new InvalidObjectException("buf is null and should not be!");
 522        buf = tmp.clone();
 523        len = fields.get("len", 0L);
 524        origLen = fields.get("origLen", 0L);
 525        blob = (Blob) fields.get("blob", null);
 526        if(buf.length != len)
 527            throw new InvalidObjectException("buf is not the expected size");
 528     }
 529     
 530     /**
 531      * writeObject is called to save the state of the SerialBlob
 532      * to a stream.
 533      */
 534     private void writeObject(ObjectOutputStream s)
 535             throws IOException, ClassNotFoundException {
 536 
 537         ObjectOutputStream.PutField fields = s.putFields();
 538         fields.put("buf", buf);
 539         fields.put("len", len);
 540         fields.put("origLen", origLen);
 541         fields.put("blob", null);
 542         fields.put("blob", blob instanceof Serializable ? blob : null);
 543         s.writeFields();    
 544     }
 545 
 546     /**
 547          * The identifier that assists in the serialization of this <code>SerialBlob</code>
 548      * object.
 549      */
 550 
 551     static final long serialVersionUID = -8144641928112860441L;
 552 }