All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.weixinmp.thirdparty.AbstractHttpService Maven / Gradle / Ivy

package net.sf.weixinmp.thirdparty;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.log4j.Logger;

/**
 * 使用开源公共的Http服务的插件
 * @author Mao, Anping
 * @param R 执行结果返回的实体bean泛型
 */
public abstract class AbstractHttpService extends GenericService{
	private final static Logger LOGGER=Logger.getLogger(AbstractHttpService.class);
	
	public static final int DEFAULT_TIMEOUT=5*1000;
	public static final int DEFAULT_RECONNECT_TIMES=1;
	
	protected HttpClient httpClient;
	
	protected HttpMethod method;
	
	private boolean autoReconnect=false;
	private long timeout=DEFAULT_TIMEOUT;
	
	private int reconnectTimes=DEFAULT_RECONNECT_TIMES;
	/**
	 * 重入锁点
	 */
	private final ReentrantLock lock = new ReentrantLock();
	/**
	 * 超时计时器
	 */
	private Timer timeoutWatchdog;
	private boolean isAbort=false;
	public final R execute(Map params) throws IOException {
		configureHttpClient();
		setInternalParameters();
		addExtraParameters(params);
		setUpTimeoutWatch();
		lock.lock();//同步方法用
		synchronized (httpClient) {// 防止用户在onSuccess和onFailure中调用httpClient
			int t = 1;
			if (autoReconnect)
				t = reconnectTimes;
			try {
				for (int i = 0; i < t&&!isAbort; i++) {
					int responseCode = httpClient.executeMethod(method);
					if (responseCode == 200) {
						LOGGER.debug("onSuccess");
						R ret=onSuccess();
						return ret;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				LOGGER.debug(e);
			} finally {
				lock.unlock();//解锁
				timeoutWatchdog.cancel();//清除超时等待线程
				method.releaseConnection();//释放http请求资源
			}
		}
		return onFailure();
	}
	private void setInternalParameters() {
		//httpClient.setTimeout(timeout);
	}
	private void setUpTimeoutWatch() {
		isAbort=false;
		timeoutWatchdog=new Timer("HttpServiceTimeoutTimer"+System.currentTimeMillis());
		timeoutWatchdog.schedule(new TimerTask() {
			public void run() {
				if (lock.isLocked()) {
					isAbort=true;
					method.abort();//如果过了超时时间锁还没有打开,则是超时,中止请求
				}
				cancel();
				LOGGER.debug("timer is canceled because of timeout");
			}
		}, getTimeout());
	}
	protected void addExtraParameters(Map params) {
		if(params==null||params.isEmpty()) return ;
		if(method==null) {
			LOGGER.error("method is null, please instance HttpMethod in configureHttpClient");
			return ;
		}
		
		Iterator> it=params.entrySet().iterator();
		NameValuePair[] urlparams=new NameValuePair[params.size()];
		int i=0;
		while(it.hasNext()) {
			Entry entry=it.next();
			urlparams[i++]=new NameValuePair(entry.getKey(), entry.getValue());
		}
		method.setQueryString(urlparams);
	}
	protected static void mockFirefox(HttpMethod method){
		method.addRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		method.addRequestHeader("Accept-Encoding", "gzip, deflate");
		method.addRequestHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
		method.addRequestHeader("Cache-Control", "max-age=0");
		method.addRequestHeader("Connection", "keep-alive");
		method.addRequestHeader("Host", "www.email-unlimited.com");
		method.addRequestHeader("Referer", "http://www.1and1-mail.com/check-email/");
		method.addRequestHeader("User-Agen", "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0");
	}
	public boolean isAutoReconnect() {
		return autoReconnect;
	}
	public void setAutoReconnect(boolean autoReconnect) {
		this.autoReconnect = autoReconnect;
	}
	public int getReconnectTimes() {
		return reconnectTimes;
	}
	public void setReconnectTimes(int reconnectTimes) {
		this.reconnectTimes = reconnectTimes;
	}
	public long getTimeout() {
		return timeout;
	}
	public void setTimeout(long timeout) {
		this.timeout = timeout;
	}
	public HttpClient getHttpClient() {
		return httpClient;
	}
	/**
	 * 配置请求参数
	 */
	protected abstract void configureHttpClient();
	
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy