1 16 17 package org.apache.taglibs.standard.tag.common.sql; 18 19 import javax.naming.Context ; 20 import javax.naming.InitialContext ; 21 import javax.naming.NamingException ; 22 import javax.servlet.jsp.JspException ; 23 import javax.servlet.jsp.JspTagException ; 24 import javax.servlet.jsp.PageContext ; 25 import javax.servlet.jsp.jstl.core.Config; 26 import javax.sql.DataSource ; 27 28 import org.apache.taglibs.standard.resources.Resources; 29 30 31 39 public class DataSourceUtil { 40 41 private static final String ESCAPE = "\\"; 42 private static final String TOKEN = ","; 43 44 50 static DataSource getDataSource(Object rawDataSource, PageContext pc) 51 throws JspException 52 { 53 DataSource dataSource = null; 54 55 if (rawDataSource == null) { 56 rawDataSource = Config.find(pc, Config.SQL_DATA_SOURCE); 57 } 58 59 if (rawDataSource == null) { 60 return null; 61 } 62 63 68 if (rawDataSource instanceof String ) { 69 try { 70 Context ctx = new InitialContext (); 71 Context envCtx = (Context ) ctx.lookup("java:comp/env"); 73 dataSource = (DataSource ) envCtx.lookup((String ) rawDataSource); 74 } catch (NamingException ex) { 75 dataSource = getDataSource((String ) rawDataSource); 76 } 77 } else if (rawDataSource instanceof DataSource ) { 78 dataSource = (DataSource ) rawDataSource; 79 } else { 80 throw new JspException ( 81 Resources.getMessage("SQL_DATASOURCE_INVALID_TYPE")); 82 } 83 84 return dataSource; 85 } 86 87 90 private static DataSource getDataSource(String params) 91 throws JspException 92 { 93 DataSourceWrapper dataSource = new DataSourceWrapper(); 94 95 String [] paramString = new String [4]; 96 int escCount = 0; 97 int aryCount = 0; 98 int begin = 0; 99 100 for(int index=0; index < params.length(); index++) { 101 char nextChar = params.charAt(index); 102 if (TOKEN.indexOf(nextChar) != -1) { 103 if (escCount == 0) { 104 paramString[aryCount] = params.substring(begin,index).trim(); 105 begin = index + 1; 106 if (++aryCount > 4) { 107 throw new JspTagException ( 108 Resources.getMessage("JDBC_PARAM_COUNT")); 109 } 110 } 111 } 112 if (ESCAPE.indexOf(nextChar) != -1) { 113 escCount++; 114 } 115 else { 116 escCount = 0; 117 } 118 } 119 paramString[aryCount] = params.substring(begin).trim(); 120 121 dataSource.setJdbcURL(paramString[0]); 123 124 if (paramString[1] != null) { 126 try { 127 dataSource.setDriverClassName(paramString[1]); 128 } catch (Exception ex) { 129 throw new JspTagException ( 130 Resources.getMessage("DRIVER_INVALID_CLASS", 131 ex.toString()), ex); 132 } 133 } 134 135 dataSource.setUserName(paramString[2]); 137 dataSource.setPassword(paramString[3]); 138 139 return dataSource; 140 } 141 142 } 143 | Popular Tags |