KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > versant > core > common > Utils


1
2 /*
3  * Copyright (c) 1998 - 2005 Versant Corporation
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  * Versant Corporation - initial API and implementation
11  */

12 package com.versant.core.common;
13
14 import com.versant.core.jdo.VersantPersistenceManager;
15 import com.versant.core.metadata.*;
16 import com.versant.core.util.classhelper.*;
17
18 import java.io.*;
19 import java.util.Date JavaDoc;
20 import java.util.Locale JavaDoc;
21 import java.util.Properties JavaDoc;
22
23 /**
24  * Utility methods.
25  */

26 public class Utils {
27
28     public static final boolean JDK14;
29
30     static {
31         String JavaDoc v = System.getProperty("java.version");
32         JDK14 = !v.startsWith("1.3"); // we can ignore 1.2 and older
33
}
34
35     /**
36      * Safe toString method. If toString on o fails then the toString of the
37      * exception is returned in angle brackets instead. This will also format
38      * a byte[] nicely showing the first few bytes in hex.
39      */

40     public static String JavaDoc toString(Object JavaDoc o) {
41         if (o == null) return "null";
42         try {
43             if (o instanceof byte[]) {
44                 byte[] a = (byte[])o;
45                 StringBuffer JavaDoc s = new StringBuffer JavaDoc();
46                 s.append("byte[]{");
47                 int i = 0;
48                 for (; i < a.length && i < 10; i++) {
49                     if (i > 0) s.append(", ");
50                     s.append("0x");
51                     s.append(Integer.toHexString(a[i]));
52                 }
53                 if (i < a.length) s.append("..." + a.length + " bytes");
54                 s.append('}');
55                 return s.toString();
56             }
57             return o.toString();
58         } catch (Throwable JavaDoc e) {
59             return "<toString failed: " + e + ">";
60         }
61     }
62
63     /**
64      * Write a UTF8 String that can be bigger than 64K. This code was cut and
65      * pasted from ObjectOutputStream.
66      *
67      * @see #readLongUTF8(java.io.DataInput)
68      */

69     public static void writeLongUTF8(String JavaDoc s, DataOutput out)
70             throws IOException {
71         byte[] buf = new byte[1024];
72         int len = s.length();
73         int bufmax = buf.length - 3;
74         out.writeInt(len);
75         int pos = 0;
76         for (int i = 0; i < len; i++) {
77             char c = s.charAt(i);
78             if (c <= 0x007F && c != 0) {
79                 buf[pos++] = (byte)c;
80             } else if (c > 0x07FF) {
81                 buf[pos + 2] = (byte)(0x80 | ((c >> 0) & 0x3F));
82                 buf[pos + 1] = (byte)(0x80 | ((c >> 6) & 0x3F));
83                 buf[pos + 0] = (byte)(0xE0 | ((c >> 12) & 0x0F));
84                 pos += 3;
85             } else {
86                 buf[pos + 1] = (byte)(0x80 | ((c >> 0) & 0x3F));
87                 buf[pos + 0] = (byte)(0xC0 | ((c >> 6) & 0x1F));
88                 pos += 2;
89             }
90             if (pos >= bufmax) {
91                 out.write(buf, 0, pos);
92                 pos = 0;
93             }
94         }
95         if (pos > 0) out.write(buf, 0, pos);
96     }
97
98     /**
99      * Read a UTF8 String previously written with writeLongUTF8. This code
100      * was cut and pasted from ObjectInputStream. This method will be slow
101      * if in is not buffered.
102      *
103      * @see #writeLongUTF8(String, DataOutput)
104      */

105     public static String JavaDoc readLongUTF8(DataInput in) throws IOException {
106         int len = in.readInt();
107         if (len == 0) return "";
108         char[] cbuf = new char[len];
109         for (int i = 0; i < len; i++) {
110             int b1, b2, b3;
111             b1 = in.readUnsignedByte();
112             switch (b1 >> 4) {
113                 case 0:
114                 case 1:
115                 case 2:
116                 case 3:
117                 case 4:
118                 case 5:
119                 case 6:
120                 case 7: // 1 byte format: 0xxxxxxx
121
cbuf[i] = (char)b1;
122                     break;
123
124                 case 12:
125                 case 13: // 2 byte format: 110xxxxx 10xxxxxx
126
b2 = in.readUnsignedByte();
127                     if ((b2 & 0xC0) != 0x80) {
128                         throw new UTFDataFormatException();
129                     }
130                     cbuf[i] = (char)(((b1 & 0x1F) << 6) |
131                             ((b2 & 0x3F) << 0));
132                     break;
133
134                 case 14: // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx
135
b2 = in.readUnsignedByte();
136                     b3 = in.readUnsignedByte();
137                     if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
138                         throw new UTFDataFormatException();
139                     }
140                     cbuf[i] = (char)(((b1 & 0x0F) << 12) |
141                             ((b2 & 0x3F) << 6) |
142                             ((b3 & 0x3F) << 0));
143                     break;
144
145                 default: // 10xx xxxx, 1111 xxxx
146
throw new UTFDataFormatException();
147             }
148         }
149         return new String JavaDoc(cbuf);
150     }
151
152     /**
153      * Util method that is responsible to check if a 'VersantObjectNotFoundException'
154      * must be thrown. This is determined from the classmetadata of the oid.
155      */

156     public static void checkToThrowRowNotFound(OID oid, ModelMetaData jmd) {
157         final ClassMetaData cmd = oid.getAvailableClassMetaData();
158         if (cmd.returnNullForRowNotFound == ClassMetaData.NULL_NO_ROW_FALSE) {
159             throw BindingSupportImpl.getInstance().objectNotFound(
160                     "No row for " +
161                     oid.getAvailableClassMetaData().storeClass + " " + oid.toSString());
162         }
163     }
164
165     /**
166      * @see #checkToThrowRowNotFound(com.versant.core.common.OID, com.versant.core.metadata.ModelMetaData)
167      */

168     public static void checkToThrowRowNotFound(OID refFrom, OID oid,
169             ModelMetaData jmd) {
170         final ClassMetaData refFromCmd = refFrom.getClassMetaData();
171         final ClassMetaData cmd = oid.getAvailableClassMetaData();
172         if (cmd.returnNullForRowNotFound == ClassMetaData.NULL_NO_ROW_FALSE
173                 || (cmd.returnNullForRowNotFound == ClassMetaData.NULL_NO_ROW_PASSON && jmd.returnNullForRowNotFound)) {
174             throw BindingSupportImpl.getInstance().objectNotFound(
175                     "No row for " +
176                     oid.getAvailableClassMetaData().storeClass
177                     + " " + oid.toSString() + " as referenced from " + refFromCmd.storeClass + " " + refFrom.toSString());
178         }
179     }
180
181     /**
182      * Writes the correct primitive or wrapper to the output stream
183      */

184     public static void writeSimple(int type, DataOutput os, Object JavaDoc toWrite)
185             throws IOException {
186         if (toWrite == null) {
187             os.writeInt(0);
188         } else {
189             os.writeInt(1);
190             switch (type) {
191                 case MDStatics.INTW:
192                 case MDStatics.INT:
193                     os.writeInt(((Integer JavaDoc)toWrite).intValue());
194                     break;
195                 case MDStatics.SHORTW:
196                 case MDStatics.SHORT:
197                     os.writeShort(((Short JavaDoc)toWrite).shortValue());
198                     break;
199                 case MDStatics.STRING:
200                     os.writeUTF((String JavaDoc)toWrite);
201                     break;
202                 case MDStatics.BOOLEANW:
203                 case MDStatics.BOOLEAN:
204                     os.writeBoolean(((Boolean JavaDoc)toWrite).booleanValue());
205                     break;
206                 case MDStatics.BYTEW:
207                 case MDStatics.BYTE:
208                     os.writeByte(((Byte JavaDoc)toWrite).byteValue());
209                     break;
210                 case MDStatics.DOUBLEW:
211                 case MDStatics.DOUBLE:
212                     os.writeDouble(((Double JavaDoc)toWrite).doubleValue());
213                     break;
214                 case MDStatics.FLOATW:
215                 case MDStatics.FLOAT:
216                     os.writeFloat(((Float JavaDoc)toWrite).floatValue());
217                     break;
218                 case MDStatics.LONGW:
219                 case MDStatics.LONG:
220                     os.writeLong(((Long JavaDoc)toWrite).longValue());
221                     break;
222                 case MDStatics.DATE:
223                     os.writeLong(((Date JavaDoc)toWrite).getTime());
224                     break;
225                 case MDStatics.BIGDECIMAL:
226                     os.writeUTF(toWrite.toString());
227                 case MDStatics.LOCALE:
228                     final Locale JavaDoc l = (Locale JavaDoc)toWrite;
229                     os.writeUTF(l.getLanguage());
230                     os.writeUTF(l.getCountry());
231                     os.writeUTF(l.getVariant());
232                     break;
233                 default:
234                     throw BindingSupportImpl.getInstance().internal("writeSimpleField for '" + MDStaticUtils.toSimpleName(
235                             type) + "' is not supported");
236             }
237         }
238     }
239
240     public static Object JavaDoc[] getObjectsById(Object JavaDoc[] objects, int count,
241             VersantPersistenceManager pm, FieldMetaData fmd, boolean isPC) {
242         // Clone data into an object[] and convert OIDs to PC instances.
243
// TODO should be possible to avoid the clone in future
244
Object JavaDoc[] data;
245         if (objects == null) {
246             data = null;
247         } else {
248             Object JavaDoc[] a = objects;
249             data = new Object JavaDoc[count];
250             if (isPC) {
251                 pm.getObjectsById(a, count, data, fmd.stateFieldNo,
252                         fmd.classMetaData.index);
253             } else {
254                 System.arraycopy(a, 0, data, 0, count);
255             }
256         }
257         return data;
258     }
259
260     /**
261      * Load resourceName as a Properties file using loader.
262      */

263     public static Properties JavaDoc loadProperties(String JavaDoc resourceName,
264             ClassLoader JavaDoc loader) {
265         Properties JavaDoc p = new Properties JavaDoc();
266         InputStream in = null;
267         try {
268             try {
269                 in = loader.getResourceAsStream(resourceName);
270                 if (in == null) {
271                     throw BindingSupportImpl.getInstance().runtime("Resource not found: " +
272                             resourceName);
273                 }
274                 p.load(in);
275             } finally {
276                 if (in != null) in.close();
277             }
278         } catch (IOException e) {
279             throw BindingSupportImpl.getInstance().runtime("Error loading resource '" +
280                     resourceName + "': " + e.getClass().getName() + ": " +
281                     e.getMessage(), e);
282         }
283         return p;
284     }
285
286     /**
287      * Is the database type Versant?
288      */

289     public static boolean isVersantDatabaseType(String JavaDoc dbt) {
290         return "versant".equals(dbt) || "vds".equals(dbt);
291     }
292
293     /**
294      * Is the URL a Versant URL?
295      */

296     public static boolean isVersantURL(String JavaDoc url) {
297         return url != null && (url.startsWith("vds:")
298                 || url.startsWith("versant:"));
299     }
300
301     public static boolean isStringEmpty(String JavaDoc str) {
302         return str == null || str.trim().length() == 0;
303     }
304
305     public static boolean isDataSource(String JavaDoc className, ClassLoader JavaDoc loader) {
306         Class JavaDoc driverClass;
307         try {
308             driverClass = ClassHelper.get().classForName(className, false, loader);
309         } catch (ClassNotFoundException JavaDoc cnfe) {
310             try {
311                 driverClass = Class.forName(className);
312             } catch (ClassNotFoundException JavaDoc e) {
313                 return false;
314             }
315         }
316
317         if ((java.sql.Driver JavaDoc.class).isAssignableFrom(driverClass)) {
318             return false;
319
320         } else if ((javax.sql.DataSource JavaDoc.class).isAssignableFrom(driverClass)) {
321             return true;
322
323         } else {
324             return false;
325         }
326
327     }
328
329 }
330
Popular Tags