通用模块封装

package gHttpClientFactory;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class gHttpsUtils
{
	private static JSONObject stringConvertJsonObject(String str)
	{
		JSONObject json = JSON.parseObject(str);
		return json;
	}

	public static JSONObject getHttpsGetJsonObject(String httpsUrl)
	{
		JSONObject json = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(httpsUrl);
			CloseableHttpResponse response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			String str = EntityUtils.toString(entity, "utf-8");
			json = stringConvertJsonObject(str);
			EntityUtils.consume(entity);
			response.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;
	}
	public static String getHttpsGetStrings(String httpsUrl)
	{
		String str = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(httpsUrl);
			CloseableHttpResponse response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			str = EntityUtils.toString(entity, "utf-8");
			EntityUtils.consume(entity);
			response.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}

	public static String getHttpPostNvp(String url, List<NameValuePair> Lnvp)
	{
		String str = null;
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(Lnvp));
			CloseableHttpResponse httpResponse=httpClient.execute(httpPost);
			HttpEntity entity=httpResponse.getEntity();
			str = EntityUtils.toString(entity, "utf-8");
			EntityUtils.consume(entity);
			httpResponse.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}
	public static String getHttpsGetString(String httpsUrl)
	{
		String str = null;
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
			{
				// 锟斤拷锟斤拷锟斤拷锟斤拷
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException
				{
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
			HttpGet httpGet = new HttpGet(httpsUrl);
			CloseableHttpResponse response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			str = EntityUtils.toString(entity, "utf-8");
			EntityUtils.consume(entity);
			response.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}
	public static JSONObject getHttpPostJson(JSONObject json, String url)
	{
		JSONObject T_Json = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			StringEntity se = new StringEntity(json.toString(), "utf-8");
			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			httpPost.setEntity(se);
			CloseableHttpResponse response = httpclient.execute(httpPost);
			response.setHeader("content-type", "application/json");
			HttpEntity entity = response.getEntity();
			String str = EntityUtils.toString(entity, "utf-8");
			T_Json = stringConvertJsonObject(str);
			EntityUtils.consume(entity);
			response.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return T_Json;
	}

	public static JSONObject getHttpsPostJson(JSONObject json, String url)
	{
		JSONObject T_Json = null;
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
			{
				// 锟斤拷锟斤拷锟斤拷锟斤拷
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException
				{
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
			HttpPost httpPost = new HttpPost(url);
			StringEntity se = new StringEntity(json.toString(), "utf-8");
			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			httpPost.setEntity(se);
			CloseableHttpResponse response = httpclient.execute(httpPost);
			response.setHeader("content-type", "application/json");
			HttpEntity entity = response.getEntity();
			String str = EntityUtils.toString(entity, "utf-8");
			System.out.println(str);
			T_Json = stringConvertJsonObject(str);
			EntityUtils.consume(entity);
			response.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return T_Json;
	}
	
	public static String getHttpsPostXml(String strMsg, String url)
	{
		String str=null;
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
			{
				// 锟斤拷锟斤拷锟斤拷锟斤拷
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException
				{
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
			HttpPost httpPost = new HttpPost(url);
			StringEntity se = new StringEntity(strMsg.toString(), "utf-8");
			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			httpPost.setEntity(se);
			CloseableHttpResponse response = httpclient.execute(httpPost);
			response.setHeader("content-type", "application/json");
			HttpEntity entity = response.getEntity();
			str = EntityUtils.toString(entity, "utf-8");
			EntityUtils.consume(entity);
			response.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return str;
	}
}

---------------------------------------------------------------------------------------------------------------------------------
package gDataBaseFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 org.apache.commons.lang3.StringUtils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import g.LogsFactory.gLogUtils;

public class gDbUtils {
	private static DataSource ds = null;

	private static String driverClassName = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://localhost:3306/mc_wx?autoReconnect=true&useUnicode=true&characterEncoding=utf-8";
	private static String username = "root";
	private static String password = "mc2016";
	private static String initialSize = "5";
	private static String maxActive = "10";
	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<String, String> druidMap = new HashMap<String, String>();
			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 void main(String[] args) throws Exception {
		Object[] parm = null;
		if (parm == null)
			System.out.println("111111111111111");
		String sql = "select * from t_oo_event ";
		JSONArray jsons = execFindJsons(sql, null);
		System.out.println(jsons);

	}

	private static Connection openConnection() throws SQLException {
		return ds.getConnection();
	}

	/** 
	 * 此方法禁止使用!!!!
	 **/
	public static List<Map<String, Object>> execFinds(String sql, Object[] parm) throws SQLException {
		Connection con = openConnection();
		QueryRunner runner = new QueryRunner();
		List<Map<String, Object>> listmap = runner.query(con, sql, new MapListHandler(), parm);
		if (con != null)
			con.close();

		JSONObject json = new JSONObject();
		json.put("type", "SqlCommand");
		json.put("method", "gFactory.gDataBaseFactory.execFinds");
		json.put("sql", sql);
		if (parm != null)
			json.put("parm", JSON.parse(Arrays.asList(parm).toString()));
		json.put("result", listmap.toString());
		gLogUtils.AppendLog(json, "sql.log");

		return listmap;
	}

	public static JSONArray execFindJsons(String sql, Object[] parm) {
		JSONArray jsons = null;
		try {
			Connection con = openConnection();
			QueryRunner runner = new QueryRunner();
			List<Map<String, Object>> listmap = runner.query(con, sql, new MapListHandler(), parm);
			jsons = JSON.parseArray(JSON.toJSONString(listmap, SerializerFeature.WriteDateUseDateFormat));
			if (con != null)
				con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		JSONObject json = new JSONObject();
		json.put("type", "SqlCommand");
		json.put("method", "gFactory.gDataBaseFactory.execFindJsons");
		json.put("sql", sql);
		if (parm != null)
			json.put("parm", Arrays.asList(parm).toString());
		json.put("result", jsons.toJSONString());
		gLogUtils.AppendLog(json, "sql.log");

		return jsons;
	}

	public static int ExecuteUpdate(String sql, Object[] parm) throws SQLException {
		Connection con = openConnection();
		QueryRunner runner = new QueryRunner();
		int i = runner.update(con, sql, parm);
		if (con != null)
			con.close();

		JSONObject json = new JSONObject();
		json.put("type", "SqlCommand");
		json.put("method", "gFactory.gDataBaseFactory.ExecuteUpdate");
		json.put("sql", sql);
		if (parm != null)
			json.put("parm", Arrays.asList(parm).toString());
		json.put("result", i);
		gLogUtils.AppendLog(json, "sql.log");

		return i;
	}

	public static int ExecuteCheckIsNull(String sql, Object[] parm) throws SQLException {
		Connection con = openConnection();
		QueryRunner runner = new QueryRunner();
		int i = (int) (long) runner.query(con, sql, new ScalarHandler<Object>(), parm);
		if (con != null)
			con.close();

		JSONObject json = new JSONObject();
		json.put("type", "SqlCommand");
		json.put("method", "gFactory.gDataBaseFactory.ExecuteCheckIsNull");
		json.put("sql", sql);
		if (parm != null)
			json.put("parm", Arrays.asList(parm).toString());
		json.put("result", i);
		gLogUtils.AppendLog(json, "sql.log");

		return i;
	}
}





package gDataBaseFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.bson.types.ObjectId;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
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;
import com.mongodb.util.JSON;

public class gMongoUtils
{

	public static void main(String[] args) throws Exception
	{
		// TODO Auto-generated method stub
		String str="usr";
		JSONObject wJson=new JSONObject();
		wJson.put("usrID", 1);
		
		JSONObject sJson=new JSONObject();
		sJson.put("usrName", "gengzg");
		sJson.put("usrMobile", "13910536016");
		
		gMongoUtils.delete(str, sJson);
		
		gMongoUtils.update(str, wJson, sJson);
		
		
		JSONObject j=new JSONObject();
		j.put("usrName", "gengzg");
		
		JSONObject jj=gMongoUtils.findOneById(str, "573ad1a9559a901abc12f9cb");
		System.out.println(jj);
		JSONArray jsons=gMongoUtils.find(str, j);
		System.out.println(jsons);
		
		long l=gMongoUtils.getCounts(str);
		System.out.println(l);
	}

	private final static String HOST = "127.0.0.1";// 端口
	private final static int PORT = 27017;// 端口
	private final static int POOLSIZE = 100;// 连接数量
	private final static int BLOCKSIZE = 300; // 等待队列长度
	private static MongoClient mongo = null;
	private static DB db = null;
	private final static gMongoUtils instance = new gMongoUtils();
	private final static String databaseName = "mcpet";

	/**
	 * 实例化
	 * 
	 * @return
	 * @throws Exception
	 */
	private static gMongoUtils 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
	 */
	private static DBCollection getCollection(String collection)
	{
		return db.getCollection(collection);
	}

	/**
	 * 插入
	 * 
	 * @param collection
	 * @param map
	 */
	public static void insert(String collection, Map<String, Object> map)
	{
		try
		{
			DBObject dbObject = map2Obj(map);
			getCollection(collection).insert(dbObject);
		} catch (MongoException e)
		{
			System.out.println(e.getMessage());
		}
	}

	public static void insert(String collection, JSONObject json)
	{
		try
		{
			DBObject obj = (DBObject) JSON.parse(json.toJSONString());
			getCollection(collection).insert(obj);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 批量插入
	 * 
	 * @param collection
	 * @param list
	 */
	public static void insertBatch(String collection, List<Map<String, Object>> list)
	{
		if (list == null || list.isEmpty())
		{
			return;
		}
		try
		{
			List<DBObject> listDB = new ArrayList<DBObject>();
			for (int i = 0; i < list.size(); i++)
			{
				DBObject dbObject = map2Obj(list.get(i));
				listDB.add(dbObject);
			}
			getCollection(collection).insert(listDB);
		} catch (MongoException e)
		{
			e.printStackTrace();
		}
	}
	
	public static void insertBatch(String collection, JSONArray jsons)
	{
		if (jsons == null || jsons.isEmpty())
		{
			return;
		}
		try
		{
			List<DBObject> listDB = new ArrayList<DBObject>();
			for (int i = 0; i < jsons.size(); i++)
			{
				DBObject dbObject = (DBObject)JSON.parse(jsons.getJSONObject(i).toJSONString());
				listDB.add(dbObject);
				System.out.println(i);
			}
			getCollection(collection).insert(listDB);
		} catch (MongoException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 删除
	 * 
	 * @param collection
	 * @param map
	 */
	public static void delete(String collection, Map<String, Object> map)
	{
		DBObject obj = map2Obj(map);
		getCollection(collection).remove(obj);
	}
	
	public static void delete(String collection, JSONObject json)
	{
		DBObject obj = (DBObject)JSON.parse(json.toJSONString());
		getCollection(collection).remove(obj);
	}

	/**
	 * 删除全部
	 * 
	 * @param collection
	 * @param map
	 */
	public static void deleteAll(String collection)
	{
		List<DBObject> 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<Map<String, Object>> list)
	{
		if (list == null || list.isEmpty())
		{
			return;
		}
		for (int i = 0; i < list.size(); i++)
		{
			getCollection(collection).remove(map2Obj(list.get(i)));
		}
	}
	
	public static void deleteBatch(String collection, JSONArray jsons)
	{
		if (jsons == null || jsons.isEmpty())
		{
			return;
		}
		for (int i = 0; i < jsons.size(); i++)
		{
			getCollection(collection).remove((DBObject)JSON.parse(jsons.getJSONObject(i).toJSONString()));
		}
	}

	/**
	 * 计算满足条件条数
	 * 
	 * @param collection
	 * @param map
	 */
	public static long getCount(String collection, Map<String, Object> map)
	{
		return getCollection(collection).getCount(map2Obj(map));
	}
	
	public static long getCount(String collection,JSONObject json)
	{
		return getCollection(collection).getCount((DBObject)JSON.parse(json.toJSONString()));
	}

	/**
	 * 计算集合总条数
	 * 
	 * @param collection
	 * @param map
	 */
	public static long getCounts(String collection)
	{
		return getCollection(collection).find().count();
	}

	/**
	 * 更新
	 * 
	 * @param collection
	 * @param setFields
	 * @param whereFields
	 */
	public static void update(String collection, Map<String, Object> setFields, Map<String, Object> whereFields)
	{
		DBObject obj1 = map2Obj(setFields);
		DBObject obj2 = map2Obj(whereFields);
		getCollection(collection).updateMulti(obj1, obj2);
	}
	public static void update(String collection, JSONObject queryJson,JSONObject updateJson)
	{
		DBObject query =(DBObject)JSON.parse(queryJson.toJSONString());
		DBObject update =(DBObject)JSON.parse(updateJson.toJSONString());
		getCollection(collection).updateMulti(query,update);
	}

	/**
	 * 查找对象(根据主键_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);
	}
	public static JSONObject findOneById(String collection, String _id)
	{
		DBObject obj = new BasicDBObject();
		obj.put("_id", massageToObjectId(_id));
		obj=getCollection(collection).findOne(obj);
		JSONObject json=com.alibaba.fastjson.JSON.parseObject(obj.toString());
		return json;
	}

	/**
	 * 查找集合所有对象
	 * 
	 * @param collection
	 */
	public static List<DBObject> findAll(String collection)
	{
		return getCollection(collection).find().toArray();
	}
	public static JSONArray findAlls(String collection)
	{
		JSONArray jsons=com.alibaba.fastjson.JSON.parseArray(getCollection(collection).find().toArray().toString());
		return jsons;
	}

	/**
	 * 查找(返回一个对象)
	 * 
	 * @param map
	 * @param collection
	 */
	public static DBObject findOne(String collection, Map<String, Object> map)
	{
		DBCollection coll = getCollection(collection);
		return coll.findOne(map2Obj(map));
	}


	public static JSONObject findOne(String collection, JSONObject json)
	{
		DBObject obj = (DBObject) JSON.parse(json.toJSONString());
		DBCollection col = getCollection(collection);
		obj = col.findOne(obj);
		// System.out.println(obj);
		json = com.alibaba.fastjson.JSON.parseObject(obj.toString());
		return json;
	}

	/**
	 * 查找(返回一个List<DBObject>)
	 * 
	 * @param <DBObject>
	 * @param map
	 * @param collection
	 * @throws Exception
	 */
	public static List<DBObject> find(String collection, Map<String, Object> map) throws Exception
	{
		DBCollection coll = getCollection(collection);
		DBCursor c = coll.find(map2Obj(map));
		if (c != null)
			return c.toArray();
		else
			return null;
	}
	public static JSONArray find(String collection, JSONObject json) throws Exception
	{
		List<DBObject> list=new ArrayList<>();
		JSONArray jsons=new JSONArray();
		DBCollection coll = getCollection(collection);
		DBCursor c = coll.find((DBObject)JSON.parse(json.toJSONString()));
		if (c != null)
		{
//			list= c.toArray();
			jsons=com.alibaba.fastjson.JSON.parseArray(c.toArray().toString());
		}
		return jsons;
	}


	private static DBObject map2Obj(Map<String, Object> map)
	{
		DBObject obj = new BasicDBObject();
		obj.putAll(map);
		// System.out.println(map);
		return obj;
	}

	private 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;
	}

	private 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;
	}
}
-------------------------------------------------------------------------------------------------
package gShellFactory;

import java.io.BufferedReader;
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;
	}
}


package g.LogsFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.omg.CORBA.OBJ_ADAPTER;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class gLogUtils
{
	public static void main(String[] args) throws Exception
	{
		Object[] parm = { 11, 22, 33, 44 };

		System.out.println();
	}

	public static void AppendLog(JSONObject json, String fileName)
	{
		if (!StringUtils.isNotBlank(fileName))
			fileName = "my.log";
		json.put("currTime", getCurrentTime());
		saveFile(fileName, json.toJSONString());
	}

	public static JSONArray ReadLog(String fileName)
	{
		if (!StringUtils.isNotBlank(fileName))
			fileName = "my.log";
		List<String> list = readLogFile(fileName);
		JSONArray jsons = JSONArray.parseArray(list.toString());
		return jsons;
	}

	private static String getCurrentTime()
	{
		Calendar cal = Calendar.getInstance();
		String currentDate = DateFormatUtils.format(cal, "yyyy-MM-dd HH:mm:ss");
		return currentDate;
	}

	private static void saveFile(String fileName, String mesg)
	{
		if (StringUtils.containsIgnoreCase(System.getProperties().getProperty("os.name"), "windows"))
			fileName = "d:/" + fileName;
		else
			fileName = "/mnt/files/" + fileName;
		try
		{
			FileUtils.writeStringToFile(new File(fileName), mesg + "\n", "utf-8", true);
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static List<String> readLogFile(String fileName)
	{
		if (StringUtils.containsIgnoreCase(System.getProperties().getProperty("os.name"), "windows"))
			fileName = "d:/" + fileName;
		else
			fileName = "/mnt/files/" + fileName;
		try
		{
			List<String> list = FileUtils.readLines(new File(fileName), "utf-8");
			return list;
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
------------------------------------------------------------------------------------------------------------
package g.EmailFactory;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;

public class gEmailUtils
{
	// 648741714@QQ.com
	// 783249409@qq.com
	// 360684468@QQ.com
	public static void main(String[] args) throws Exception
	{
		String str = "select * from t_oo_order";
		String s = str.toUpperCase();
		System.out.println(s);

		String strEmails = "gzg@mengchongpet.com;wm@mengchongpet.com;420708005@qq.com;648741714@QQ.com;783249409@qq.com;360684468@QQ.com";
//		for (int i = 0; i < 50; i++) {
//			boolean b = sendEmail("测试邮件-"+String.valueOf(i), "测试新订单邮件", strEmails);
//			System.out.println(i);
//			System.out.println(b);
//		}
	}

	public static boolean sendEmail(String aSubject, String message, String toEmails)
	{
		try {
			Email email = new SimpleEmail();
			email.setCharset("utf-8");
			email.setHostName("smtp.263.net");
			email.setSmtpPort(25);
			email.setAuthenticator(new DefaultAuthenticator("info@mengchongpet.com", "mc123456789"));
			// email.setAuthentication("info@mengchongpet.com", "mcpet2015");
			email.setSSLOnConnect(true);
			email.setFrom("info@mengchongpet.com", "盟宠科技-新订单提醒");
			email.setSubject(aSubject);
			email.setMsg(message);
			String[] ss = toEmails.split(";");
			for (int i = 0; i < ss.length; i++)
				email.addTo(ss[i]);
			email.send();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
		return true;
	}
}


package g.SecretFactory;

import java.net.URLEncoder;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;

import g.daojia.DjsUtils;

public class gSecretUtils
{
	// private static final String DEFAULT_PASSWORD_CRYPT_KEY = "__jDlog_";
	private static final String DES = "DES";
	private static Cipher cipher = null;

	public static void main(String[] args)
	{
		String str;
		str = gSecretUtils.encrypt("13910536016");
		System.err.println(str);
		str = gSecretUtils.decrypt("720FA464462E88B0C2537AE078D588D0");
		System.out.println(str);
		str = gSecretUtils.decrypt("720FA464462E88B0C2537AE078D588D0", DjsUtils.desPassword);
		System.out.println(str);
	}

	public static String jmMobile(String mobile) throws Exception
	{
		Base64 b = new Base64();
		String str = new String(b.encode(mobile.getBytes()));
		str = URLEncoder.encode(str, "utf-8");
		return str;
	}

	static
	{
		// Cipher对象实际完成加密操作
		try
		{
			cipher = Cipher.getInstance(DES);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	// des解密
	public static String decrypt(byte[] src, String password) throws Exception
	{
		// DES算法要求有一个可信任的随机数源
		SecureRandom random = new SecureRandom();
		// 创建一个DESKeySpec对象
		DESKeySpec desKey = new DESKeySpec(password.getBytes());
		// 创建一个密匙工厂
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		// 将DESKeySpec对象转换成SecretKey对象
		SecretKey securekey = keyFactory.generateSecret(desKey);
		// Cipher对象实际完成解密操作
		Cipher cipher = Cipher.getInstance("DES");
		// 用密匙初始化Cipher对象
		cipher.init(Cipher.DECRYPT_MODE, securekey, random);
		// 真正开始解密操作
		// byte[] b = cipher.doFinal(Base64.decode(new String(src)));
		byte[] b = cipher.doFinal(Base64.decodeBase64(src));
		return new String(b, "utf-8");
	}

	public static byte[] encrypt(byte[] src, byte[] key) throws Exception
	{
		// DES算法要求有一个可信任的随机数源
		SecureRandom sr = new SecureRandom();

		// 从原始密匙数据创建DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key);

		// 创建一个密匙工厂,然后用它把DESKeySpec转换成
		// 一个SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);

		// 用密匙初始化Cipher对象
		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

		// 正式执行加密操作
		return cipher.doFinal(src);
	}

	public static byte[] decrypt(byte[] src, byte[] key) throws Exception
	{

		// DES算法要求有一个可信任的随机数源
		SecureRandom sr = new SecureRandom();

		// 从原始密匙数据创建一个DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key);

		// 创建一个密匙工厂,然后用它把DESKeySpec对象转换成
		// 一个SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);

		// 用密匙初始化Cipher对象
		cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

		// 正式执行解密操作
		return cipher.doFinal(src);
	}

	// 解密
	public static String decrypt(String data)
	{
		try
		{
			return new String(decrypt(hex2byte(data.getBytes()), DjsUtils.desPassword.getBytes()));
		} catch (Exception e)
		{
			e.printStackTrace();

		}
		return null;
	}

	// 解密
	public static String decrypt(String data, String key)
	{
		try
		{
			return new String(decrypt(hex2byte(data.getBytes()), key.getBytes()));
		} catch (Exception e)
		{
			e.printStackTrace();

		}
		return null;
	}

	// 加密
	public static String encrypt(String data)
	{
		try
		{
			return byte2hex(encrypt(data.getBytes(), DjsUtils.desPassword.getBytes()));
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	// 加密
	public static String encrypt(String data, String key)
	{
		try
		{
			return byte2hex(encrypt(data.getBytes(), key.getBytes()));
		} catch (Exception e)
		{
			e.printStackTrace();

		}
		return null;
	}

	public static String byte2hex(byte[] b)
	{
		String hs = "";
		String stmp = "";

		for (int n = 0; n < b.length; n++)
		{
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
			{
				hs = hs + "0" + stmp;
			} else
			{
				hs = hs + stmp;
			}
		}

		return hs.toUpperCase();
	}

	public static byte[] hex2byte(byte[] b)
	{
		if ((b.length % 2) != 0)
		{
			throw new IllegalArgumentException("长度不是偶数");
		}

		byte[] b2 = new byte[b.length / 2];
		for (int n = 0; n < b.length; n += 2)
		{
			String item = new String(b, n, 2);
			b2[n / 2] = (byte) Integer.parseInt(item, 16);
		}

		return b2;
	}
}
package g.SmsFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


//import org.apache.commons.httpclient.HttpClient;
//import org.apache.commons.httpclient.HttpStatus;
//import org.apache.commons.httpclient.NameValuePair;
//import org.apache.commons.httpclient.URI;
//import org.apache.commons.httpclient.methods.GetMethod;

/** 
* @author Lc 
* @version 创建时间:2016年5月12日
*/
public class gSmsUtils {
	

//		private static String url = "http://222.73.117.158/msg/";// 应用地址,地址废弃,换成156
		private static String url = "http://222.73.117.156/msg/HttpBathSendSM";// 应用地址
		private static String account = "mcpet888";// 账号
		private static String pswd = "MC12345cm54321";// 密码
		private static boolean needstatus = true;// 是否需要状态报告,需要true,不需要false
		private static String extno = null;// 扩展码
		private static String product = null;
		
		/**
		 * 
		 * @param mobile 多个用逗号隔开,最大数量<5000
		 * @param msg 发送短信内容
		 * @return String 发送结果 0为正常,否则返回本地错误信息
		 */
		public static String sendSms (String mobile, String msg, boolean ...brief) {

			try {
				String returnString = batchSend(url, account, pswd, mobile, msg, needstatus, product, extno);
				if (null!=brief && brief.length>0)
					if (brief[0]==false)
						return returnString;
				return returnString.substring(returnString.indexOf(",")+1, 17);
				
			} catch (Exception e) {
				
				e.printStackTrace();
				return e.getMessage();
			}
		}
		
		// 测试用
//		public static void main(String[] args) {
//			// 18630227082
//			System.out.println( 
//					sendSms("13716023505"
//							, "尊敬的58到家用户您好,因您的订单在45分钟内未支付,该订单已被系统自动取消。") );
//		}
		
		/**
		 * 
		 * @param url 应用地址,类似于http://ip:port/msg/
		 * @param account 账号
		 * @param pswd 密码
		 * @param mobile 手机号码,多个号码使用","分割
		 * @param msg 短信内容
		 * @param needstatus 是否需要状态报告,需要true,不需要false
		 * @return 返回值定义参见HTTP协议文档
		 * @throws Exception
		 */
		static String batchSend(String url, String account, String pswd, String mobile, String msg,
				boolean needstatus, String product, String extno) throws Exception {
//			HttpClient client = new HttpClient();
//			GetMethod method = new GetMethod();
//			try {
//				URI base = new URI(url, false);
//				method.setURI(new URI(base, "HttpBatchSendSM", false));
//				method.setQueryString(new NameValuePair[] { 
//						new NameValuePair("account", account),
//						new NameValuePair("pswd", pswd), 
//						new NameValuePair("mobile", mobile),
//						new NameValuePair("needstatus", String.valueOf(needstatus)), 
//						new NameValuePair("msg", msg),
//						new NameValuePair("product", product),
//						new NameValuePair("extno", extno), 
//					});
//				int result = client.executeMethod(method);
//				if (result == HttpStatus.SC_OK) {
//					InputStream in = method.getResponseBodyAsStream();
//					ByteArrayOutputStream baos = new ByteArrayOutputStream();
//					byte[] buffer = new byte[1024];
//					int len = 0;
//					while ((len = in.read(buffer)) != -1) {
//						baos.write(buffer, 0, len);
//					}
//					return URLDecoder.decode(baos.toString(), "UTF-8");
//				} else {
//					throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
//				}
//			} finally {
//				method.releaseConnection();
//			}

			String str = "";
				List<NameValuePair> nvps = new ArrayList<>();
				nvps.add(new BasicNameValuePair("account", account));
				nvps.add(new BasicNameValuePair ("pswd", pswd));
				nvps.add(new BasicNameValuePair ("mobile", mobile));
				nvps.add(new BasicNameValuePair ("needstatus", String.valueOf(needstatus)));
				nvps.add(new BasicNameValuePair ("msg", msg));
				nvps.add(new BasicNameValuePair ("product", product));
				nvps.add(new BasicNameValuePair ("extno", extno));	
				try {
					CloseableHttpClient httpClient = HttpClients.createDefault();
					HttpPost httpPost = new HttpPost(url);
					httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
					CloseableHttpResponse httpResponse=httpClient.execute(httpPost);
					HttpEntity entity=httpResponse.getEntity();
					str = EntityUtils.toString(entity, "utf-8");
					EntityUtils.consume(entity);
					httpResponse.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return str;
				
		}

	}
package g.weixin;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import gHttpClientFactory.gHttpsUtils;

public class wxUtils
{
//	public static String access_token = "UQzcjm2FIVMngBIBQsnparlkQCNKHzJ53Kqc_iyi_ud6BUwHbvj9YbITNI3qYrHjiOaVzf4jq2Cj-PzmWA_8zVI8zjWp9DGozt5eH7KiAlJAhD7mzBhfZnu2G9qqT7xYFJKaAIAZDE";

	public static void main(String[] args) throws Exception
	{
//		deleteMenu();
//		createMenu();
//		getMenu();
	}

	public static String getToken()
	{
		String fileName = "wxToken.log";
		JSONObject mJson = readFile(fileName);
		if (System.currentTimeMillis() <= mJson.getLongValue("mTime")) {
			String wxToken = mJson.getString("access_token");
			return wxToken;
		} else {
			String appid = "wx57dfcca9eab1d229";
			String secret = "c84807b969ea6f9af5a4b41832189bdf";
			String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
			JSONObject json = gHttpsUtils.getHttpsGetJsonObject(url);
			json.put("mTime", System.currentTimeMillis() + (7000 * 1000));
			saveFile("wxToken.log", json.toJSONString());
			return json.getString("access_token");
		}
	}

	public static JSONObject getwxIp()
	{
		String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=" + getToken();
		JSONObject json = gHttpsUtils.getHttpsGetJsonObject(url);
		System.out.println(json);
		return json;
	}

	public static JSONObject createMenu() throws IOException
	{
		JSONObject mJson = (JSONObject) JSON.parse(FileUtils.readFileToString(new File("d:/menu.txt"), "utf-8"));
		System.out.println(mJson);
		String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + getToken();
		JSONObject json = gHttpsUtils.getHttpsPostJson(mJson, url);
		System.out.println(json);
		return json;
	}

	public static JSONObject getMenu()
	{
		String url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + getToken();
		JSONObject json = gHttpsUtils.getHttpsGetJsonObject(url);
		System.out.println(json);
		return json;
	}
	public static JSONObject deleteMenu()
	{
		String url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+getToken();
		JSONObject json=gHttpsUtils.getHttpsGetJsonObject(url);
		System.out.println(json);
		return json;
	}

	public static void saveFile(String fileName, String mesg)
	{
		if (StringUtils.containsIgnoreCase(System.getProperties().getProperty("os.name"), "windows"))
			fileName = "d:/" + fileName;
		else
			fileName = "/mnt/files/" + fileName;
		try {
			FileUtils.writeStringToFile(new File(fileName), mesg, "utf-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static JSONObject readFile(String fileName)
	{
		if (StringUtils.containsIgnoreCase(System.getProperties().getProperty("os.name"), "windows"))
			fileName = "d:/" + fileName;
		else
			fileName = "/mnt/files/" + fileName;
		try {
			String mesg = FileUtils.readFileToString(new File(fileName), "utf-8");
			JSONObject json = JSON.parseObject(mesg);
			return json;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
package g.weixin;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import g.LogsFactory.gLogUtils;
import gDataBaseFactory.gDbUtils;
import gHttpClientFactory.gHttpsUtils;
/**
 * 微信扫码支付统一下单
 * @author miaosc
 *
 */
public class wxPayUtils {
	private static String wxPayUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";//接口地址
	private static String appid="wxbdfd899082c8ec5c";//公众账号ID
	private static String mch_id="1291083601";//商户号
	private static String Key = "MENGchong2015weixinLlysc1sykrYhs";// 密钥 不要改
	private static String spbill_create_ip="101.200.126.208";//终端IP,APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。
	private static String notify_url="http://www.mengchongpet.com/alipayService/wxPay_notify_url.jsp";//通知地址,接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
	/**
	 * 微信统一下单(扫码支付下单)
	 * @return
	 */
	public static String unifiedOrder(String orderId){
		System.out.println("微信扫码统一下单开始,orderId-->"+orderId);
		//1.所有参数
		String device_info="WEB";//设备号,终端设备号(门店号或收银设备ID),注意:PC网页或公众号内支付请传"WEB"
		String nonce_str=getRandomStringByLength(12);//随机字符串,不长于32位。
		String sign="";//签名
		String body="宠物上门服务";//商品描述,商品或支付单简要描述
		String detail="";//商品详情,商品名称明细列表
		String attach="";//附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据
		String out_trade_no=orderId;//商户订单号,商户系统内部的订单号,32个字符内、可包含字母
		String fee_type="";//货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY
		String total_fee="";//订单总金额,单位为分
		String time_start="";//交易起始时间,订单生成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010
		String time_expire="";//交易结束时间,订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010
		String goods_tag="";//商品标记,代金券或立减优惠功能的参数
		String trade_type="NATIVE";//交易类型,取值如下:JSAPI,NATIVE,APP
		String product_id=orderId;//商品ID,trade_type=NATIVE,此参数必传。此id为二维码中包含的商品ID,商户自行定义。
		String limit_pay="";//指定支付方式,no_credit--指定不能使用信用卡支付
		String openid="";//用户标识	,trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识
		//2.查询订单并赋值
		String order_sql="SELECT * FROM T_OO_ORDER_GOHOME WHERE ORDER_ID = '"+orderId+"'";
		JSONArray order_gohomes = gDbUtils.execFindJsons(order_sql, null);
		if(order_gohomes!=null&&order_gohomes.size()>0){
			JSONObject order_gohome = order_gohomes.getJSONObject(0);
			total_fee = order_gohome.getString("AMOUNT")+"00";
		}else{
			System.out.println("微信扫码统一下单没有找到订单,orderId-->"+orderId);
			return "fail|没有找到该订单";
		}
		//3.sign参数组装
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		parameters.put("appid", appid);
		parameters.put("mch_id", mch_id);
		parameters.put("device_info", device_info);
		parameters.put("nonce_str", nonce_str);
//		parameters.put("sign", sign);
		parameters.put("body", body);
//		parameters.put("detail", detail);
//		parameters.put("attach", attach);
		parameters.put("out_trade_no", out_trade_no);
//		parameters.put("fee_type", fee_type);
		parameters.put("total_fee", total_fee);
		parameters.put("spbill_create_ip", spbill_create_ip);
//		parameters.put("time_start", time_start);
//		parameters.put("time_expire", time_expire);
//		parameters.put("goods_tag", goods_tag);
		parameters.put("notify_url", notify_url);
		parameters.put("trade_type", trade_type);
		parameters.put("product_id", product_id);
//		parameters.put("limit_pay", limit_pay);
//		parameters.put("openid", openid);
		sign = createSign("UTF-8", parameters);
		
		//4.xml组装
		Element root = DocumentHelper.createElement("xml");
		root.addElement("appid").setText(appid);
		root.addElement("mch_id").setText(mch_id);
		root.addElement("device_info").setText(device_info);
		root.addElement("nonce_str").setText(nonce_str);
		root.addElement("sign").setText(sign);
		root.addElement("body").setText(body);
//		root.addElement("detail").setText(detail);
//		root.addElement("attach").setText(attach);
		root.addElement("out_trade_no").setText(out_trade_no);
//		root.addElement("fee_type").setText(fee_type);
		root.addElement("total_fee").setText(total_fee);
		root.addElement("spbill_create_ip").setText(spbill_create_ip);
//		root.addElement("time_start").setText(time_start);
//		root.addElement("time_expire").setText(time_expire);
//		root.addElement("goods_tag").setText(goods_tag);
		root.addElement("notify_url").setText(notify_url);
		root.addElement("trade_type").setText(trade_type);
		root.addElement("product_id").setText(product_id);
//		root.addElement("limit_pay").setText(limit_pay);
//		root.addElement("openid").setText(openid);
		String sendXml = root.asXML();
		
		//5.请求接口
		System.out.println("微信扫码统一下单,orderId-->"+orderId+",sendXml-->"+sendXml);
		JSONObject json = new JSONObject();
		json.put("模块", "微信扫码支付统一下单");
		json.put("orderId", orderId);
		json.put("sendXml", sendXml);
		gLogUtils.AppendLog(json, "wxPay.log");
		
		String getXml = gHttpsUtils.getHttpsPostXml(sendXml, wxPayUrl);
		
		System.out.println("微信扫码统一下单,orderId-->"+orderId+",getXml-->"+getXml);
		json = new JSONObject();
		json.put("模块", "微信扫码支付统一下单");
		json.put("orderId", orderId);
		json.put("sendXml", sendXml);
		gLogUtils.AppendLog(json, "wxPay.log");
		
		//6.解析XML
		try {
			Document document = DocumentHelper.parseText(getXml);  
			//获得文档的根节点
			Element element = document.getRootElement();
			String return_code = element.elementText("return_code"); 
			if("SUCCESS".equals(return_code)){
				//通讯成功
				if("SUCCESS".equals(element.elementText("result_code"))){
					//下单成功
					System.out.println("微信扫码统一下单成功,orderId-->"+orderId+",code_url-->"+element.elementText("code_url"));
					return "success|"+element.elementText("code_url");
				}else{
					//下单失败
					System.out.println("微信扫码统一下单失败,orderId-->"+orderId
							+",result_code-->"+element.elementText("result_code")
							+",err_code-->"+element.elementText("err_code")
							+",err_code_des-->"+element.elementText("err_code_des"));
					return "fail|"+element.elementText("err_code_des");
				}
				
			}else{
				//通讯成功
				System.out.println("微信扫码统一下单通讯失败,orderId-->"+orderId+",return_code-->"+return_code+",return_msg-->"+element.elementText("return_msg"));
				return "fail|"+element.elementText("return_msg");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("微信扫码统一下单XML解析失败,orderId-->"+orderId);
			return "fail|解析XML错误";
		}
	}
	public static void main(String[] args) throws IOException {
		String orderId="O201605101949500232";
		/**
		 * 调用方法
		 * orderId	T_OO_ORDER_GOHOME表中的订单号(ORDER_ID)
		 * return	返回状态码	|返回信息
		 * 			success|weixin://wxpay/bizpayurl?pr=pUBhDua
		 * 			fail|错误信息
		 */
		wxPayUtils.unifiedOrder(orderId);
	}

	private static String createSign(String characterEncoding, SortedMap<Object, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序(升序)
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + Key);
		String sign = MD5Encode(sb.toString(), characterEncoding).toUpperCase();
		return sign;
	}

	private static String getRandomStringByLength(int length) {
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	private static String byteArrayToHexString(byte b[]) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++)
			resultSb.append(byteToHexString(b[i]));

		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n += 256;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	private static String MD5Encode(String origin, String charsetname) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (charsetname == null || "".equals(charsetname))
				resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
			else
				resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
		} catch (Exception exception) {
		}
		return resultString;
	}

	private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
			"e", "f" };
}
package g.Framework;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import gDataBaseFactory.gDbUtils;

public class gAutoCode
{

	public static void main(String[] args) throws Exception
	{
		// TODO Auto-generated method stub
//		 createInsertSql();
		createSelectSql();
//		createUpdateSql();
//		createDeleteSql();
	}
	public static void createGetParameter() throws Exception
	{
		
	}

	public static void createInsertSql() throws Exception
	{
		String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'mc_wx';";
		JSONArray jsons = gDbUtils.execFindJsons(sql, null);
		for (int i = 0; i < jsons.size(); i++) {
			String parms = "Object[] parm = {";
			JSONObject json = jsons.getJSONObject(i);
			String str = json.getString("TABLE_NAME");
			sql = "desc " + str;
			String newSql = "INSERT INTO ";
			String endSql = "(";
			newSql += str + "(";
			String m="";
			JSONArray jsonsDesc = gDbUtils.execFindJsons(sql, null);
			for (int k = 0; k < jsonsDesc.size(); k++) {
				JSONObject jsonField = jsonsDesc.getJSONObject(k);
				String field = jsonField.getString("Field");
				newSql += field + ",";
				endSql += "?,";
				parms += field + ",";
				m+="String "+field+",";
			}
			newSql += " ) VALUES ";
			endSql += ");";
			parms += "};";
			newSql = StringUtils.replace(newSql, ", )", ")");
			endSql = StringUtils.replace(endSql, ",)", ")");
			parms = StringUtils.replace(parms, ",}", "}");

			newSql = newSql + endSql;
			String method="public static boolean In_"+str+"("+m+")";
			method+="\n{\n";
			method+="String sql=\""+newSql+"\"\n";
			method+=parms+"\n";
			method+="try {\n gDbUtils.ExecuteUpdate(sql, parms);\n} catch (Exception e) {\ne.printStackTrace();\nreturn false;\n}\nreturn true;\n";
			method+="}";
			System.out.println(method);
		}
	}

	public static void createSelectSql() throws Exception
	{
		String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'mc_wx';";
		JSONArray jsons = gDbUtils.execFindJsons(sql, null);
		for (int i = 0; i < jsons.size(); i++) {
			String parms = "Object[] parm = {";
			JSONObject json = jsons.getJSONObject(i);
			String table = json.getString("TABLE_NAME");
			sql = "desc " + table;
			String newSql = "SELECT ";
			String where = " WHERE ";
			String m="";
			JSONArray jsonsDesc = gDbUtils.execFindJsons(sql, null);
			for (int k = 0; k < jsonsDesc.size(); k++) {
				JSONObject jsonField = jsonsDesc.getJSONObject(k);
				String field = jsonField.getString("Field");
				newSql += field + ",";
				parms += "?,";
				where += field + "=?,";
				m+="String "+field+",";
			}
			newSql += " FROM " + table;
			where+=";";
			parms += "};";
			newSql=StringUtils.replace(newSql, ", FROM", " FROM");
			where=StringUtils.replace(where, ",;", ";");
			parms=StringUtils.replace(parms, ",};", "};");
			String str=newSql+where;
			String method="public static JSONArray Se_"+table+"("+m+")";
			method+="\n{\nJSONArray jsons=null;\n";
			method+="String sql=\""+newSql+"\"\n";
			method+=parms+"\n";
			method+="try {\n jsons =gDbUtils.execFindJsons(sql, parms);\n} catch (Exception e) {\ne.printStackTrace();\nreturn jsons;\n}\nreturn jsons;\n";
			method+="}";
			System.out.println(method);
		}
	}

	public static void createUpdateSql() throws Exception
	{
		String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'mc_wx';";
		JSONArray jsons = gDbUtils.execFindJsons(sql, null);
		for (int i = 0; i < jsons.size(); i++) {
			String parms = "Object[] parm = {";
			JSONObject json = jsons.getJSONObject(i);
			String table = json.getString("TABLE_NAME");
			sql = "desc " + table;
			String newSql = "UPDATE " + table + " SET ";
			String m="";
			JSONArray jsonsDesc = gDbUtils.execFindJsons(sql, null);
			for (int k = 1; k < jsonsDesc.size(); k++) {
				JSONObject jsonField = jsonsDesc.getJSONObject(k);
				String field = jsonField.getString("Field");
				newSql += field + "=?,";
				parms += "?,";
				m+="String "+field+",";
			}
			newSql += " WHERE " + jsonsDesc.getJSONObject(0).getString("ID") + "=?;";

			parms += "?};";
			newSql = StringUtils.replace(newSql, ", WHERE", " WHERE");
			String method="public static boolean Up_"+table+"("+m+")";
			method+="\n{\n";
			method+="String sql=\""+newSql+"\"\n";
			method+=parms+"\n";
			method+="try {\n gDbUtils.ExecuteUpdate(sql, parms);\n} catch (Exception e) {\ne.printStackTrace();\nreturn false;\n}\nreturn true;\n";
			method+="}";
			System.out.println(method);
		}
	}

	public static void createDeleteSql() throws Exception
	{
		String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'mc_wx';";
		JSONArray jsons = gDbUtils.execFindJsons(sql, null);
		for (int i = 0; i < jsons.size(); i++) {
			String parms = "Object[] parm = {?};";
			JSONObject json = jsons.getJSONObject(i);
			String table = json.getString("TABLE_NAME");
			String m="String ID";
			sql = "desc " + table;
			String newSql = "DELETE FROM " + table + " WHERE ID=?;";
			String method="public static boolean Del_"+table+"("+m+")";
			method+="\n{\n";
			method+="String sql=\""+newSql+"\"\n";
			method+=parms+"\n";
			method+="try {\n gDbUtils.ExecuteUpdate(sql, parms);\n} catch (Exception e) {\ne.printStackTrace();\nreturn false;\n}\nreturn true;\n";
			method+="}";
			System.out.println(method);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值