Path: blob/master/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialBlob.java
40948 views
/*1* Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.sql.rowset.serial;2627import java.sql.*;28import java.io.*;29import java.lang.reflect.*;30import java.util.Arrays;313233/**34* A serialized mapping in the Java programming language of an SQL35* <code>BLOB</code> value.36* <P>37* The <code>SerialBlob</code> class provides a constructor for creating38* an instance from a <code>Blob</code> object. Note that the39* <code>Blob</code>40* object should have brought the SQL <code>BLOB</code> value's data over41* to the client before a <code>SerialBlob</code> object42* is constructed from it. The data of an SQL <code>BLOB</code> value can43* be materialized on the client as an array of bytes (using the method44* <code>Blob.getBytes</code>) or as a stream of uninterpreted bytes45* (using the method <code>Blob.getBinaryStream</code>).46* <P>47* <code>SerialBlob</code> methods make it possible to make a copy of a48* <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 a50* <code>Blob</code> object within a <code>SerialBlob</code> object51* and to update or truncate a <code>Blob</code> object.52*53* <h2> Thread safety </h2>54*55* <p> A SerialBlob is not safe for use by multiple concurrent threads. If a56* SerialBlob is to be used by more than one thread then access to the SerialBlob57* should be controlled by appropriate synchronization.58*59* @author Jonathan Bruce60* @since 1.561*/62public class SerialBlob implements Blob, Serializable, Cloneable {6364/**65* A serialized array of uninterpreted bytes representing the66* value of this <code>SerialBlob</code> object.67* @serial68*/69private byte[] buf;7071/**72* The internal representation of the <code>Blob</code> object on which this73* <code>SerialBlob</code> object is based.74*/75@SuppressWarnings("serial") // Not statically typed as Serializable; checked in writeObject76private Blob blob;7778/**79* The number of bytes in this <code>SerialBlob</code> object's80* array of bytes.81* @serial82*/83private long len;8485/**86* The original number of bytes in this <code>SerialBlob</code> object's87* array of bytes when it was first established.88* @serial89*/90private long origLen;9192/**93* Constructs a <code>SerialBlob</code> object that is a serialized version of94* the given <code>byte</code> array.95* <p>96* The new <code>SerialBlob</code> object is initialized with the data from the97* <code>byte</code> array, thus allowing disconnected <code>RowSet</code>98* objects to establish serialized <code>Blob</code> objects without99* touching the data source.100*101* @param b the <code>byte</code> array containing the data for the102* <code>Blob</code> object to be serialized103* @throws SerialException if an error occurs during serialization104* @throws SQLException if a SQL errors occurs105*/106public SerialBlob(byte[] b)107throws SerialException, SQLException {108109len = b.length;110buf = new byte[(int)len];111for(int i = 0; i < len; i++) {112buf[i] = b[i];113}114origLen = len;115}116117118/**119* Constructs a <code>SerialBlob</code> object that is a serialized120* version of the given <code>Blob</code> object.121* <P>122* The new <code>SerialBlob</code> object is initialized with the123* data from the <code>Blob</code> object; therefore, the124* <code>Blob</code> object should have previously brought the125* SQL <code>BLOB</code> value's data over to the client from126* the database. Otherwise, the new <code>SerialBlob</code> object127* will contain no data.128*129* @param blob the <code>Blob</code> object from which this130* <code>SerialBlob</code> object is to be constructed;131* cannot be null.132* @throws SerialException if an error occurs during serialization133* @throws SQLException if the <code>Blob</code> passed to this134* to this constructor is a <code>null</code>.135* @see java.sql.Blob136*/137public SerialBlob (Blob blob)138throws SerialException, SQLException {139140if (blob == null) {141throw new SQLException(142"Cannot instantiate a SerialBlob object with a null Blob object");143}144145len = blob.length();146buf = blob.getBytes(1, (int)len );147this.blob = blob;148origLen = len;149}150151/**152* Copies the specified number of bytes, starting at the given153* position, from this <code>SerialBlob</code> object to154* another array of bytes.155* <P>156* Note that if the given number of bytes to be copied is larger than157* the length of this <code>SerialBlob</code> object's array of158* bytes, the given number will be shortened to the array's length.159*160* @param pos the ordinal position of the first byte in this161* <code>SerialBlob</code> object to be copied;162* numbering starts at <code>1</code>; must not be less163* than <code>1</code> and must be less than or equal164* to the length of this <code>SerialBlob</code> object165* @param length the number of bytes to be copied166* @return an array of bytes that is a copy of a region of this167* <code>SerialBlob</code> object, starting at the given168* position and containing the given number of consecutive bytes169* @throws SerialException if the given starting position is out of bounds;170* if {@code free} had previously been called on this object171*/172public byte[] getBytes(long pos, int length) throws SerialException {173isValid();174if (length > len) {175length = (int)len;176}177178if (pos < 1 || len - pos < 0 ) {179throw new SerialException("Invalid arguments: position cannot be "180+ "less than 1 or greater than the length of the SerialBlob");181}182183pos--; // correct pos to array index184185byte[] b = new byte[length];186187for (int i = 0; i < length; i++) {188b[i] = this.buf[(int)pos];189pos++;190}191return b;192}193194/**195* Retrieves the number of bytes in this <code>SerialBlob</code>196* object's array of bytes.197*198* @return a <code>long</code> indicating the length in bytes of this199* <code>SerialBlob</code> object's array of bytes200* @throws SerialException if an error occurs;201* if {@code free} had previously been called on this object202*/203public long length() throws SerialException {204isValid();205return len;206}207208/**209* Returns this <code>SerialBlob</code> object as an input stream.210* Unlike the related method, <code>setBinaryStream</code>,211* a stream is produced regardless of whether the <code>SerialBlob</code>212* was created with a <code>Blob</code> object or a <code>byte</code> array.213*214* @return a <code>java.io.InputStream</code> object that contains215* this <code>SerialBlob</code> object's array of bytes216* @throws SerialException if an error occurs;217* if {@code free} had previously been called on this object218* @see #setBinaryStream219*/220public java.io.InputStream getBinaryStream() throws SerialException {221isValid();222InputStream stream = new ByteArrayInputStream(buf);223return stream;224}225226/**227* Returns the position in this <code>SerialBlob</code> object where228* the given pattern of bytes begins, starting the search at the229* specified position.230*231* @param pattern the pattern of bytes for which to search232* @param start the position of the byte in this233* <code>SerialBlob</code> object from which to begin234* the search; the first position is <code>1</code>;235* must not be less than <code>1</code> nor greater than236* the length of this <code>SerialBlob</code> object237* @return the position in this <code>SerialBlob</code> object238* where the given pattern begins, starting at the specified239* position; <code>-1</code> if the pattern is not found240* or the given starting position is out of bounds; position241* numbering for the return value starts at <code>1</code>242* @throws SerialException if an error occurs when serializing the blob;243* if {@code free} had previously been called on this object244* @throws SQLException if there is an error accessing the <code>BLOB</code>245* value from the database246*/247public long position(byte[] pattern, long start)248throws SerialException, SQLException {249250isValid();251if (start < 1 || start > len) {252return -1;253}254255int pos = (int)start-1; // internally Blobs are stored as arrays.256int i = 0;257long patlen = pattern.length;258259while (pos < len) {260if (pattern[i] == buf[pos]) {261if (i + 1 == patlen) {262return (pos + 1) - (patlen - 1);263}264i++; pos++; // increment pos, and i265} else if (pattern[i] != buf[pos]) {266pos++; // increment pos only267}268}269return -1; // not found270}271272/**273* Returns the position in this <code>SerialBlob</code> object where274* the given <code>Blob</code> object begins, starting the search at the275* specified position.276*277* @param pattern the <code>Blob</code> object for which to search;278* @param start the position of the byte in this279* <code>SerialBlob</code> object from which to begin280* the search; the first position is <code>1</code>;281* must not be less than <code>1</code> nor greater than282* the length of this <code>SerialBlob</code> object283* @return the position in this <code>SerialBlob</code> object284* where the given <code>Blob</code> object begins, starting285* at the specified position; <code>-1</code> if the pattern is286* not found or the given starting position is out of bounds;287* position numbering for the return value starts at <code>1</code>288* @throws SerialException if an error occurs when serializing the blob;289* if {@code free} had previously been called on this object290* @throws SQLException if there is an error accessing the <code>BLOB</code>291* value from the database292*/293public long position(Blob pattern, long start)294throws SerialException, SQLException {295isValid();296return position(pattern.getBytes(1, (int)(pattern.length())), start);297}298299/**300* Writes the given array of bytes to the <code>BLOB</code> value that301* this <code>Blob</code> object represents, starting at position302* <code>pos</code>, and returns the number of bytes written.303*304* @param pos the position in the SQL <code>BLOB</code> value at which305* to start writing. The first position is <code>1</code>;306* must not be less than <code>1</code> nor greater than307* the length of this <code>SerialBlob</code> object.308* @param bytes the array of bytes to be written to the <code>BLOB</code>309* value that this <code>Blob</code> object represents310* @return the number of bytes written311* @throws SerialException if there is an error accessing the312* <code>BLOB</code> value; or if an invalid position is set; if an313* invalid offset value is set;314* if {@code free} had previously been called on this object315* @throws SQLException if there is an error accessing the <code>BLOB</code>316* value from the database317* @see #getBytes318*/319public int setBytes(long pos, byte[] bytes)320throws SerialException, SQLException {321return setBytes(pos, bytes, 0, bytes.length);322}323324/**325* Writes all or part of the given <code>byte</code> array to the326* <code>BLOB</code> value that this <code>Blob</code> object represents327* 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 which332* to start writing. The first position is <code>1</code>;333* must not be less than <code>1</code> nor greater than334* the length of this <code>SerialBlob</code> object.335* @param bytes the array of bytes to be written to the <code>BLOB</code>336* value337* @param offset the offset in the <code>byte</code> array at which338* to start reading the bytes. The first offset position is339* <code>0</code>; must not be less than <code>0</code> nor greater340* than the length of the <code>byte</code> array341* @param length the number of bytes to be written to the342* <code>BLOB</code> value from the array of bytes <i>bytes</i>.343*344* @return the number of bytes written345* @throws SerialException if there is an error accessing the346* <code>BLOB</code> value; if an invalid position is set; if an347* invalid offset value is set; if number of bytes to be written348* is greater than the <code>SerialBlob</code> length; or the combined349* values of the length and offset is greater than the Blob buffer;350* if {@code free} had previously been called on this object351* @throws SQLException if there is an error accessing the <code>BLOB</code>352* value from the database.353* @see #getBytes354*/355public int setBytes(long pos, byte[] bytes, int offset, int length)356throws SerialException, SQLException {357358isValid();359if (offset < 0 || offset > bytes.length) {360throw new SerialException("Invalid offset in byte array set");361}362363if (pos < 1 || pos > this.length()) {364throw new SerialException("Invalid position in BLOB object set");365}366367if ((long)(length) > origLen) {368throw new SerialException("Buffer is not sufficient to hold the value");369}370371if ((length + offset) > bytes.length) {372throw new SerialException("Invalid OffSet. Cannot have combined offset " +373"and length that is greater that the Blob buffer");374}375376int i = 0;377pos--; // correct to array indexing378while ( i < length || (offset + i +1) < (bytes.length-offset) ) {379this.buf[(int)pos + i] = bytes[offset + i ];380i++;381}382return i;383}384385/**386* Retrieves a stream that can be used to write to the <code>BLOB</code>387* value that this <code>Blob</code> object represents. The stream begins388* at position <code>pos</code>. This method forwards the389* <code>setBinaryStream()</code> call to the underlying <code>Blob</code> in390* the event that this <code>SerialBlob</code> object is instantiated with a391* <code>Blob</code>. If this <code>SerialBlob</code> is instantiated with392* a <code>byte</code> array, a <code>SerialException</code> is thrown.393*394* @param pos the position in the <code>BLOB</code> value at which395* to start writing396* @return a <code>java.io.OutputStream</code> object to which data can397* be written398* @throws SQLException if there is an error accessing the399* <code>BLOB</code> value400* @throws SerialException if the SerialBlob in not instantiated with a401* <code>Blob</code> object that supports <code>setBinaryStream()</code>;402* if {@code free} had previously been called on this object403* @see #getBinaryStream404*/405public java.io.OutputStream setBinaryStream(long pos)406throws SerialException, SQLException {407408isValid();409if (this.blob != null) {410return this.blob.setBinaryStream(pos);411} else {412throw 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}417418/**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 be424* truncated425* @throws SerialException if there is an error accessing the Blob value;426* or the length to truncate is greater that the SerialBlob length;427* if {@code free} had previously been called on this object428*/429public void truncate(long length) throws SerialException {430isValid();431if (length > len) {432throw new SerialException(433"Length more than what can be truncated");434} else if((int)length == 0) {435buf = new byte[0];436len = length;437} else {438len = length;439buf = this.getBytes(1, (int)len);440}441}442443444/**445* Returns an446* <code>InputStream</code> object that contains a partial447* {@code Blob} value, starting with the byte specified by pos, which is448* length bytes in length.449*450* @param pos the offset to the first byte of the partial value to be451* retrieved. The first byte in the {@code Blob} is at position 1452* @param length the length in bytes of the partial value to be retrieved453* @return454* <code>InputStream</code> through which the partial {@code Blob} value can455* be read.456* @throws SQLException if pos is less than 1 or if pos is greater than the457* number of bytes in the {@code Blob} or if pos + length is greater than458* the number of bytes in the {@code Blob}459* @throws SerialException if the {@code free} method had been previously460* called on this object461*462* @since 1.6463*/464public InputStream getBinaryStream(long pos, long length) throws SQLException {465isValid();466if (pos < 1 || pos > this.length()) {467throw new SerialException("Invalid position in BLOB object set");468}469if (length < 1 || length > len - pos + 1) {470throw new SerialException(471"length is < 1 or pos + length > total number of bytes");472}473return new ByteArrayInputStream(buf, (int) pos - 1, (int) length);474}475476477/**478* This method frees the {@code SerialBlob} object and releases the479* resources that it holds. The object is invalid once the {@code free}480* method is called. <p> If {@code free} is called multiple times, the481* subsequent calls to {@code free} are treated as a no-op. </P>482*483* @throws SQLException if an error occurs releasing the Blob's resources484* @since 1.6485*/486public void free() throws SQLException {487if (buf != null) {488buf = null;489if (blob != null) {490blob.free();491}492blob = null;493}494}495496/**497* Compares this SerialBlob to the specified object. The result is {@code498* true} if and only if the argument is not {@code null} and is a {@code499* SerialBlob} object that represents the same sequence of bytes as this500* object.501*502* @param obj The object to compare this {@code SerialBlob} against503*504* @return {@code true} if the given object represents a {@code SerialBlob}505* equivalent to this SerialBlob, {@code false} otherwise506*507*/508public boolean equals(Object obj) {509if (this == obj) {510return true;511}512if (obj instanceof SerialBlob) {513SerialBlob sb = (SerialBlob)obj;514if (this.len == sb.len) {515return Arrays.equals(buf, sb.buf);516}517}518return false;519}520521/**522* Returns a hash code for this {@code SerialBlob}.523* @return a hash code value for this object.524*/525public int hashCode() {526return ((31 + Arrays.hashCode(buf)) * 31 + (int)len) * 31 + (int)origLen;527}528529/**530* Returns a clone of this {@code SerialBlob}. The copy will contain a531* reference to a clone of the internal byte array, not a reference532* to the original internal byte array of this {@code SerialBlob} object.533* The underlying {@code Blob} object will be set to null.534*535* @return a clone of this SerialBlob536*/537public Object clone() {538try {539SerialBlob sb = (SerialBlob) super.clone();540sb.buf = (buf != null) ? Arrays.copyOf(buf, (int)len) : null;541sb.blob = null;542return sb;543} catch (CloneNotSupportedException ex) {544// this shouldn't happen, since we are Cloneable545throw new InternalError();546}547}548549/**550* readObject is called to restore the state of the SerialBlob from551* a stream.552* @param s the {@code ObjectInputStream} to read from.553*554* @throws ClassNotFoundException if the class of a serialized object555* could not be found.556* @throws IOException if an I/O error occurs.557*/558private void readObject(ObjectInputStream s)559throws IOException, ClassNotFoundException {560561ObjectInputStream.GetField fields = s.readFields();562byte[] tmp = (byte[])fields.get("buf", null);563if (tmp == null)564throw new InvalidObjectException("buf is null and should not be!");565buf = tmp.clone();566len = fields.get("len", 0L);567if (buf.length != len)568throw new InvalidObjectException("buf is not the expected size");569origLen = fields.get("origLen", 0L);570blob = (Blob) fields.get("blob", null);571}572573/**574* writeObject is called to save the state of the SerialBlob575* to a stream.576* @param s the {@code ObjectOutputStream} to write to.577* @throws IOException if an I/O error occurs.578*/579private void writeObject(ObjectOutputStream s)580throws IOException {581582ObjectOutputStream.PutField fields = s.putFields();583fields.put("buf", buf);584fields.put("len", len);585fields.put("origLen", origLen);586// Note: this check to see if it is an instance of Serializable587// is for backwards compatibility588fields.put("blob", blob instanceof Serializable ? blob : null);589s.writeFields();590}591592/**593* Check to see if this object had previously had its {@code free} method594* called595*596* @throws SerialException597*/598private void isValid() throws SerialException {599if (buf == null) {600throw new SerialException("Error: You cannot call a method on a " +601"SerialBlob instance once free() has been called.");602}603}604605/**606* The identifier that assists in the serialization of this607* {@code SerialBlob} object.608*/609static final long serialVersionUID = -8144641928112860441L;610}611612613