CollStorageWithHTTPS.java 10.7 KB
package com.sitech.ismp.coll.centercoll;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.log4j.Logger;

import com.sitech.ismp.coll.CollBase;
import com.sitech.ismp.util.IsmpSecureProtocolSocketFactory;

public class CollStorageWithHTTPS extends CollBase {

	private final String PRE_UNITID = "10-12-14"; // Resin的标识
	private final String PRE_UNITID_PM = PRE_UNITID + "-11"; // 性能指标
	private final String PRE_UNITID_CM = PRE_UNITID + "-10"; // 配置指标
	private final String PRE_UNITID_FM = PRE_UNITID + "-12"; // 状态指标

	private final static String COLL_IP = "COLL_IP";
	private final static String JMX_PORT = "JMX_PORT";
	private final static String HTTP_PORT = "HTTP_PORT";

	String hostName = "";
	MBeanServerConnection mbsc = null;
	JMXConnector connector = null;

	public void init(HashMap params) {

		String collIp = (String) params.get(COLL_IP);
		String jmxPort = (String) params.get(JMX_PORT);

		String jmxURL = "service:jmx:rmi:///jndi/rmi://" + collIp + ":"
				+ jmxPort + "/jmxrmi";// tomcat jmx url
		try {

			// System.out.println("connect jmx sevice");
			System.out.println("jmxURL=" + jmxURL);
			JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);
			Map map = new HashMap();
			String[] credentials = new String[] { "monitorRole", "QED" };
			map.put("jmx.remote.credentials", credentials);
			connector = JMXConnectorFactory.connect(serviceURL, map);
			mbsc = connector.getMBeanServerConnection();
			// 获取主机名称
			ObjectName runtimeObjName = new ObjectName("java.lang:type=Runtime");
			hostName = (String) mbsc.getAttribute(runtimeObjName, "Name");
			int pos = hostName.indexOf("@", 0);
			hostName = hostName.substring(pos + 1, hostName.length());

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
	}

	/**
	 * 采集会话指标
	 * 
	 * @param params
	 * @return
	 */
	public Vector getSession(HashMap params) {
		logger.info("begin getSession");
		// 保存采集结果,并返回值
		CollBase collResult = new CollBase();
		try {
			init(params);
			String httPort = (String) params.get(HTTP_PORT);

			ObjectName threadpoolObjName = new ObjectName(
					"resin:type=Port,name=" + httPort);
			// 请求总数
			String reqCountTotal = mbsc.getAttribute(threadpoolObjName,
					"RequestCountTotal").toString();
			// 最大连接数
			String idleThreads = mbsc.getAttribute(threadpoolObjName,
					"ConnectionMax").toString();
			// 请求时间总数
			String reqTimeTotal = mbsc.getAttribute(threadpoolObjName,
					"RequestTimeTotal").toString();
			// 保持活动总数
			String minSpareThreads = mbsc.getAttribute(threadpoolObjName,
					"KeepaliveCountTotal").toString();
			// 保持最大数
			String maxThreads = mbsc.getAttribute(threadpoolObjName,
					"KeepaliveMax").toString();

			//
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-session",
					"PM-00-04-004-10", reqCountTotal);
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-11", idleThreads);
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-12", reqTimeTotal);
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-13", minSpareThreads);
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-14", maxThreads);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				connector.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return collResult.getKPISet();
	}

	public static void post(String viewStr1) {
		IsmpSecureProtocolSocketFactory socket = new IsmpSecureProtocolSocketFactory();
		Protocol myhttps = new Protocol("https", socket, 443);

		HttpClient httpClient = new HttpClient();
		httpClient.getHostConfiguration().setHost("192.168.1.245", 6789,
				myhttps);
		String viewStr="";
		GetMethod get = new GetMethod("/console/faces/jsp/login/UserLogin.jsp");
		try {
			httpClient.executeMethod(get);
			Cookie[] cookies = httpClient.getState().getCookies();
			httpClient.getState().addCookies(cookies);			
			String responseString = new String(get.getResponseBodyAsString().getBytes("gbk"));

			// 向控制台打印登陆后页面的html
			System.out
					.println("================第一次转向后的页面==========================");
			System.out.println(responseString);
			//com.sun.faces.VIEW
			int start = responseString.indexOf("VIEW\" value=\"");
			int end = responseString.indexOf("\" />",start);
			viewStr = responseString.substring(start+13, end);
			System.out.println(viewStr);
		} catch (Exception e) {
			// 发生网络异常
			e.printStackTrace();
		} finally {
			// 释放连接
			//get.releaseConnection();
		}
		
		// HttpClient httpClient = new HttpClient();
		// String url = "https://192.168.111.219:8443/login.do";
		PostMethod postMethod = new PostMethod(
				"/console/faces/jsp/login/UserLogin.jsp");
		// 填入各个表单域的值
		NameValuePair[] data = {
				new NameValuePair("userLoginForm:username", "root"),
				new NameValuePair("userLoginForm:password", "root"),
				new NameValuePair("userLoginForm_hidden",
						"userLoginForm_hidden"),
				new NameValuePair(
						"com.sun.faces.VIEW",viewStr
						),
				new NameValuePair("userLoginForm:hidden", "needed") };

		// 将表单的值放入postMethod中
		postMethod.setRequestBody(data);
		try {

			// 执行postMethod
			int statusCode = httpClient.executeMethod(postMethod);

			// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
			// 301或者302
			// String responseString = new
			// String(postMethod.getResponseBodyAsString().getBytes("gbk"));
			String responseString = new String(postMethod
					.getResponseBodyAsString());
			System.out
					.println("=========================登录页面===========================");
			System.out.println(responseString);
			// Cookie[] cookies = httpClient.getState().getCookies();
			// httpClient.getState().addCookies(cookies);
			/*
			 * GetMethod get = new GetMethod("/portal.do");
			 * get.setRequestHeader("Cookie", cookies.toString());
			 * httpClient.executeMethod(get); responseString = new
			 * String(get.getResponseBodyAsString().getBytes("gbk"));
			 * 
			 * //向控制台打印登陆后页面的html System.out.println(
			 * "==========================第一次转向后的页面=================================="
			 * ); System.out.println(responseString);
			 */

			if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
					|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
				// 从头中取出转向的地址
				Header locationHeader = postMethod
						.getResponseHeader("location");
				String location = null;
				if (locationHeader != null) {
					location = locationHeader.getValue();
					System.out
							.println("The page was redirected to:" + location);
				} else {
					System.err.println("Location field value is null.");
				}
			}
		} catch (HttpException e) {
			// 发生致命的异常,可能是协议不对或者返回的内容有问题
			System.out.println("Please check your provided http address!");
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			e.printStackTrace();
		} finally {
			// 释放连接
			postMethod.releaseConnection();
		}

	}

	public static String getView() {
		IsmpSecureProtocolSocketFactory socket = new IsmpSecureProtocolSocketFactory();
		Protocol myhttps = new Protocol("https", socket, 443);

		HttpClient httpClient = new HttpClient();
		httpClient.getHostConfiguration().setHost("192.168.1.245", 6789,
				myhttps);
		String viewStr="";
		GetMethod get = new GetMethod("/console/faces/jsp/login/UserLogin.jsp");
		try {
			httpClient.executeMethod(get);
			String responseString = new String(get.getResponseBodyAsString().getBytes("gbk"));

			// 向控制台打印登陆后页面的html
			System.out
					.println("================第一次转向后的页面==========================");
			System.out.println(responseString);
			//com.sun.faces.VIEW
			int start = responseString.indexOf("VIEW\" value=\"");
			int end = responseString.indexOf("\" />",start);
			viewStr = responseString.substring(start+13, end);
			System.out.println(viewStr);
		} catch (Exception e) {
			// 发生网络异常
			e.printStackTrace();
		} finally {
			// 释放连接
			get.releaseConnection();
		}
		return viewStr;

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		//String viewStr = getView();
		post("xdf");

		/*
		 * // 构造HttpClient的实例 HttpClient httpClient = new HttpClient(); //
		 * 创建GET方法的实例 GetMethod getMethod = new
		 * GetMethod("https://127.0.0.1:8443/"); // 使用系统提供的默认的恢复策略
		 * getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
		 * new DefaultHttpMethodRetryHandler()); try { // 执行getMethod
		 * System.setProperty
		 * ("javax.net.ssl.trustStore","C:/WINDOWS/system32/config/systemprofile/"
		 * ); int statusCode = httpClient.executeMethod(getMethod); if
		 * (statusCode != HttpStatus.SC_OK) {
		 * System.err.println("Method failed: " + getMethod.getStatusLine()); }
		 * // 读取内容 byte[] responseBody = getMethod.getResponseBody(); // 处理内容
		 * System.out.println(new String(responseBody)); } catch (HttpException
		 * e) { // 发生致命的异常,可能是协议不对或者返回的内容有问题
		 * System.out.println("Please check your provided http address!");
		 * e.printStackTrace(); } catch (IOException e) { // 发生网络异常
		 * e.printStackTrace(); } finally { // 释放连接
		 * getMethod.releaseConnection(); }
		 */
		IsmpSecureProtocolSocketFactory socket = new IsmpSecureProtocolSocketFactory();
		Protocol myhttps = new Protocol("https", socket, 443);

		HttpClient httpclient = new HttpClient();
		httpclient.getHostConfiguration().setHost("127.0.0.1", 8443, myhttps);
		GetMethod httpget = new GetMethod("/");
		try {
			httpclient.executeMethod(httpget);
			System.out.println(httpget.getStatusLine());
		} catch (Exception e) {
			// 发生网络异常
			e.printStackTrace();

		} finally {
			httpget.releaseConnection();
		}

	}

}