import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class DataBaseFactory
{
private static DataSource ds = null;
private static String driverClassName = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/db?autoReconnect=true&useUnicode=true&characterEncoding=utf-8";
private static String username = "root";
private static String password = "M@@321";
private static String initialSize = "1";
private static String maxActive = "2";
private static String minIdle = "1";
private static String maxWait = "60000";
private static String removeAbandoned = "true";
private static String removeAbandonedTimeout = "180";
private static String timeBetweenEvictionRunsMillis = "60000";
private static String minEvictableIdleTimeMillis = "300000";
private static String validationQuery = "SELECT 1 FROM DUAL";
private static String testWhileIdle = "true";
private static String testOnBorrow = "false";
private static String testOnReturn = "false";
private static String poolPreparedStatements = "true";
private static String maxPoolPreparedStatementPerConnectionSize = "50";
private static String filters = "stat";
static
{
try
{
// InputStream in = DataBaseFactory.class.getClassLoader().getResourceAsStream("ds.properties");
// Properties props = new Properties();
// props.load(in);
Map druidMap = new HashMap();
druidMap.put(DruidDataSourceFactory.PROP_DRIVERCLASSNAME, driverClassName);
druidMap.put(DruidDataSourceFactory.PROP_URL, url);
druidMap.put(DruidDataSourceFactory.PROP_USERNAME, username);
druidMap.put(DruidDataSourceFactory.PROP_PASSWORD, password);
druidMap.put(DruidDataSourceFactory.PROP_INITIALSIZE, initialSize);
druidMap.put(DruidDataSourceFactory.PROP_MAXACTIVE, maxActive);
druidMap.put(DruidDataSourceFactory.PROP_MINIDLE, minIdle);
druidMap.put(DruidDataSourceFactory.PROP_MAXWAIT, maxWait);
druidMap.put(DruidDataSourceFactory.PROP_REMOVEABANDONED, removeAbandoned);
druidMap.put(DruidDataSourceFactory.PROP_REMOVEABANDONEDTIMEOUT, removeAbandonedTimeout);
druidMap.put(DruidDataSourceFactory.PROP_TIMEBETWEENEVICTIONRUNSMILLIS, timeBetweenEvictionRunsMillis);
druidMap.put(DruidDataSourceFactory.PROP_MINEVICTABLEIDLETIMEMILLIS, minEvictableIdleTimeMillis);
druidMap.put(DruidDataSourceFactory.PROP_VALIDATIONQUERY, validationQuery);
druidMap.put(DruidDataSourceFactory.PROP_TESTWHILEIDLE, testWhileIdle);
druidMap.put(DruidDataSourceFactory.PROP_TESTONBORROW, testOnBorrow);
druidMap.put(DruidDataSourceFactory.PROP_TESTONRETURN, testOnReturn);
druidMap.put(DruidDataSourceFactory.PROP_POOLPREPAREDSTATEMENTS, poolPreparedStatements);
druidMap.put(DruidDataSourceFactory.PROP_MAXOPENPREPAREDSTATEMENTS, maxPoolPreparedStatementPerConnectionSize);
druidMap.put(DruidDataSourceFactory.PROP_FILTERS, filters);
ds = DruidDataSourceFactory.createDataSource(druidMap);
} catch (Exception ex)
{
ex.printStackTrace();
}
}
public static Connection openConnection() throws SQLException
{
return ds.getConnection();
}
public static List
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoException;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
@SuppressWarnings("deprecation")
public class MongoDBManager
{
private final static String HOST = "127.0.0.1";// 端口
private final static int PORT = 27017;// 端口
private final static int POOLSIZE = 10;// 连接数量
private final static int BLOCKSIZE = 300; // 等待队列长度
private static MongoClient mongo = null;
private static DB db = null;
private final static MongoDBManager instance = new MongoDBManager();
private final static String databaseName = "gwdb";
/**
* 实例化
*
* @return
* @throws Exception
*/
public static MongoDBManager getInstance() throws Exception
{
return instance;
}
static
{
try
{
mongo = new MongoClient(new ServerAddress(HOST, PORT), getConfOptions());
db = mongo.getDB(databaseName);
// db.slaveOk();
} catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
private static MongoClientOptions getConfOptions()
{
return new MongoClientOptions.Builder().socketKeepAlive(true) // 是否保持长链接
.connectTimeout(5000) // 链接超时时间
.socketTimeout(5000) // read数据超时时间
.readPreference(ReadPreference.primary()) // 最近优先策略
.connectionsPerHost(POOLSIZE) // 每个地址最大请求数
.maxWaitTime(1000 * 60 * 2) // 长链接的最大等待时间
.threadsAllowedToBlockForConnectionMultiplier(BLOCKSIZE) // 一个socket最大的等待请求数
.writeConcern(WriteConcern.NORMAL).build();
}
/**
* 获取集合(表)
*
* @param collection
*/
public static DBCollection getCollection(String collection)
{
return db.getCollection(collection);
}
/**
* 插入
*
* @param collection
* @param map
*/
public static void insert(String collection, Map map)
{
try
{
DBObject dbObject = map2Obj(map);
getCollection(collection).insert(dbObject);
} catch (MongoException e)
{
System.out.println(e.getMessage());
}
}
/**
* 批量插入
*
* @param collection
* @param list
*/
public static void insertBatch(String collection, List> list)
{
if (list == null || list.isEmpty())
{
return;
}
try
{
List listDB = new ArrayList();
for (int i = 0; i < list.size(); i++)
{
DBObject dbObject = map2Obj(list.get(i));
listDB.add(dbObject);
}
getCollection(collection).insert(listDB);
} catch (MongoException e)
{
System.out.println(e.getMessage());
}
}
/**
* 删除
*
* @param collection
* @param map
*/
public static void delete(String collection, Map map)
{
DBObject obj = map2Obj(map);
getCollection(collection).remove(obj);
}
/**
* 删除全部
*
* @param collection
* @param map
*/
public static void deleteAll(String collection)
{
List rs = findAll(collection);
if (rs != null && !rs.isEmpty())
{
for (int i = 0; i < rs.size(); i++)
{
getCollection(collection).remove(rs.get(i));
}
}
}
/**
* 批量删除
*
* @param collection
* @param list
*/
public static void deleteBatch(String collection, List> list)
{
if (list == null || list.isEmpty())
{
return;
}
for (int i = 0; i < list.size(); i++)
{
getCollection(collection).remove(map2Obj(list.get(i)));
}
}
/**
* 计算满足条件条数
*
* @param collection
* @param map
*/
public static long getCount(String collection, Map map)
{
return getCollection(collection).getCount(map2Obj(map));
}
/**
* 计算集合总条数
*
* @param collection
* @param map
*/
public static long getCount(String collection)
{
return getCollection(collection).find().count();
}
/**
* 更新
*
* @param collection
* @param setFields
* @param whereFields
*/
public static void update(String collection, Map setFields, Map whereFields)
{
DBObject obj1 = map2Obj(setFields);
DBObject obj2 = map2Obj(whereFields);
getCollection(collection).updateMulti(obj1, obj2);
}
/**
* 查找对象(根据主键_id)
*
* @param collection
* @param _id
*/
public static DBObject findById(String collection, String _id)
{
DBObject obj = new BasicDBObject();
obj.put("_id", massageToObjectId(_id));
return getCollection(collection).findOne(obj);
}
/**
* 查找集合所有对象
*
* @param collection
*/
public static List findAll(String collection)
{
return getCollection(collection).find().toArray();
}
/**
* 查找(返回一个对象)
*
* @param map
* @param collection
*/
public static DBObject findOne(String collection, Map map)
{
DBCollection coll = getCollection(collection);
return coll.findOne(map2Obj(map));
}
/**
* 查找(返回一个List)
*
* @param
* @param map
* @param collection
* @throws Exception
*/
public static List find(String collection, Map map) throws Exception
{
DBCollection coll = getCollection(collection);
DBCursor c = coll.find(map2Obj(map));
if (c != null)
return c.toArray();
else
return null;
}
private static DBObject map2Obj(Map map)
{
DBObject obj = new BasicDBObject();
obj.putAll(map);
// System.out.println(map);
return obj;
}
public static ObjectId massageToObjectId(Object o)
{
if (o == null)
return null;
if (o instanceof ObjectId)
return (ObjectId) o;
if (o instanceof String)
{
String s = o.toString();
if (isValid(s))
return new ObjectId(s);
}
return null;
}
public static boolean isValid(String s)
{
if (s == null)
return false;
if (s.length() < 18)
return false;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c >= '0' && c <= '9')
continue;
if (c >= 'a' && c <= 'f')
continue;
if (c >= 'A' && c <= 'F')
continue;
return false;
}
return true;
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import org.apache.commons.lang3.StringUtils;
public class JavaShell
{
public static String ExceuteShell(String command) throws InterruptedException
{
String returnString = StringUtils.EMPTY;
Process pro = null;
Runtime runTime = Runtime.getRuntime();
if (runTime == null)
{
System.err.println("Create runtime false!");
returnString = "gNULL";
}
try
{
String[] cmd =
{ "/bin/sh", "-c", command };
pro = runTime.exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
String line;
while ((line = input.readLine()) != null)
{
returnString = returnString + line + "\n";
}
input.close();
output.close();
pro.destroy();
pro.destroyForcibly();
} catch (IOException ex)
{
ex.printStackTrace();
}
return returnString;
}
public static String GetStringToTxt(String fileName) throws Exception
{
String str = null;
BufferedReader br = new BufferedReader(new FileReader(new File(fileName)));
String s = null;
while ((s = br.readLine()) != null)
{
str = str + "\n" + s;
}
br.close();
return str;
}
public static String StringToSave(String strMsg, String fileName) throws IOException
{
FileWriter fwriter = new FileWriter(fileName);
fwriter.write(strMsg);
fwriter.flush();
fwriter.close();
return null;
}
}
ScheduledExecutorService executor_gw_BasicState = Executors.newScheduledThreadPool(1);
executor_gw_BasicState.scheduleWithFixedDelay(new gw_BasicState(), 0, 1000 * 60 * 1, TimeUnit.MILLISECONDS);