package com.viathink.utils;

import java.io.File;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

/**
 * HTML页面静态化工具
 * @author LiuJunGuang
 * @date 2014年2月22日上午11:46:42
 */
public class HtmlGeneratorUtils {
	private static Logger log = Logger.getLogger(HtmlGeneratorUtils.class);
	private static final String encoding = "UTF-8";

	/** 根据模版及参数产生静态页面 */
	public static boolean createHtmlPage(String url, String htmlFileName) {
		GetMethod getMethod = null;
		try {
			HttpClient httpClient = new HttpClient();
			httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
			getMethod = new GetMethod(url);
			getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());// 使用系统提供的默认的恢复策略,在发生异常时候将自动重试3次
			getMethod.addRequestHeader("Content-Type", "text/html;charset=UTF-8");// 设置Get方法提交参数时使用的字符集,以支持中文参数的正常传递
			int statusCode = httpClient.executeMethod(getMethod);// 执行Get方法并取得返回状态码,200表示正常,其它代码为异常
			if (statusCode != 200) {
				log.error("静态页面引擎在解析" + url + "产生静态页面" + htmlFileName + "时出错!");
			} else {
				IOUtils.copy(getMethod.getResponseBodyAsStream(), FileUtils.openOutputStream(new File(htmlFileName)));
			}
			return true;
		} catch (Exception ex) {
			log.error("静态页面引擎在解析" + url + "产生静态页面" + htmlFileName + "时出错:" + ex.getMessage(), ex);
		} finally {
			if (getMethod != null)
				getMethod.releaseConnection();
		}
		return false;
	}

	// 测试方法
	public static void main(String[] args) {
		HtmlGeneratorUtils.createHtmlPage("http://localhost:8080/MSDCP/index.action", "c:/a/a.html");
	}
}