大家都知道jmx的功能,一般都是使用三方包jmxtools.jar.他的原理是自己写了一个socket服务,然后根据请求自己拼装简单的html元素然后返回给请求的socket.这个原理和tomcat的原理一样,只是没有做到那么强大。
最近发现jmxtools的HtmlAdaptorServer展示参数输入框是<INPUT TYPE=\"text\". 有时候我们输入的参数需要支持换行输入。这个原生的就不支持了。 展示的是在htmlObjectPage这个类拼装的HTML页面元素,具体拼装方法在buildOperationWithParam这个method里面。部分代码如下:
for (int m = 0; m < j; m++) { str1 = paramArrayOfMBeanParameterInfo[m].getType(); if (paramArrayOfMBeanParameterInfo[m].getName().length() > 0) str2 = paramArrayOfMBeanParameterInfo[m].getName(); else { str2 = "param" + m; } if (m != 0) localStringBuffer.append("<TD></TD>"); String str3 = paramArrayOfMBeanParameterInfo[m].getDescription(); if ((str3 != null) && (str3.length() > 0)) localStringBuffer.append("<TD>(" + str1 + ")<A HREF=\"javascript:alert('" + str3 + "');\">" + str2 + "</A></TD>" + "\r\n"); else { localStringBuffer.append("<TD>(" + str1 + ")" + str2 + "</TD>" + "\r\n"); } if (i == 0) { localStringBuffer.append("<TD></TD>\r\n"); } else if ((str1.endsWith("Boolean")) || (str1.endsWith("boolean"))) { localStringBuffer.append("<TD>" + boolToHtml(str2, str1, "true", true) + "</TD>" + "\r\n"); } else { localStringBuffer.append("<TD><INPUT TYPE=\"text\" NAME=\"" + str2 + "+" + str1 + "\" "); localStringBuffer.append("SIZE=50%"); localStringBuffer.append("></TD>\r\n"); } localStringBuffer.append("</TR><TR><TD></TD>\r\n"); } localStringBuffer.append("</TR></TABLE>\r\n"); if (i != 0) { localStringBuffer.append("</FORM>\r\n"); } return localStringBuffer.toString();
因此我和同事进行了扩展,原理是在Response要返回的客户端的时候换input type="text"标签替换成textarea.他的代码很多地方都是直接new的对象,没办法进行扩展,所以只好重写HtmlAdaptorServer和HtmlRequestHandler.
先说怎么用吧。
只需要将在spring里面注册的HtmlAdaptorServer换成我的扩展server就可以了.配置如下:
<bean id="htmlAdaptor" class="com.sun.jdmk.comm.HtmlAdaptorServerExt" init-method="start"> <property name="port" value="5168"></property> </bean>
代码的话需要你在工程里面建四个类:
com.sun.jdmk.comm.HtmlAdaptorServer
com.sun.jdmk.comm.HtmlAdaptorServerExt
com.sun.jdmk.comm.HtmlRequestHandler
com.sun.jdmk.comm.HtmlRequestHandlerExt
代码如下:
com.sun.jdmk.comm.HtmlAdaptorServer(包名不能换)
package com.sun.jdmk.comm; import javax.management.ObjectName; public abstract class HtmlAdaptorServer extends CommunicatorServer{ public HtmlAdaptorServer(int arg0) throws IllegalArgumentException { super(arg0); // TODO Auto-generated constructor stub } public abstract ObjectName getParser(); public abstract void resetParser(); }
com.sun.jdmk.comm.HtmlAdaptorServerExt(包名不能换):
package com.sun.jdmk.comm; import java.io.IOException; import java.io.InterruptedIOException; import java.lang.reflect.Constructor; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.Enumeration; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.StringTokenizer; import java.util.Vector; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanRegistration; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.RuntimeOperationsException; import javax.management.ServiceNotFoundException; public class HtmlAdaptorServerExt extends HtmlAdaptorServer implements MBeanRegistration, DynamicMBean { private String dclassName = getClass().getName(); private String ddescription = "HtmlAdaptorServer class: Provides a management interface of an agent to Web browser clients."; private MBeanAttributeInfo[] dattributes = new MBeanAttributeInfo[12]; private MBeanConstructorInfo[] dconstructors = new MBeanConstructorInfo[3]; private MBeanOperationInfo[] doperations = new MBeanOperationInfo[5]; private MBeanInfo dmbeaninfo = null; private InetAddress addrLastClient = null; private Vector authInfo = new Vector(); private ObjectName userParser = null; private transient ServerSocket sockListen = null; private transient Socket sock = null; private static final String InterruptSysCallMsg = "Interrupted system call"; public HtmlAdaptorServerExt() { this(8082); } public HtmlAdaptorServerExt(int paramInt) { super(3); this.port = paramInt; this.maxActiveClientCount = 10; this.dbgTag = makeDebugTag(); buildInfo(); } public HtmlAdaptorServerExt(int paramInt, AuthInfo[] paramArrayOfAuthInfo) { this(paramInt); if (paramArrayOfAuthInfo != null) for (int i = 0; i < paramArrayOfAuthInfo.length; i++) addUserAuthenticationInfo(paramArrayOfAuthInfo[i]); } public void setParser(ObjectName paramObjectName) throws InstanceNotFoundException, ServiceNotFoundException { if (paramObjectName == null) { resetParser(); return; } ObjectInstance localObjectInstance = this.bottomMBS.getObjectInstance(paramObjectName); try { Class localClass = loadClass(localObjectInstance.getClassName()); if (!HtmlParser.class.isAssignableFrom(localClass)) { throw new ServiceNotFoundException("The HtmlParser interface is not implemented by the MBbean = " + paramObjectName); } this.userParser = paramObjectName; } catch (ClassNotFoundException localClassNotFoundException) { if (isDebugOn()) { debug("setParser", "Class not found [Exception=" + localClassNotFoundException + "]"); } throw new ServiceNotFoundException(localClassNotFoundException.toString()); } } public ObjectName getParser() { return this.userParser; } public void resetParser() { this.userParser = null; } public void createParser(String paramString1, String paramString2, String paramString3) throws MalformedObjectNameException, ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException { Object localObject = null; if ((paramString3 != null) && (paramString3.length() > 0)) { ObjectName localObjectName = new ObjectName(paramString3); localObject = this.bottomMBS.instantiate(paramString1, localObjectName); } else { localObject = this.bottomMBS.instantiate(paramString1); } if (!HtmlParser.class.isAssignableFrom(localObject.getClass())) { localObject = null; throw new MBeanException(new ServiceNotFoundException("The HtmlParser interface is not implemented by the MBbean = " + paramString1)); } ObjectName localObjectName = new ObjectName(paramString2); this.bottomMBS.registerMBean(localObject, localObjectName); try { setParser(localObjectName); } catch (ServiceNotFoundException localServiceNotFoundException) { if (isDebugOn()) { debug("setParser", " Service not found. [Exception=" + localServiceNotFoundException + "]"); } throw new MBeanException(localServiceNotFoundException); } } public String getLastConnectedClient() { if (this.addrLastClient == null) { return "unknown"; } return this.addrLastClient.getHostAddress(); } public String getProtocol() { return "html"; } public int getServedClientCount() { return super.getServedClientCount(); } public int getActiveClientCount() { return super.getActiveClientCount(); } public int getMaxActiveClientCount() { return super.getMaxActiveClientCount(); } public void setMaxActiveClientCount(int paramInt) throws IllegalStateException { super.setMaxActiveClientCount(paramInt); } public synchronized void addUserAuthenticationInfo(AuthInfo paramAuthInfo) { if (paramAuthInfo != null) { String str = paramAuthInfo.getLogin(); for (Enumeration localEnumeration = this.authInfo.elements(); localEnumeration.hasMoreElements(); ) { AuthInfo localAuthInfo = (AuthInfo)localEnumeration.nextElement(); if (localAuthInfo.getLogin().equals(str)) { this.authInfo.removeElement(localAuthInfo); break; } } this.authInfo.addElement(paramAuthInfo); } } public synchronized void removeUserAuthenticationInfo(AuthInfo paramAuthInfo) { if (paramAuthInfo != null) { String str = paramAuthInfo.getLogin(); for (Enumeration localEnumeration = this.authInfo.elements(); localEnumeration.hasMoreElements(); ) { AuthInfo localAuthInfo = (AuthInfo)localEnumeration.nextElement(); if (localAuthInfo.getLogin().equals(str)) { this.authInfo.removeElement(localAuthInfo); break; } } } } public boolean isAuthenticationOn() { return !this.authInfo.isEmpty(); } public void stop() { if ((this.state == 0) || (this.state == 3)) { super.stop(); try { Socket localSocket = new Socket(InetAddress.getLocalHost(), this.port); localSocket.close(); } catch (IOException localIOException) { if (isDebugOn()) debug("stop", "I/O exception. [Exception=" + localIOException + "]"); } } } public ObjectName preRegister(MBeanServer paramMBeanServer, ObjectName paramObjectName) throws Exception { if (paramObjectName == null) { paramObjectName = new ObjectName(paramMBeanServer.getDefaultDomain() + ":" + "name=HtmlAdaptorServer"); } return super.preRegister(paramMBeanServer, paramObjectName); } public void postRegister(Boolean paramBoolean) { super.postRegister(paramBoolean); } public void preDeregister() throws Exception { super.preDeregister(); } public void postDeregister() { super.postDeregister(); } public MBeanInfo getMBeanInfo() { return this.dmbeaninfo; } public Object getAttribute(String paramString) throws AttributeNotFoundException, MBeanException, ReflectionException { if ((paramString == null) || (paramString.trim().equals(""))) { throw new RuntimeOperationsException(new IllegalArgumentException("Attribute name cannot be null or empty"), "The getAttribute method of HtmlAdaptorServer was called with a null or empty attribute name string."); } if (paramString.equals("Active")) return new Boolean(isActive()); if (paramString.equals("ActiveClientCount")) return new Integer(getActiveClientCount()); if (paramString.equals("AuthenticationOn")) return new Boolean(isAuthenticationOn()); if (paramString.equals("Host")) return getHost(); if (paramString.equals("LastConnectedClient")) return getLastConnectedClient(); if (paramString.equals("MaxActiveClientCount")) return new Integer(getMaxActiveClientCount()); if (paramString.equals("Parser")) return getParser(); if (paramString.equals("Port")) return new Integer(getPort()); if (paramString.equals("Protocol")) return getProtocol(); if (paramString.equals("ServedClientCount")) return new Integer(getServedClientCount()); if (paramString.equals("State")) return new Integer(getState()); if (paramString.equals("StateString")) { return getStateString(); } throw new AttributeNotFoundException(paramString + " is unknown in HtmlAdaptorServer"); } public AttributeList getAttributes(String[] paramArrayOfString) { AttributeList localAttributeList = new AttributeList(); String str1 = null; if (paramArrayOfString == null) { throw new RuntimeOperationsException(new IllegalArgumentException("Attributes cannot be null"), "Exception occured trying to invoke the getter on the HtmlAdaptorServer"); } if (paramArrayOfString.length == 0) { return localAttributeList; } for (int i = 0; i < paramArrayOfString.length; i++) { str1 = paramArrayOfString[i]; String str2 = paramArrayOfString[i]; try { Object localObject = getAttribute(str2); localAttributeList.add(new Attribute(str2, localObject)); } catch (Exception localException) { if (isDebugOn()) { debug("getAttributes", "Unexpected exception [Exception=" + localException + "]"); } } } return localAttributeList; } public Object invoke(String paramString, Object[] paramArrayOfObject, String[] paramArrayOfString) throws MBeanException, ReflectionException { if ((paramString == null) || (paramString.trim().equals(""))) { throw new RuntimeOperationsException(new IllegalArgumentException("String parameter 'actionName' of invoke method of HtmlAdaptorServer cannot be null or empty"), "String parameter 'actionName' of invoke method of HtmlAdaptorServer cannot be null or empty"); } if (paramString.equals("start")) { start(); return null; } if (paramString.equals("stop")) { stop(); return null; } if (paramString.equals("waitState")) { try { if ((paramArrayOfObject.length != 2) || (!(paramArrayOfObject[0] instanceof Integer)) || (!(paramArrayOfObject[1] instanceof Long))) { throw new RuntimeOperationsException(new IllegalArgumentException("invoke waitState: expecting params[0] instanceof Integer and params[1] instanceof Long"), "Wrong content for array Object[] params to invoke waitState method of HtmlAdaptorServer"); } if ((paramArrayOfString.length != 2) || (!paramArrayOfString[0].equals("int")) || (!paramArrayOfString[1].equals("long"))) { throw new RuntimeOperationsException(new IllegalArgumentException("invoke waitState: expecting signature[0].equals(\"int\") and signature[1].equals(\"long\")"), "Wrong content for array String[] signature to invoke waitState method of HtmlAdaptorServer"); } return new Boolean(waitState(((Integer)paramArrayOfObject[0]).intValue(), ((Long)paramArrayOfObject[1]).longValue())); } catch (Exception localException1) { throw new MBeanException(localException1, "invoke waitState: " + localException1.getClass().getName() + "caught [" + localException1.getMessage() + "]"); } } if (paramString.equals("createParser")) { try { if ((paramArrayOfObject.length != 3) || (!(paramArrayOfObject[0] instanceof String)) || (!(paramArrayOfObject[1] instanceof String)) || (!(paramArrayOfObject[2] instanceof String))) { throw new RuntimeOperationsException(new IllegalArgumentException("invoke createParser: expecting params[0] instanceof String and params[1] instanceof String and params[2] instanceof String"), "Wrong content for array Object[] params to invoke createParser method of HtmlAdaptorServer"); } if ((paramArrayOfString.length != 3) || (!paramArrayOfString[0].equals("String")) || (!paramArrayOfString[1].equals("String")) || (!paramArrayOfString[2].equals("String"))) { throw new RuntimeOperationsException(new IllegalArgumentException("invoke createParser: expecting signature[0].equals(\"String\") and signature[1].equals(\"String\") and signature[2].equals(\"String\")"), "Wrong content for array String[] signature to invoke createParser method of HtmlAdaptorServer"); } createParser((String)paramArrayOfObject[0], (String)paramArrayOfObject[1], (String)paramArrayOfObject[2]); } catch (Exception localException2) { throw new MBeanException(localException2, "invoke createParser: " + localException2.getClass().getName() + "caught [" + localException2.getMessage() + "]"); } return null; } if (paramString.equals("resetParser")) { resetParser(); return null; } String str; if ((paramString.startsWith("get")) && (paramString.length() > 3)) { str = paramString.substring(3); try { return getAttribute(str); } catch (AttributeNotFoundException localAttributeNotFoundException1) { throw new ReflectionException(new NoSuchMethodException(paramString), "The action with name " + paramString + " could not be found in HtmlAdaptorServer"); } } if ((paramString.startsWith("is")) && (paramString.length() > 2)) { str = paramString.substring(2); try { return getAttribute(str); } catch (AttributeNotFoundException localAttributeNotFoundException2) { throw new ReflectionException(new NoSuchMethodException(paramString), "The action with name " + paramString + " could not be found in HtmlAdaptorServer"); } } if ((paramString.startsWith("set")) && (paramString.length() > 3)) { str = paramString.substring(3); if (paramArrayOfObject.length != 1) { throw new RuntimeOperationsException(new IllegalArgumentException("invoke " + paramString + ": expecting params.length == 1"), "Array Object[] params to invoke createParser method of HtmlAdaptorServer should be of length 1"); } try { setAttribute(new Attribute(str, paramArrayOfObject[0])); } catch (AttributeNotFoundException localAttributeNotFoundException3) { throw new ReflectionException(new NoSuchMethodException(paramString), "The action with name " + paramString + " could not be found in HtmlAdaptorServer"); } catch (InvalidAttributeValueException localInvalidAttributeValueException) { throw new MBeanException(localInvalidAttributeValueException, "InvalidAttributeValueException thrown when invoking setAttribute for attribute with [name=" + str + "] and [value=" + paramArrayOfObject[0] + "]"); } return null; } throw new ReflectionException(new NoSuchMethodException(paramString), "The action with name " + paramString + " could not be found in HtmlAdaptorServer"); } public void setAttribute(Attribute paramAttribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { if (paramAttribute == null) { throw new RuntimeOperationsException(new IllegalArgumentException("setAttribute: attribute parameter cannot be null"), "Cannot invoke setAttribute method of " + this.dclassName + " with null attribute parameter"); } String str = paramAttribute.getName(); Object localObject = paramAttribute.getValue(); if ((str == null) || (str.trim().equals(""))) { throw new RuntimeOperationsException(new IllegalArgumentException("setAttribute: name field of attribute parameter cannot be null or empty"), "Cannot invoke setAttribute method of " + this.dclassName + " with null or empty attribute parameter name field"); } if (str.equals("Port")) { try { if (Integer.class.isAssignableFrom(localObject != null ? localObject.getClass() : Integer.class)) { setPort(((Integer)paramAttribute.getValue()).intValue()); } else throw new InvalidAttributeValueException("Cannot set attribute " + str + " to a " + (localObject != null ? localObject.getClass().getName() : localObject) + " object, java.lang.Integer expected"); } catch (Exception localException1) { if (isDebugOn()) { debug("setAttribute", "setAttribute Port: caught [Exception=" + localException1 + "]"); } throw new MBeanException(localException1, "setAttribute Port: " + localException1.getClass().getName() + " caught [" + localException1.getMessage() + "]"); } } else if (str.equals("MaxActiveClientCount")) { try { if (Integer.class.isAssignableFrom(localObject != null ? localObject.getClass() : Integer.class)) { setMaxActiveClientCount(((Integer)paramAttribute.getValue()).intValue()); } else throw new InvalidAttributeValueException("Cannot set attribute " + str + " to a " + (localObject != null ? localObject.getClass().getName() : localObject) + " object, java.lang.Integer expected"); } catch (Exception localException2) { if (isDebugOn()) { debug("setAttribute", "setAttribute MaxActiveClientCount: caught [Exception=" + localException2 + "]"); } throw new MBeanException(localException2, "setAttribute MaxActiveClientCount: " + localException2.getClass().getName() + " caught [" + localException2.getMessage() + "]"); } } else if (str.equals("Parser")) try { if (ObjectName.class.isAssignableFrom(localObject != null ? localObject.getClass() : ObjectName.class)) { setParser((ObjectName)paramAttribute.getValue()); } else throw new InvalidAttributeValueException("Cannot set attribute " + str + " to a " + (localObject != null ? localObject.getClass().getName() : localObject) + " object, javax.management.ObjectName expected"); } catch (Exception localException3) { if (isDebugOn()) { debug("setAttribute", "setAttribute Parser: caught [Exception=" + localException3 + "]"); } throw new MBeanException(localException3, "setAttribute Parser: " + localException3.getClass().getName() + " caught [" + localException3.getMessage() + "]"); } else throw new AttributeNotFoundException("Attribute " + str + " is unknown in HtmlAdaptorServer, or is not writable"); } public AttributeList setAttributes(AttributeList paramAttributeList) { if (paramAttributeList == null) { throw new RuntimeOperationsException(new IllegalArgumentException("AttributeList cannot be null"), "Exception occured trying to invoke the setter on the MBean"); } AttributeList localAttributeList = new AttributeList(); if (paramAttributeList.isEmpty()) { return localAttributeList; } for (Iterator localIterator = paramAttributeList.iterator(); localIterator.hasNext(); ) { Attribute localAttribute = (Attribute)localIterator.next(); String str = localAttribute.getName(); Object localObject1 = localAttribute.getValue(); try { Object localObject2 = null; setAttribute(localAttribute); localAttributeList.add(new Attribute(str, getAttribute(str))); } catch (Exception localException) { if (isDebugOn()) { debug("setAttributes", "Exception when setting " + str + ". [Exception=" + localException + "]"); } } } return localAttributeList; } protected void doError(Exception paramException) throws CommunicationException { } protected void doBind() throws CommunicationException, InterruptedException { if (isTraceOn()) { trace("doBind", "Bind the socket listener to [Port=" + this.port + ", MaxActiveClientCount=" + this.maxActiveClientCount + "]"); } try { this.sockListen = new ServerSocket(this.port, 2 * this.maxActiveClientCount); if (isTraceOn()) trace("doBind", "Bound to [Address=" + this.sockListen.getInetAddress() + ", Port=" + this.sockListen.getLocalPort() + "]"); } catch (SocketException localSocketException) { if (localSocketException.getMessage().equals("Interrupted system call")) { throw new InterruptedException(localSocketException.toString()); } throw new CommunicationException(localSocketException); } catch (InterruptedIOException localInterruptedIOException) { throw new InterruptedException(localInterruptedIOException.toString()); } catch (IOException localIOException) { throw new CommunicationException(localIOException); } } protected void doUnbind() throws CommunicationException, InterruptedException { if (isTraceOn()) trace("doUnbind", "Finally close the socket [Listener=" + this.sockListen + "]"); try { this.sockListen.close(); } catch (SocketException localSocketException) { if (localSocketException.getMessage().equals("Interrupted system call")) { throw new InterruptedException(localSocketException.toString()); } throw new CommunicationException(localSocketException); } catch (InterruptedIOException localInterruptedIOException) { throw new InterruptedException(localInterruptedIOException.toString()); } catch (IOException localIOException) { throw new CommunicationException(localIOException); } } protected void doReceive() throws CommunicationException, InterruptedException { if (isTraceOn()) trace("doReceive", "Listens for a connection on [Listener=" + this.sockListen + "]"); try { this.sock = this.sockListen.accept(); if (isTraceOn()) trace("doReceive", "Accepted a connection on [Socket=" + this.sock + "]"); } catch (SocketException localSocketException) { if (localSocketException.getMessage().equals("Interrupted system call")) { throw new InterruptedException(localSocketException.toString()); } throw new CommunicationException(localSocketException); } catch (InterruptedIOException localInterruptedIOException) { throw new InterruptedException(localInterruptedIOException.toString()); } catch (IOException localIOException) { throw new CommunicationException(localIOException); } } protected void doProcess() throws CommunicationException, InterruptedException { if (isTraceOn()) { trace("doProcess", "Process a request received on [Socket=" + this.sock + "]"); } this.addrLastClient = this.sock.getInetAddress(); HtmlRequestHandler localHtmlRequestHandler = new HtmlRequestHandlerExt(this.sock, this, this.topMBS , this.objectName, this.servedClientCount); this.sock = null; } synchronized boolean checkChallengeResponse(String paramString) { if (isTraceOn()) { trace("checkChallengeResponse", " Validate request"); } if (paramString == null) { return false; } String str1 = null; String str2 = null; StringTokenizer localStringTokenizer = new StringTokenizer(paramString, ":"); try { if (localStringTokenizer.hasMoreTokens()) { str1 = localStringTokenizer.nextToken(); str2 = localStringTokenizer.nextToken(); } } catch (NoSuchElementException localNoSuchElementException) { if (isDebugOn()) { debug("checkChallengeResponse", "No such element. [Exception=" + localNoSuchElementException + "]"); } return false; } if (isTraceOn()) { trace("checkChallengeResponse", " Validate the request for [Login=" + str1 + ", Password=" + str2 + "]"); } for (Enumeration localEnumeration = this.authInfo.elements(); localEnumeration.hasMoreElements(); ) { AuthInfo localAuthInfo = (AuthInfo)localEnumeration.nextElement(); if ((localAuthInfo.getLogin().equals(str1)) && (localAuthInfo.getPassword().equals(str2))) { return true; } } return false; } private void buildInfo() { this.dattributes[0] = new MBeanAttributeInfo("Active", "boolean", "Active: True if the HtmlAdaptorServer is in the ONLINE state.", true, false, true); this.dattributes[1] = new MBeanAttributeInfo("ActiveClientCount", "int", "ActiveClientCount: The number of clients being processed currently by the HtmlAdaptorServer.", true, false, false); this.dattributes[2] = new MBeanAttributeInfo("AuthenticationOn", "boolean", "AuthenticationOn: True if the HtmlAdaptorServer requests authentication.", true, false, true); this.dattributes[3] = new MBeanAttributeInfo("Host", "java.lang.String", "Host: Hostname.", true, false, false); this.dattributes[4] = new MBeanAttributeInfo("LastConnectedClient", "java.lang.String", "LastConnectedClient: The IP address of the last connected client.", true, false, false); this.dattributes[5] = new MBeanAttributeInfo("MaxActiveClientCount", "int", "MaxActiveClientCount: The maximum number of clients the HtmlAdaptorServer can process concurrently.", true, true, false); this.dattributes[6] = new MBeanAttributeInfo("Parser", "javax.management.ObjectName", "Parser: ObjectName of the MBean used to customized HTML pages generated by the HtmlAdaptorServer.", true, true, false); this.dattributes[7] = new MBeanAttributeInfo("Port", "int", "Port: Port number used.", true, true, false); this.dattributes[8] = new MBeanAttributeInfo("Protocol", "java.lang.String", "Protocol: html.", true, false, false); this.dattributes[9] = new MBeanAttributeInfo("ServedClientCount", "int", "ServedClientCount: The number of clients that have been processed by the HtmlAdaptorServer since its creation.", true, false, false); this.dattributes[10] = new MBeanAttributeInfo("State", "int", "State: State of the HtmlAdaptorServer.", true, false, false); this.dattributes[11] = new MBeanAttributeInfo("StateString", "java.lang.String", "StateString: State of the HtmlAdaptorServer.", true, false, false); Constructor[] arrayOfConstructor = getClass().getConstructors(); for (int i = 0; i < arrayOfConstructor.length; i++) { if (arrayOfConstructor[i].getParameterTypes().length == 0) this.dconstructors[0] = new MBeanConstructorInfo("Instantiate HtmlAdaptorServer with default port number equal to 8082.", arrayOfConstructor[i]); else if (arrayOfConstructor[i].getParameterTypes().length == 1) this.dconstructors[1] = new MBeanConstructorInfo("Instantiate HtmlAdaptorServer with the specified port number.", arrayOfConstructor[i]); else { this.dconstructors[2] = new MBeanConstructorInfo("Instantiate HtmlAdaptorServer with the specified port number and user authentication information list.", arrayOfConstructor[i]); } } this.doperations[0] = new MBeanOperationInfo("start", "start: Start the HtmlAdaptorServer.", null, "void", 1); this.doperations[1] = new MBeanOperationInfo("stop", "stop: Stop the HtmlAdaptorServer.", null, "void", 1); MBeanParameterInfo[] arrayOfMBeanParameterInfo1 = new MBeanParameterInfo[2]; arrayOfMBeanParameterInfo1[0] = new MBeanParameterInfo("state", "int", "state: The state to wait for."); arrayOfMBeanParameterInfo1[1] = new MBeanParameterInfo("timeout", "long", "timeout: The maximum time to wait in milliseconds."); this.doperations[2] = new MBeanOperationInfo("waitState", "waitState: Waits to be notified of a specific state change in the HtmlAdaptorServer.", arrayOfMBeanParameterInfo1, "boolean", 1); MBeanParameterInfo[] arrayOfMBeanParameterInfo2 = new MBeanParameterInfo[3]; arrayOfMBeanParameterInfo2[0] = new MBeanParameterInfo("className", "java.lang.String", "class name: The name of the class used to parse HTML page."); arrayOfMBeanParameterInfo2[1] = new MBeanParameterInfo("objectName", "java.lang.String", "object name: The name of the MBean to register in the MBeanServer."); arrayOfMBeanParameterInfo2[2] = new MBeanParameterInfo("classLoaderName", "java.lang.String", "class loader name: The ObjectName of the MBean to use as class loader, if it is empty, the default agent class loader will be used by the MBeanServer."); this.doperations[3] = new MBeanOperationInfo("createParser", "createParser: Create, Register to the MBeanServer and set Parser attribute with the HTML parser MBean", arrayOfMBeanParameterInfo2, "void", 1); this.doperations[4] = new MBeanOperationInfo("resetParser", "resetParser: Remove the customization from HtmlAdaptorServer by reseting the Parser property to null.", null, "void", 1); this.dmbeaninfo = new MBeanInfo(this.dclassName, this.ddescription, this.dattributes, this.dconstructors, this.doperations, new MBeanNotificationInfo[0]); } String makeDebugTag() { return "HtmlAdaptorServer[" + getProtocol() + ":" + getPort() + "]"; } }
com.sun.jdmk.comm.HtmlRequestHandler(包名不能改)
package com.sun.jdmk.comm; import java.io.EOFException; import java.io.IOException; import java.io.InterruptedIOException; import java.net.Socket; import java.net.SocketException; import java.util.Date; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.ReflectionException; public class HtmlRequestHandler extends ClientHandler { private Socket sockClient = null; private String bgPageColor = null; private static final String InterruptSysCallMsg = "Interrupted system call"; public HtmlRequestHandler(Socket paramSocket, HtmlAdaptorServerExt paramHtmlAdaptorServer, MBeanServer paramMBeanServer, ObjectName paramObjectName, int paramInt) { super(paramHtmlAdaptorServer, paramInt, paramMBeanServer, paramObjectName); this.sockClient = paramSocket; this.thread.start(); } public Socket getSockClient() { return sockClient; } public void doRun() { if (isTraceOn()) { trace("doRun", "Start Html request handler"); } try { HttpRequest localHttpRequest = new HttpRequest(new HttpBody()); int i = 1; while (i != 0) { HttpResponse localHttpResponse = null; try { localHttpRequest.readFrom(this.sockClient.getInputStream()); localHttpResponse = processRequest(localHttpRequest); } catch (MalformedHttpException localMalformedHttpException) { if (isDebugOn()) { debug("doRun", "Malformed HTTP request rejected. [Exception=" + localMalformedHttpException + "]"); } localHttpResponse = makeErrorResponse(400); } localHttpResponse.writeTo(this.sockClient.getOutputStream()); i = (localHttpRequest.hasKeepAliveFlag()) && (localHttpResponse.statusCode == 200) && (!this.interruptCalled) ? 1 : 0; } } catch (InterruptedIOException localInterruptedIOException) { if (isDebugOn()) debug("doRun", "Request handler interrupted"); } catch (EOFException localEOFException) { if (isDebugOn()) debug("doRun", "Connection closed by peer"); } catch (SocketException localSocketException) { if (localSocketException.getMessage().equals("Interrupted system call")) { if (isDebugOn()) { debug("doRun", "Request handler interrupted"); } } else if (isDebugOn()) debug("doRun", "I/O exception. [Exception=" + localSocketException + "]"); } catch (IOException localIOException1) { if (isDebugOn()) debug("doRun", "I/O exception. [Exception=" + localIOException1 + "]"); } finally { try { this.sockClient.close(); if (isDebugOn()) debug("doRun", "Socket is now closed"); } catch (IOException localIOException2) { if (isDebugOn()) debug("doRun", "Socket closed with [Exception=" + localIOException2 + "]"); } } } protected HttpResponse processRequest(HttpRequest paramHttpRequest) throws IOException { if (isTraceOn()) { trace("processRequest", "Process the Html request"); } HttpResponse localHttpResponse = null; if (!authenticateRequest(paramHttpRequest)) { if (isTraceOn()) { trace("processRequest", "Authentication failed"); } localHttpResponse = makeErrorResponse(401); } else if (paramHttpRequest.method == 1) { localHttpResponse = processGetRequest(paramHttpRequest); } else { if (isTraceOn()) { trace("processRequest", "Bad request: request not supported"); } localHttpResponse = makeErrorResponse(400); } localHttpResponse.setHeader(3, paramHttpRequest.getHeader(3)); return localHttpResponse; } protected boolean authenticateRequest(HttpRequest paramHttpRequest) throws IOException {return true;} protected HttpResponse processGetRequest(HttpRequest paramHttpRequest) throws IOException { String str1 = paramHttpRequest.getURIPath(); int i = 200; String str2 = null; HtmlAdaptorServer localHtmlAdaptorServer = (HtmlAdaptorServer)this.adaptorServer; Object localObject1 = null; if (isTraceOn()) trace("processGetRequest", "Process a GET request = " + str1); Object localObject2; Object localObject4; String str7; if (localHtmlAdaptorServer.getParser() != null) { localObject2 = new String[1]; ((String[])localObject2)[0] = str1; localObject4 = new String[1]; ((String[])localObject4)[0] = "java.lang.String"; try { str2 = (String)this.mbs.invoke(localHtmlAdaptorServer.getParser(), "parseRequest", (String[])localObject2, (String[])localObject4);//invoke(localHtmlAdaptorServer.getParser(), "parseRequest", localObject2, localObject4); } catch (InstanceNotFoundException localInstanceNotFoundException1) { if (isDebugOn()) { debug("processGetRequest", "Invalid user's parser = " + localInstanceNotFoundException1); } String str4 = "Instance Not Found<P>Invalid user's parser: " + localHtmlAdaptorServer.getParser().toString() + " is unknown"; localHtmlAdaptorServer.resetParser(); return makeErrorResponse(459, str4); } catch (MBeanException localMBeanException1) { if (isDebugOn()) { debug("processGetRequest", "Parser exception = " + localMBeanException1.getTargetException()); } String str6 = "MBean Failure<P>" + localHtmlAdaptorServer.getParser().toString() + " throws <BR>" + localMBeanException1.getTargetException(); localHtmlAdaptorServer.resetParser(); return makeErrorResponse(472, str6); } catch (ReflectionException localReflectionException1) { if (isDebugOn()) { debug("processGetRequest", "MBeanServer reflection exception = " + localReflectionException1.getTargetException()); } str7 = "Reflection<P>MBeanServer throws:<BR>" + localReflectionException1.getTargetException() + "<BR> when reflecting: " + localHtmlAdaptorServer.getParser().toString(); localHtmlAdaptorServer.resetParser(); return makeErrorResponse(470, str7); } if (str2 != null); } else { String str5; Object localObject6; Object localObject3; Object localObject5; if (str1.startsWith("/Request/")) { localObject2 = str1.substring(9); if (((String)localObject2).equals("getDomain")) str2 = this.mbs.getDefaultDomain() + ":"; else { i = 400; } } else if (str1.startsWith("/ViewObjectRes")) { localObject2 = str1.substring("/ViewObjectRes".length()); localObject4 = new HtmlObjectPage(this.mbs, true, true, localHtmlAdaptorServer); ((HtmlObjectPage)localObject4).buildPage((String)localObject2); str2 = ((HtmlObjectPage)localObject4).getPage(); } else if (str1.startsWith("/AutoRefresh")) { localObject2 = str1.substring("/AutoRefresh".length()); localObject4 = new HtmlObjectPage(this.mbs, true, true, localHtmlAdaptorServer); ((HtmlObjectPage)localObject4).buildMeta((String)localObject2); ((HtmlObjectPage)localObject4).buildPage(((String)localObject2).substring(0, ((String)localObject2).indexOf("?period="))); str2 = ((HtmlObjectPage)localObject4).getPage(); } else if (str1.startsWith("/ViewProperty")) { localObject2 = str1.substring("/ViewProperty".length()); localObject4 = new HtmlArrayPage(this.mbs, true, true, localHtmlAdaptorServer); ((HtmlArrayPage)localObject4).buildPage((String)localObject2); str2 = ((HtmlArrayPage)localObject4).getPage(); } else if (str1.startsWith("/SetForm")) { str5 = str1.substring("/SetForm".length()); int k = str5.indexOf('/', 1); int j = str5.indexOf('?'); if ((k < 0) || (j < 0)) { i = 400; } else { String str3 = str5.substring(j); str5 = str5.substring(0, j); localObject6 = new HtmlObjectPage(this.mbs, true, true, localHtmlAdaptorServer); if (isTraceOn()) { trace("processGetRequest", "SetForm for [objName=" + str5 + " ,request=" + str3 + "]"); } if (!((HtmlObjectPage)localObject6).setObjectValue(str5, str3)) { str2 = ((HtmlObjectPage)localObject6).getPage(); } else { ((HtmlObjectPage)localObject6).buildPage(str5); str2 = ((HtmlObjectPage)localObject6).getPage(); } } } else if (str1.startsWith("/Admin")) { localObject3 = str1.substring("/Admin".length()); localObject3 = ((String)localObject3).trim(); localObject5 = new HtmlAdminPage(this.mbs, true, true); ((HtmlAdminPage)localObject5).buildPage((String)localObject3); str2 = ((HtmlAdminPage)localObject5).getPage(); } else if (str1.startsWith("/InvokeAction")) { localObject3 = str1.substring("/InvokeAction".length()); localObject3 = ((String)localObject3).trim(); localObject5 = new HtmlInvokePage(this.mbs, true, true); ((HtmlInvokePage)localObject5).buildPage((String)localObject3); str2 = ((HtmlInvokePage)localObject5).getPage(); } else if ((str1.equals("/")) || (str1.startsWith("/Filter"))) { localObject3 = new HtmlMasterPage(this.mbs, true, true); ((HtmlMasterPage)localObject3).buildPage(str1); str2 = ((HtmlMasterPage)localObject3).getPage(); } else { i = 400; } if (localHtmlAdaptorServer.getParser() != null) { localObject3 = new String[1]; ((String[])localObject3)[0]= str2;//((String[])localObject2) localObject5 = new String[1]; ((String[])localObject5)[0] = "java.lang.String"; try { str2 = (String)this.mbs.invoke (localHtmlAdaptorServer.getParser(), "parsePage",(String[]) localObject3, (String[])localObject5); } catch (InstanceNotFoundException localInstanceNotFoundException2) { if (isDebugOn()) { debug("processGetRequest", "Invalid user's parser [" + localInstanceNotFoundException2 + "]"); } str5 = "Instance Not Found<P>Invalid user's parser: " + localHtmlAdaptorServer.getParser().toString() + " is unknown"; localHtmlAdaptorServer.resetParser(); return makeErrorResponse(459, str5); } catch (MBeanException localMBeanException2) { if (isDebugOn()) { debug("processGetRequest", "Parser exception = " + localMBeanException2.getTargetException()); } localObject6 = "MBean Failure<P>" + localHtmlAdaptorServer.getParser().toString() + " throws <BR>" + localMBeanException2.getTargetException(); localHtmlAdaptorServer.resetParser(); return makeErrorResponse(472, (String)localObject6); } catch (ReflectionException localReflectionException2) { if (isDebugOn()) { debug("processGetRequest", "MBeanServer reflection exception = " + localReflectionException2.getTargetException()); } str7 = "Reflection<P>MBeanServer throws:<BR>" + localReflectionException2.getTargetException() + "<BR> when reflecting: " + localHtmlAdaptorServer.getParser().toString(); localHtmlAdaptorServer.resetParser(); return makeErrorResponse(470, str7); } } } if ((str2 != null) && (i == 200)) { return makeOkResponse(str2); } if (isDebugOn()) { debug("processGetRequest", "Bad request: request not supported or HTML page empty"); } return (HttpResponse)(HttpResponse)(HttpResponse)(HttpResponse)(HttpResponse)makeErrorResponse(400); } protected HttpResponse makeErrorResponse(int paramInt) { return makeErrorResponse(paramInt, null); } protected HttpResponse makeErrorResponse(int paramInt, String paramString) { String str1 = "<HTML>\r\n<BODY>\r\n<HR><P><FONT SIZE=+3 COLOR=red><B>" + paramInt + "</B></FONT><P>" + "\r\n" + "<HR><P>" + paramString + "</P>" + "\r\n" + "</BODY>" + "\r\n" + "</HTML>" + "\r\n"; HttpResponse localHttpResponse = new HttpResponse(new HttpBody(str1.getBytes())); localHttpResponse.statusCode = paramInt; localHttpResponse.setHeader(1, "text/html"); localHttpResponse.setHeader(2, new Date().toString()); String str2 = paramInt == 401 ? "Basic realm=\"JDMK\"" : null; localHttpResponse.setHeader(4, str2); return localHttpResponse; } protected HttpResponse makeOkResponse(String paramString) { HttpBody localHttpBody = new HttpBody(paramString.getBytes()); HttpResponse localHttpResponse = new HttpResponse(localHttpBody); localHttpResponse.statusCode = 200; localHttpResponse.setHeader(1, "text/html"); localHttpResponse.setHeader(2, new Date().toString()); return localHttpResponse; } protected String makeDebugTag() { return "HtmlRequestHandler[" + this.adaptorServer.getProtocol() + ":" + this.adaptorServer.getPort() + "][" + this.requestId + "]"; } }
com.sun.jdmk.comm.HtmlRequestHandlerExt (包名不能换)
package com.sun.jdmk.comm; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InterruptedIOException; import java.net.Socket; import java.net.SocketException; import javax.management.MBeanServer; import javax.management.ObjectName; public class HtmlRequestHandlerExt extends HtmlRequestHandler { public HtmlRequestHandlerExt(Socket arg0, HtmlAdaptorServerExt arg1, MBeanServer arg2, ObjectName arg3, int arg4) { super(arg0, arg1, arg2, arg3, arg4); // TODO Auto-generated constructor stub } public void textTotextArea(HttpResponse localHttpResponse){ try { String content=new String(localHttpResponse.getContentBytes(),"UTF-8"); String resString= content.replaceAll("<TD><INPUT TYPE=\"text\"", "<TD><TEXTAREA "); resString=resString.replaceAll("SIZE=50%></TD>", "SIZE=50%></TEXTAREA></TD>"); byte[] contentByte=resString.getBytes("UTF-8"); localHttpResponse.readBodyFrom(new ByteArrayInputStream(contentByte),contentByte.length); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doRun() { if (isTraceOn()) { trace("doRun", "Start Html request handler"); } try { HttpRequest localHttpRequest = new HttpRequest(new HttpBody()); int i = 1; while (i != 0) { HttpResponse localHttpResponse = null; try { localHttpRequest.readFrom(this .getSockClient().getInputStream()); localHttpResponse = processRequest(localHttpRequest); } catch (MalformedHttpException localMalformedHttpException) { if (isDebugOn()) { debug("doRun", "Malformed HTTP request rejected. [Exception=" + localMalformedHttpException + "]"); } localHttpResponse = makeErrorResponse(400); } textTotextArea(localHttpResponse); localHttpResponse.writeTo(this.getSockClient().getOutputStream()); i = (localHttpRequest.hasKeepAliveFlag()) && (localHttpResponse.statusCode == 200) && (!this.interruptCalled) ? 1 : 0; } } catch (InterruptedIOException localInterruptedIOException) { if (isDebugOn()) debug("doRun", "Request handler interrupted"); } catch (EOFException localEOFException) { if (isDebugOn()) debug("doRun", "Connection closed by peer"); } catch (SocketException localSocketException) { if (localSocketException.getMessage().equals("Interrupted system call")) { if (isDebugOn()) { debug("doRun", "Request handler interrupted"); } } else if (isDebugOn()) debug("doRun", "I/O exception. [Exception=" + localSocketException + "]"); } catch (IOException localIOException1) { if (isDebugOn()) debug("doRun", "I/O exception. [Exception=" + localIOException1 + "]"); } finally { try { this.getSockClient().close(); if (isDebugOn()) debug("doRun", "Socket is now closed"); } catch (IOException localIOException2) { if (isDebugOn()) debug("doRun", "Socket closed with [Exception=" + localIOException2 + "]"); } } } }
这四个类的代码我都放在附件里面了,导进去。然后配置一下spring的xml就可以了。xml配置在在上面。