KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jdesktop > jdic > filetypes > internal > WinRegistryWrapper


1 /*
2  * Copyright (C) 2004 Sun Microsystems, Inc. All rights reserved. Use is
3  * subject to license terms.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the Lesser GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA.
19  */

20
21 package org.jdesktop.jdic.filetypes.internal;
22
23 import java.io.DataInputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.net.URL JavaDoc;
26
27
28 /**
29  * Bottom layer java wrapper for Windows registry relevant APIs
30  */

31 public class WinRegistryWrapper {
32     static {
33         System.loadLibrary("jdic");
34     }
35  
36     /**
37      * Windows handles to <tt>HKEY_CURRENT_USER</tt> and
38      * <tt>HKEY_LOCAL_MACHINE</tt> hives.
39      */

40     public final static int HKEY_CLASSES_ROOT = 0x80000000;
41     public final static int HKEY_CURRENT_USER = 0x80000001;
42     public final static int HKEY_LOCAL_MACHINE = 0x80000002;
43     public final static int HKEY_USERS = 0x80000003;
44     public final static int HKEY_CURRENT_CONFIG = 0x80000005;
45   
46     /* Windows error or status codes. */
47     public static final int ERROR_SUCCESS = 0;
48     public static final int ERROR_FILE_NOT_FOUND = 2;
49     public static final int ERROR_ACCESS_DENIED = 5;
50     public static final int ERROR_ITEM_EXIST = 0;
51     public static final int ERROR_ITEM_NOTEXIST = 9;
52   
53     /* Constants for Windows registry element size limits */
54     public static final int MAX_KEY_LENGTH = 255;
55     public static final int MAX_VALUE_NAME_LENGTH = 255;
56
57     /* Constants used to interpret returns of native functions */
58     private static final int OPENED_KEY_HANDLE = 0;
59     private static final int ERROR_CODE = 1;
60     private static final int SUBKEYS_NUMBER = 0;
61     private static final int VALUES_NUMBER = 2;
62     
63     /* Windows security masks */
64     public static final int DELETE = 0x10000;
65     public static final int KEY_QUERY_VALUE = 1;
66     public static final int KEY_SET_VALUE = 2;
67     public static final int KEY_CREATE_SUB_KEY = 4;
68     public static final int KEY_ENUMERATE_SUB_KEYS = 8;
69     public static final int KEY_READ = 0x20019;
70     public static final int KEY_WRITE = 0x20006;
71     public static final int KEY_ALL_ACCESS = 0xf003f;
72   
73     /**
74      * Java wrapper for Windows registry API RegOpenKey()
75      * @param hKey Windows registry folder
76      * @param subKey key name
77      * @return ERROR_SUCCESS if succeed, or error code if fail
78      */

79     private static native int[] RegOpenKey(int hKey, byte[] subKey,
80             int securityMask);
81                                                  
82     /**
83      * Java wrapper for Windows registry API RegCloseKey()
84      */

85     private static native int RegCloseKey(int hKey);
86   
87     /**
88      * Java wrapper for Windows registry API RegCreateKeyEx()
89      */

90     private static native int[] RegCreateKeyEx(int hKey, byte[] subKey);
91   
92     /**
93      * Java wrapper for Windows registry API RegDeleteKey()
94      */

95     private static native int RegDeleteKey(int hKey, byte[] subKey);
96   
97     /**
98      * Java wrapper for Windows registry API RegFlushKey()
99      */

100     private static native int RegFlushKey(int hKey);
101   
102     /**
103      * Java wrapper for Windows registry API RegQueryValueEx()
104      */

105     private static native byte[] RegQueryValueEx(int hKey, byte[] valueName);
106
107     /**
108      * Java wrapper for Windows registry API RegSetValueEx()
109      */

110     private static native int RegSetValueEx(int hKey, byte[] valueName,
111             byte[] value);
112
113     /**
114      * Java wrapper for Windows registry API RegDeleteValue()
115      */

116     private static native int RegDeleteValue(int hKey, byte[] valueName);
117   
118     /**
119      * Java wrapper for Windows registry API RegQueryInfoKey()
120      */

121     private static native int[] RegQueryInfoKey(int hKey);
122
123     /**
124      * Java wrapper for Windows registry API RegEnumKeyEx()
125      */

126     private static native byte[] RegEnumKeyEx(int hKey, int subKeyIndex,
127             int maxKeyLength);
128
129     /**
130      * Java wrapper for Windows registry API RegEnumValue()
131      */

132     private static native byte[] RegEnumValue(int hKey, int valueIndex,
133             int maxValueNameLength);
134
135     /**
136      * Java wrapper for Windows API FindMimeFromData()
137      */

138     private static native byte[] FindMimeFromData(byte[] url, byte[] data);
139   
140     /*
141      * Java wrapper for Windows API ExpandEnvironmentStrings()
142      */

143     private static native byte[] ExpandEnvironmentStrings(byte[] envBytes);
144
145     /**
146      * Returns this java string as a null-terminated byte array
147      */

148     private static byte[] stringToByteArray(String JavaDoc str) {
149         if (str == null) {
150             return null;
151         }
152     
153         byte[] srcByte = str.getBytes();
154         int srcLength = srcByte.length;
155         byte[] result = new byte[srcLength + 1];
156
157         System.arraycopy(srcByte, 0, result, 0, srcLength);
158         result[srcLength] = 0;
159   
160         return result;
161     }
162     
163     /**
164      * Converts a null-terminated byte array to java string
165      */

166     private static String JavaDoc byteArrayToString(byte[] array) {
167         if (array != null) {
168             String JavaDoc temString = new String JavaDoc(array);
169
170             if (temString != null) {
171                 return temString.substring(0, temString.length() - 1);
172             }
173         }
174         return null;
175     }
176
177     /**
178      * Suppress default constructor for noninstantiability.
179      */

180     private WinRegistryWrapper() {}
181
182     /**
183      * Creates the specified subkey under the parent key(hKey).
184      * <p>
185      * If the subkey already exists in the registry, the function just returns successfully.
186      * An application can create a subkey several levels deep at the same time. Such as the
187      * three preceding subkeys by specifying a string of the following form for the subKey
188      * parameter: subkey1\subkey2\subkey3\subkey4
189      * </p>
190      * @param hKey specified windows registry folder constant
191      * @param subKey given sub key (not null)
192      * @return ERROR_SUCCESS if succedd, or error code if fail
193      */

194     public static int WinRegCreateKeyEx(int hKey, String JavaDoc subKey) {
195         byte[] lpSubKey = stringToByteArray(subKey);
196         int[] createResult = RegCreateKeyEx(hKey, lpSubKey);
197     
198         if (createResult == null) {
199             return -1;
200         }
201     
202         if (createResult[ERROR_CODE] == ERROR_SUCCESS) {
203             RegCloseKey(createResult[OPENED_KEY_HANDLE]);
204         }
205       
206         return createResult[ERROR_CODE];
207     }
208
209     /**
210      * Removes the specified subkey under the parent key(hKey) from the registry.
211      * The entire sub key, including all of its values, is removed.
212      * @param hKey specified windows registry folder constant
213      * @param subKey given sub key (not null)
214      * @return ERROR_SUCCESS if succedd, or error code if fail
215      */

216     public static int WinRegDeleteKey(int hKey, String JavaDoc subKey) {
217         int result;
218         byte[] lpSubKey = stringToByteArray(subKey);
219
220         result = RegDeleteKey(hKey, lpSubKey);
221     
222         if (result == ERROR_SUCCESS) {
223             return result;
224         } else {
225             int res = WinRegSubKeyExist(hKey, subKey);
226
227             if (res == ERROR_ITEM_NOTEXIST) {
228                 return result;
229             } else {
230                 String JavaDoc subSubKey;
231                 String JavaDoc[] subSubKeys = WinRegGetSubKeys(hKey, subKey,
232                         MAX_KEY_LENGTH);
233
234                 for (int keyIndex = 0; keyIndex < subSubKeys.length; keyIndex++) {
235                     subSubKey = subKey + "\\" + subSubKeys[keyIndex];
236                     if (subSubKey != null) {
237                         WinRegDeleteKey(hKey, subSubKey);
238                     }
239                 }
240                 result = RegDeleteKey(hKey, lpSubKey);
241                 return result;
242             }
243         }
244     }
245
246     /**
247      * Writes all the attributes of the specified sub key into the registry.
248      * @param hKey specified windows registry folder constant
249      * @param subKey given sub key (not null)
250      * @return ERROR_SUCCESS if succedd, or error code if fail
251      */

252     public static int WinRegFlushKey(int hKey, String JavaDoc subKey) {
253         byte[] lpSubKey = stringToByteArray(subKey);
254         int[] openResult = RegOpenKey(hKey, lpSubKey, KEY_WRITE);
255     
256         if (openResult == null) {
257             return -1;
258         }
259     
260         if (openResult[ERROR_CODE] != ERROR_SUCCESS) {
261             return openResult[ERROR_CODE];
262         } else {
263             int flushResult = RegFlushKey(openResult[OPENED_KEY_HANDLE]);
264
265             RegCloseKey(openResult[OPENED_KEY_HANDLE]);
266             return flushResult;
267         }
268     }
269
270     /**
271      * Retrieves the data associated with the default or unnamed value of a specified
272      * registry key. The data must be a null-terminated string.
273      * @param hKey specified windows registry folder constant
274      * @param subKey given sub key (not null)
275      * @param valueName given value name (not null)
276      * @return content of the value, or null if fail or not exist
277      */

278     public static String JavaDoc WinRegQueryValueEx(int hKey, String JavaDoc subKey, String JavaDoc valueName) {
279         byte[] lpSubKey = stringToByteArray(subKey);
280         int[] openResult = RegOpenKey(hKey, lpSubKey, KEY_READ);
281     
282         if (openResult == null) {
283             return null;
284         }
285
286         if (openResult[ERROR_CODE] != ERROR_SUCCESS) {
287             return null;
288         } else {
289             byte[] valueBytes;
290             byte[] lpValueName = stringToByteArray(valueName);
291
292             valueBytes = RegQueryValueEx(openResult[OPENED_KEY_HANDLE],
293                     lpValueName);
294             RegCloseKey(openResult[OPENED_KEY_HANDLE]);
295       
296             if (valueBytes != null) {
297                 if ((valueBytes.length == 1) && (valueBytes[0] == 0) && (valueName.equals("")) ){
298                     return null;
299                 } else {
300                     return byteArrayToString(valueBytes);
301                 }
302             } else {
303                 return null;
304             }
305         }
306     }
307
308     /**
309      * Sets the data and type of a specified value under a registry key.
310      * @param hKey specified windows registry folder constant
311      * @param subKey given sub key (not null)
312      * @param valueName given value name (not null)
313      * @param value given value (not null)
314      * @return ERROR_SUCCESS if succedd, or error code if fail
315      */

316     public static int WinRegSetValueEx(int hKey, String JavaDoc subKey, String JavaDoc valueName, String JavaDoc value) {
317         byte[] lpSubKey = stringToByteArray(subKey);
318         int[] openResult = RegOpenKey(hKey, lpSubKey, KEY_SET_VALUE);
319
320         if (openResult == null) {
321             return -1;
322         }
323     
324         if (openResult[ERROR_CODE] != ERROR_SUCCESS) {
325             return openResult[ERROR_CODE];
326         } else {
327             byte[] lpValueName = stringToByteArray(valueName);
328             byte[] lpValue = stringToByteArray(value);
329             int setResult = RegSetValueEx(openResult[OPENED_KEY_HANDLE],
330                     lpValueName, lpValue);
331
332             RegCloseKey(openResult[OPENED_KEY_HANDLE]);
333       
334             return setResult;
335         }
336     }
337
338     /**
339      * Removes a named value from the specified registry key.
340      * @param hKey specified windows registry folder constant
341      * @param subKey given sub key (not null)
342      * @param valueName given value name (not null)
343      * @return ERROR_SUCCESS if succedd, or error code if fail
344      */

345     public static int WinRegDeleteValue(int hKey, String JavaDoc subKey, String JavaDoc valueName) {
346         byte[] lpSubKey = stringToByteArray(subKey);
347         int[] openResult = RegOpenKey(hKey, lpSubKey, KEY_WRITE);
348
349         if (openResult == null) {
350             return -1;
351         }
352     
353         if (openResult[ERROR_CODE] != ERROR_SUCCESS) {
354             return openResult[ERROR_CODE];
355         } else {
356             byte[] lpValueName = stringToByteArray(valueName);
357             int deleteResult = RegDeleteValue(openResult[OPENED_KEY_HANDLE],
358                     lpValueName);
359
360             RegCloseKey(openResult[OPENED_KEY_HANDLE]);
361       
362             return deleteResult;
363         }
364     }
365
366     /**
367      * Retrieves information about a specified registry key.
368      * @param hKey specified windows registry folder constant
369      * @param subKey given sub key (not null)
370      * @return array contain query result
371      */

372     public static int[] WinRegQueryInfoKey(int hKey, String JavaDoc subKey) {
373         byte[] lpSubKey = stringToByteArray(subKey);
374         int[] openResult = RegOpenKey(hKey, lpSubKey, KEY_READ);
375
376         if (openResult == null) {
377             return null;
378         }
379     
380         if (openResult[ERROR_CODE] != ERROR_SUCCESS) {
381             return openResult;
382         } else {
383             int[] queryResult = RegQueryInfoKey(openResult[OPENED_KEY_HANDLE]);
384
385             RegCloseKey(openResult[OPENED_KEY_HANDLE]);
386       
387             return queryResult;
388         }
389     }
390
391     /**
392      * Enumerates subkeys of the specified registry key. The function retrieves information
393      * about one subkey each time it is called.
394      * @param hKey specified windows registry folder constant
395      * @param subKey given sub key (not null)
396      * @param subKeyIndex index of the sub key
397      * @param maxKeyLength max length of sub keys
398      * @return name of the sub key
399      */

400     public static String JavaDoc WinRegEnumKeyEx(int hKey, String JavaDoc subKey, int subKeyIndex, int maxKeyLength) {
401         byte[] lpSubKey = stringToByteArray(subKey);
402         int[] openResult = RegOpenKey(hKey, lpSubKey, KEY_READ);
403
404         if (openResult == null) {
405             return null;
406         }
407     
408         if (openResult[ERROR_CODE] != ERROR_SUCCESS) {
409             return null;
410         } else {
411             byte[] keyBytes = RegEnumKeyEx(openResult[OPENED_KEY_HANDLE],
412                     subKeyIndex, maxKeyLength);
413
414             RegCloseKey(openResult[OPENED_KEY_HANDLE]);
415       
416             if (keyBytes != null) {
417                 return byteArrayToString(keyBytes);
418             } else {
419                 return null;
420             }
421         }
422     }
423
424     /**
425      * Enumerates the values for the specified registry key. The function copies one indexed
426      * value name and data block for the key each time it is called.
427      * @param hKey specified windows registry folder constant
428      * @param subKey given sub key (not null)
429      * @param valueIndex value index
430      * @param maxValueNameLength max length of the value name
431      * @return value name
432      */

433     public static String JavaDoc WinRegEnumValue(int hKey, String JavaDoc subKey, int valueIndex, int maxValueNameLength) {
434         byte[] lpSubKey = stringToByteArray(subKey);
435         int[] openResult = RegOpenKey(hKey, lpSubKey, KEY_READ);
436
437         if (openResult == null) {
438             return null;
439         }
440     
441         if (openResult[ERROR_CODE] != ERROR_SUCCESS) {
442             return null;
443         } else {
444             byte[] valueBytes = RegEnumValue(openResult[OPENED_KEY_HANDLE],
445                     valueIndex, maxValueNameLength);
446
447             RegCloseKey(openResult[OPENED_KEY_HANDLE]);
448       
449             if (valueBytes != null) {
450                 return byteArrayToString(valueBytes);
451             } else {
452                 return null;
453             }
454         }
455     }
456
457     /**
458      * Enumerates all the sub keys under the specified registry key.
459      * @param hKey specified windows registry folder constant
460      * @param subKey given sub key (not null)
461      * @param maxKeyLength max number of sub keys
462      * @return a array containing name of the sub keys
463      */

464     public static String JavaDoc[] WinRegGetSubKeys(int hKey, String JavaDoc subKey, int maxKeyLength) {
465         byte[] lpSubKey = stringToByteArray(subKey);
466         int[] openResult = RegOpenKey(hKey, lpSubKey, KEY_READ);
467
468         if (openResult == null) {
469             return null;
470         }
471     
472         if (openResult[ERROR_CODE] != ERROR_SUCCESS) {
473             return null;
474         } else {
475             int[] queryResult = RegQueryInfoKey(openResult[OPENED_KEY_HANDLE]);
476             int subKeysNum = queryResult[SUBKEYS_NUMBER];
477
478             if (subKeysNum == 0) {
479                 RegCloseKey(openResult[OPENED_KEY_HANDLE]);
480                 return null;
481             } else {
482                 String JavaDoc[] keyStrings = new String JavaDoc[subKeysNum];
483                 byte[] keyBytes;
484       
485                 for (int subKeyIndex = 0; subKeyIndex < subKeysNum; subKeyIndex++) {
486                     keyBytes = RegEnumKeyEx(openResult[OPENED_KEY_HANDLE],
487                             subKeyIndex, maxKeyLength);
488                     keyStrings[subKeyIndex] = byteArrayToString(keyBytes);
489                 }
490                 RegCloseKey(openResult[OPENED_KEY_HANDLE]);
491     
492                 return keyStrings;
493             }
494         }
495     }
496   
497     /**
498      * Enumerates all the values under the specified registry key.
499      * @param hKey specified windows registry folder constant
500      * @param subKey given sub key (not null)
501      * @param maxValueLength max number of values
502      * @return a string array containing the name of each value
503      */

504     public static String JavaDoc[] WinRegGetValues(int hKey, String JavaDoc subKey, int maxValueLength) {
505         byte[] lpSubKey = stringToByteArray(subKey);
506         int[] openResult = RegOpenKey(hKey, lpSubKey, KEY_READ);
507     
508         if (openResult == null) {
509             return null;
510         }
511     
512         if (openResult[ERROR_CODE] != ERROR_SUCCESS) {
513             return null;
514         } else {
515             int[] queryResult = RegQueryInfoKey(openResult[OPENED_KEY_HANDLE]);
516             int valuesNum = queryResult[VALUES_NUMBER];
517
518             if (valuesNum == 0) {
519                 RegCloseKey(openResult[OPENED_KEY_HANDLE]);
520                 return null;
521             } else {
522                 String JavaDoc[] valueStrings = new String JavaDoc[valuesNum];
523                 byte[] valueBytes;
524      
525                 for (int valueIndex = 0; valueIndex < valuesNum; valueIndex++) {
526                     valueBytes = RegEnumValue(openResult[OPENED_KEY_HANDLE],
527                             valueIndex, maxValueLength);
528                     valueStrings[valueIndex] = byteArrayToString(valueBytes);
529                 }
530                 RegCloseKey(openResult[OPENED_KEY_HANDLE]);
531         
532                 return valueStrings;
533             }
534         }
535     }
536   
537     /**
538      * Checks whether the specified registry key exsists in the registry.
539      * @param hKey specified windows registry folder constant
540      * @param subKey given sub key (not null)
541      * @return ERROR_SUCCESS if succedd, or error code if fail
542      */

543     public static int WinRegSubKeyExist(int hKey, String JavaDoc subKey) {
544         byte[] lpSubKey = stringToByteArray(subKey);
545         int[] openResult = RegOpenKey(hKey, lpSubKey, KEY_READ);
546
547         if (openResult == null) {
548             return ERROR_ITEM_NOTEXIST;
549         }
550
551         if (openResult[ERROR_CODE] != ERROR_SUCCESS) {
552             return ERROR_ITEM_NOTEXIST;
553         } else {
554             RegCloseKey(openResult[OPENED_KEY_HANDLE]);
555             return ERROR_ITEM_EXIST;
556         }
557     }
558   
559     /**
560      * Checks whether the specified value exsists in the specified registry key.
561      * @param hKey specified windows registry folder constant
562      * @param subKey given sub key (not null)
563      * @param valueName given value name (not null)
564      * @return ERROR_ITEM_EXIST if the value exists under given sub key
565      */

566     public static int WinRegValueExist(int hKey, String JavaDoc subKey, String JavaDoc valueName) {
567         if (subKey.trim().equals("")) {
568             return ERROR_ITEM_NOTEXIST;
569         }
570     
571         byte[] lpSubKey = stringToByteArray(subKey);
572         int[] openResult = RegOpenKey(hKey, lpSubKey, KEY_READ);
573
574         if (openResult == null) {
575             return ERROR_ITEM_NOTEXIST;
576         }
577     
578         if (openResult[ERROR_CODE] != ERROR_SUCCESS) {
579             return ERROR_ITEM_NOTEXIST;
580         } else {
581             byte[] lpValueName = stringToByteArray(valueName);
582             byte[] valueBytes = RegQueryValueEx(openResult[OPENED_KEY_HANDLE],
583                     lpValueName);
584
585             RegCloseKey(openResult[OPENED_KEY_HANDLE]);
586       
587             if (valueBytes == null) {
588                 return ERROR_ITEM_NOTEXIST;
589             } else {
590                 if ((valueBytes.length == 1) && (valueBytes[0] == 0) && (valueName.equals("")) ){
591                     return ERROR_ITEM_NOTEXIST;
592                 } else {
593                     return ERROR_ITEM_EXIST;
594                 }
595             }
596         }
597     }
598   
599     /**
600      * Determines the MIME type from the data provided.
601      * Now the input data comes from the specified URL object.
602      * @param url given url (not null)
603      * @return correponding mime type information, or null if couldn't
604      */

605     public static String JavaDoc WinFindMimeFromData(URL JavaDoc url) {
606         byte[] urlBytes;
607         byte[] result;
608         String JavaDoc urlString = url.toString();
609     
610         urlBytes = stringToByteArray(urlString);
611         
612         result = FindMimeFromData(urlBytes, null);
613         if (result != null) {
614             return byteArrayToString(result);
615         } else {
616             byte[] dataBytes = new byte[256];
617       
618             DataInputStream JavaDoc inStream = null;
619             try {
620                 inStream = new DataInputStream JavaDoc(url.openStream());
621                 // Read a buffer size of 256 bytes of data to sniff the mime type.
622
inStream.read(dataBytes, 0, 256);
623                 inStream.close();
624             } catch (IOException JavaDoc e) {
625                 // Cannot open the connection to the URL, return.
626
return null;
627             } finally {
628                 // No matter what happens, always close streams already opened.
629
if (inStream != null) {
630                     try {
631                         inStream.close();
632                     } catch (IOException JavaDoc e) {
633                     }
634                 }
635             }
636             
637             result = FindMimeFromData(null, dataBytes);
638             if (result != null) {
639                 return byteArrayToString(result);
640             } else {
641                 return null;
642             }
643         }
644     }
645   
646     /**
647      * Expands environment-variable strings and replaces them with their defined values.
648      * <P>
649      * E.g: "%SystemRoot%\\system32\\NOTEPAD.EXE %1" -> "C:\\system32\\NOTEPAD.EXE %1"
650      * </P>
651      * @param envVariable given environment variable (not null)
652      * @return expression after environment variable replacement
653      */

654     public static String JavaDoc WinExpandEnvironmentStrings(String JavaDoc envVariable) {
655         byte[] envVariableBytes = stringToByteArray(envVariable);
656         byte[] resultBytes = ExpandEnvironmentStrings(envVariableBytes);
657     
658         return (byteArrayToString(resultBytes));
659     }
660 }
661
662
663
Popular Tags