package com.local.uitls;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.alibaba.fastjson.JSON;
import common.Logger;
/**
* 工具类
*
* @ClassName: CommonUtils
* @Description: TODO
* @author Lan
* @date 2015年9月7日 下午8:09:17
*
*/
public class CommonUtils extends BaseAction {
private static Logger log=Logger.getLogger(CommonUtils.class);
/**
* Get百度接口请求
* @param url
* @return
* @throws ParseException
* @throws IOException
*/
public static JSONObject doBetJson(String url) throws ParseException, IOException{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
HttpResponse httpResponse = client.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity,"UTF-8");
//处理百度接口返回值的外部括号
result=result.substring(result.indexOf("(")+1, result.length()-1);
jsonObject = JSONObject.fromObject(result);
}
httpGet.releaseConnection();
return jsonObject;
}
/**
* Get请求
* @param url
* @return
* @throws ParseException
* @throws IOException
*/
public static JSONObject doGetJson(String url) throws ParseException, IOException{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
HttpResponse httpResponse = client.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity,"UTF-8");
jsonObject = JSONObject.fromObject(result);
}
httpGet.releaseConnection();
return jsonObject;
}
/**
* POST请求
* @param url
* @param outStr
* @return
* @throws ParseException
* @throws IOException
*/
public static JSONObject doPostStr(String url,String outStr) throws ParseException, IOException{
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
JSONObject jsonObject = null;
httpost.setEntity(new StringEntity(outStr,"UTF-8"));
HttpResponse response = client.execute(httpost);
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
jsonObject = JSONObject.fromObject(result);
httpost.releaseConnection();
return jsonObject;
}
//json字符串发送
public void writeJson(Object object) {
try {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
response.getWriter().print(JSON.toJSONString(object));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 泛型方法,将javaBean转成Map集合
* @param t
* @return
*/
public static <T> Map toMap(T t){
Map<String,Object> map=new HashMap<String, Object>();
//泛型对象转成Map方便操作特定属性
JSONObject json=new JSONObject();
json=json.fromObject(t);
Iterator it = json.keys();
// 遍历jsonObject数据,//net.sf最初的JSON将NULL字符串转成“”;org.json/alibaba.fast.json将不会显示为NULL的字符串
while (it.hasNext())
{
String key = String.valueOf(it.next());
map.put(key, isEmpty(String.valueOf(json.get(key)))?null:json.get(key));
}
return map;
}
/**
* 获取UUID替换里面的-字符
*
* @return
*/
public final static String getUUID() {
UUID uuid = UUID.randomUUID();
return uuid.toString().replaceAll("-", "");
}
/**
* 是否为数字
* @param str
* @return
*/
public static boolean isNumeric(String str){
return StringUtils.isNumeric(str);
}
/**
* 字符串是否为空
* @param str
* @return
*/
public static boolean isEmpty(String str){
return str==null||str.trim().equalsIgnoreCase("null")||str.trim().length()==0;
}
/**
* 判断一个字符串是否为double long 是否为数字
* @param str
* @return
*/
public static boolean isNumber(String str){
try{
double db = Double.parseDouble(str);
return true;
}catch(NumberFormatException e){
return false;
}
}
/**
* 字符串加上UUID
*
* @param pre
* 字符串类型参数
* @return
*/
public final static String getUUID(String pre) {
return pre + getUUID();
}
//枷锁时间戳生成ID
public synchronized static String getKey() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//加上两位随机数
Random random = new Random();
int end2 = random.nextInt(99);
//如果不足两位前面补0
String str = millis + String.format("%02d", end2);
return str;
}
//得到"yyyy-MM-dd HH:mm:ss"格式的时间字符串
public String getTime(){
return Toolkits.Obtain_date(Toolkits.GENERAL_TIME);
}
/**
* 判断数组是否为空
* @param s
* 需判断的数组
* @return boolean
* @author Guan
*/
@SuppressWarnings("rawtypes")
public final static boolean isNull(Collection collection) {
return collection == null || collection.isEmpty();
}
@SuppressWarnings("rawtypes")
public final static boolean isNotNull(Collection collection) {
return !CommonUtils.isNull(collection);
}
@SuppressWarnings("rawtypes")
public final static boolean isNull(Map m) {
return m == null || m.isEmpty();
}
@SuppressWarnings("rawtypes")
public final static boolean isNotNull(Map m) {
return !CommonUtils.isNull(m);
}
/**
*
* @Title: isConnect
* @Description: 功能:检测当前URL是否可连接或是否有效
* @Description: 已加锁,只能单线程运行调用
* @param @param urlStr 指定URL网络地址
* @return int HTTP状态码(200)-正常访问,(404)-资源不存在,(500)–服务器错误,(-1)-URL无效
* @author Tyrone.Li
* @throws
*/
public synchronized static int isConnect(String urlStr) {
URL url;
HttpURLConnection con;
// 返回页面代码
int state = -1;
// 如果传递进来的URL为空或者长度为0,则无效
if (urlStr == null || urlStr.length() <= 0) {
return state;
}
try {
url = new URL(urlStr);
con = (HttpURLConnection) url.openConnection();
// 设置连接主机超时
con.setConnectTimeout(5000