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.util.Arrays;
  31 import java.util.Objects;
  32 
  33 /**
  34  * A serialized mapping in the Java programming language of an SQL
  35  * <code>CLOB</code> value.
  36  * <P>
  37  * The <code>SerialClob</code> class provides a constructor for creating
  38  * an instance from a <code>Clob</code> object.  Note that the <code>Clob</code>
  39  * object should have brought the SQL <code>CLOB</code> value's data over
  40  * to the client before a <code>SerialClob</code> object
  41  * is constructed from it.  The data of an SQL <code>CLOB</code> value can
  42  * be materialized on the client as a stream of Unicode characters.
  43  * <P>
  44  * <code>SerialClob</code> methods make it possible to get a substring
  45  * from a <code>SerialClob</code> object or to locate the start of
  46  * a pattern of characters.
  47  *
  48  * @author Jonathan Bruce
  49  */
  50 public class SerialClob implements Clob, Serializable, Cloneable {
  51 
  52     /**
  53      * A serialized array of characters containing the data of the SQL
  54      * <code>CLOB</code> value that this <code>SerialClob</code> object
  55      * represents.
  56      *
  57      * @serial
  58      */
  59     private char buf[];
  60 
  61     /**
  62      * Internal Clob representation if SerialClob is initialized with a
  63      * Clob. Null if SerialClob is initialized with a char[].
  64      */
  65     private Clob clob;
  66 
  67     /**
  68      * The length in characters of this <code>SerialClob</code> object's
  69      * internal array of characters.
  70      *
  71      * @serial
  72      */
  73     private long len;
  74 
  75     /**
  76      * The original length in characters of this <code>SerialClob</code>
  77      * object's internal array of characters.
  78      *
  79      * @serial
  80      */
  81     private long origLen;
  82 
  83     /**
  84      * Constructs a <code>SerialClob</code> object that is a serialized version of
  85      * the given <code>char</code> array.
  86      * <p>
  87      * The new <code>SerialClob</code> object is initialized with the data from the
  88      * <code>char</code> array, thus allowing disconnected <code>RowSet</code>
  89      * objects to establish a serialized <code>Clob</code> object without touching
  90      * the data source.
  91      *
  92      * @param ch the char array representing the <code>Clob</code> object to be
  93      *         serialized
  94      * @throws SerialException if an error occurs during serialization
  95      * @throws SQLException if a SQL error occurs
  96      */
  97     public SerialClob(char ch[]) throws SerialException, SQLException {
  98 
  99         // %%% JMB. Agreed. Add code here to throw a SQLException if no
 100         // support is available for locatorsUpdateCopy=false
 101         // Serializing locators is not supported.
 102 
 103         len = ch.length;
 104         buf = new char[(int)len];
 105         for (int i = 0; i < len ; i++){
 106            buf[i] = ch[i];
 107         }
 108         origLen = len;
 109         clob = null;
 110     }
 111 
 112     /**
 113      * Constructs a <code>SerialClob</code> object that is a serialized
 114      * version of the given <code>Clob</code> object.
 115      * <P>
 116      * The new <code>SerialClob</code> object is initialized with the
 117      * data from the <code>Clob</code> object; therefore, the
 118      * <code>Clob</code> object should have previously brought the
 119      * SQL <code>CLOB</code> value's data over to the client from
 120      * the database. Otherwise, the new <code>SerialClob</code> object
 121      * object will contain no data.
 122      * <p>
 123      * Note: The <code>Clob</code> object supplied to this constructor must
 124      * return non-null for both the <code>Clob.getCharacterStream()</code>
 125      * and <code>Clob.getAsciiStream</code> methods. This <code>SerialClob</code>
 126      * constructor cannot serialize a <code>Clob</code> object in this instance
 127      * and will throw an <code>SQLException</code> object.
 128      *
 129      * @param  clob the <code>Clob</code> object from which this
 130      *     <code>SerialClob</code> object is to be constructed; cannot be null
 131      * @throws SerialException if an error occurs during serialization
 132      * @throws SQLException if a SQL error occurs in capturing the CLOB;
 133      *     if the <code>Clob</code> object is a null; or if either of the
 134      *     <code>Clob.getCharacterStream()</code> and <code>Clob.getAsciiStream()</code>
 135      *     methods on the <code>Clob</code> returns a null
 136      * @see java.sql.Clob
 137      */
 138     public SerialClob(Clob clob) throws SerialException, SQLException {
 139 
 140         if (clob == null) {
 141             throw new SQLException("Cannot instantiate a SerialClob " +
 142                 "object with a null Clob object");
 143         }
 144         len = clob.length();
 145         this.clob = clob;
 146         buf = new char[(int)len];
 147         int read = 0;
 148         int offset = 0;
 149 
 150         try (Reader charStream = clob.getCharacterStream()) {
 151             if (charStream == null) {
 152                 throw new SQLException("Invalid Clob object. The call to getCharacterStream " +
 153                     "returned null which cannot be serialized.");
 154             }
 155 
 156             // Note: get an ASCII stream in order to null-check it,
 157             // even though we don't do anything with it.
 158             try (InputStream asciiStream = clob.getAsciiStream()) {
 159                 if (asciiStream == null) {
 160                     throw new SQLException("Invalid Clob object. The call to getAsciiStream " +
 161                         "returned null which cannot be serialized.");
 162                 }
 163             }
 164 
 165             try (Reader reader = new BufferedReader(charStream)) {
 166                 do {
 167                     read = reader.read(buf, offset, (int)(len - offset));
 168                     offset += read;
 169                 } while (read > 0);
 170             }
 171         } catch (java.io.IOException ex) {
 172             throw new SerialException("SerialClob: " + ex.getMessage());
 173         }
 174 
 175         origLen = len;
 176     }
 177 
 178     /**
 179      * Retrieves the number of characters in this <code>SerialClob</code>
 180      * object's array of characters.
 181      *
 182      * @return a <code>long</code> indicating the length in characters of this
 183      *         <code>SerialClob</code> object's array of character
 184      * @throws SerialException if an error occurs
 185      */
 186     public long length() throws SerialException {
 187         return len;
 188     }
 189 
 190     /**
 191      * Returns this <code>SerialClob</code> object's data as a stream
 192      * of Unicode characters. Unlike the related method, <code>getAsciiStream</code>,
 193      * a stream is produced regardless of whether the <code>SerialClob</code> object
 194      * was created with a <code>Clob</code> object or a <code>char</code> array.
 195      *
 196      * @return a <code>java.io.Reader</code> object containing this
 197      *         <code>SerialClob</code> object's data
 198      * @throws SerialException if an error occurs
 199      */
 200     public java.io.Reader getCharacterStream() throws SerialException {
 201         return (java.io.Reader) new CharArrayReader(buf);
 202     }
 203 
 204     /**
 205      * Retrieves the <code>CLOB</code> value designated by this <code>SerialClob</code>
 206      * object as an ascii stream. This method forwards the <code>getAsciiStream</code>
 207      * call to the underlying <code>Clob</code> object in the event that this
 208      * <code>SerialClob</code> object is instantiated with a <code>Clob</code>
 209      * object. If this <code>SerialClob</code> object is instantiated with
 210      * a <code>char</code> array, a <code>SerialException</code> object is thrown.
 211      *
 212      * @return a <code>java.io.InputStream</code> object containing
 213      *     this <code>SerialClob</code> object's data
 214      * @throws SerialException if this <code>SerialClob</code> object was not instantiated
 215      *     with a <code>Clob</code> object
 216      * @throws SQLException if there is an error accessing the
 217      *     <code>CLOB</code> value represented by the <code>Clob</code> object that was
 218      *     used to create this <code>SerialClob</code> object
 219      */
 220     public java.io.InputStream getAsciiStream() throws SerialException, SQLException {
 221         if (this.clob != null) {
 222             return this.clob.getAsciiStream();
 223         } else {
 224             throw new SerialException("Unsupported operation. SerialClob cannot " +
 225                 "return a the CLOB value as an ascii stream, unless instantiated " +
 226                 "with a fully implemented Clob object.");
 227         }
 228     }
 229 
 230     /**
 231      * Returns a copy of the substring contained in this
 232      * <code>SerialClob</code> object, starting at the given position
 233      * and continuing for the specified number or characters.
 234      *
 235      * @param pos the position of the first character in the substring
 236      *            to be copied; the first character of the
 237      *            <code>SerialClob</code> object is at position
 238      *            <code>1</code>; must not be less than <code>1</code>,
 239      *            and the sum of the starting position and the length
 240      *            of the substring must be less than the length of this
 241      *            <code>SerialClob</code> object
 242      * @param length the number of characters in the substring to be
 243      *               returned; must not be greater than the length of
 244      *               this <code>SerialClob</code> object, and the
 245      *               sum of the starting position and the length
 246      *               of the substring must be less than the length of this
 247      *               <code>SerialClob</code> object
 248      * @return a <code>String</code> object containing a substring of
 249      *         this <code>SerialClob</code> object beginning at the
 250      *         given position and containing the specified number of
 251      *         consecutive characters
 252      * @throws SerialException if either of the arguments is out of bounds
 253      */
 254     public String getSubString(long pos, int length) throws SerialException {
 255 
 256         if (pos < 1 || pos > this.length()) {
 257             throw new SerialException("Invalid position in BLOB object set");
 258         }
 259 
 260         if ((pos-1) + length > this.length()) {
 261             throw new SerialException("Invalid position and substring length");
 262         }
 263 
 264         try {
 265             return new String(buf, (int)pos - 1, length);
 266 
 267         } catch (StringIndexOutOfBoundsException e) {
 268             throw new SerialException("StringIndexOutOfBoundsException: " +
 269                 e.getMessage());
 270         }
 271 
 272     }
 273 
 274     /**
 275      * Returns the position in this <code>SerialClob</code> object
 276      * where the given <code>String</code> object begins, starting
 277      * the search at the specified position. This method returns
 278      * <code>-1</code> if the pattern is not found.
 279      *
 280      * @param searchStr the <code>String</code> object for which to
 281      *                  search
 282      * @param start the position in this <code>SerialClob</code> object
 283      *         at which to start the search; the first position is
 284      *         <code>1</code>; must not be less than <code>1</code> nor
 285      *         greater than the length of this <code>SerialClob</code> object
 286      * @return the position at which the given <code>String</code> object
 287      *         begins, starting the search at the specified position;
 288      *         <code>-1</code> if the given <code>String</code> object is
 289      *         not found or the starting position is out of bounds; position
 290      *         numbering for the return value starts at <code>1</code>
 291      * @throws SerialException if an error occurs locating the String signature
 292      * @throws SQLException if there is an error accessing the Blob value
 293      *         from the database.
 294      */
 295     public long position(String searchStr, long start)
 296         throws SerialException, SQLException {
 297 
 298         if (start < 1 || start > len) {
 299             return -1;
 300         }
 301 
 302         char pattern[] = searchStr.toCharArray();
 303 
 304         int pos = (int)start-1;
 305         int i = 0;
 306         long patlen = pattern.length;
 307 
 308         while (pos < len) {
 309             if (pattern[i] == buf[pos]) {
 310                 if (i + 1 == patlen) {
 311                     return (pos + 1) - (patlen - 1);
 312                 }
 313                 i++; pos++; // increment pos, and i
 314 
 315             } else if (pattern[i] != buf[pos]) {
 316                 pos++; // increment pos only
 317             }
 318         }
 319         return -1; // not found
 320     }
 321 
 322     /**
 323      * Returns the position in this <code>SerialClob</code> object
 324      * where the given <code>Clob</code> signature begins, starting
 325      * the search at the specified position. This method returns
 326      * <code>-1</code> if the pattern is not found.
 327      *
 328      * @param searchStr the <code>Clob</code> object for which to search
 329      * @param start the position in this <code>SerialClob</code> object
 330      *        at which to begin the search; the first position is
 331      *         <code>1</code>; must not be less than <code>1</code> nor
 332      *         greater than the length of this <code>SerialClob</code> object
 333      * @return the position at which the given <code>Clob</code>
 334      *         object begins in this <code>SerialClob</code> object,
 335      *         at or after the specified starting position
 336      * @throws SerialException if an error occurs locating the Clob signature
 337      * @throws SQLException if there is an error accessing the Blob value
 338      *         from the database
 339      */
 340     public long position(Clob searchStr, long start)
 341         throws SerialException, SQLException {
 342 
 343         return position(searchStr.getSubString(1,(int)searchStr.length()), start);
 344     }
 345 
 346     /**
 347      * Writes the given Java <code>String</code> to the <code>CLOB</code>
 348      * value that this <code>SerialClob</code> object represents, at the position
 349      * <code>pos</code>.
 350      *
 351      * @param pos the position at which to start writing to the <code>CLOB</code>
 352      *         value that this <code>SerialClob</code> object represents; the first
 353      *         position is <code>1</code>; must not be less than <code>1</code> nor
 354      *         greater than the length of this <code>SerialClob</code> object
 355      * @param str the string to be written to the <code>CLOB</code>
 356      *        value that this <code>SerialClob</code> object represents
 357      * @return the number of characters written
 358      * @throws SerialException if there is an error accessing the
 359      *     <code>CLOB</code> value; if an invalid position is set; if an
 360      *     invalid offset value is set; if number of bytes to be written
 361      *     is greater than the <code>SerialClob</code> length; or the combined
 362      *     values of the length and offset is greater than the Clob buffer
 363      */
 364     public int setString(long pos, String str) throws SerialException {
 365         return (setString(pos, str, 0, str.length()));
 366     }
 367 
 368     /**
 369      * Writes <code>len</code> characters of <code>str</code>, starting
 370      * at character <code>offset</code>, to the <code>CLOB</code> value
 371      * that this <code>Clob</code> represents.
 372      *
 373      * @param pos the position at which to start writing to the <code>CLOB</code>
 374      *         value that this <code>SerialClob</code> object represents; the first
 375      *         position is <code>1</code>; must not be less than <code>1</code> nor
 376      *         greater than the length of this <code>SerialClob</code> object
 377      * @param str the string to be written to the <code>CLOB</code>
 378      *        value that this <code>Clob</code> object represents
 379      * @param offset the offset into <code>str</code> to start reading
 380      *        the characters to be written
 381      * @param length the number of characters to be written
 382      * @return the number of characters written
 383      * @throws SerialException if there is an error accessing the
 384      *     <code>CLOB</code> value; if an invalid position is set; if an
 385      *     invalid offset value is set; if number of bytes to be written
 386      *     is greater than the <code>SerialClob</code> length; or the combined
 387      *     values of the length and offset is greater than the Clob buffer
 388      */
 389     public int setString(long pos, String str, int offset, int length)
 390         throws SerialException {
 391         String temp = str.substring(offset);
 392         char cPattern[] = temp.toCharArray();
 393 
 394         if (offset < 0 || offset > str.length()) {
 395             throw new SerialException("Invalid offset in byte array set");
 396         }
 397 
 398         if (pos < 1 || pos > this.length()) {
 399             throw new SerialException("Invalid position in BLOB object set");
 400         }
 401 
 402         if ((long)(length) > origLen) {
 403             throw new SerialException("Buffer is not sufficient to hold the value");
 404         }
 405 
 406         if ((length + offset) > str.length()) {
 407             // need check to ensure length + offset !> bytes.length
 408             throw new SerialException("Invalid OffSet. Cannot have combined offset " +
 409                 " and length that is greater that the Blob buffer");
 410         }
 411 
 412         int i = 0;
 413         pos--;  //values in the array are at position one less
 414         while ( i < length || (offset + i +1) < (str.length() - offset ) ) {
 415             this.buf[(int)pos + i ] = cPattern[offset + i ];
 416             i++;
 417         }
 418         return i;
 419     }
 420 
 421     /**
 422      * Retrieves a stream to be used to write Ascii characters to the
 423      * <code>CLOB</code> value that this <code>SerialClob</code> object represents,
 424      * starting at position <code>pos</code>. This method forwards the
 425      * <code>setAsciiStream()</code> call to the underlying <code>Clob</code> object in
 426      * the event that this <code>SerialClob</code> object is instantiated with a
 427      * <code>Clob</code> object. If this <code>SerialClob</code> object is instantiated
 428      *  with a <code>char</code> array, a <code>SerialException</code> object is thrown.
 429      *
 430      * @param pos the position at which to start writing to the
 431      *        <code>CLOB</code> object
 432      * @return the stream to which ASCII encoded characters can be written
 433      * @throws SerialException if SerialClob is not instantiated with a
 434      *     Clob object that supports <code>setAsciiStream</code>
 435      * @throws SQLException if there is an error accessing the
 436      *     <code>CLOB</code> value
 437      * @see #getAsciiStream
 438      */
 439     public java.io.OutputStream setAsciiStream(long pos)
 440         throws SerialException, SQLException {
 441          if (this.clob != null) {
 442              return this.clob.setAsciiStream(pos);
 443          } else {
 444              throw new SerialException("Unsupported operation. SerialClob cannot " +
 445                 "return a writable ascii stream\n unless instantiated with a Clob object " +
 446                 "that has a setAsciiStream() implementation");
 447          }
 448     }
 449 
 450     /**
 451      * Retrieves a stream to be used to write a stream of Unicode characters
 452      * to the <code>CLOB</code> value that this <code>SerialClob</code> object
 453      * represents, at position <code>pos</code>. This method forwards the
 454      * <code>setCharacterStream()</code> call to the underlying <code>Clob</code>
 455      * object in the event that this <code>SerialClob</code> object is instantiated with a
 456      * <code>Clob</code> object. If this <code>SerialClob</code> object is instantiated with
 457      * a <code>char</code> array, a <code>SerialException</code> is thrown.
 458      *
 459      * @param  pos the position at which to start writing to the
 460      *        <code>CLOB</code> value
 461      *
 462      * @return a stream to which Unicode encoded characters can be written
 463      * @throws SerialException if the SerialClob is not instantiated with
 464      *     a Clob object that supports <code>setCharacterStream</code>
 465      * @throws SQLException if there is an error accessing the
 466      *            <code>CLOB</code> value
 467      * @see #getCharacterStream
 468      */
 469     public java.io.Writer setCharacterStream(long pos)
 470         throws SerialException, SQLException {
 471         if (this.clob != null) {
 472             return this.clob.setCharacterStream(pos);
 473         } else {
 474             throw new SerialException("Unsupported operation. SerialClob cannot " +
 475                 "return a writable character stream\n unless instantiated with a Clob object " +
 476                 "that has a setCharacterStream implementation");
 477         }
 478     }
 479 
 480     /**
 481      * Truncates the <code>CLOB</code> value that this <code>SerialClob</code>
 482      * object represents so that it has a length of <code>len</code>
 483      * characters.
 484      * <p>
 485      * Truncating a <code>SerialClob</code> object to length 0 has the effect of
 486      * clearing its contents.
 487      *
 488      * @param length the length, in bytes, to which the <code>CLOB</code>
 489      *        value should be truncated
 490      * @throws SQLException if there is an error accessing the
 491      *        <code>CLOB</code> value
 492      */
 493     public void truncate(long length) throws SerialException {
 494          if (length > len) {
 495             throw new SerialException
 496                ("Length more than what can be truncated");
 497          } else {
 498               len = length;
 499               // re-size the buffer
 500 
 501               if (len == 0) {
 502                   buf = new char[] {};
 503               } else {
 504                 buf = (this.getSubString(1, (int)len)).toCharArray();
 505               }
 506 
 507          }
 508     }
 509 
 510 
 511     public Reader getCharacterStream(long pos, long length) throws SQLException {
 512         throw new java.lang.UnsupportedOperationException("Not supported");
 513     }
 514 
 515     public void free() throws SQLException {
 516         throw new java.lang.UnsupportedOperationException("Not supported");
 517     }
 518    /**
 519      * Compares this SerialClob to the specified object.  The result is {@code
 520      * true} if and only if the argument is not {@code null} and is a {@code
 521      * SerialClob} object that represents the same sequence of characters as this
 522      * object.
 523      *
 524      * @param  obj
 525      *         The object to compare this {@code SerialClob} against
 526      *
 527      * @return  {@code true} if the given object represents a {@code SerialClob}
 528      *          equivalent to this SerialClob, {@code false} otherwise
 529      *
 530      */
 531     public boolean equals(Object obj) {
 532         if (this == obj) {
 533             return true;
 534         }
 535         if(obj == null || !(obj instanceof SerialClob)) {
 536             return false;
 537         }
 538         
 539         SerialClob sc = (SerialClob)obj;
 540         if(this.len == sc.len) {
 541             return Arrays.equals(buf, sc.buf);
 542         }
 543         return false;
 544     }
 545 
 546     /**
 547      * Returns a hash code for this {@code SerialClob}.
 548      * @return  a hash code value for this object.
 549      */
 550     public int hashCode() {
 551        return Objects.hash(buf, len, origLen);
 552     }
 553 
 554     /**
 555      * Returns a clone of this {@code SerialClob}. The copy will contain a
 556      * reference to a clone of the internal character array, not a reference
 557      * to the original internal character array of this {@code SerialClob} object.
 558      * The internal {@code Clob} field will be set to null.
 559      *
 560      * @return  a clone of this SerialClob
 561      */
 562     public Object clone() {
 563         SerialClob sc = null;
 564         try {
 565             sc = (SerialClob) super.clone();
 566             sc.buf = Arrays.copyOf(buf, (int)len);
 567             sc.clob = null;
 568 
 569         } catch (CloneNotSupportedException ex) {
 570             // this shouldn't happen, since we are Cloneable
 571         }
 572        return sc;
 573     }
 574 
 575     /**
 576      * readObject is called to restore the state of the SerialClob from
 577      * a stream.
 578      */
 579     private void readObject(ObjectInputStream s)
 580             throws IOException, ClassNotFoundException {
 581 
 582         ObjectInputStream.GetField fields = s.readFields();
 583        char[] tmp = (char[])fields.get("buf", null);
 584        if (tmp == null)
 585            throw new InvalidObjectException("buf is null and should not be!");
 586        buf = tmp.clone();
 587        len = fields.get("len", 0L);
 588        origLen = fields.get("origLen", 0L);
 589        clob = (Clob) fields.get("clob", null);
 590        if(buf.length != len)
 591            throw new InvalidObjectException("buf is not the expected size");
 592     }
 593 
 594     /**
 595      * writeObject is called to save the state of the SerialClob
 596      * to a stream.
 597      */
 598     private void writeObject(ObjectOutputStream s)
 599             throws IOException, ClassNotFoundException {
 600 
 601         ObjectOutputStream.PutField fields = s.putFields();
 602         fields.put("buf", buf);
 603         fields.put("len", len);
 604         fields.put("origLen", origLen);
 605         fields.put("clob", clob instanceof Serializable ? clob : null);
 606         s.writeFields();
 607     }
 608 
 609     /**
 610          * The identifier that assists in the serialization of this <code>SerialClob</code>
 611      * object.
 612      */
 613     static final long serialVersionUID = -1662519690087375313L;
 614 }