View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.chukwa.util;
19  
20  import java.sql.Connection;
21  import java.sql.DriverManager;
22  import java.sql.SQLException;
23  import java.util.Properties;
24  
25  public class DriverManagerUtil {
26    
27    @SuppressWarnings("unchecked")
28    public static Class loadDriver() throws ClassNotFoundException {
29      String jdbcDriver = System.getenv("JDBC_DRIVER");
30      if(jdbcDriver == null) {
31        jdbcDriver = "com.mysql.jdbc.Driver";
32      }
33      return Class.forName(jdbcDriver);
34    }
35    
36    public static Connection getConnection(String url) throws SQLException {
37      ConnectionInfo info = new ConnectionInfo(url);
38      return DriverManager.getConnection(info.getUri(), info.getProperties());
39    }
40    
41    public static class ConnectionInfo {
42      private Properties properties = new Properties();
43      private String uri = null;
44      
45      public ConnectionInfo(String url) {
46        int pos = url.indexOf('?');
47        if(pos == -1) {
48          uri = url;
49        } else {
50          uri = url.substring(0, pos);
51          String[] paras = url.substring(pos + 1).split("&");
52          for(String s : paras) {
53            if(s==null || s.length()==0) {
54              continue;
55            }
56            String[] kv = s.split("=");
57            if(kv.length > 1) {
58              properties.put(kv[0], kv[1]);
59            }
60            else {
61              properties.put(kv[0], "");
62            }
63          }
64        }
65      }
66  
67      public Properties getProperties() {
68        return properties;
69      }
70  
71      public String getUri() {
72        return uri;
73      }
74    }
75  }