KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > jdo > spi > persistence > utility > database > DBVendorTypeHelper


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24
25 package com.sun.jdo.spi.persistence.utility.database;
26
27 import com.sun.jdo.spi.persistence.utility.LogHelperUtility;
28 import com.sun.jdo.spi.persistence.utility.PropertyHelper;
29 import com.sun.jdo.spi.persistence.utility.logging.Logger;
30
31 import java.io.IOException JavaDoc;
32 import java.sql.DatabaseMetaData JavaDoc;
33 import java.sql.SQLException JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.Map JavaDoc;
36 import java.util.Properties JavaDoc;
37 import java.util.regex.Pattern JavaDoc;
38 import java.util.regex.PatternSyntaxException JavaDoc;
39
40 /**
41  * @author Mitesh Meswani
42  * This class defines string constants representing database names.
43  * This class is responsible to translate given database name to internal name.
44  */

45 public class DBVendorTypeHelper {
46     //Enum that corresponds to unknown database.
47
public final static int OTHER_ENUM = -1;
48
49     //Known databases.
50
public final static int DEFAULT_DB_ENUM = 0;
51     public final static int ORACLE_ENUM = 1;
52     public final static int POINTBASE_ENUM = 2;
53     public final static int MSSQL_ENUM = 3;
54     public final static int SYBASE_ENUM = 4;
55     public final static int DB2_ENUM = 5;
56     public final static int MYSQL_ENUM = 6;
57     public final static int INFORMIX_ENUM = 7;
58     public final static int INGRES_ENUM = 8;
59     public final static int DERBY_ENUM = 9;
60
61     //Please increment following when a new known database is added.
62
public final static int MAX_KNOWN_DB = 10;
63
64     /**
65      * Array that defines mapping from given string name to enum.
66      * Please make sure that array indexes and enum values are kept in sync.
67      */

68     private final static String JavaDoc enumToStringMapping[] =
69         {"SQL92", "ORACLE", "POINTBASE", "MSSQL", "SYBASE", "DB2", "MYSQL",
70          "INFORMIX", "INGRES", "DERBY"}; // NOI18N
71

72     public final static String JavaDoc DEFAULT_DB = enumToStringMapping[DEFAULT_DB_ENUM];
73     public final static String JavaDoc ORACLE = enumToStringMapping[ORACLE_ENUM];
74     public final static String JavaDoc POINTBASE = enumToStringMapping[POINTBASE_ENUM];
75     public final static String JavaDoc MSSQL = enumToStringMapping[MSSQL_ENUM];
76     public final static String JavaDoc SYBASE = enumToStringMapping[SYBASE_ENUM];
77     public final static String JavaDoc DB2 = enumToStringMapping[DB2_ENUM];
78     public final static String JavaDoc MYSQL = enumToStringMapping[MYSQL_ENUM];
79     public final static String JavaDoc INFORMIX = enumToStringMapping[INFORMIX_ENUM];
80     public final static String JavaDoc INGRES = enumToStringMapping[INGRES_ENUM];
81     public final static String JavaDoc DERBY = enumToStringMapping[DERBY_ENUM];
82
83     private final static String JavaDoc PROPERTY_PATH = "com/sun/jdo/spi/persistence/utility/database/"; // NOI18N
84

85     private final static String JavaDoc VENDOR_NAME_TO_TYPE_PROPERTY =
86         "com.sun.jdo.spi.persistence.utility.database.VENDOR_NAME_TO_TYPE"; //NOI18N
87
private final static String JavaDoc VENDOR_NAME_TO_TYPE_RESOURCE_PROPERTY =
88         "com.sun.jdo.spi.persistence.utility.database.VENDOR_NAME_TO_TYPE_RESOURCE"; //NOI18N
89
private final static String JavaDoc VENDOR_NAME_TO_TYPE_RESOURCE_DEFAULT_NAME =
90         PROPERTY_PATH + "VendorNameToTypeMapping.properties"; //NOI18N
91

92     /**
93      * The logger.
94      */

95     private static final Logger logger = LogHelperUtility.getLogger();
96
97     /**
98      * Holds mapping between possible vendor names to internal types defined above.
99      * vendor names are treated as regular expressions.
100      */

101     private static Properties JavaDoc _nameToVendorType = initializeNameToVendorType();;
102
103     /** Get Database Vendor Type from vendor name.
104      * @param vendorName Input vendor name. Typically this is obtained by querying
105      * <code>DatabaseMetaData</code>.
106      * @return Database type that corresponds to <code>vendorName</code>.
107      * If vendorName does not match any of predefined vendor names, the database type
108      * returned is generated using following logic.
109      * <PRE>
110      * detectedDbType = vendorName.toUpperCase();
111      * int i = detectedDbType.indexOf('/');
112      * if (i > -1) {
113      * detectedDbType = detectedDbType.substring(0, i);
114      * }
115      * </PRE>
116      * If vendorName is null, <code>DEFAULT_DB</code> is returned.
117      */

118     public static String JavaDoc getDBType(String JavaDoc vendorName) {
119         boolean debug = logger.isLoggable();
120         if(debug) {
121             logger.fine("utility.database.DBVendorTypeHelper.inputVendorName", //NOI18N
122
vendorName);
123         }
124         String JavaDoc detectedDbType = DEFAULT_DB;
125         if(vendorName != null) {
126             detectedDbType = matchVendorNameInProperties(vendorName, _nameToVendorType);
127             //If not able to detect dbType from properties, invent one by
128
//manipulating input vendorName.
129
if(detectedDbType == null) {
130                 detectedDbType = vendorName.toUpperCase();
131                 int i = detectedDbType.indexOf('/');
132                 if (i > -1) {
133                     detectedDbType = detectedDbType.substring(0, i);
134                 }
135             }
136         }
137         if(debug)
138             logger.fine("utility.database.DBVendorTypeHelper.detectedVendorType",detectedDbType); //NOI18N
139
return detectedDbType;
140     }
141
142     /** Gets enumerated database type for given metaData
143      * @param metaData Input DataBaseMetaData.
144      * @return Enumerated database type as described by
145      * {@link #getEnumDBType(java.lang.String)}.
146      */

147      public static int getEnumDBType(DatabaseMetaData JavaDoc metaData)
148             throws SQLException JavaDoc {
149         String JavaDoc dbType = getDBType(metaData.getDatabaseProductName());
150         return getEnumDBType(dbType);
151      }
152
153    /** Gets enumerated database type for given dbType
154     * @param dbType Input database Type. This should have been obtained from a previous call to
155     * {@link #getDBType(java.lang.String)}
156     * @return dbType translated to one of the enumerations above. If dbType does not correspond to
157     * one of the predefined types, OTHER is returned
158     */

159     public static int getEnumDBType(String JavaDoc dbType) {
160         int enumDBType = OTHER_ENUM;
161         //Search through the array for dbType
162
for(int i = 0; i < MAX_KNOWN_DB - 1 && enumDBType == OTHER_ENUM; i++) {
163             if(enumToStringMapping[i].equals(dbType) )
164                 enumDBType = i;
165         }
166         return enumDBType;
167     }
168
169     /**
170      * Determines whether to use uppercase schema name for a give database.
171      * @param dmd The DatabaseMetaData for the database
172      * @return true if upper case schemaname is to be used. False otherwise.
173      * @throws SQLException
174      */

175     public static boolean requireUpperCaseSchema(DatabaseMetaData JavaDoc dmd)
176             throws SQLException JavaDoc {
177         int vendorTypeEnum = getEnumDBType(dmd);
178         return ORACLE_ENUM == vendorTypeEnum ||
179                 POINTBASE_ENUM == vendorTypeEnum;
180     }
181
182     /**
183      * Allocate and initialize nameToVendorType if not already done.
184      */

185     private static Properties JavaDoc initializeNameToVendorType() {
186         synchronized(DBVendorTypeHelper.class) {
187             if(_nameToVendorType == null) {
188                 _nameToVendorType = new Properties JavaDoc();
189                 String JavaDoc resourceName = System.getProperty(VENDOR_NAME_TO_TYPE_RESOURCE_PROPERTY,
190                                     VENDOR_NAME_TO_TYPE_RESOURCE_DEFAULT_NAME);
191                 try {
192                     PropertyHelper.loadFromResource(_nameToVendorType,resourceName,
193                                             DBVendorTypeHelper.class.getClassLoader() );
194                 } catch (IOException JavaDoc e) {
195                     if(logger.isLoggable() ) {
196                         logger.fine("utility.database.DBVendorTypeHelper.couldNotLoadResource", // NOI18N
197
resourceName,e);
198                     }
199                 }
200                 overrideWithSystemProperties(_nameToVendorType);
201             }
202         }
203
204         return _nameToVendorType;
205     }
206
207     /**
208      * Match vendorName in properties specifieid by nameToVendorType.
209      */

210     private static String JavaDoc matchVendorNameInProperties(String JavaDoc vendorName, Properties JavaDoc nameToVendorType) {
211         String JavaDoc dbType = null;
212         //Iterate over all properties till we find match.
213
for( Iterator JavaDoc iterator = nameToVendorType.entrySet().iterator();
214                 dbType == null && iterator.hasNext();) {
215             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
216             String JavaDoc regExpr = (String JavaDoc) entry.getKey();
217             String JavaDoc value = (String JavaDoc) entry.getValue();
218             if(logger.isLoggable(Logger.FINEST) )
219                 logger.finest("utility.database.DBVendorTypeHelper.regExprDbType",regExpr,value); // NOI18N
220
if( matchPattern(regExpr,vendorName) ) {
221                 dbType = value;
222             }
223         }
224         return dbType;
225     }
226
227    /** Matches target to pattern specified regExp. Returns false if there is
228     * any error compiling regExp.
229     * @param regExp The regular expression.
230     * @param target The target against which we are trying to match regExp.
231     * @return false if there is error compiling regExp or target does not
232     * match regExp. true if regExp matches pattern.
233     */

234     private static boolean matchPattern(String JavaDoc regExp, String JavaDoc target) {
235         boolean matches = false;
236         try {
237             matches = Pattern.matches(regExp,target);
238         } catch (PatternSyntaxException JavaDoc e){
239             logger.fine("utility.database.DBVendorTypeHelper.patternSyntaxException",e); // NOI18N
240
}
241         return matches;
242     }
243
244     /**
245      * Overrides nameToVendorType with any system properties defined.
246      */

247     private static void overrideWithSystemProperties(Properties JavaDoc nameToVendorType) {
248         String JavaDoc vendorNameToType = null;
249         boolean debug = logger.isLoggable();
250
251         int counter = 1;
252         do {
253             String JavaDoc vendorNameToTypeProperty = VENDOR_NAME_TO_TYPE_PROPERTY + counter++;
254             vendorNameToType = System.getProperty(vendorNameToTypeProperty);
255             if(vendorNameToType != null) {
256                 //Split the vendorNameToType into two at char '='
257
String JavaDoc[] parsedProperty = vendorNameToType.split("=",2); //NOI18N
258
if( parsedProperty.length >= 2) {
259                     String JavaDoc suggestedDbType = parsedProperty[0];
260                     String JavaDoc regExp = parsedProperty[1];
261                     if(debug) {
262                         logger.fine("utility.database.DBVendorTypeHelper.traceVendorNameToTypeProperty", //NOI18N
263
vendorNameToTypeProperty,regExp,suggestedDbType);
264                     }
265                     nameToVendorType.put(regExp,suggestedDbType);
266                 }
267                 else {
268                     if(debug)
269                         logger.fine("utility.database.DBVendorTypeHelper.errorParsingVendorNameToTypeProperty", //NOI18N
270
vendorNameToTypeProperty,vendorNameToType);
271                 }
272             }
273         } while (vendorNameToType != null);
274      }
275
276
277 }
278
Popular Tags