J2EE java 获取数据源

package com.tobacco.ermsuite.interfaces.util;

import java.sql.Connection;

import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;

public class ConnectionSource {

private static BasicDataSource dataSourceDrp;

/**

* 通过数据源获取数据库连接

*/

public synchronized static Connection getConnDsp() {

Connection ConnDsp = null;

// SimpleDateFormat df = new

// SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");// 格式化时间

// String beforeDate = df.format(new Date(System.currentTimeMillis()));

// System.out.println("获取连接之前时间是:"+beforeDate);

if (dataSourceDrp == null) {

String SourceName = "jdbc/dsp";

String driverClassName = "oracle.jdbc.driver.OracleDriver";

String url = "jdbc:oracle:thin:@localhost:1521:ORCL";

String username = "lms";

String password = "lms";

dataSourceDrp = DBCPManager.getDataSource(SourceName,

driverClassName, url, username, password);

}

try {

ConnDsp = dataSourceDrp.getConnection();

// String afterDate = df.format(new

// Date(System.currentTimeMillis()));

// // System.out.println("获取连接之后时间是:"+afterDate);

// long time = (df.parse(afterDate)).getTime()

// - (df.parse(beforeDate)).getTime();

// System.out.println("时间差:" + time + "ms");

} catch (Exception e) {

e.printStackTrace();

}

return ConnDsp;

}

public static void releaseConn(Connection conn) {

try {

if (conn != null && !conn.isClosed()) {

conn.close();

}

} catch (SQLException e) {

e.printStackTrace();

}

}

}

package com.tobacco.ermsuite.interfaces.util;

import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBCPManager {

private static String maxActive = "4";// 最大活动连接数,如果非正整数,则不做限制。

private static String maxIdle = "2";// 最大空闲连接数。

private static String maxWait = "5000";// (在没有连接可用时)连接池等待一个数据连接可用时的以毫秒计的最大等待时间,超时以后抛出异常,

/**

* 通过相关参数获取数据源

*/

public static BasicDataSource getDataSource(String SourceName,

String driverClassName, String url, String username, String password) {

BasicDataSource dataSource = null;

try {

Properties p = new Properties();

p.setProperty("name", SourceName);

p.setProperty("driverClassName", driverClassName);

p.setProperty("url", url);

p.setProperty("password", password);

p.setProperty("username", username);

p.setProperty("maxActive", maxActive);

p.setProperty("maxIdle", maxIdle);

p.setProperty("maxWait", maxWait);

p.setProperty("removeAbandoned", "true");

p.setProperty("removeAbandonedTimeout", "180");// 活动连接的最大空闲时间为3分钟,以秒为单位

p.setProperty("testOnBorrow", "true");

p.setProperty("logAbandoned", "true");

p.setProperty("type", "javax.sql.DataSource");

dataSource = (BasicDataSource) BasicDataSourceFactory

.createDataSource(p);

} catch (Exception e) {

e.printStackTrace();

}

return dataSource;

}

public void shutdownDataSource(BasicDataSource dataSource) {

try {

if (dataSource != null) {

dataSource.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

package com.tobacco.ermsuite.interfaces.util;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

public class SqlUtilTool {

/**

* 通过sql查询,返回list结果

*/

public static List<Map> getResultList(Connection conn, String sql) {

PreparedStatement stmt = null;

ResultSet rset = null;

List<Map> resList = null;

try {

stmt = conn.prepareStatement(sql);

rset = stmt.executeQuery();

if (rset != null) {

// 获取列名

ResultSetMetaData meta = rset.getMetaData();

List columnnameTable = new ArrayList();

int colCount = meta.getColumnCount();

for (int i = 1; i < colCount + 1; i++) {

columnnameTable.add(meta.getColumnName(i));

}

// 把结果封装到List通过Map形式

resList = new ArrayList();

while (rset.next()) {

Map mdata = new HashMap();

for (int i = 0; i < columnnameTable.size(); i++) {

String columnName = String.valueOf(columnnameTable

.get(i));

String columnVal = rset.getString(columnName);

mdata.put(columnName, columnVal);

}

resList.add(mdata);

}

}

} catch (SQLException e) {

e.printStackTrace();

} finally {

try {

if (rset != null) {

rset.close();

}

if (stmt != null) {

stmt.close();

}

if (conn != null) {

conn.close();

}

} catch (SQLException e) {

e.printStackTrace();

}

}

return resList;

}

}

package com.tobacco.ermsuite.interfaces.util;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.zip.ZipEntry;

import java.util.zip.ZipInputStream;

import java.util.zip.ZipOutputStream;

import org.jdom.Document;

import org.jdom.Element;

import org.jdom.output.Format;

import org.jdom.output.XMLOutputter;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

public class StringUtilTool {

/**

* 处理通过传递的字符串进行转换空格处理

*/

public static String convertStr(String strParam) {

if (null == strParam) {

strParam = "";

} else {

strParam = strParam.trim();

}

return strParam;

}

/**

* /** 创建目录

* @param fileDir

*            目标目录名

* @return

*/

public static boolean createDir(String fileDir) {

boolean isDir = false;

try {

File folder = new File(fileDir);

if (!(folder.exists() && folder.isDirectory())) {

folder.mkdirs();

}

isDir = true;

} catch (Exception e) {

e.printStackTrace();

isDir = false;

}

return isDir;

}

/**

* 将Zip压缩字节数组解压

* @param zipBytes

* @return byte[]

* @throws IOException

*/

public static byte[] unzip(byte[] zipBytes) throws IOException {

ByteArrayInputStream bais = new ByteArrayInputStream(zipBytes);

ZipInputStream zis = new ZipInputStream(bais);

zis.getNextEntry();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

final int BUFSIZ = 4096;

byte inbuf[] = new byte[BUFSIZ];

int n;

while ((n = zis.read(inbuf, 0, BUFSIZ)) != -1) {

baos.write(inbuf, 0, n);

}

byte[] data = baos.toByteArray();

zis.close();

return data;

}

/**

* 将字节数组Zip压缩

* @param data

* @return byte[]

* @throws IOException

*/

public static byte[] zip(byte[] data) throws IOException {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

ZipEntry ze = new ZipEntry("servletservice");

ZipOutputStream zos = new ZipOutputStream(baos);

zos.putNextEntry(ze);

zos.write(data, 0, data.length);

zos.close();

byte[] zipBytes = baos.toByteArray();

return zipBytes;

}

/**

* 对字符串先进行zip压缩,再进行base64编码

* @param qrStr

* @return String

* @throws IOException

*/

public static String encode(String qrStr) throws IOException {

BASE64Encoder encoder = new BASE64Encoder();

return new String(encoder.encode(zip(qrStr.getBytes())));

}

/**

* 对字符串先进行base64解码,再进行zip解压

* @param qrStr

* @return String

* @throws IOException

*/

public static String decode(String qrStr) throws IOException {

BASE64Decoder decoder = new BASE64Decoder();

byte[] bytes = decoder.decodeBuffer(qrStr);

return new String(unzip(bytes), "GBK");

}

/**

* 对DOC 文件输出xml字符串

* @param qrStr

* @return String

* @throws IOException

*/

public static String docToXml(Document doc) throws IOException {

Format format = Format.getPrettyFormat();

format.setEncoding("GBK");// 设置xml文件的字符为GBK,解决中文问题

XMLOutputter xmlout = new XMLOutputter(format);

ByteArrayOutputStream bo = new ByteArrayOutputStream();

xmlout.output(doc, bo);

String xmlStr = bo.toString();

return xmlStr;

}

/**

* 对List 中Map 转换成xml字符串

* @param List

*            <Map>

* @return String

* @throws IOException

*/

public static String listToXmlString(List<Map> list) throws IOException {

Document result = new Document();

Element root = new Element("DATASETS");

root.setText("");

if (list != null) {

for (Map map : list) {

Set keys = map.keySet();

Iterator iterator = keys.iterator();

Element data = new Element("DATASET");

while (iterator.hasNext()) {

String key = String.valueOf(iterator.next());

String value = String.valueOf(map.get(key));

Element node = new Element(key);

node.setText(value);

data.addContent(node);

}

root.addContent(data);

}

}

ArrayList arrayList = new ArrayList();

arrayList.add(root);

result.setContent(arrayList);

String resultXML = docToXml(result);

return resultXML;

}

/**

* 对List 中Map 转换成json字符串

* @param List

*            <Map>

* @return String

* @throws IOException

*/

public static String listToJsonString(List<Map> list) throws IOException {

String resStr;

StringBuffer jsons;

StringBuffer json;

if (list != null) {

jsons = new StringBuffer("");

jsons.append("{\"list\":[");

for (Map map : list) {

Set keys = map.keySet();

Iterator iterator = keys.iterator();

json = new StringBuffer("{");

while (iterator.hasNext()) {

String key = String.valueOf(iterator.next());

String value = String.valueOf(map.get(key));

json.append("\"").append(key).append("\",");

json.append("\"").append(value).append("\",");

}

jsons.append(json.substring(0, json.length() - 1)).append("},");

}

resStr = jsons.substring(0, jsons.length() - 1) + "]}";

} else {

resStr = "{}";

}

return resStr;

}

}

package com.tobacco.ermsuite.interfaces.util;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.apache.axis.client.Call;

import org.apache.axis.client.Service;

import com.tobacco.ermsuite.interfaces.mail.MailFactory;

public class TestWebService extends Thread {

public static void main(String[] args) {

// for (int i = 0; i < 1; i++) {

// TestWebService myThread = new TestWebService();

// myThread.start();

// System.out.println("----------" + i);

// }

}

public void run() {

try {

invokeService();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static void invokeService() throws Exception {

Object result = null;

Service serv = new Service();

String url = "http://localhost:9080/lms/services/DrpDataService";

String method = "testSearchList";

try {

Call call = (Call) serv.createCall();

call.setTargetEndpointAddress(url);

call.setOperationName(method);

result = call.invoke(new Object[] {});

// System.out.println("调用web服务的方法:+" + method + " 成功!\n返回值为:" +

// result);

} catch (Exception e) {

e.printStackTrace();

throw e;

}

}

}

猜你喜欢

转载自wengzil.iteye.com/blog/1889485
今日推荐