KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sqlmagic > tinysql > Utils


1 /*
2  * Utils.java
3  * tinySQL, some helper methods
4  *
5  * $Author: davis $
6  * $Date: 2004/12/18 21:27:20 $
7  * $Revision: 1.1 $
8  */

9 package com.sqlmagic.tinysql;
10
11 import java.util.*;
12 import java.lang.*;
13 import java.io.*;
14 import java.sql.Types JavaDoc;
15
16
17 /**
18 Some helper methods for tinySQL
19 @author Brian Jepson <bjepson@home.com>
20 @author Marcel Ruff <ruff@swand.lake.de> Added write access to dBase and JDK 2 support
21 */

22 public class Utils
23 {
24   // JLex (the lexical analyzer) doesn´t support unicode
25
// so we must play around with the different code pages:
26
// "Cp437" = 7 bit MS-DOS, US-ASCII
27
// "Cp850" = 8 bit MS-DOS, Multilingual Latin 1, &auml; = 0x83 = 131
28
// "Cp1252" = 8 bit Windows Multilingual, &auml; = 0xe4 = 228
29
// In future the code page should be passed at connection time using the URL
30
final static String JavaDoc encode = "Cp1252"; // dBase encoding
31

32   /**
33    * Converts a long to a little-endian four-byte array
34    *
35    */

36   public final static byte[] intToLittleEndian(int val)
37   {
38     byte[] b = new byte[4];
39     for (int i = 0; i < 4; i++) {
40       b[i] = (byte)(val % 256);
41       val = val / 256;
42     }
43     return b;
44   }
45
46
47   /**
48    * Converts a long to a little-endian two-byte array
49    *
50    */

51   public final static byte[] shortToLittleEndian(short val)
52   {
53     byte[] b = new byte[2];
54     for (int i = 0; i < 2; i++) {
55       b[i] = (byte)(val % 256);
56       val = (short)(val / 256);
57     }
58     return b;
59   }
60
61
62   /**
63    *
64    * Converts a little-endian four-byte array to a long,
65    * represented as a double, since long is signed.
66    *
67    * I don't know why Java doesn't supply this. It could
68    * be that it's there somewhere, but I looked and couldn't
69    * find it.
70    *
71    */

72   public final static double vax_to_long(byte[] b) {
73
74     //existing code that has been commented out
75
//return fixByte(b[0]) + ( fixByte(b[1]) * 256) +
76
//( fixByte(b[2]) * (256^2)) + ( fixByte(b[3]) * (256^3));
77

78     // Fix courtesy Preetha Suri <Preetha.Suri@sisl.co.in>
79
//
80
long lngTmp = (long)(0x0ffL & b[0])
81                   | ( (0x0ffL & (long)b[1]) << 8 )
82                   | ( (0x0ffL & (long)b[2]) << 16 )
83                   | ( (0x0ffL & (long)b[3]) << 24 );
84
85
86     return((double)lngTmp);
87
88   }
89
90
91   /**
92    *
93    * Converts a little-endian four-byte array to a short,
94    * represented as an int, since short is signed.
95    *
96    * I don't know why Java doesn't supply this. It could
97    * be that it's there somewhere, but I looked and couldn't
98    * find it.
99    *
100    */

101   public final static int vax_to_short(byte[] b) {
102     return (int) ( fixByte(b[0]) + ( fixByte(b[1]) * 256));
103   }
104
105
106   /*
107    *
108    * bytes are signed; let's fix them...
109    *
110    */

111   public final static short fixByte (byte b) {
112
113     if (b < 0) {
114       return (short) ( b + 256);
115     }
116     return b;
117   }
118
119   /**
120   Cut or padd the string to the given size
121   @param a string
122   @param size the wanted length
123   @param padChar char to use for padding (must be of length()==1!)
124   @return the string with correct lenght, padded with pad if necessary
125   */

126   public final static String JavaDoc forceToSize(String JavaDoc str, int size, String JavaDoc padChar)
127   {
128     if (str != null && str.length() == size)
129       return str;
130
131     StringBuffer JavaDoc tmp;
132     if (str == null)
133       tmp = new StringBuffer JavaDoc(size);
134     else
135       tmp = new StringBuffer JavaDoc(str);
136
137     if (tmp.length() > size) {
138       return tmp.toString().substring(0, size); // do cutting
139
}
140     else {
141       // or add some padding to the end of the string
142
StringBuffer JavaDoc pad = new StringBuffer JavaDoc(size);
143       int numBlanks = size - tmp.length();
144       for (int p = 0; p < numBlanks; p++) {
145         pad.append(padChar);
146       }
147       return tmp.append(pad).toString();
148     }
149   }
150
151
152   /**
153   Cut or padd the string to the given size
154   @param a string
155   @param size the wanted length
156   @param padByte char to use for padding
157   @return the string with correct lenght, padded with pad if necessary
158   */

159   public final static byte[] forceToSize(String JavaDoc str, int size, byte padByte) throws java.io.UnsupportedEncodingException JavaDoc
160   {
161     if (str != null && str.length() == size)
162       return str.getBytes(encode);
163
164     byte[] result = new byte[size];
165
166     if (str == null) {
167       for (int ii = 0; ii<size; ii++) result[ii] = padByte;
168       return result;
169     }
170
171     if (str.length() > size)
172       return str.substring(0, size).getBytes(encode); // do cutting
173

174     // do padding
175
byte[] tmp = str.getBytes(encode);
176     for (int jj = 0; jj < tmp.length; jj++)
177       result[jj] = tmp[jj];
178     for (int kk = tmp.length; kk < size; kk++)
179       result[kk] = padByte;
180     return result;
181   }
182
183
184   /*
185    * Delete a file in the data directory
186    */

187   public final static void delFile (String JavaDoc fname) throws NullPointerException JavaDoc, IOException
188   {
189     File f = new File( fname );
190
191     // only delete a file that exists
192
//
193
if (f.exists())
194     {
195       // try the delete. If it fails, complain
196
//
197
if (!f.delete()) {
198         throw new IOException("Could not delete: " + f.getAbsolutePath() + ".");
199       }
200     }
201   }
202   public final static void delFile (String JavaDoc dataDir, String JavaDoc fname) throws NullPointerException JavaDoc, IOException {
203
204     File f = new File( dataDir + File.separator + fname );
205
206     // only delete a file that exists
207
//
208
if (f.exists()) {
209       // try the delete. If it fails, complain
210
//
211
if (!f.delete()) {
212         throw new IOException("Could not delete file: " +
213                                dataDir + "/" + fname + ".");
214       }
215     }
216   }
217
218
219   /**
220   rename a file
221   @return true if succeeded
222   */

223   public final static boolean renameFile(String JavaDoc oldName, String JavaDoc newName)
224   {
225     File f_old = new File(oldName);
226     File f_new = new File(newName);
227     boolean ret = f_old.renameTo(f_new);
228     return ret;
229   }
230
231
232   /**
233   Strip the path and suffix of a file name
234   @param file "/usr/local/dbase/test.DBF"
235   @return "test"
236   */

237   public final static String JavaDoc stripPathAndExtension(final String JavaDoc file)
238   {
239     String JavaDoc sep = File.separator;
240     int begin = file.lastIndexOf(sep);
241     if (begin < 0) begin = 0;
242     else begin++;
243     int end = file.lastIndexOf(".");
244     if (end < 0) end = file.length();
245     String JavaDoc str = file.substring(begin, end);
246     return str;
247   }
248
249
250 /*
251  * Scan the given directory for files containing the substrMatch<br>
252  * Small case extensions '.dbf' are recognized and returned as '.DBF'
253  */

254    public final static Vector getAllFiles(final String JavaDoc path, final String JavaDoc suffix)
255    {
256     Vector vec = (Vector)null;
257     String JavaDoc[] fileNameList;
258     File currentDir,f;
259     String JavaDoc fileName,upperSuffix;
260     int i;
261     upperSuffix = suffix.toUpperCase();
262     currentDir = new File(path);
263     fileNameList = currentDir.list();
264     if(fileNameList == null)
265     {
266        System.out.println("*** null for " + path);
267     } else {
268        vec = new Vector(fileNameList.length);
269        for( i = 0; i < fileNameList.length; i++ )
270        {
271           f = new File(fileNameList[i]);
272           if(!f.isDirectory())
273           {
274              fileName = f.getPath().toString().toUpperCase();
275 // lastModified = new java.util.Date(f.lastModified());
276
if (upperSuffix == null | fileName.endsWith(upperSuffix))
277              {
278                 vec.addElement(f);
279              }
280           }
281        }
282     }
283     return vec;
284   }
285   public static boolean isDateColumn(int columnType)
286   {
287      if ( columnType == Types.DATE | columnType == Types.TIMESTAMP )
288         return true;
289      else return false;
290   }
291   public static boolean isCharColumn(int columnType)
292   {
293      if (columnType == Types.CHAR || columnType == Types.VARCHAR ||
294          columnType == Types.LONGVARCHAR) return true;
295      else return false;
296   }
297   public static boolean isNumberColumn(int columnType)
298   {
299      if (columnType == Types.NUMERIC || columnType == Types.INTEGER ||
300          columnType == Types.TINYINT || columnType == Types.SMALLINT ||
301          columnType == Types.BIGINT || columnType == Types.FLOAT ||
302          columnType == Types.DOUBLE || columnType == Types.REAL) return true;
303      else return false;
304   }
305 /*
306  * Move the input table to the top of the selection list.
307  */

308    public static void setPriority(Vector inputList,String JavaDoc inputTable)
309    {
310       String JavaDoc tableName;
311       int i;
312       if ( inputList == (Vector)null ) return;
313       for ( i = 0; i < inputList.size(); i++ )
314       {
315          tableName = (String JavaDoc)inputList.elementAt(i);
316          if ( tableName.equals(inputTable) )
317          {
318             if ( i > 0 )
319             {
320                inputList.removeElementAt(i);
321                inputList.insertElementAt(tableName,0);
322             }
323             break;
324          }
325       }
326    }
327
328   /**
329   For debugging/tracing
330   Switch the debug mode on/off:
331   */

332   final static boolean debug=false;
333   final static void log(String JavaDoc id, String JavaDoc str)
334   {
335     if (debug) log(id + ": " + str);
336   }
337   final static void log(String JavaDoc str)
338   {
339     if (debug) System.out.println(str);
340   }
341
342 }
Popular Tags