KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > access > types > ByteArrayType


1 /* ====================================================================
2  *
3  * The ObjectStyle Group Software License, version 1.1
4  * ObjectStyle Group - http://objectstyle.org/
5  *
6  * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
7  * of the software. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if any,
22  * must include the following acknowlegement:
23  * "This product includes software developed by independent contributors
24  * and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
29  * or promote products derived from this software without prior written
30  * permission. For written permission, email
31  * "andrus at objectstyle dot org".
32  *
33  * 5. Products derived from this software may not be called "ObjectStyle"
34  * or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
35  * names without prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals and hosted on ObjectStyle Group web site. For more
53  * information on the ObjectStyle Group, please see
54  * <http://objectstyle.org/>.
55  */

56 package org.objectstyle.cayenne.access.types;
57
58 import java.io.BufferedInputStream JavaDoc;
59 import java.io.ByteArrayOutputStream JavaDoc;
60 import java.io.IOException JavaDoc;
61 import java.io.InputStream JavaDoc;
62 import java.sql.Blob JavaDoc;
63 import java.sql.CallableStatement JavaDoc;
64 import java.sql.PreparedStatement JavaDoc;
65 import java.sql.ResultSet JavaDoc;
66 import java.sql.SQLException JavaDoc;
67 import java.sql.Types JavaDoc;
68
69 import org.apache.log4j.Logger;
70 import org.objectstyle.cayenne.CayenneException;
71 import org.objectstyle.cayenne.dba.TypesMapping;
72 import org.objectstyle.cayenne.map.DbAttribute;
73 import org.objectstyle.cayenne.validation.BeanValidationFailure;
74 import org.objectstyle.cayenne.validation.ValidationResult;
75
76 /**
77  * @author Andrei Adamchik
78  */

79 public class ByteArrayType extends AbstractType {
80     private static Logger logObj = Logger.getLogger(ByteArrayType.class);
81
82     private static final int BUF_SIZE = 8 * 1024;
83     private static final byte[] EMPTY_BYTES = new byte[0];
84
85     protected boolean trimmingBytes;
86     protected boolean usingBlobs;
87
88     /**
89      * Strips null bytes from the byte array, returning a potentially smaller
90      * array that contains no trailing zero bytes.
91      */

92     public static byte[] trimBytes(byte[] bytes) {
93         int bytesToTrim = 0;
94         for (int i = bytes.length - 1; i >= 0; i--) {
95             if (bytes[i] != 0) {
96                 bytesToTrim = bytes.length - 1 - i;
97                 break;
98             }
99         }
100
101         if (bytesToTrim == 0) {
102             return bytes;
103         }
104
105         byte[] dest = new byte[bytes.length - bytesToTrim];
106         System.arraycopy(bytes, 0, dest, 0, dest.length);
107         return dest;
108     }
109
110     public ByteArrayType(boolean trimmingBytes, boolean usingBlobs) {
111         this.usingBlobs = usingBlobs;
112         this.trimmingBytes = trimmingBytes;
113     }
114
115     public String JavaDoc getClassName() {
116         return "byte[]";
117     }
118     
119     /**
120      * Validates byte[] property.
121      *
122      * @since 1.1
123      */

124     public boolean validateProperty(
125         Object JavaDoc source,
126         String JavaDoc property,
127         Object JavaDoc value,
128         DbAttribute dbAttribute,
129         ValidationResult validationResult) {
130
131         if (!(value instanceof byte[])) {
132             return true;
133         }
134
135         if (dbAttribute.getMaxLength() <= 0) {
136             return true;
137         }
138
139         byte[] bytes = (byte[]) value;
140         if (bytes.length > dbAttribute.getMaxLength()) {
141             String JavaDoc message =
142                 "\""
143                     + property
144                     + "\" exceeds maximum allowed length ("
145                     + dbAttribute.getMaxLength()
146                     + " bytes): "
147                     + bytes.length;
148             validationResult.addFailure(
149                 new BeanValidationFailure(source, property, message));
150             return false;
151         }
152
153         return true;
154     }
155
156     public Object JavaDoc materializeObject(ResultSet JavaDoc rs, int index, int type)
157         throws Exception JavaDoc {
158
159         byte[] bytes = null;
160
161         if (type == Types.BLOB) {
162             bytes =
163                 (isUsingBlobs())
164                     ? readBlob(rs.getBlob(index))
165                     : readBinaryStream(rs, index);
166         } else {
167             bytes = rs.getBytes(index);
168
169             // trim BINARY type
170
if (bytes != null && type == Types.BINARY && isTrimmingBytes()) {
171                 bytes = trimBytes(bytes);
172             }
173         }
174
175         return bytes;
176     }
177
178     public Object JavaDoc materializeObject(CallableStatement JavaDoc cs, int index, int type)
179         throws Exception JavaDoc {
180
181         byte[] bytes = null;
182
183         if (type == Types.BLOB) {
184             if (!isUsingBlobs()) {
185                 throw new CayenneException("Binary streams are not supported in stored procedure parameters.");
186             }
187             bytes = readBlob(cs.getBlob(index));
188         } else {
189
190             bytes = cs.getBytes(index);
191
192             // trim BINARY type
193
if (bytes != null && type == Types.BINARY && isTrimmingBytes()) {
194                 bytes = trimBytes(bytes);
195             }
196         }
197
198         return bytes;
199     }
200
201     public void setJdbcObject(
202         PreparedStatement JavaDoc st,
203         Object JavaDoc val,
204         int pos,
205         int type,
206         int precision)
207         throws Exception JavaDoc {
208
209         // if this is a BLOB column, set the value as "bytes"
210
// instead. This should work with most drivers
211
if (type == Types.BLOB) {
212             st.setBytes(pos, (byte[]) val);
213         } else {
214             try {
215             super.setJdbcObject(st, val, pos, type, precision);
216             }
217             catch(Exception JavaDoc ex) {
218                 logObj.warn("bad type: " + TypesMapping.getSqlNameByType(type), ex);
219                 throw ex;
220             }
221         }
222     }
223
224     protected byte[] readBlob(Blob JavaDoc blob) throws IOException JavaDoc, SQLException JavaDoc {
225         if (blob == null) {
226             return null;
227         }
228
229         // sanity check on size
230
if (blob.length() > Integer.MAX_VALUE) {
231             throw new IllegalArgumentException JavaDoc(
232                 "BLOB is too big to be read as byte[] in memory: "
233                     + blob.length());
234         }
235
236         int size = (int) blob.length();
237         if(size == 0) {
238             return EMPTY_BYTES;
239         }
240         
241         int bufSize = (size < BUF_SIZE) ? size : BUF_SIZE;
242         InputStream JavaDoc in = blob.getBinaryStream();
243         return (in != null)
244             ? readValueStream(
245                 new BufferedInputStream JavaDoc(in, bufSize),
246                 size,
247                 bufSize)
248             : null;
249     }
250
251     protected byte[] readBinaryStream(ResultSet JavaDoc rs, int index)
252         throws IOException JavaDoc, SQLException JavaDoc {
253         InputStream JavaDoc in = rs.getBinaryStream(index);
254         return (in != null) ? readValueStream(in, -1, BUF_SIZE) : null;
255     }
256
257     protected byte[] readValueStream(
258         InputStream JavaDoc in,
259         int streamSize,
260         int bufSize)
261         throws IOException JavaDoc {
262
263         byte[] buf = new byte[bufSize];
264         int read;
265         ByteArrayOutputStream JavaDoc out =
266             (streamSize > 0)
267                 ? new ByteArrayOutputStream JavaDoc(streamSize)
268                 : new ByteArrayOutputStream JavaDoc();
269
270         try {
271             while ((read = in.read(buf, 0, bufSize)) >= 0) {
272                 out.write(buf, 0, read);
273             }
274             return out.toByteArray();
275         } finally {
276             in.close();
277         }
278     }
279
280     /**
281      * Returns <code>true</code> if byte columns are handled as BLOBs
282      * internally.
283      */

284     public boolean isUsingBlobs() {
285         return usingBlobs;
286     }
287
288     public void setUsingBlobs(boolean usingBlobs) {
289         this.usingBlobs = usingBlobs;
290     }
291
292     public boolean isTrimmingBytes() {
293         return trimmingBytes;
294     }
295
296     public void setTrimmingBytes(boolean trimingBytes) {
297         this.trimmingBytes = trimingBytes;
298     }
299 }
300
Popular Tags