mc4j-cvs Mailing List for MC4J JMX Console (Page 8)
Brought to you by:
ghinkl
You can subscribe to this list here.
2004 |
Jan
|
Feb
|
Mar
(7) |
Apr
(135) |
May
(32) |
Jun
(34) |
Jul
|
Aug
|
Sep
(7) |
Oct
(139) |
Nov
(11) |
Dec
(5) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2005 |
Jan
(34) |
Feb
(1) |
Mar
(12) |
Apr
|
May
(87) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(27) |
Nov
(49) |
Dec
(13) |
2006 |
Jan
|
Feb
|
Mar
|
Apr
(252) |
May
(16) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(1) |
Sep
|
Oct
|
Nov
|
Dec
|
2008 |
Jan
|
Feb
|
Mar
(2) |
Apr
(2) |
May
|
Jun
|
Jul
(1) |
Aug
|
Sep
(3) |
Oct
|
Nov
(1) |
Dec
|
2009 |
Jan
|
Feb
|
Mar
(1) |
Apr
|
May
(1) |
Jun
(2) |
Jul
(15) |
Aug
(1) |
Sep
|
Oct
|
Nov
|
Dec
|
2010 |
Jan
|
Feb
(2) |
Mar
|
Apr
|
May
|
Jun
|
Jul
(3) |
Aug
(6) |
Sep
(1) |
Oct
|
Nov
|
Dec
|
2011 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(2) |
Oct
(1) |
Nov
|
Dec
|
From: Greg H. <gh...@us...> - 2006-04-12 19:14:01
|
Update of /cvsroot/mc4j/mc4j/application/dist In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20162/application/dist Added Files: ide.policy module_manifest.mf manifest.mf Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: manifest.mf --- Manifest-Version: 1.0 Class-Path: animation-1.1.3.jar javax77.jar jcommon-0.9.3.jar jdnc-0_6-all.jar jfreechart-0.9.18.jar log4j-1.2.8.jar utilConcurrent1.3.2.jar zql.jar Specified-By: org/mc4j/console/mc4j.jarContent OpenIDE-Module-Layer: org/mc4j/console/mf-layer.xml OpenIDE-Module-Name: MC4J Management Console OpenIDE-Module-Short-Description: MC4J - Remote JMX Management OpenIDE-Module-Implementation-Version: 1.0.12 OpenIDE-Module-Long-Description: The MC4J module supports remote manag ement of JMX compliant services. Created-By: NetBeans OpenIDE-Module-Specification-Version: 1.0.12 OpenIDE-Module-Display-Category: Infrastructure OpenIDE-Module: org.mc4j.console Name: org/mc4j/console/ManagementNode.class OpenIDE-Module-Class: Node Type: roots --- NEW FILE: module_manifest.mf --- Manifest-Version: 1.0 Class-Path: ext/org-mc4j-ems.jar ext/ognl-2.6.7.jar ext/swingx.jar ext/forms-1.0.5.jar ext/commons-logging.jar ext/animation-1.1.3.jar ext/javax77.jar ext/jcommon-1.0.0.jar ext/jfreechart-1.0.1.jar ext/log4j-1.2.8.jar ext/utilConcurrent1.3.2.jar ext/zql.jar OpenIDE-Module-Long-Description: The MC4J JMX Management Tool OpenIDE-Module-Name: MC4J Management Console OpenIDE-Module-Display-Category: Infrastructure Created-By: NetBeans OpenIDE-Module-Specification-Version: 1.3.0 OpenIDE-Module-IDE-Dependencies: IDE/1 > 4.43 OpenIDE-Module-Module-Dependencies: org.netbeans.core/2 > 3.1, org.openide.loaders, org.openide.io, org.netbeans.core.output2/1 OpenIDE-Module-Requires: org.openide.modules.InstalledFileLocator OpenIDE-Module: org.mc4j.console OpenIDE-Module-Short-Description: MC4J - Remote JMX Management OpenIDE-Module-Implementation-Version: 1.4.0 OpenIDE-Module-Layer: org/mc4j/console/mc4j-mf-layer.xml OpenIDE-Module-Public-Packages: - --- NEW FILE: ide.policy --- grant { permission java.security.AllPermission; }; |
From: Greg H. <gh...@us...> - 2006-04-12 19:13:30
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/connection/settings In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/connection/settings Added Files: ConnectionSettings.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: ConnectionSettings.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.settings; import org.mc4j.ems.connection.support.metadata.ConnectionTypeDescriptor; import java.io.File; import java.io.ObjectStreamField; import java.io.Serializable; import java.util.List; import java.util.Properties; import java.util.Map; /** * Options for connections * * @author Greg Hinkle (gh...@us...), January 2002 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:34 $) */ public class ConnectionSettings implements Serializable, Comparable { private ConnectionTypeDescriptor connectionType; private String connectionName; private String jndiName; private String initialContextName; private String serverUrl; private String principal; private String credentials; private Properties advancedProperties; private Properties controlProperties = new Properties(); private boolean autoConnect; private boolean liveTree; private String libraryURI; /** * Holds value of property classPathEntries. */ private List<File> classPathEntries; /** * Version -1371536502434280115L: MC4J 1.2bx * Version 2: 1.3 */ private static final long serialVersionUID = 3; private static final ObjectStreamField[] serialPersistentFields = { new java.io.ObjectStreamField("autoConnect", boolean.class), new java.io.ObjectStreamField("liveTree", boolean.class), new java.io.ObjectStreamField("classPathEntries", java.io.File[].class), new java.io.ObjectStreamField("connectionName", java.lang.String.class), new java.io.ObjectStreamField("connectionType", ConnectionTypeDescriptor.class), new java.io.ObjectStreamField("credentials", java.lang.String.class), new java.io.ObjectStreamField("initialContextName", java.lang.String.class), new java.io.ObjectStreamField("jndiName", java.lang.String.class), new java.io.ObjectStreamField("libraryURI", java.lang.String.class), new java.io.ObjectStreamField("principal", java.lang.String.class), new java.io.ObjectStreamField("serverUrl", java.lang.String.class), new java.io.ObjectStreamField("advancedProperties", Properties.class), new java.io.ObjectStreamField("controlProperties", Properties.class)}; public boolean equals(Object object) { boolean result = false; if (object instanceof ConnectionSettings) { ConnectionSettings that = (ConnectionSettings) object; if ((that.getConnectionName().equals(this.getConnectionName())) && (that.getServerUrl().equals(this.getServerUrl()))) { result = true; } } return result; } /** * Getter for property connectionType. * * @return Value of property connectionType. */ public ConnectionTypeDescriptor getConnectionType() { return connectionType; } public void initializeConnectionType(ConnectionTypeDescriptor connectionTypeDescriptor) { this.connectionType = connectionTypeDescriptor; this.advancedProperties = connectionType.getDefaultAdvancedProperties(); this.initialContextName = connectionType.getDefaultInitialContext(); this.serverUrl = connectionType.getDefaultServerUrl(); this.jndiName = connectionType.getDefaultJndiName(); } /** * Setter for property connectionType. * * @param connectionType New value of property connectionType. */ public void setConnectionType(ConnectionTypeDescriptor connectionType) { this.connectionType = connectionType; } /** * Getter for property credentials. * * @return Value of property credentials. */ public String getCredentials() { return credentials; } /** * Setter for property credentials. * * @param credentials New value of property credentials. */ public void setCredentials(String credentials) { this.credentials = credentials; } /** * Getter for property initialContextName. * * @return Value of property initialContextName. */ public String getInitialContextName() { return initialContextName; } /** * Setter for property initialContextName. * * @param initialContextName New value of property initialContextName. */ public void setInitialContextName(String initialContextName) { this.initialContextName = initialContextName; } /** * Getter for property jndiName. * * @return Value of property jndiName. */ public String getJndiName() { return jndiName; } /** * Setter for property jndiName. * * @param jndiName New value of property jndiName. */ public void setJndiName(String jndiName) { this.jndiName = jndiName; } /** * Getter for property name. * * @return Value of property name. */ public String getConnectionName() { return this.connectionName; } /** * Setter for property name. * * @param connectionName New value of property name. */ public void setConnectionName(String connectionName) { this.connectionName = connectionName; } /** * Getter for property principal. * * @return Value of property principal. */ public String getPrincipal() { return principal; } /** * Setter for property principal. * * @param principal New value of property principal. */ public void setPrincipal(String principal) { this.principal = principal; } /** * Getter for property serverUrl. * * @return Value of property serverUrl. */ public String getServerUrl() { return serverUrl; } /** * Setter for property serverUrl. * * @param serverUrl New value of property serverUrl. */ public void setServerUrl(String serverUrl) { this.serverUrl = serverUrl; } /** * Getter for property autoConnect. * * @return Value of property autoConnect. */ public boolean isAutoConnect() { return autoConnect; } /** * Setter for property autoConnect. * * @param autoConnect New value of property autoConnect. */ public void setAutoConnect(boolean autoConnect) { this.autoConnect = autoConnect; } /** * Getter for property liveTree. * * @return Value of property liveTree. */ public boolean isLiveTree() { return liveTree; } /** * Setter for property liveTree. * * @param liveTree New value of property liveTree. */ public void setLiveTree(boolean liveTree) { this.liveTree = liveTree; } /** * The installation path (on disk) for the server to be * connected to. Setting this allows you to utilize the connection * factory to find the classpath libraries needed to make the connection. */ public String getLibraryURI() { return this.libraryURI; } public void setLibraryURI(String libraryURI) { this.libraryURI = libraryURI; } /** * Getter for property classPathEntries. * * @return Value of property classPathEntries. */ public List<File> getClassPathEntries() { return this.classPathEntries; } /** * Setter for property classPathEntries. * * @param classPathEntries New value of property classPathEntries. */ public void setClassPathEntries(List<File> classPathEntries) { this.classPathEntries = classPathEntries; } public Properties getAdvancedProperties() { return advancedProperties; } public void setAdvancedProperties(Properties advancedProperties) { this.advancedProperties = advancedProperties; } public int compareTo(Object o) { return getConnectionName().compareTo(((ConnectionSettings)o).getConnectionName()); } public Properties getControlProperties() { return controlProperties; } public void setControlProperties(Properties controlProperties) { this.controlProperties = controlProperties; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("EmsConnection ["); buf.append(connectionType.getConnectionType()); buf.append("]\n\tInitial Context = "); buf.append(initialContextName); buf.append("\n\tJNDI Name = "); buf.append(jndiName); buf.append("\n\tServer URL = "); buf.append(serverUrl); buf.append("\n\tPrinciple = "); buf.append(principal); buf.append("\n\tCredentials = "); buf.append(credentials); for (Map.Entry entry : advancedProperties.entrySet()) { buf.append("\n\t Advanced Property ["); buf.append(entry.getKey()); buf.append("] = "); buf.append(entry.getValue()); } return buf.toString(); } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:59
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/test/org/mc4j/ems/test/beans In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/test/org/mc4j/ems/test/beans Added Files: BeanTest.java MyTestBean.java MyTestBeanMBean.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: BeanTest.java --- /* * Copyright 2002-2005 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.test.beans; import org.mc4j.ems.connection.ConnectionFactory; import org.mc4j.ems.connection.EmsConnection; import org.mc4j.ems.connection.bean.EmsBean; import org.mc4j.ems.connection.bean.notification.EmsNotification; import org.mc4j.ems.connection.bean.notification.EmsNotificationListener; import org.mc4j.ems.connection.bean.notification.EmsNotificationEvent; import org.mc4j.ems.connection.bean.attribute.EmsAttribute; import org.mc4j.ems.connection.settings.ConnectionSettings; import org.mc4j.ems.connection.support.metadata.J2SE5ConnectionTypeDescriptor; import org.testng.annotations.Configuration; import org.testng.annotations.Test; import javax.management.ObjectName; import java.util.SortedSet; import java.util.List; import java.util.ArrayList; /** * @author Greg Hinkle (gh...@us...), Nov 11, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:34 $) */ public class BeanTest { EmsConnection connection; EmsBean testBean; String name; MyTestBeanMBean proxy; String testMBeanName = "ems.test:type=test,name=MyTestMBean"; @Configuration(beforeTestClass = true) public void setup() { System.out.println("Here"); ConnectionSettings settings = new ConnectionSettings(); settings.initializeConnectionType(new J2SE5ConnectionTypeDescriptor()); settings.setServerUrl("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi"); ConnectionFactory factory = new ConnectionFactory(); connection = factory.connect(settings); connection.loadSynchronous(true); } @Test(groups = "functest") public void testRegistration() throws ClassNotFoundException { testBean = connection.registerBean(MyTestBean.class.getName(), testMBeanName); name = testBean.getBeanName().toString(); } @Test(dependsOnMethods = {"testRegistration"}) public void testLookup() { EmsBean bean = connection.getBean(name); assert bean != null; // Found bean? ObjectName o; bean = connection.getBean(testMBeanName); assert bean != null; } @Test(dependsOnMethods = {"testRegistration"}) public void testProxy() throws ClassNotFoundException { Object obj = testBean.getProxy(MyTestBeanMBean.class); assert obj instanceof MyTestBeanMBean; proxy = (MyTestBeanMBean) obj; String msgVal = (String) testBean.getAttribute("message").refresh(); assert proxy.getMessage().equals(msgVal); } @Test(dependsOnMethods = {"testRegistration"}) public void testAttributes() throws Exception { SortedSet<EmsAttribute> attributes = testBean.getAttributes(); System.out.println("Attributes found: " + attributes.size()); // assert attributes.size() == 3; EmsAttribute msgAttr = testBean.getAttribute("message"); assert msgAttr != null; Class typeClass = msgAttr.getTypeClass(); assert typeClass.equals(String.class); // Try refreshing assert msgAttr.refresh().equals(MyTestBeanMBean.DEFAULT_MESSAGE); msgAttr.setValue("New Value"); assert msgAttr.getValue().equals("New Value"); } @Test(dependsOnMethods = {"testRegistration", "testProxy"}) public void testNotifications() throws InterruptedException { SortedSet<EmsNotification> notifications = testBean.getNotifications(); for (EmsNotification notification : notifications) { System.out.println(notification.getName()); } final List<EmsNotificationEvent> recievedEvents = new ArrayList<EmsNotificationEvent>(); EmsNotification notification = testBean.getNotification("attributeChange"); notification.addNotificationListener(new EmsNotificationListener() { public void handleNotification(EmsNotificationEvent event) { recievedEvents.add(event); System.out.println("Notification received: " + event.toString()); } }); notification.startListening(); proxy.setMessage("New Message"); Thread.sleep(500); assert recievedEvents.size() == 1; EmsNotificationEvent event = recievedEvents.get(0); assert event.getBean() == testBean; } } --- NEW FILE: MyTestBean.java --- /* * Copyright 2002-2005 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.test.beans; import javax.management.NotificationBroadcasterSupport; import javax.management.AttributeChangeNotification; import javax.management.MBeanNotificationInfo; /** * @author Greg Hinkle (gh...@us...), Nov 10, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:34 $) */ public class MyTestBean extends NotificationBroadcasterSupport implements MyTestBeanMBean { private String message = DEFAULT_MESSAGE; private long number = 1L; private long sequenceNumber = 0L; public String getMessage() { return message; } public void setMessage(String message) { sendNotification( new AttributeChangeNotification(this, sequenceNumber++, System.currentTimeMillis(), "Attribute changed", "message", "String", this.message, message)); this.message = message; } public Long getNumber() { sendNotification( new AttributeChangeNotification(this, sequenceNumber++, System.currentTimeMillis(), "Attribute changed", "number", "Long", this.number, number)); return number; } public void setNumber(Long number) { this.number = number; } public MBeanNotificationInfo[] getNotificationInfo() { return new MBeanNotificationInfo[] { new MBeanNotificationInfo(new String[] {"custom.event"},"event","A special custom evemt"), new MBeanNotificationInfo(new String[] {AttributeChangeNotification.ATTRIBUTE_CHANGE},"attributeChange","An attribute changed") }; } } --- NEW FILE: MyTestBeanMBean.java --- /* * Copyright 2002-2005 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.test.beans; import javax.management.NotificationBroadcaster; /** * @author Greg Hinkle (gh...@us...), Nov 10, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:34 $) */ public interface MyTestBeanMBean extends NotificationBroadcaster { public static final String DEFAULT_MESSAGE = "Hello, World!"; String getMessage(); void setMessage(String message); Long getNumber(); void setNumber(Long number); } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:50
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/connection/support/classloader/deepjar In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/connection/support/classloader/deepjar Added Files: Handler.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: Handler.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.classloader.deepjar; import org.mc4j.ems.connection.support.classloader.NestedJarClassLoader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.net.URLStreamHandler; import java.net.URLConnection; import java.net.URL; import java.io.IOException; import java.io.InputStream; /** * @author Greg Hinkle (gh...@us...), May 9, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class Handler extends URLStreamHandler { private static Log log = LogFactory.getLog(Handler.class); static { log.debug("Deepjar handler initialized"); } ClassLoader parent; public Handler(ClassLoader parent) { this.parent = parent; } public Handler() { super(); } public static String PROTOCOL = "deepjar"; protected static int PROTOCOL_LENGTH = PROTOCOL.length()+3; /** * @see java.net.URLStreamHandler#openConnection(java.net.URL) */ protected URLConnection openConnection(final URL u) throws IOException { log.debug("Deepjar handler is opening " + u); final String resource = u.toString().substring(PROTOCOL_LENGTH); return new URLConnection(u) { public void connect() { } public InputStream getInputStream() { ClassLoader parent = NestedJarClassLoader.getRunningLoader(u); return parent.getResourceAsStream(resource); } }; } } |
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/connection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/connection Added Files: EmsInvocationException.java Refreshable.java MBeanRegistrationEvent.java EmsMalformedObjectNameException.java ConnectionFactory.java EmsConnection.java LoadException.java MBeanRegistrationListener.java ConnectionTracker.java ConnectionException.java EmsConnectException.java EmsException.java UpdateException.java EmsConnectionContext.java EmsBeanNotFoundException.java EmsUnsupportedTypeException.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: EmsInvocationException.java --- /* * Copyright 2002-2005 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; /** * @author Greg Hinkle (gh...@us...), Nov 11, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class EmsInvocationException extends EmsException { public EmsInvocationException(String message) { super(message); } public EmsInvocationException(String message, Throwable cause) { super(message, cause); } } --- NEW FILE: Refreshable.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; /** * @author Greg Hinkle (gh...@us...), Apr 14, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public interface Refreshable { void refresh(); } --- NEW FILE: EmsUnsupportedTypeException.java --- /* * Copyright 2002-2005 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; /** * @author Greg Hinkle (gh...@us...), Nov 11, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class EmsUnsupportedTypeException extends EmsException { public EmsUnsupportedTypeException(String message) { super(message); } public EmsUnsupportedTypeException(String message, Throwable cause) { super(message, cause); } } --- NEW FILE: UpdateException.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; /** * @author Greg Hinkle (gh...@us...), Apr 12, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class UpdateException extends EmsException { public UpdateException(String message) { super(message); } public UpdateException(String message, Throwable cause) { super(message, cause); } } --- NEW FILE: MBeanRegistrationEvent.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; import org.mc4j.ems.connection.bean.EmsBean; import java.util.Set; /** * @author Greg Hinkle (gh...@us...), Apr 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class MBeanRegistrationEvent { private Set<EmsBean> registered; private Set<EmsBean> deregistered; public MBeanRegistrationEvent(Set<EmsBean> registered, Set<EmsBean> deregistered) { this.registered = registered; this.deregistered = deregistered; } public Set<EmsBean> getRegistered() { return registered; } public Set<EmsBean> getDeregistered() { return deregistered; } } --- NEW FILE: EmsException.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; /** * @author Greg Hinkle (gh...@us...), Apr 12, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class EmsException extends RuntimeException { public EmsException(String message) { super(message); } public EmsException(String message, Throwable cause) { super(message, cause); } public EmsException(Throwable cause) { super(cause); } } --- NEW FILE: EmsConnectException.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; /** * @author Greg Hinkle (gh...@us...), Apr 12, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class EmsConnectException extends EmsException { public EmsConnectException(String message) { super(message); } public EmsConnectException(String message, Throwable cause) { super(message, cause); } public EmsConnectException(Throwable cause) { super(cause); } } --- NEW FILE: ConnectionException.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; /** * @author Greg Hinkle (gh...@us...), Apr 12, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class ConnectionException extends EmsException { public ConnectionException(String message) { super(message); } public ConnectionException(String message, Throwable cause) { super(message, cause); } } --- NEW FILE: EmsBeanNotFoundException.java --- /* * Copyright 2002-2005 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; /** * @author Greg Hinkle (gh...@us...), Nov 10, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class EmsBeanNotFoundException extends EmsException { public EmsBeanNotFoundException(String message) { super(message); } public EmsBeanNotFoundException(String message, Throwable cause) { super(message, cause); } } --- NEW FILE: ConnectionTracker.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; /** * @author Greg Hinkle (gh...@us...), Apr 12, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public interface ConnectionTracker { void stopTracker(); void registerUpdateRequest(String objectName, long delay); void removeUpdateRequest(String objectName); } --- NEW FILE: EmsConnection.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; import org.mc4j.ems.connection.bean.EmsBean; import org.mc4j.ems.connection.support.ConnectionProvider; import java.util.List; import java.util.SortedSet; /** * TODO GH: Decide exception handling strategy (runtime?) * * @author Greg Hinkle (gh...@us...), Apr 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public interface EmsConnection extends Refreshable { ConnectionTracker getTracker(); void close(); void loadSynchronous(boolean deep); void addRegistrationListener(MBeanRegistrationListener registrationListener); void removeRegistrationListener(MBeanRegistrationListener registrationListener); /** * This will register a new MBean, but that may not be immediately recognized * @param className * @param objectName */ void createMBean(String className, String objectName) throws EmsException; void removeMBean(String objectName) throws EmsException; SortedSet<EmsBean> getBeans(); EmsBean getBean(String objectName); List<EmsBean> queryBeans(String objectName); EmsBean registerBean(String className, String objectName); EmsBean registerBean(String className, String objectName, Object[] params, String[] signature); /** * * @param objectName * @return * @throws EmsMalformedObjectNameException when an invalid object name is provided */ Object buildObjectName(String objectName) throws EmsMalformedObjectNameException ; /** * * @return * @since 1.0.5 */ long getRoundTrips(); /** * * @return * @since 1.0.5 */ long getFailures(); /** * * @since 1.0.6 * @return */ public ConnectionProvider getConnectionProvider(); } --- NEW FILE: MBeanRegistrationListener.java --- package org.mc4j.ems.connection; import org.mc4j.ems.connection.MBeanRegistrationEvent; /** * @author Greg Hinkle (gh...@us...), Apr 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public interface MBeanRegistrationListener { void registrationChanged(MBeanRegistrationEvent event); } --- NEW FILE: EmsMalformedObjectNameException.java --- /* * Copyright 2002-2005 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; /** * @author Greg Hinkle (gh...@us...), Nov 15, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class EmsMalformedObjectNameException extends EmsException { public EmsMalformedObjectNameException(String message) { super(message); } public EmsMalformedObjectNameException(String message, Throwable cause) { super(message, cause); } } --- NEW FILE: LoadException.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; import org.mc4j.ems.connection.EmsException; /** * @author Greg Hinkle (gh...@us...), Apr 12, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class LoadException extends EmsException { public LoadException(String message) { super(message); } public LoadException(String message, Throwable cause) { super(message, cause); } } --- NEW FILE: EmsConnectionContext.java --- package org.mc4j.ems.connection; /** * @author Greg Hinkle (gh...@us...), May 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public interface EmsConnectionContext { // TODO GH: what values to store in history and how long // TODO GH: Debug level, output of errors? // TODO GH: Read from xml, allow custom mbean lists and detail levels, predefined monitors, rules? } --- NEW FILE: ConnectionFactory.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mc4j.ems.connection.settings.ConnectionSettings; import org.mc4j.ems.connection.support.ConnectionProvider; import org.mc4j.ems.connection.support.classloader.ClassLoaderFactory; import org.mc4j.ems.connection.support.metadata.*; import java.io.File; import java.io.FilenameFilter; import java.io.FileFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author Greg Hinkle (gh...@us...), Apr 5, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class ConnectionFactory { private static final String BROAD_SEARCH_PROPERTY = "mc4j.ems.fileSearchBroad"; private static final int DEFAULT_SEARCH_DEPTH = 6; private static final String SEARCH_DEPTH_PROPERTY = "mc4j.ems.fileSearchDepth"; private boolean broadSearch = false; private int searchDepth = DEFAULT_SEARCH_DEPTH; private static Log log = LogFactory.getLog(ConnectionFactory.class); public static final ConnectionTypeDescriptor[] CONNECTION_DESCRIPTORS = new ConnectionTypeDescriptor[]{ new JBossConnectionTypeDescriptor(), new Tomcat55ConnectionTypeDescriptor(), new JDMKConnectionTypeDescriptor(), new J2SE5ConnectionTypeDescriptor(), new JSR160ConnectionTypeDescriptor(), new GeronimoConnectionTypeDescriptor(), new Mx4jConnectionTypeDescriptor(), new Oc4jConnectionTypeDescriptor(), new PramatiConnectionTypeDescriptor(), new SJSASConnectionTypeDescriptor(), new WeblogicConnectionTypeDescriptor(), new Weblogic9ConnectionTypeDescriptor(), new Weblogic9Jsr77ConnectionTypeDescriptor(), new WebsphereConnectionTypeDescriptor(), new WebsphereStudioConnectionTypeDescriptor()}; // TODO GH: Move to a SPI model allowing new types to be added later? // TODO GH: Perhaps go to a more externalized descriptor based model? public static List<ConnectionTypeDescriptor> getConnectionTypes() { return Arrays.asList(CONNECTION_DESCRIPTORS); } public ConnectionFactory() { if (System.getProperty(BROAD_SEARCH_PROPERTY) != null) { broadSearch = Boolean.valueOf(System.getProperty(BROAD_SEARCH_PROPERTY)); } if (System.getProperty(SEARCH_DEPTH_PROPERTY) != null) { searchDepth = Integer.parseInt(System.getProperty(SEARCH_DEPTH_PROPERTY)); } } public EmsConnection connect(ConnectionSettings connectionSettings) { log.info("Connecting to " + connectionSettings.toString()); String className = connectionSettings.getConnectionType().getConnectionNodeClassName(); try { // TODO GH: Does this need to be configurable per connection? ClassLoader loader = ClassLoaderFactory.getInstance().buildClassLoader(connectionSettings); log.debug("Loading connection class from ClassLoader [" + loader + "] ConnectionProvider class [" + className + "]"); // TODO GH: Add intelligent classloader layer here that can either work // directly against current classloader or build a non-delegating child // to override with connection specific classes Class clazz = Class.forName(className, false, loader); ConnectionProvider connectionProvider = (ConnectionProvider) clazz.newInstance(); connectionProvider.initialize(connectionSettings); return connectionProvider.connect(); } catch (IllegalAccessException e) { throw new ConnectionException("Could not access ConnectionClass", e); } catch (InstantiationException e) { throw new ConnectionException("Could not instantiate ConnectionClass", e); } catch (ClassNotFoundException e) { throw new ConnectionException("Could not find ConnectionClass " + className, e); } } /** * This will find server classes for a ConnectionSettings by using the supplied * LibraryURI of the ConnectionSettings and searching for the ConnectClassPathEntries * of the ConnectionType supplied with the settings. * <p/> * This method should only be called once. If the entries need to be reset, you should * first clear the settings' classpath entries. This method appends class path entries * to the existing list. * * @param connectionSettings the ConnectionSettings to update with recommeneded class * path entries */ public void discoverServerClasses(ConnectionSettings connectionSettings) { if (connectionSettings.getLibraryURI() != null) { long start = System.currentTimeMillis(); String[] serverFiles = connectionSettings.getConnectionType().getConnectionClasspathEntries(); // No server file dependencies if (serverFiles == null) return; File serverInstall = new File(connectionSettings.getLibraryURI()); if (!serverInstall.exists()) throw new LoadException("Supplied server installation does not exist " + connectionSettings.getLibraryURI()); List<File> foundFiles = new ArrayList<File>(); for (String serverFile : serverFiles) { if (broadSearch && serverFile.indexOf('/') >= 0) { serverFile = serverFile.substring(serverFile.lastIndexOf('/')+1); } log.debug("Searching for library " + serverFile); File[] matchedFiles = null; try { if (serverFile.indexOf('/') >= 0) { matchedFiles = findDeepFiles(serverInstall, serverFile); } else { File file = findFile(serverInstall, serverFile); if (file != null) matchedFiles = new File[]{file}; } } catch (Exception e) { log.info("Library dependency not found " + serverFile, e); } if (matchedFiles != null) { for (File matchedFile : matchedFiles) { if (matchedFile != null && !foundFiles.contains(matchedFile)) { foundFiles.add(matchedFile); log.debug("Library dependency resolved " + matchedFile.getAbsolutePath()); } } } else { log.info("Connection library dependancy [" + serverFile+ "] not found in directory: " + serverInstall); } } if (connectionSettings.getClassPathEntries() == null) connectionSettings.setClassPathEntries(foundFiles); else connectionSettings.getClassPathEntries().addAll(foundFiles); log.info("Discovered libraries in " + (System.currentTimeMillis() - start) + " ms"); } } private File findFile(File directory, String filename) { return findFile(directory, filename, 1); } private File findFile(File directory, String filename, int depth) { if (depth > searchDepth) return null; File[] children = directory.listFiles(); if (children == null) return null; for (File child : children) { if (child.isDirectory()) { File result = findFile(child, filename, depth + 1); if (result != null) return result; } else { if (filename.equalsIgnoreCase(child.getName())) return child; } } return null; } private File[] findDeepFiles(File directory, String filename) { if (filename.startsWith("/")) filename = filename.substring(1); int in = filename.indexOf("/"); if (in < 0) { if (filename.equals("*")) { return directory.listFiles(); } else { File match = getChild(directory, filename); if (match == null) return null; else return new File[]{match}; } } else { String dir = filename.substring(0, in); String restOfName = filename.substring(in + 1, filename.length()); if (dir.equals("*")) { File[] children = directory.listFiles(new DirectoryFilter()); if (children != null) { for (File child : children) { File[] childDir = findDeepFiles(child, restOfName); if (childDir != null) { return childDir; } } } log.debug("Could not find " + directory.getAbsolutePath() + " :: " + restOfName); return null; } else { File childDir = getChild(directory, dir); if (childDir == null) { log.debug("Could not find " + directory.getAbsolutePath() + " :: " + restOfName); return null; } else { return findDeepFiles(childDir, restOfName); } } } } private static class DirectoryFilter implements FileFilter { public boolean accept(File pathname) { return pathname.isDirectory(); } } public File getChild(File directory, final String childName) { if (directory == null) return null; if (!directory.exists()) return null; File[] children = directory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return childName.equals(name); } }); if (children.length == 1) { return children[0]; } else { //log.info("Connection library dependancy [" + childName + "] not found in directory: " + directory.getAbsolutePath()); return null; } } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:48
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/connection/bean/parameter In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/connection/bean/parameter Added Files: EmsParameter.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: EmsParameter.java --- package org.mc4j.ems.connection.bean.parameter; /** * Created: Jul 20, 2005 1:16:45 AM * * @author Greg Hinkle (gh...@us...) * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:36 $) */ public interface EmsParameter { String getName(); String getDescription(); String getType(); } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:48
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/connection/bean/attribute In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/connection/bean/attribute Added Files: AttributeChangeListener.java AttributeChangeEvent.java EmsAttribute.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: AttributeChangeListener.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.bean.attribute; /** * @author Greg Hinkle (gh...@us...), Apr 6, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public interface AttributeChangeListener { void attributeChange(AttributeChangeEvent event); } --- NEW FILE: EmsAttribute.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.bean.attribute; import org.mc4j.ems.store.ValueHistory; /** * @author Greg Hinkle (gh...@us...), Apr 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public interface EmsAttribute extends Comparable { /** Default true */ String CONTROL_ATTRIBUTE_HISTORY = "Attribute.history"; /** Default CompleteValueHistory */ String CONTROL_ATTRIBUTE_HISTORY_CLASS = "Attribute.history.class"; /** Default 1 */ String CONTROL_ATTRIBUTE_HISTORY_DEPTH = "Attribute.history.depth"; void registerAttributeChangeListener(AttributeChangeListener listener); Object getValue(); /** * Set the attribute on the server * @param newValue The value to be set * @throws Exception */ void setValue(Object newValue) throws Exception; /** * Alters the internally stored value of this attribute. Does not update the * server value. Is intended for mass load of attribute data via the MBean. * @param newValue */ void alterValue(Object newValue); /** * Updates the local value of this mbean from the server */ Object refresh(); ValueHistory getValueHistory(); String getName(); String getType(); Class getTypeClass(); boolean isNumericType(); String getDescription() ; boolean isReadable(); boolean isWritable(); boolean isSupportedType(); void setSupportedType(boolean supportedType); int getValueSize(); } --- NEW FILE: AttributeChangeEvent.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.bean.attribute; /** * @author Greg Hinkle (gh...@us...), Apr 6, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class AttributeChangeEvent { private EmsAttribute attribute; private Object oldValue; private Object newValue; private long timeOfChange; public AttributeChangeEvent() { } public AttributeChangeEvent(EmsAttribute attribute, Object oldValue, Object newValue) { this.attribute = attribute; this.oldValue = oldValue; this.newValue = newValue; timeOfChange = System.currentTimeMillis(); } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:47
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection Added Files: PooledConnectionTracker.java DConnection.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: DConnection.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mc4j.ems.connection.ConnectionTracker; import org.mc4j.ems.connection.EmsConnection; import org.mc4j.ems.connection.EmsException; import org.mc4j.ems.connection.EmsMalformedObjectNameException; import org.mc4j.ems.connection.EmsUnsupportedTypeException; import org.mc4j.ems.connection.MBeanRegistrationEvent; import org.mc4j.ems.connection.MBeanRegistrationListener; import org.mc4j.ems.connection.bean.EmsBean; import org.mc4j.ems.connection.support.ConnectionProvider; import org.mc4j.ems.impl.jmx.connection.bean.DAdvancedBean; import org.mc4j.ems.impl.jmx.connection.bean.DMBean; import org.mc4j.ems.impl.jmx.connection.support.providers.AbstractConnectionProvider; import javax.management.MBeanException; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.OperationsException; import javax.management.QueryExp; import javax.management.ReflectionException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.Comparator; /** * TODO GH: Decide exception handling strategy (runtime?) * * @author Greg Hinkle (gh...@us...), Apr 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class DConnection implements EmsConnection { private static Log log = LogFactory.getLog(DConnection.class); protected String connectionName; protected AbstractConnectionProvider connectionProvider; protected SortedMap<DObjectName, EmsBean> beanMap; protected boolean loaded; // TODO Do this with 1.4 support // protected PooledConnectionTracker tracker; protected List<MBeanRegistrationListener> registrationListeners = new ArrayList<MBeanRegistrationListener>(); public DConnection(String connectionName, ConnectionProvider connectionProvider) { this.connectionName = connectionName; this.connectionProvider = (AbstractConnectionProvider) connectionProvider; beanMap = new TreeMap<DObjectName, EmsBean>(new DObjectNameComparator()); // this.tracker = new PooledConnectionTracker(this); } public void setConnectionProvider(AbstractConnectionProvider connectionProvider) { this.connectionProvider = connectionProvider; } public ConnectionTracker getTracker() { // return tracker; return null; } public void refresh() { try { loadSynchronous(false); } catch (Exception e) { log.warn("Could not refresh connection [" + connectionProvider.getConnectionSettings().getServerUrl() + "] " + e.toString(), e); } } public void close() { // tracker.stopTracker(); connectionProvider.disconnect(); } /* TODO: Check WebLogic <= 8.1 This was how mc4j worked since weblogic <= 8.1 won't allow a null search on queryNames, but will on queryMBeans if (connectionSettings.getConnectionType() instanceof WeblogicConnectionTypeDescriptor) { Set objectInstances = server.queryMBeans(null,null); objectNames = new HashSet(); for (Iterator iterator = objectInstances.iterator(); iterator.hasNext();) { ObjectInstance objectInstance = (ObjectInstance) iterator.next(); objectNames.add(objectInstance.getObjectName()); } } else { objectNames = server.queryNames(null,null); }*/ /** * Does a *:* load of all MBean names. Puts them in a list * * @param deep */ @SuppressWarnings({"unchecked"}) public synchronized void loadSynchronous(boolean deep) { if (!connectionProvider.isConnected()) connectionProvider.connect(); log.info("Querying MBeanServer for all MBeans"); Set<ObjectName> objectNames = null; try { objectNames = (Set<ObjectName>) connectionProvider.getMBeanServer().queryNames(new ObjectName("*:*"), null); } catch (MalformedObjectNameException e) { /* Should never happen */ } SortedMap<ObjectName, DMBean> retrievedBeansMap = new TreeMap<ObjectName, DMBean>(new ObjectNameComparator()); if (!loaded) log.info("Found " + objectNames.size() + " MBeans, starting load"); Set<DObjectName> currentKeys = new HashSet<DObjectName>(this.beanMap.keySet()); for (ObjectName objectName : objectNames) { // TODO: We're loading the beans on every run here i think... only load it if its not in the beanMap DMBean bean = mapBean(connectionProvider, objectName, deep); retrievedBeansMap.put(objectName, bean); } Set<EmsBean> newBeans = new HashSet<EmsBean>(); Set<EmsBean> removedBeans = new HashSet<EmsBean>(); for (Map.Entry<ObjectName, DMBean> entry : retrievedBeansMap.entrySet()) { if (!currentKeys.contains(entry.getKey())) { newBeans.add(entry.getValue()); } } for (DObjectName name : currentKeys) { if (!retrievedBeansMap.containsKey(name.getObjectName())) { removedBeans.add(beanMap.remove(name)); } } // if (false) // log.debug("Added " + newBeans.size() + " and removed " + removedBeans.size()); loaded = true; fireRegistrationEvent(newBeans, removedBeans); } static boolean isJMX12 = false; static { try { Class.forName("javax.management.MBeanServerInvocationHandler"); isJMX12 = true; } catch (ClassNotFoundException e) { } } private DMBean mapBean(ConnectionProvider provider, ObjectName objectName, boolean loadSynchronous) { DMBean bean = null; DObjectName dObjectName = new DObjectName(objectName); // If the bean is unkown to the internal map, create our local representation and add it synchronized (this) { if (!this.beanMap.keySet().contains(dObjectName)) { if (isJMX12) { bean = new DAdvancedBean(connectionProvider, objectName); } else { bean = new DMBean(connectionProvider, objectName); } beanMap.put(dObjectName, bean); } } // If the bean was just created then optional load its metadata syncrhonously // Do this outside the syncrhonized block if (bean != null && loadSynchronous) { try { bean.loadSynchronous(); } catch (EmsUnsupportedTypeException e) { // Keep loading other beans even if one has an unsupported type log.info("Bean metadata not loaded, unsupported type on [" + objectName.toString() + "]", e); } } if (bean == null) { return (DMBean) this.beanMap.get(dObjectName); } else { return bean; } } private void fireRegistrationEvent(Set<EmsBean> added, Set<EmsBean> removed) { if (!registrationListeners.isEmpty()) { MBeanRegistrationEvent event = new MBeanRegistrationEvent(added, removed); for (MBeanRegistrationListener listener : registrationListeners) { listener.registrationChanged(event); } } } public synchronized void addRegistrationListener(MBeanRegistrationListener registrationListener) { registrationListeners.add(registrationListener); } public synchronized void removeRegistrationListener(MBeanRegistrationListener registrationListener) { registrationListeners.remove(registrationListener); } /** * This will register a new MBean, but that may not be immediately recognized * * @param className * @param objectName */ public void createMBean(String className, String objectName) throws EmsException { ObjectName on = null; try { on = new ObjectName(objectName); connectionProvider.getMBeanServer().createMBean(className, on); } catch (Exception e) { throw new EmsException("Could not create MBean", e); } } public void removeMBean(String objectName) throws EmsException { ObjectName on = null; try { on = new ObjectName(objectName); connectionProvider.getMBeanServer().unregisterMBean(on); } catch (Exception e) { throw new EmsException("Could not remove MBean", e); } } public synchronized SortedSet<EmsBean> getBeans() { if (!loaded) { refresh(); } return new TreeSet<EmsBean>(beanMap.values()); } protected EmsBean getBean(ObjectName objectName) { return this.beanMap.get(new DObjectName(objectName)); } public EmsBean getBean(String objectName) { try { ObjectName name = new ObjectName(objectName); return getBean(name); } catch (MalformedObjectNameException e) { throw new EmsMalformedObjectNameException("Invalid ObjectName [" + objectName + "]",e); } } /** * This will run the query, creating our internal bean representation * as needed and return the full list of both previously and newly * mapped beans from the corresponding query. * * @param objectName * @param query * @return The list of EmsBeans representing mbeans that match the query */ @SuppressWarnings({"unchecked"}) public List<EmsBean> queryBeans(ObjectName objectName, QueryExp query) { Set<ObjectName> objectNames = (Set<ObjectName>) connectionProvider.getMBeanServer().queryNames(objectName, query); List<EmsBean> results = new ArrayList<EmsBean>(); for (ObjectName name : objectNames) { results.add(mapBean(connectionProvider, name, false)); } return results; } /** * Utility to perform a query without ObjectName in your classpath * * @param objectName * @return the list of EmsBeans matching your query * @throws RuntimeException when the ObjectName is not valid */ public List<EmsBean> queryBeans(String objectName) { try { ObjectName name = null; if (objectName != null) name = new ObjectName(objectName); return queryBeans(name, null); } catch (MalformedObjectNameException e) { throw new RuntimeException("Illegal ObjectName " + objectName, e); } } public EmsBean registerBean(String className, String objectName) { try { ObjectName objName = new ObjectName(objectName); ObjectInstance instance = connectionProvider.getMBeanServer().createMBean(className, objName); return mapBean(connectionProvider, instance.getObjectName(), false); } catch (MBeanException e) { e.printStackTrace(); throw new EmsException("Couldn't create MBean", e); } catch (OperationsException e) { throw new EmsException("Couldn't create MBean", e); } catch (ReflectionException e) { throw new EmsException("Couldn't create MBean", e); } } public EmsBean registerBean(String className, String objectName, Object[] params, String[] signature) { try { ObjectName objName = new ObjectName(objectName); ObjectInstance instance = connectionProvider.getMBeanServer().createMBean(className, objName, params, signature); return mapBean(connectionProvider, instance.getObjectName(), false); } catch (MBeanException e) { e.printStackTrace(); throw new EmsException("Couldn't create MBean", e); } catch (OperationsException e) { throw new EmsException("Couldn't create MBean", e); } catch (ReflectionException e) { throw new EmsException("Couldn't create MBean", e); } } public long getRoundTrips() { return connectionProvider.getRoundTrips(); } public long getFailures() { return connectionProvider.getFailures(); } public Object buildObjectName(String objectName) throws EmsMalformedObjectNameException { try { return new ObjectName(objectName); } catch (MalformedObjectNameException e) { throw new EmsMalformedObjectNameException("Object Name not valid [" + objectName + "]", e); } } private static class ObjectNameComparator implements Comparator { public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } } public ConnectionProvider getConnectionProvider() { return connectionProvider; } /** * Some object name implementations are not equal if the properties are in different orders. * The RI compares cannonical property forms as expected, JBoss is broken. * * This class is a key to search and get around that potential issue by always key on * the cannoical form, but ordering by the default form. */ public static class DObjectName { private ObjectName objectName; public DObjectName(ObjectName objectName) { this.objectName = objectName; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DObjectName that = (DObjectName) o; return objectName.getCanonicalName().equals(that.objectName.getCanonicalName()); } public int hashCode() { return objectName.getCanonicalName().hashCode(); } public int compareTo(DObjectName o) { return toString().compareTo(o.toString()); } public String toString() { return objectName.toString(); } public ObjectName getObjectName() { return objectName; } } public static class DObjectNameComparator implements Comparator<DObjectName> { public int compare(DObjectName o1, DObjectName o2) { return o1.getObjectName().getCanonicalName().compareTo(o2.getObjectName().getCanonicalName()); } } } --- NEW FILE: PooledConnectionTracker.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection; import org.mc4j.ems.connection.ConnectionTracker; import org.mc4j.ems.connection.bean.EmsBean; import org.mc4j.ems.connection.bean.attribute.EmsAttribute; import org.mc4j.ems.impl.jmx.connection.bean.DMBean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * @author Greg Hinkle (gh...@us...), Apr 12, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class PooledConnectionTracker implements ConnectionTracker { private static Log log = LogFactory.getLog(PooledConnectionTracker.class); protected DConnection connection; protected List<RefreshItem> refreshItems = new ArrayList<RefreshItem>(); protected ScheduledThreadPoolExecutor executor; private static int POOL_SIZE = 2; public PooledConnectionTracker(DConnection connection) { this.connection = connection; initTracker(); } protected void initTracker() { // TODO GH: Build registration system RefreshItem connectionRefresh = new ConnectionRefresh(20000, connection); refreshItems.add(connectionRefresh); RefreshItem attributeRefresh = new MBeanRefresh(20000); refreshItems.add(attributeRefresh); // Give names to the threads with a custom thread factory executor = new ScheduledThreadPoolExecutor(POOL_SIZE, new ThreadFactory() { private AtomicInteger index = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "EMS-ConnectionTracker-"+index.getAndIncrement()); } }); executor.scheduleAtFixedRate(connectionRefresh,1000,connectionRefresh.getUpdateDelay(), TimeUnit.MILLISECONDS); executor.scheduleAtFixedRate(attributeRefresh,1500,attributeRefresh.getUpdateDelay(), TimeUnit.MILLISECONDS); } public void stopTracker() { executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); executor.shutdown(); } public void registerUpdateRequest(String objectName, long delay) { throw new UnsupportedOperationException(); } public void removeUpdateRequest(String objectName) { throw new UnsupportedOperationException(); } private interface RefreshItem extends Runnable { long getUpdateDelay(); } private abstract class AbstractConnectionRefresh implements RefreshItem{ long updateDelay; public AbstractConnectionRefresh(long updateDelay) { this.updateDelay = updateDelay; } public long getUpdateDelay() { return updateDelay; } } private class ConnectionRefresh extends AbstractConnectionRefresh{ private DConnection connection; public ConnectionRefresh(long updateDelay, DConnection connection) { super(updateDelay); this.connection = connection; } public void run() { connection.loadSynchronous(false); } } private class MBeanRefresh extends AbstractConnectionRefresh { private DMBean mbean; Set<String> attributes; public MBeanRefresh(long updateDelay) { super(updateDelay); } public MBeanRefresh(long updateDelay, DMBean mbean) { super(updateDelay); this.mbean = mbean; } public MBeanRefresh(long updateDelay, DMBean mbean, Set<String> attributes) { super(updateDelay); this.mbean = mbean; this.attributes = attributes; } boolean first = true; public void run() { if (mbean == null) { System.gc(); long beforeMem = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()); // System.out.println("BeforeMem: " + ); // Map m = new TreeMap(new Comparator() { // public int compare(Object o, Object o1) { // return ((Comparable)o1).compareTo(o); // } // }); long total = 0; long count = 0; for (EmsBean bean : connection.getBeans()) { bean.refreshAttributes(); //if (first) { //System.out.println(bean.getObjectName().getCanonicalName()); for (EmsAttribute attribute : bean.getAttributes()) { int size = attribute.getValueSize(); total += size; if (size > 0) count++; //m.put(new Integer(size),/*bean.getObjectName() + "::" +*/attribute.getName()); //System.out.println("\t"+attribute.getName() + " - " + attribute.getValueSize()); if (attribute.getName().equalsIgnoreCase("stats")) { log.debug("Stats size: " + com.vladium.utils.ObjectProfiler.sizeof(attribute.getValue())); } } // } } log.debug("Total size of " + count + " attributes: " + total); // Expensive log.debug("Total connection size: " + com.vladium.utils.ObjectProfiler.sizeof(connection)); /*Iterator<Map.Entry> iter = m.entrySet().iterator(); // for (int i = 0;i<50;i++) { for (;iter.hasNext();) { Map.Entry entry = iter.next(); log.debug(entry.getKey() + " " + entry.getValue()); } first = false;*/ System.gc(); long afterMem = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()); log.debug("Memory difference for update: " + (afterMem - beforeMem)); // log.debug("AfterMem: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); } else if (attributes == null) { // reload all attributes mbean.refreshAttributes(); } else { // TODO GH: Implement mbean.refreshAttributes(set attributes) for (String attributeName :attributes) { mbean.getAttribute(attributeName).refresh(); } } } } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:47
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection/bean/notification In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection/bean/notification Added Files: DNotification.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: DNotification.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.bean.notification; import org.mc4j.ems.connection.EmsBeanNotFoundException; import org.mc4j.ems.connection.bean.notification.EmsNotification; import org.mc4j.ems.connection.bean.notification.EmsNotificationEvent; import org.mc4j.ems.connection.bean.notification.EmsNotificationListener; import org.mc4j.ems.connection.bean.EmsBean; import org.mc4j.ems.impl.jmx.connection.bean.DBeanName; import org.mc4j.ems.impl.jmx.connection.bean.DMBean; import javax.management.*; import java.io.Serializable; import java.util.*; /** * @author Greg Hinkle (gh...@us...), Apr 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:34 $) */ public class DNotification implements EmsNotification { protected MBeanNotificationInfo info; protected DMBean bean; protected List<String> notifTypes; protected List<EmsNotificationEvent> events = new ArrayList<EmsNotificationEvent>(); protected Set<EmsNotificationListener> listeners = new HashSet<EmsNotificationListener>(); protected NotificationListenerImpl notificationListener; protected NotificationFilterImpl notificationFilter; public DNotification(MBeanNotificationInfo info, DMBean bean) { this.info = info; this.bean = bean; notifTypes = Arrays.asList(getTypes()); } public String getName() { return info.getName(); } public String getDescription() { return info.getDescription(); } public String[] getTypes() { return info.getNotifTypes(); } public int compareTo(Object o) { DNotification otherNotification = (DNotification) o; return this.info.getName().compareTo( otherNotification.getName()); } public void addNotificationListener(EmsNotificationListener listener) { listeners.add(listener); } public boolean removeNotificationListener(EmsNotificationListener listener) { return listeners.remove(listener); } public boolean isListening() { return notificationListener != null; } public void startListening() { if (isListening()) { // Already listening return; } try { notificationListener = new NotificationListenerImpl(this); notificationFilter = new NotificationFilterImpl(notifTypes); bean.getConnectionProvider().getMBeanServer(). addNotificationListener( ((DBeanName)bean.getBeanName()).getObjectName(), notificationListener, null, null); } catch (InstanceNotFoundException e) { throw new EmsBeanNotFoundException("Could not register notification listener", e); } } public void stopListening() { if (!isListening()) { // Not current listening return; } try { bean.getConnectionProvider().getMBeanServer(). removeNotificationListener( ((DBeanName)bean.getBeanName()).getObjectName(), notificationListener, null, null); notificationListener = null; notificationFilter = null; } catch (InstanceNotFoundException e) { throw new EmsBeanNotFoundException("Could not deregister notification listener, bean missing", e); } catch (ListenerNotFoundException e) { // That's ok } } protected EmsBean getBean() { return bean; } public List<EmsNotificationEvent> getEvents() { return Collections.unmodifiableList(events); } protected void fireNotifications(EmsNotificationEvent event) { events.add(event); for (EmsNotificationListener listener : listeners) { listener.handleNotification(event); } } private static class NotificationListenerImpl implements NotificationListener, Serializable { DNotification n; public NotificationListenerImpl(DNotification n) { this.n = n; } public void handleNotification(Notification notification, Object object) { // This will do client side filter if (Arrays.asList(n.getTypes()).contains(notification.getType())) { EmsNotificationEvent event = new EmsNotificationEvent( n.getBean(), notification.getMessage(), notification.getSequenceNumber(), notification.getType(), notification.getTimeStamp(), notification.getUserData(), notification.getSource()); n.fireNotifications(event); } } } /* private List<NotificationFilter> getNotificationFilters() { List<NotificationFilter> filters = new ArrayList<NotificationFilter>(); boolean uncrecognisedNotifiationFound = false; try { Vector raw = new Vector(10); MBeanNotificationInfo [] notifyInfo = (MBeanNotificationInfo[]) server.getMBeanInfo(objectName).getNotifications(); for(int i = 0; i < notifyInfo.length && !uncrecognisedNotifiationFound; i++) { if(notifyInfo[i].getName().equals(getName())) //fetch notification specific to this node... { String [] notifyTypes = notifyInfo[i].getNotifTypes(); NotificationFilter filter = null; for(int j = 0; j < notifyTypes.length && !uncrecognisedNotifiationFound; j++) { //TODO in the future add more filter support here, if nessesary.... if(notifyTypes[j].equals(AttributeChangeNotification.ATTRIBUTE_CHANGE)) { filter = new AttributeChangeNotificationFilter(); ((AttributeChangeNotificationFilter) filter).enableAttribute(getName()); } else if(notifyTypes[j].equals(MBeanServerNotification.REGISTRATION_NOTIFICATION)) { filter = new MBeanServerNotificationFilter(); ((MBeanServerNotificationFilter) filter).disableAllTypes(); ((MBeanServerNotificationFilter) filter).enableType(MBeanServerNotification.REGISTRATION_NOTIFICATION); ((MBeanServerNotificationFilter) filter).enableAllObjectNames(); } else if(notifyTypes[j].equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) { filter = new MBeanServerNotificationFilter(); ((MBeanServerNotificationFilter) filter).disableAllTypes(); ((MBeanServerNotificationFilter) filter).enableType(MBeanServerNotification.UNREGISTRATION_NOTIFICATION); ((MBeanServerNotificationFilter) filter).enableAllObjectNames(); } else //unrecognised notification type, set filter to null.... { filter = null; uncrecognisedNotifiationFound = true; //break the loop... //once we have a null filter there is no point of //having any other filters as all of the notifications will have to be //coming through (in other words we don't know how to filer, so dont' filter at all). raw.removeAllElements(); } raw.add(filter); } } } if(raw.size() > 0) //do we have anything other than a default result? { result = new NotificationFilter[raw.size()]; result = (NotificationFilter[]) raw.toArray(result); } } catch(ReflectionException e) { //DO NOTHING object is not a Notification Broadcaster... } catch (javax.management.IntrospectionException e) { //DO NOTHING object is not a Notification Broadcaster... } catch(InstanceNotFoundException e) { ErrorManager.getDefault().notify(e); } return result; } */ private static class NotificationFilterImpl implements NotificationFilter { List<String> notifTypes; public NotificationFilterImpl(List<String> notifTypes) { this.notifTypes = notifTypes; } public boolean isNotificationEnabled(Notification notification) { return (notifTypes.contains(notification.getType())); } } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:46
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/test/org/mc4j/ems/test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/test/org/mc4j/ems/test Added Files: MultiConnectionTest.java TestServiceMBean.java LoaderTest.java ConnectionTest.java TestService.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: ConnectionTest.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.test; import org.mc4j.ems.connection.ConnectionFactory; import org.mc4j.ems.connection.EmsConnection; import org.mc4j.ems.connection.support.metadata.JBossConnectionTypeDescriptor; import org.mc4j.ems.connection.bean.EmsBean; import org.mc4j.ems.connection.bean.attribute.EmsAttribute; import org.mc4j.ems.connection.settings.ConnectionSettings; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; /** * @author Greg Hinkle (gh...@us...), Apr 5, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class ConnectionTest { private EmsConnection connection; public static void main(String[] args) throws Exception, InstanceNotFoundException, IntrospectionException { ConnectionTest test = new ConnectionTest(); try { // test.testUpdateSpeed(); // test.testCreateRemove(); Thread.sleep(10000); } finally{ test.testClose(); } } public ConnectionTest() throws Exception { ConnectionSettings settings = getSettings(); ConnectionFactory factory = new ConnectionFactory(); factory.discoverServerClasses(settings); EmsConnection connection = factory.connect(settings); connection.loadSynchronous(true); /*SortedSet<EmsBean> beans = connection.getBeans(); for (EmsBean bean : beans) { System.out.println("Bean [" + bean.getObjectName() + "]" + bean); for (EmsAttribute attribute : bean.getAttributes()) { System.out.println("\t" + attribute.getName() + " - " + attribute.getDescription()); } }*/ this.connection = connection; } private ConnectionSettings getSettings() { ConnectionSettings settings = new ConnectionSettings(); // Local JDK 5 test // settings.initializeConnectionType(new J2SE5ConnectionTypeDescriptor()); // settings.setConnectionName("test"); // settings.setServerUrl("service:jmx:rmi:///jndi/rmi://localhost:9777/jmxrmi"); settings.initializeConnectionType(new JBossConnectionTypeDescriptor()); settings.setConnectionName("JBoss Test"); settings.setServerUrl("jnp://localhost:1099"); settings.setLibraryURI("/Users/ghinkle/development/tools/jboss-4.0.3SP1-installer"); settings.setPrincipal("admin"); settings.setCredentials("admin"); // Local Tomcat/Chires test // settings.initializeConnectionType(new J2SE5ConnectionTypeDescriptor()); // settings.setConnectionName("tomcat"); // settings.setServerUrl("service:jmx:rmi:///jndi/rmi://localhost:9003/jmxrmi"); // settings.setPrincipal("adminRole"); // settings.setCredentials("admin"); // settings.setClassPathEntries(new File[] { // new File("C:\\projects\\chires\\dist\\chires.jar"), // new File("E:\\tools\\jakarta-tomcat-5.0.27\\server\\lib\\catalina.jar"), // new File("E:\\tools\\jakarta-tomcat-5.0.27\\server\\lib\\catalina-optional.jar") // }); // Weblogic 8.1 test // settings.initializeConnectionType(new WeblogicConnectionTypeDescriptor()); // settings.setConnectionName("test"); // settings.setCredentials("weblogic"); // settings.setPrincipal("weblogic"); // settings.setClassPathEntries(new File[] { new File("c:\\bea\\weblogic81\\server\\lib\\weblogic.jar")}); // Weblogic 9 - jsr 77 test // settings.setConnectionName("test"); // settings.setServerUrl("service:jmx:t3://localhost:7001/jndi/weblogic.management.mbeanservers.runtime");//edit");//domainruntime"); // settings.setConnectionType(new Weblogic9Jsr77ConnectionTypeDescriptor()); // settings.setConnectionName("test"); // settings.setConnectionType(new Weblogic9ConnectionTypeDescriptor()); // settings.setPrincipal("weblogic"); // settings.setCredentials("weblogic"); // Weblogic 9 - test // settings.setConnectionName("test"); // settings.setServerUrl("service:jmx:t3://localhost:7001/jndi/weblogic.management.mbeanservers.runtime");//edit");//domainruntime"); // settings.initializeConnectionType(new Weblogic9ConnectionTypeDescriptor()); // settings.setConnectionName("test"); // settings.setPrincipal("weblogic"); // settings.setCredentials("weblogic"); // settings.setClassPathEntries(Arrays.asList(new File[] { // new File("E:\\tools\\weblogic9\\weblogic90b\\server\\lib\\weblogic.jar") // })); return settings; // String xml = ConnectionSettingPersistence.getInstance().encodeSettings(settings); // System.out.println(xml); // return ConnectionSettingPersistence.getInstance().decodeSettings(xml); } public void testClose() { connection.close(); } public void testUpdateSpeed() { long start = System.currentTimeMillis(); for (EmsBean bean :connection.getBeans()) { bean.refreshAttributes(); } System.out.println("Batched update time: " + (System.currentTimeMillis() - start) + "ms"); start = System.currentTimeMillis(); for (EmsBean bean :connection.getBeans()) { for (EmsAttribute attribute : bean.getAttributes()) { attribute.refresh(); // System.out.println("Update history: " + attribute.getValueHistory().getValues().size()); } } System.out.println("Individual update time: " + (System.currentTimeMillis() - start) + "ms"); } public void testContinuousRefresh() throws Exception { while (true) { for (EmsBean bean :connection.getBeans()) { for (EmsAttribute attribute : bean.getAttributes()) { if ("HeapFreeCurrent".equals(attribute.getName())) { System.out.println(bean.getBeanName().getCanonicalName() + " - " + attribute.getValue()); System.out.println("Tracking history: " + attribute.getValueHistory().getHistorySize()); } } } try { Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } } public void testCreateRemove() throws Exception { final Boolean failure = Boolean.FALSE; connection.loadSynchronous(true); Thread t = new Thread(new Runnable() { public void run() { for (int i = 0; i < 100; i++) { try { connection.createMBean(TestService.class.getName(), "test:type=TestService,id=bean_" + i); // connection.removeMBean(new ObjectName("test:type=TestService,id=bean_" + (i - 1))); Thread.sleep(200); } catch (Exception e) { e.printStackTrace(); } } } }); t.start(); Thread t2 = new Thread(new Runnable() { public void run() { for (int i = 0; i < 100; i++) { try { connection.removeMBean("test:type=TestService,id=bean_" + (i - 1)); Thread.sleep(210); } catch (Exception e) { try { Thread.sleep(300); } catch (InterruptedException e1) { } e.printStackTrace(); } } } }); t2.start(); t.join(); t2.join(); connection.loadSynchronous(false); } } --- NEW FILE: TestServiceMBean.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.test; /** * @author Greg Hinkle (gh...@us...), Apr 11, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public interface TestServiceMBean { double getNumber(); } --- NEW FILE: TestService.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.test; /** * @author Greg Hinkle (gh...@us...), Apr 11, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class TestService implements TestServiceMBean { public double getNumber() { return Math.random(); } } --- NEW FILE: LoaderTest.java --- package org.mc4j.ems.test; import org.mc4j.ems.connection.support.classloader.ClassLoaderFactory; import org.mc4j.ems.connection.support.ConnectionProvider; import org.mc4j.ems.connection.support.metadata.J2SE5ConnectionTypeDescriptor; import org.mc4j.ems.connection.settings.ConnectionSettings; /** * Created by IntelliJ IDEA. * User: ghinkle * Date: Sep 21, 2005 * Time: 11:04:09 PM * To change this template use File | Settings | File Templates. */ public class LoaderTest { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException { ConnectionSettings connectionSettings = new ConnectionSettings(); connectionSettings.setConnectionType(new J2SE5ConnectionTypeDescriptor()); String className = connectionSettings.getConnectionType().getConnectionNodeClassName(); // TODO GH: Does this need to be configurable per connection? ClassLoader loader = ClassLoaderFactory.getInstance().buildClassLoader(connectionSettings); // TODO GH: Add intelligent classloader layer here that can either work // directly against current classloader or build a non-delegating child // to override with connection specific classes Class clazz = Class.forName(className, true, loader); ConnectionProvider connectionProvider = (ConnectionProvider) clazz.newInstance(); System.out.println("ConnectionProvider: " + connectionProvider); } } --- NEW FILE: MultiConnectionTest.java --- package org.mc4j.ems.test; import org.mc4j.ems.connection.ConnectionFactory; import org.mc4j.ems.connection.EmsConnection; import org.mc4j.ems.connection.bean.EmsBean; import org.mc4j.ems.connection.bean.attribute.EmsAttribute; import org.mc4j.ems.connection.settings.ConnectionSettings; import org.mc4j.ems.connection.support.metadata.J2SE5ConnectionTypeDescriptor; import org.mc4j.ems.connection.support.metadata.JBossConnectionTypeDescriptor; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.List; /** * Created by IntelliJ IDEA. * User: ghinkle * Date: Oct 25, 2005 * Time: 1:42:06 PM * To change this template use File | Settings | File Templates. */ public class MultiConnectionTest { public static void main2(String[] args) throws MalformedURLException, ClassNotFoundException { URLClassLoader a = new URLClassLoader(new URL[] { new URL("file:/Users/ghinkle/Desktop/Downloads/jboss-3.2.5/lib/jboss-jmx.jar")}); URLClassLoader b = new URLClassLoader(new URL[] { new URL("file:/Users/ghinkle/development/tools/jboss-4.0.2/lib/jboss-jmx.jar")}); Class.forName("javax.management.MBeanServer",true,a); Class.forName("javax.management.MBeanServer",true,b); } public static void main(String[] args) throws InterruptedException { ConnectionSettings jboss = new ConnectionSettings(); jboss.initializeConnectionType(new JBossConnectionTypeDescriptor()); jboss.setConnectionName("JBoss Test"); // jboss.setServerUrl("jnp://10.0.1.2:2099");//edit");//domainruntime"); jboss.setServerUrl("jnp://127.0.0.1:1099"); // jboss.setLibraryURI("/Users/ghinkle/development/tools/jboss-3.2.3"); // jboss.setLibraryURI("/Users/ghinkle/development/tools/jboss-3.2.4"); // jboss.setLibraryURI("/Users/ghinkle/development/tools/jboss-3.2.5"); jboss.setLibraryURI("/Users/ghinkle/development/tools/jboss-4.0.3SP1-installer/"); // jboss.setPrincipal("admin"); jboss.setCredentials("admin"); ConnectionFactory factory = new ConnectionFactory(); factory.discoverServerClasses(jboss); EmsConnection jbossConnection = factory.connect(jboss); long start = System.currentTimeMillis(); jbossConnection.loadSynchronous(true); System.out.println("Loaded " + jbossConnection.getBeans().size() + " in " + (System.currentTimeMillis()-start) + "ms"); EmsBean bean1 = jbossConnection.getBean("jboss.mq.destination:service=Queue,name=A"); //"jboss.mq:service=MessageCache"); System.out.println("QUEUE SEARCH: " + bean1); List beans = jbossConnection.queryBeans("jboss:service=*"); System.out.println("Found " + beans.size() + " beans from query."); EmsBean bean = jbossConnection.getBean("jboss:service=TransactionManager"); //"jboss.mq:service=MessageCache"); //jbossConnection.getBean("jboss.system:type=ServerInfo"); EmsAttribute attribute = bean.getAttribute("TransactionCount"); //"TotalCacheSize"); /* for (int i=0;i<20;i++) { try { Thread.sleep(10000); System.out.println("Attribute " + attribute.getName() + ": " + attribute.refresh()); } catch(Exception e) { System.out.println("Exc: " + e.getClass().getName()); } }*/ } public static void main3(String[] args) { ConnectionSettings jboss32 = new ConnectionSettings(); jboss32.initializeConnectionType(new JBossConnectionTypeDescriptor()); jboss32.setConnectionName("JBoss 3.2"); jboss32.setServerUrl("jnp://localhost:1099");//edit");//domainruntime"); jboss32.setLibraryURI("/Users/ghinkle/Desktop/Downloads/jboss-3.2.5"); ConnectionFactory factory = new ConnectionFactory(); factory.discoverServerClasses(jboss32); EmsConnection jboss32Connection = factory.connect(jboss32); ConnectionSettings jboss4 = new ConnectionSettings(); jboss4.initializeConnectionType(new JBossConnectionTypeDescriptor()); jboss4.setConnectionName("JBoss 3.2"); jboss4.setServerUrl("jnp://10.0.1.2:2099");//edit");//domainruntime"); jboss4.setLibraryURI("/Users/ghinkle/development/tools/jboss-4.0.2/"); factory.discoverServerClasses(jboss4); EmsConnection jboss4Connection = factory.connect(jboss4); jboss4Connection.loadSynchronous(false); // EmsBean bean = jboss4Connection.getBean("jboss.management.local:EJBModule=hq-entity.jar,J2EEApplication=hq.ear,J2EEServer=Local,j2eeType=EntityBean,name=LocalPlatform"); // // Stats stats = (Stats) bean.getAttribute("stats").refresh(); // System.out.println(stats.getClass()); jboss32Connection.loadSynchronous(false); System.out.println("JBoss 3.2 - bean count: " + jboss32Connection.getBeans().size()); System.out.println("JBoss 4.0.2 - bean count: " + jboss4Connection.getBeans().size()); ConnectionSettings jdk5 = new ConnectionSettings(); jdk5.initializeConnectionType(new J2SE5ConnectionTypeDescriptor()); // jdk5.setServerUrl("service:jmx:rmi://10.0.1.2/jndi/rmi://10.0.1.2:1099/jmxconnectorjcmd"); EmsConnection jdk5Connection = factory.connect(jdk5); jdk5Connection.loadSynchronous(false); } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:45
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/connection/support In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/connection/support Added Files: ConnectionProvider.java ConnectionListener.java ConnectionEvent.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: ConnectionListener.java --- package org.mc4j.ems.connection.support; /** * Created: Jun 21, 2005 2:16:04 AM * * @author Greg Hinkle (gh...@us...) * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public interface ConnectionListener { void connect(); void disconnect(); void connectionFailure(); } --- NEW FILE: ConnectionEvent.java --- package org.mc4j.ems.connection.support; /** * Created: Jun 21, 2005 2:15:42 AM * * @author Greg Hinkle (gh...@us...) * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public interface ConnectionEvent { } --- NEW FILE: ConnectionProvider.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support; import org.mc4j.ems.connection.EmsConnection; import org.mc4j.ems.connection.settings.ConnectionSettings; /** * @author Greg Hinkle (gh...@us...), Apr 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public interface ConnectionProvider { // MBeanServer getMBeanServer(); ConnectionSettings getConnectionSettings(); boolean isConnected(); EmsConnection connect(); void initialize(ConnectionSettings settings); void disconnect(); void addConnectionListener(ConnectionListener connectionListener); void removeConnectionListener(ConnectionListener connectionListener); long getRoundTrips(); long getFailures(); } |
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection/support/providers/proxy In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection/support/providers/proxy Added Files: JSR77ManagementMBeanServerProxy.java StatsProxy.java JMXRemotingMBeanServerProxy.java GenericMBeanServerProxy.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: GenericMBeanServerProxy.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.support.providers.proxy; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mc4j.ems.connection.EmsConnectException; import org.mc4j.ems.connection.EmsUnsupportedTypeException; import org.mc4j.ems.connection.LoadException; import org.mc4j.ems.connection.support.ConnectionProvider; import javax.management.MBeanServer; import java.io.NotSerializableException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.rmi.NoSuchObjectException; /** * * @author Greg Hinkle (gh...@us...), January 2002 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class GenericMBeanServerProxy implements InvocationHandler, StatsProxy { private static Log log = LogFactory.getLog(GenericMBeanServerProxy.class); private Object remoteServer; private ConnectionProvider provider; private long roundTrips; private long failures; private boolean reconnecting = false; /** Creates a new instance of Proxy */ public GenericMBeanServerProxy(Object remoteServer) { this.remoteServer = remoteServer; } public GenericMBeanServerProxy() { } public ConnectionProvider getProvider() { return provider; } public void setProvider(ConnectionProvider provider) { this.provider = provider; } public Object getRemoteServer() { return remoteServer; } public void setRemoteServer(Object remoteServer) { this.remoteServer = remoteServer; } public Object invoke( Object proxy, Method m, Object[] args) throws Throwable { // SwingUtility.eventThreadAlert(); // // ConnectionInfoAction.addHit(); Class serverClass = this.remoteServer.getClass(); //org.openide.windows.IOProvider.getDefault().getStdOut().println("Looking at object: " + serverClass.getName()); // TODO GH: This is horribly inneficient Method[] ms = serverClass.getMethods(); Method queryMethod = null; for (int i = 0; i < ms.length; i++) { //org.openide.windows.IOProvider.getDefault().getStdOut().println("\t" + ms[i].getName() + // Arrays.asList(ms[i].getParameterTypes())); if (ms[i].getName().equals("queryMBeans")) queryMethod = ms[i]; } Method method = null; if ("queryMBeans".equals(m.getName())) { method = queryMethod; //method = serverClass.getMethod(m.getName(), new Class[] { ObjectName.class, QueryExp.class }); } else { method = serverClass.getMethod(m.getName(),m.getParameterTypes()); } if (method == null) { throw new EmsConnectException("Unsupported operation [" + m.getName() + "]"); } ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader(); try { roundTrips++; // Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); return method.invoke(this.remoteServer, args); } catch(InvocationTargetException e) { failures++; if (e.getCause() != null) { Throwable t = e.getCause(); if (t instanceof java.rmi.ConnectException) { throw new EmsConnectException(t); } else if (t instanceof NoSuchObjectException) { // This happens when the server comes back up and the stub is stale // try to reconnect if this provider supports it (if it told the proxy what the provider was) if (provider != null && !reconnecting) { try { log.info("Reestablishing RMI stub " + this.provider.getConnectionSettings().getServerUrl()); reconnecting = true; provider.connect(); // Retry the request once return this.invoke(proxy, m, args); } catch(Exception f) { log.warn("Unable to reestablish RMI stub to restarted server.",f); } finally{ reconnecting = false; } } // The reconnect failed, throw the original exception // If the retry fails, it will throw its own exception throw new EmsConnectException(t); } else if (t instanceof java.io.IOException) { throw new EmsConnectException(t); } else if (t instanceof NotSerializableException) { throw new EmsUnsupportedTypeException("Value was not serializable " + t.getLocalizedMessage(),t); } else { throw new EmsConnectException("Connection failure " + t.getLocalizedMessage(), t); } } else { throw e; } } catch (Exception e) { failures++; //e.printStackTrace(); throw e; } finally { // Thread.currentThread().setContextClassLoader(ctxLoader); } } public long getRoundTrips() { return roundTrips; } public long getFailures() { return failures; } public MBeanServer buildServerProxy() { try { Object proxy = Proxy.newProxyInstance( GenericMBeanServerProxy.class.getClassLoader(), new Class<?>[] { Class.forName("javax.management.MBeanServer")}, this); return (MBeanServer) proxy; } catch (ClassNotFoundException e) { throw new LoadException("Unable to find JMX Classes", e); } } } --- NEW FILE: JSR77ManagementMBeanServerProxy.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.support.providers.proxy; import javax.management.MBeanServer; import javax.management.j2ee.Management; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * * @author Greg Hinkle (gh...@us...), January 2002 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class JSR77ManagementMBeanServerProxy implements InvocationHandler, StatsProxy { private Management mejb; private long roundTrips; private long failures; private static final Class[] INTERFACES = { MBeanServer.class }; /** Creates a new instance of Proxy */ public JSR77ManagementMBeanServerProxy(Management mejb) { this.mejb = mejb; } public JSR77ManagementMBeanServerProxy(Object omejb) { this((Management) omejb); } public Object invoke( Object proxy, Method m, Object[] args) throws Throwable { Class serverClass = Management.class; // this.remoteServer.getClass(); Method method = serverClass.getMethod(m.getName(),m.getParameterTypes()); // TODO CSC: should all IOExceptions been catched here and thrown as an MC4JIOException (RuntimeException) // to avoid the occurence of an UndeclaredThrowableExcpetion??? try { roundTrips++; return method.invoke(this.mejb, args); } catch(Exception e) { failures++; throw e; } } // TODO GH: Think about notification listers and how management ejbs have a seperate registry public MBeanServer buildServerProxy() { Object proxy = Proxy.newProxyInstance( JSR77ManagementMBeanServerProxy.class.getClassLoader(), JSR77ManagementMBeanServerProxy.INTERFACES, this); return (MBeanServer) proxy; } public long getRoundTrips() { return roundTrips; } public long getFailures() { return failures; } } --- NEW FILE: StatsProxy.java --- /* * Copyright 2002-2005 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.support.providers.proxy; import javax.management.MBeanServer; /** * An interface for proxies to declare their capability to track and provide statistics * on the network traffic. * * @author Greg Hinkle (gh...@us...), Nov 22, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public interface StatsProxy { /** * @return a newly built dynamic proxy that will manage the connection */ MBeanServer buildServerProxy(); /** * @return the count of server calls made by this proxied connection */ long getRoundTrips(); /** * @return the count of server calls that threw an exception */ long getFailures(); } --- NEW FILE: JMXRemotingMBeanServerProxy.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.support.providers.proxy; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.InvocationTargetException; /** * * @author Greg Hinkle (gh...@us...), January 2002 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class JMXRemotingMBeanServerProxy implements InvocationHandler, StatsProxy { private MBeanServerConnection remoteServer; private long roundTrips; private long failures; private static final Class[] INTERFACES = { MBeanServer.class }; /** Creates a new instance of Proxy */ public JMXRemotingMBeanServerProxy(MBeanServerConnection remoteServer) { this.remoteServer = remoteServer; } public Object invoke( Object proxy, Method m, Object[] args) throws Throwable { Class serverClass = MBeanServerConnection.class; // this.remoteServer.getClass(); Method method = serverClass.getMethod(m.getName(),m.getParameterTypes()); // TODO GH: Throw as Runtime? try { roundTrips++; return method.invoke(this.remoteServer, args); } catch(InvocationTargetException ite) { failures++; Throwable t = ite.getTargetException(); if (t != null) throw t; else throw ite; } } public MBeanServer buildServerProxy() { Object proxy = Proxy.newProxyInstance( JMXRemotingMBeanServerProxy.class.getClassLoader(), JMXRemotingMBeanServerProxy.INTERFACES, this); return (MBeanServer) proxy; } public long getRoundTrips() { return roundTrips; } public long getFailures() { return failures; } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:44
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection/bean In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection/bean Added Files: DBeanName.java DAdvancedBean.java DMBean.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: DMBean.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.bean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mc4j.ems.connection.EmsBeanNotFoundException; import org.mc4j.ems.connection.EmsUnsupportedTypeException; import org.mc4j.ems.connection.bean.EmsBean; import org.mc4j.ems.connection.bean.EmsBeanName; import org.mc4j.ems.connection.bean.attribute.EmsAttribute; import org.mc4j.ems.connection.bean.notification.EmsNotification; import org.mc4j.ems.connection.bean.operation.EmsOperation; import org.mc4j.ems.impl.jmx.connection.bean.attribute.DAttribute; import org.mc4j.ems.impl.jmx.connection.bean.attribute.DUnkownAttribute; import org.mc4j.ems.impl.jmx.connection.bean.notification.DNotification; import org.mc4j.ems.impl.jmx.connection.bean.operation.DOperation; import org.mc4j.ems.impl.jmx.connection.support.providers.AbstractConnectionProvider; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.InstanceNotFoundException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.ObjectName; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; /** * @author Greg Hinkle (gh...@us...), Apr 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class DMBean implements EmsBean { private static Log log = LogFactory.getLog(DMBean.class); protected AbstractConnectionProvider connectionProvider; protected ObjectName objectName; protected EmsBeanName beanName; private MBeanInfo info; private boolean loaded = false; private boolean unsupportedType = false; protected boolean deleted = false; private Map<String, EmsAttribute> attributes = new TreeMap<String, EmsAttribute>(String.CASE_INSENSITIVE_ORDER); private Map<String, EmsOperation> operations = new TreeMap<String, EmsOperation>(String.CASE_INSENSITIVE_ORDER); private Map<String, EmsNotification> notifications = new TreeMap<String, EmsNotification>(String.CASE_INSENSITIVE_ORDER); protected List<Throwable> failures; public DMBean(AbstractConnectionProvider connectionProvider, ObjectName objectName) { this.connectionProvider = connectionProvider; this.objectName = objectName; this.beanName = new DBeanName(objectName); } public ObjectName getObjectName() { return objectName; } public EmsBeanName getBeanName() { return beanName; } public AbstractConnectionProvider getConnectionProvider() { return connectionProvider; } public List<Throwable> getFailures() { return failures; } protected void registerFailure(Throwable t) { if (failures == null) { failures = new LinkedList<Throwable>(); } failures.add(t); log.debug("MBean access failure", t); } public boolean isHasUnsupportedType() { return unsupportedType; } public boolean isNotificationEmiter() { try { return connectionProvider.getMBeanServer().isInstanceOf(getObjectName(), "javax.management.NotificationEmitter"); } catch (InstanceNotFoundException e) { throw new EmsBeanNotFoundException("Bean doesn't exist", e); } } /** * @param beanInterface */ @SuppressWarnings("unchecked") public <T> T getProxy(Class<T> beanInterface) { throw new UnsupportedOperationException("Proxies not supported pre-jmx 1.2"); } /** * Loads local representations of attributes, operations and notifications. * Current attribute values are not retrived. */ public synchronized void loadSynchronous() { if (!loaded) { // TODO GH: Support loading twice to handle dynamic mbeans with changing descriptors? try { info = connectionProvider.getMBeanServer().getMBeanInfo(this.objectName); MBeanAttributeInfo[] attributes = info.getAttributes(); for (MBeanAttributeInfo attributeInfo : attributes) { DAttribute attribute = new DAttribute(attributeInfo, this); this.attributes.put(attributeInfo.getName(), attribute); } MBeanOperationInfo[] operations = info.getOperations(); for (MBeanOperationInfo operationInfo : operations) { DOperation operation = new DOperation(operationInfo, this); this.operations.put(operationInfo.getName(), operation); } MBeanNotificationInfo[] notifications = info.getNotifications(); for (MBeanNotificationInfo notificationInfo : notifications) { DNotification notification = new DNotification(notificationInfo, this); this.notifications.put(notificationInfo.getName(), notification); } loaded = true; } catch (InstanceNotFoundException infe) { this.deleted = true; } catch (Exception e) { unsupportedType = true; RuntimeException f = new EmsUnsupportedTypeException("Could not load MBean info, unsupported type on bean " + objectName, e); registerFailure(f); // TODO should we throw this here? //throw f; } } } public boolean isRegistered() { MBeanServer server = getConnectionProvider().getMBeanServer(); return server.isRegistered(getObjectName()); } public EmsAttribute getAttribute(String name) { if (!loaded) loadSynchronous(); EmsAttribute attribute = this.attributes.get(name); if (attribute == null && unsupportedType) { attribute = new DUnkownAttribute(this, name); this.attributes.put(name,attribute); } return attribute; } public SortedSet<EmsAttribute> getAttributes() { if (!loaded) loadSynchronous(); return new TreeSet<EmsAttribute>(this.attributes.values()); } protected boolean hasUnsupportedType = false; public List<EmsAttribute> refreshAttributes() { if (info == null) loadSynchronous(); MBeanAttributeInfo[] infos = this.info.getAttributes(); // MUST be careful to only ask for types that we know we have // otherwise the RMI call will fail and we will get no data. List<String> nameList = new ArrayList<String>(); for (MBeanAttributeInfo info : infos) { try { findType(info.getType()); // If we know the type, add it to the list nameList.add(info.getName()); } catch (ClassNotFoundException cnfe) { log.info("Can't load attribute type of [" + info.getName() + "] because class not locally available"); } } return refreshAttributes(nameList); } public List<EmsAttribute> refreshAttributes(List<String> attributeNames) { if (info == null) loadSynchronous(); MBeanServer server = getConnectionProvider().getMBeanServer(); try { String[] names = attributeNames.toArray(new String[attributeNames.size()]); AttributeList attributeList = server.getAttributes( getObjectName(), names); List<EmsAttribute> attributeResults = new ArrayList<EmsAttribute>(); for (Attribute attr : ((List<Attribute>) attributeList)) { EmsAttribute attribute = getAttribute(attr.getName()); attribute.alterValue(attr.getValue()); // if (!values.containsKey(attribute.getName())) { // attribute.setSupportedType(false); // } attributeResults.add(attribute); } return attributeResults; } catch (InstanceNotFoundException infe) { this.deleted = true; throw new RuntimeException("Unable to load attributes, bean not found", infe); } catch (Exception e) { // TODO: determine which exceptions to register, which to throw and what to log // e.printStackTrace(); // Don't load them as a set anymore... this.hasUnsupportedType = true; //System.out.println(ExceptionUtility.printStackTracesToString(e)); // If we still we're unable to load all the attributes at once // lets load as many as we can, one at a time. // for (EmsAttribute attribute : getAttributes()) { // attribute.refresh(); // } throw new RuntimeException("Unable to load attributes", e); } // } else { // // If the object has unsupported attribute types // // lets load as many as we can, one at a time. // System.out.println("Loading individually: " + getObjectName().getCanonicalName()); // for (EmsAttribute attribute : getAttributes()) { // attribute.refresh(); // } // } } public String getClassTypeName() { return getMBeanInfo().getClassName(); } private static final Map TYPES = new HashMap(); static { TYPES.put(Boolean.TYPE.getName(), Boolean.TYPE); TYPES.put(Character.TYPE.getName(), Character.TYPE); TYPES.put(Byte.TYPE.getName(), Byte.TYPE); TYPES.put(Short.TYPE.getName(), Short.TYPE); TYPES.put(Integer.TYPE.getName(), Integer.TYPE); TYPES.put(Long.TYPE.getName(), Long.TYPE); TYPES.put(Float.TYPE.getName(), Float.TYPE); TYPES.put(Double.TYPE.getName(), Double.TYPE); TYPES.put(Void.TYPE.getClass(), Void.TYPE); } public static Class findType(String className) throws ClassNotFoundException { if (TYPES.containsKey(className)) { return (Class) TYPES.get(className); } else { return Class.forName(className, true, DMBean.class.getClassLoader()); } } public Class getClassType() throws ClassNotFoundException { String className = getMBeanInfo().getClassName(); return findType(className); } public EmsOperation getOperation(String name) { if (info == null) loadSynchronous(); return this.operations.get(name); } public SortedSet<EmsOperation> getOperations() { if (info == null) loadSynchronous(); return new TreeSet<EmsOperation>(this.operations.values()); } public EmsNotification getNotification(String name) { if (info == null) loadSynchronous(); return this.notifications.get(name); } public SortedSet<EmsNotification> getNotifications() { if (info == null) loadSynchronous(); return new TreeSet<EmsNotification>(this.notifications.values()); } public void unregister() { try { connectionProvider.getMBeanServer().unregisterMBean(getObjectName()); } catch (MBeanRegistrationException e) { e.printStackTrace(); } catch (InstanceNotFoundException e) { throw new EmsBeanNotFoundException("Could not unregister bean, instance not found [" + getObjectName().getCanonicalName() + "]", e); } } protected MBeanInfo getMBeanInfo() { if (info == null) loadSynchronous(); return info; } public int compareTo(Object o) { DMBean otherBean = (DMBean) o; return this.getObjectName().getCanonicalName().compareTo( otherBean.getObjectName().getCanonicalName()); } public String toString() { return this.getBeanName().toString(); } } --- NEW FILE: DAdvancedBean.java --- /* * Copyright 2002-2005 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.bean; import org.mc4j.ems.impl.jmx.connection.support.providers.AbstractConnectionProvider; import javax.management.ObjectName; import javax.management.MBeanServer; import javax.management.MBeanServerInvocationHandler; import java.lang.reflect.Method; /** * @author Greg Hinkle (gh...@us...), Nov 16, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class DAdvancedBean extends DMBean { protected Object mbeanProxy; public DAdvancedBean(AbstractConnectionProvider connectionProvider, ObjectName objectName) { super(connectionProvider, objectName); } @SuppressWarnings("unchecked") public <T> T getProxy(Class<T> beanInterface) { if (mbeanProxy == null) { try { // 1.5 only stuff Class c = Class.forName("java.lang.management.ManagementFactory"); Class mbsc = Class.forName("javax.management.MBeanServerConnection"); Method m = c.getMethod("newPlatformMXBeanProxy",mbsc,String.class,Class.class); return (T) m.invoke(null,connectionProvider.getMBeanServer(), getBeanName().getCanonicalName(), beanInterface); } catch (Exception e) { // Expected if its not a platform mbean // e.printStackTrace(); } MBeanServer server = getConnectionProvider().getMBeanServer(); mbeanProxy = MBeanServerInvocationHandler.newProxyInstance(server, getObjectName(), beanInterface, getNotifications().size() > 0); } return (T) mbeanProxy; } } --- NEW FILE: DBeanName.java --- package org.mc4j.ems.impl.jmx.connection.bean; import org.mc4j.ems.connection.bean.EmsBeanName; import org.mc4j.ems.connection.EmsMalformedObjectNameException; import javax.management.ObjectName; import javax.management.MalformedObjectNameException; import java.util.Map; /** * Created by IntelliJ IDEA. * User: ghinkle * Date: Oct 25, 2005 * Time: 1:18:47 AM * To change this template use File | Settings | File Templates. */ public class DBeanName implements EmsBeanName { private ObjectName objectName; public DBeanName(ObjectName objectName) { this.objectName = objectName; } public ObjectName getObjectName() { return objectName; } public String getDomain() { return objectName.getDomain(); } public String getCanonicalName() { return objectName.getCanonicalName(); } public Map<String,String> getKeyProperties() { // TODO: Build an ordered map out of the properties? return (Map<String, String>) objectName.getKeyPropertyList(); } public String getKeyProperty(String key) { return objectName.getKeyProperty(key); } public boolean apply(String objectNameFilterString) { try { return this.objectName.apply(new ObjectName(objectNameFilterString)); } catch (MalformedObjectNameException e) { throw new EmsMalformedObjectNameException("Invalid object name filter [" + objectNameFilterString + "]",e); } } /** * Output the generalized objectname string in input format * @return */ public String toString() { return this.objectName.toString(); } public int compareTo(Object o) { if (this == o) return 0; return toString().compareTo(((EmsBeanName) o).toString()); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DBeanName dBeanName = (DBeanName) o; return objectName.equals(dBeanName.objectName); } public int hashCode() { return objectName.hashCode(); } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:44
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/connection/settings/persistence In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/connection/settings/persistence Added Files: ConnectionSettingPersistence.java ConnectionSettingsStore.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: ConnectionSettingsStore.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.settings.persistence; import org.mc4j.ems.connection.settings.ConnectionSettings; import java.util.prefs.Preferences; import com.sun.org.apache.xerces.internal.util.XML11Char; /** * @author Greg Hinkle (gh...@us...), May 5, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class ConnectionSettingsStore { Preferences prefs = Preferences.systemNodeForPackage(ConnectionSettingsStore.class); public void storeConnectionSettings(ConnectionSettings settings) { Preferences sPref = prefs.node("settings." + settings.getConnectionName()); } } --- NEW FILE: ConnectionSettingPersistence.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.settings.persistence; import org.mc4j.ems.connection.settings.ConnectionSettings; import org.mc4j.ems.connection.EmsException; import java.io.ByteArrayOutputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.ByteArrayInputStream; import java.beans.XMLEncoder; import java.beans.ExceptionListener; import java.beans.PersistenceDelegate; import java.beans.Expression; import java.beans.Encoder; import java.beans.XMLDecoder; /** * @author Greg Hinkle (gh...@us...), May 9, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class ConnectionSettingPersistence { private static final ConnectionSettingPersistence INSTANCE = new ConnectionSettingPersistence(); public static ConnectionSettingPersistence getInstance() { return INSTANCE; } public String encodeSettings(ConnectionSettings settings) { ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(settings.getClass().getClassLoader()); try { ByteArrayOutputStream os = new ByteArrayOutputStream(); XMLEncoder e = new XMLEncoder(new BufferedOutputStream(os)); e.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception e) { throw new EmsException("Could not encode connection settings",e); } }); e.setPersistenceDelegate(File.class,new PersistenceDelegate() { protected Expression instantiate(Object oldInstance, Encoder out) { File f = (File) oldInstance; return new Expression(oldInstance, oldInstance.getClass(),"new", new Object[]{ f.getAbsolutePath() }); } }); e.writeObject(settings); e.close(); e.flush(); return os.toString(); } finally{ Thread.currentThread().setContextClassLoader(oldLoader); } } public ConnectionSettings decodeSettings(String xml) { ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(ConnectionSettings.class.getClassLoader()); try { XMLDecoder dec = new XMLDecoder(new ByteArrayInputStream(xml.getBytes())); ConnectionSettings newSettings = (ConnectionSettings) dec.readObject(); return newSettings; } finally{ Thread.currentThread().setContextClassLoader(oldLoader); } } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:44
|
Update of /cvsroot/mc4j/mc4j/modules/ems/lib/test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/lib/test Added Files: log4j.properties log4j.jar Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: log4j.jar --- (This appears to be a binary file; contents omitted.) --- NEW FILE: log4j.properties --- ### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=DEBUG, stdout, file |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:43
|
Update of /cvsroot/mc4j/mc4j/modules/ems/lib/jsr160-includes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/lib/jsr160-includes Added Files: mx4j-remote.jar mx4j.jar Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: mx4j.jar --- (This appears to be a binary file; contents omitted.) --- NEW FILE: mx4j-remote.jar --- (This appears to be a binary file; contents omitted.) |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:43
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/connection/bean In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/connection/bean Added Files: EmsBeanName.java EmsBean.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: EmsBean.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.bean; import org.mc4j.ems.connection.bean.attribute.EmsAttribute; import org.mc4j.ems.connection.bean.notification.EmsNotification; import org.mc4j.ems.connection.bean.operation.EmsOperation; import org.mc4j.ems.connection.support.ConnectionProvider; import java.util.List; import java.util.SortedSet; /** * @author Greg Hinkle (gh...@us...), Apr 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public interface EmsBean extends Comparable { EmsBeanName getBeanName(); ConnectionProvider getConnectionProvider(); <T> T getProxy(Class<T> beanInterface); void loadSynchronous() ; EmsAttribute getAttribute(String name); SortedSet<EmsAttribute> getAttributes(); /** * Refresh, from the server, all attribute values for an MBean * @return the List<EmsAttribute> attribute list */ List<EmsAttribute> refreshAttributes(); /** * Return a specific subset of EmsAttributes for a bean based on * the requested list of attributes by name. * This method can be used to load a group of attributes with a single * server call. Attributes updated in this fashion do update their * internal representation and do fire events on the changes. * @param attributeNames the names of attributes to load. * @return the list of requested attribute objects updated */ List<EmsAttribute> refreshAttributes(List<String> attributeNames); String getClassTypeName(); Class getClassType() throws ClassNotFoundException; EmsOperation getOperation(String name); SortedSet<EmsOperation> getOperations(); EmsNotification getNotification(String name); SortedSet<EmsNotification> getNotifications(); void unregister(); /** * This runs an live mbean server request to check that the * MBean represented by this bean is still registered. * @return true if the MBean is still registered in the MBeanServer */ boolean isRegistered(); boolean isNotificationEmiter(); boolean isHasUnsupportedType(); } --- NEW FILE: EmsBeanName.java --- package org.mc4j.ems.connection.bean; import java.util.Map; /** * Created by IntelliJ IDEA. * User: ghinkle * Date: Oct 25, 2005 * Time: 1:13:12 AM * To change this template use File | Settings | File Templates. */ public interface EmsBeanName extends Comparable { String getDomain(); String getCanonicalName(); Map<String,String> getKeyProperties(); String getKeyProperty(String key); boolean apply(String objectName); } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:42
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/connection/bean/operation In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/connection/bean/operation Added Files: EmsOperation.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: EmsOperation.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.bean.operation; import org.mc4j.ems.connection.bean.parameter.EmsParameter; import org.mc4j.ems.connection.EmsInvocationException; import java.util.List; import java.util.Collections; import java.util.Arrays; import java.io.Serializable; import java.io.ObjectStreamException; /** * @author Greg Hinkle (gh...@us...), Apr 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:36 $) */ public interface EmsOperation extends Comparable { String getName(); String getDescription(); List<EmsParameter> getParameters(); String getReturnType(); Impact getImpact(); Object invoke(Object... parameters) throws EmsInvocationException; public static class Impact implements Serializable { private int ordinal; private String name; public static Impact INFO = new Impact(0,"Info"); public static Impact ACTION = new Impact(0,"Action"); public static Impact ACTION_INFO = new Impact(0,"Action Info"); public static Impact UNKNOWN = new Impact(0,"Unknown"); private static final Impact[] arrayValues = {INFO, ACTION, ACTION_INFO, UNKNOWN }; public static final List VALUES = Collections.unmodifiableList(Arrays.asList(arrayValues)); private Impact(int ordinal, String name) { this.ordinal = ordinal; this.name = name; } public String getName() { return name; } public int getOrdinal() { return ordinal; }; private Object readResolve() throws ObjectStreamException { return arrayValues[ordinal]; } } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:42
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection/bean/operation In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection/bean/operation Added Files: DOperation.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: DOperation.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.bean.operation; import org.mc4j.ems.impl.jmx.connection.bean.DMBean; import org.mc4j.ems.impl.jmx.connection.bean.parameter.DParameter; import org.mc4j.ems.connection.bean.operation.EmsOperation; import org.mc4j.ems.connection.bean.parameter.EmsParameter; import org.mc4j.ems.connection.EmsInvocationException; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.ReflectionException; import java.util.List; import java.util.ArrayList; /** * @author Greg Hinkle (gh...@us...), Apr 4, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class DOperation implements EmsOperation { protected MBeanOperationInfo info; protected DMBean bean; public static final int MAX_EXECUTION_TIME = 10000; protected List<EmsParameter> parameters = new ArrayList<EmsParameter>(); protected Impact impact; public DOperation(MBeanOperationInfo info, DMBean bean) { this.info = info; this.bean = bean; MBeanParameterInfo[] params = info.getSignature(); for (MBeanParameterInfo param : params) { parameters.add(new DParameter(param)); } switch (info.getImpact()) { case MBeanOperationInfo.ACTION: impact = Impact.ACTION; break; case MBeanOperationInfo.INFO: impact = Impact.INFO; break; case MBeanOperationInfo.ACTION_INFO: impact = Impact.ACTION_INFO; break; default: impact = Impact.UNKNOWN; } } public String getName() { return info.getName(); } public String getDescription() { return info.getDescription(); } public List<EmsParameter> getParameters() { return parameters; } public Impact getImpact() { return impact; } public String getReturnType() { return info.getReturnType(); } @SuppressWarnings({"EmptyCatchBlock"}) public Object invoke(Object... parameters) throws EmsInvocationException { MBeanParameterInfo[] parameterInfos = info.getSignature(); final Object[] parameterValues = new Object[parameterInfos.length]; final String[] parameterTypes = new String[parameterInfos.length]; int i = 0; for (Object param : parameters) { String name = parameterInfos[i].getName(); parameterValues[i] = param; parameterTypes[i] = parameterInfos[i].getType(); i++; } class Future { boolean done = false; Object results; Exception e; } final Future f = new Future(); Runnable execution = new Runnable() { public void run() { try { f.results = bean.getConnectionProvider().getMBeanServer().invoke( bean.getObjectName(), getName(), parameterValues, parameterTypes); } catch (ReflectionException re) { Exception cause = re.getTargetException(); if (cause != null) { f.e = cause; } else { f.e = re; } } catch (Exception e) { f.e = e; } finally { f.done = true; } } }; // Need to run this outside the AWT update thread // so as not to freeze the UI in case of failed connection. Thread t = new Thread(execution, "MC4J Operation Execution [" + getName() + "]"); t.start(); // TODO: The timeout is nice, but providing a method that actually returns a future would be nice try { t.join(MAX_EXECUTION_TIME); } catch (InterruptedException e) { } if (!f.done) { // TODO: Write exceptions throw new EmsInvocationException("Operation timed out."); } if (f.e != null) { throw new EmsInvocationException("Exception on invocation of [" + getName() + "]" + f.e.toString(),f.e); } else { return f.results; } } public int compareTo(Object o) { DOperation otherOperation = (DOperation) o; return this.getName().compareTo( otherOperation.getName()); } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:42
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection/support/providers In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems-impl/org/mc4j/ems/impl/jmx/connection/support/providers Added Files: Oc4jConnectionProvider.java JBossConnectionProvider.java AbstractConnectionProvider.java JMXRemotingConnectionProvider.java PramatiConnectionProvider.java WebsphereConnectionProvider.java WeblogicConnectionProvider.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: WeblogicConnectionProvider.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.support.providers; import org.mc4j.ems.impl.jmx.connection.support.providers.proxy.GenericMBeanServerProxy; import javax.management.MBeanServer; import javax.naming.Context; import javax.naming.InitialContext; import java.lang.reflect.Method; import java.util.Hashtable; /** * This Node acts as a connection to a WebLogic(tm) MBean Server. * * @author Greg Hinkle (gh...@us...), March 2002 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class WeblogicConnectionProvider extends AbstractConnectionProvider { protected MBeanServer mbeanServer; public void doConnect() throws Exception { Context ctx = null; System.setProperty("jmx.serial.form", "1.0"); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); // Class.forName(super.initialContextFactory, true, loader); Hashtable props = new Hashtable(); props.put(Context.INITIAL_CONTEXT_FACTORY, connectionSettings.getInitialContextName()); props.put(Context.PROVIDER_URL, connectionSettings.getServerUrl()); props.put(Context.SECURITY_PRINCIPAL, connectionSettings.getPrincipal()); props.put(Context.SECURITY_CREDENTIALS, connectionSettings.getCredentials()); ctx = new InitialContext(props); //Class homeClass = Class.forName("weblogic.management.MBeanHome"); //Field field = homeClass.getField("ADMIN_JNDI_NAME"); //String adminJndiName = (String) field.get(null); //String adminJndiName = "weblogic.management.adminhome"; Object home = ctx.lookup(connectionSettings.getJndiName()); Class homeClass = home.getClass(); Method method = homeClass.getMethod("getMBeanServer",new Class[] { } ); Object mbeanServerObject = method.invoke(home, new Object[] { } ); GenericMBeanServerProxy proxy = new GenericMBeanServerProxy(mbeanServerObject); setStatsProxy(proxy); this.mbeanServer = proxy.buildServerProxy(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } public MBeanServer getMBeanServer() { return this.mbeanServer; } } --- NEW FILE: Oc4jConnectionProvider.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.support.providers; import org.mc4j.ems.impl.jmx.connection.support.providers.proxy.GenericMBeanServerProxy; import javax.management.MBeanServer; import javax.management.j2ee.Management; import javax.management.j2ee.ManagementHome; import javax.naming.Context; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; import java.lang.reflect.Field; import java.util.Hashtable; /** * This Node acts as a connection to an OC4J MBean Server via a MEJB. * The MEJB connection is ontained using a J2EE ApplicationClient. This * involves a workaround which requires a META-INF/application-client.xml to be * present in one of the JAR files which the client is loading. The application-client.xml * file can be completely empty, it just needs to be present. * <p/> * Accordingly, an empty application-client.xml has been added to the src/etc directory * and is included in the mc4j_core.jar file when it is created. * * @author Steve Button(sb...@us...), March 2004 * @version 1.0 */ public class Oc4jConnectionProvider extends AbstractConnectionProvider { private static final boolean M_DEBUG = false; protected MBeanServer mbeanServer; protected Management mejb; /** * Connect to the OC4J ManagementEJB. This should only be used while the JSR160 * interface is not available. * */ protected void doConnect() throws Exception { log("Oc4jConnectionProvider"); log(connectionSettings.toString()); logMessage("ConnectionSettings: " + connectionSettings.toString()); Context ctx = null; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); try { //The OC4J connection type Hashtable env = new Hashtable(); env.put(Context.PROVIDER_URL, connectionSettings.getServerUrl()); env.put(Context.SECURITY_PRINCIPAL, connectionSettings.getPrincipal()); env.put(Context.SECURITY_CREDENTIALS, connectionSettings.getCredentials()); env.put(Context.INITIAL_CONTEXT_FACTORY, connectionSettings.getInitialContextName()); Context oc4jctx = new InitialContext(env); Object obj = (ManagementHome) oc4jctx.lookup(connectionSettings.getJndiName()); ManagementHome mgmtHome = (ManagementHome) PortableRemoteObject.narrow(obj, ManagementHome.class); Management oc4jmbs = mgmtHome.create(); GenericMBeanServerProxy proxy = new GenericMBeanServerProxy(getMBeanServer()); setStatsProxy(proxy); this.mbeanServer = proxy.buildServerProxy(); this.mejb = oc4jmbs; super.connect(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } public String getConstant(Class clazz, String name) throws Exception { Field field = clazz.getField(name); return (String) field.get(null); } public void doDisconnect() { //this.connector.close(); super.connected = false; } public Management getMEJB() { return this.mejb; } public MBeanServer getMBeanServer() { return this.mbeanServer; } private void logMessage(String msg) { if (!M_DEBUG) return; /* NotifyDescriptor d = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(d);*/ } private void log(String msg) { if (!M_DEBUG) return; System.out.println(msg); } } --- NEW FILE: PramatiConnectionProvider.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.support.providers; import org.mc4j.ems.impl.jmx.connection.support.providers.proxy.JMXRemotingMBeanServerProxy; import org.mc4j.ems.impl.jmx.connection.support.providers.proxy.StatsProxy; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.naming.Context; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class PramatiConnectionProvider extends AbstractConnectionProvider { private JMXConnector jmxConnector; private MBeanServerConnection serverConnection; private MBeanServer mbeanServer; private static final String PROTOCOL_PROVIDER_PACKAGE = "jmx.remote.protocol.provider.pkgs"; private static final String PRAMATI_PROTOCOL_PROVIDER_PACKAGE = "com.pramati.jmx.connector"; protected void doConnect() throws Exception { ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); // Create an RMI connector client JMXServiceURL url = new JMXServiceURL(this.connectionSettings.getServerUrl()); HashMap<String, Object> env = new HashMap<String, Object>(); /*if ((connectionSettings.getInitialContextName() != null) && (connectionSettings.getInitialContextName().trim().length() > 0)) { env.put(Context.INITIAL_CONTEXT_FACTORY, connectionSettings.getInitialContextName()); } else { env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); }*/ env.put(Context.SECURITY_PRINCIPAL, connectionSettings.getPrincipal()); env.put(Context.SECURITY_CREDENTIALS, connectionSettings.getCredentials()); // Set and custom, advanced properties if (connectionSettings.getAdvancedProperties() != null) { for (Map.Entry<Object, Object> entry : connectionSettings.getAdvancedProperties().entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); env.put(key, value); } } //<prashant> Change here </prashant> env.put(PROTOCOL_PROVIDER_PACKAGE, PRAMATI_PROTOCOL_PROVIDER_PACKAGE);//Is this an advanced Property? // Set the credential String[] credentials = new String[]{ this.connectionSettings.getPrincipal(), this.connectionSettings.getCredentials()}; env.put(JMXConnector.CREDENTIALS, credentials); this.jmxConnector = JMXConnectorFactory.connect(url, env); serverConnection = this.jmxConnector.getMBeanServerConnection(); //serverConnection.queryNames(null,null); StatsProxy proxy = new JMXRemotingMBeanServerProxy(serverConnection); setStatsProxy(proxy); this.mbeanServer = proxy.buildServerProxy(); super.connect(); } public void doDisconnect() { try { this.jmxConnector.close(); } catch (IOException e) { e.printStackTrace(); } super.connected = false; } public MBeanServer getMBeanServer() { return this.mbeanServer; } } --- NEW FILE: WebsphereConnectionProvider.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.support.providers; import org.mc4j.ems.impl.jmx.connection.support.providers.proxy.GenericMBeanServerProxy; import javax.management.MBeanServer; import javax.management.j2ee.Management; import javax.naming.Context; import javax.naming.NamingException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URI; import java.util.Properties; /** * This Node acts as a connection to a WebSphere(tm) MBean Server (TMX4J based). * * @author Greg Hinkle (gh...@us...), January 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class WebsphereConnectionProvider extends AbstractConnectionProvider { protected GenericMBeanServerProxy statsProxy; protected MBeanServer mbeanServer; private Management mejb; private static final String MEJB_JNDI = "ejb/mgmt/MEJB"; protected void doConnect() throws Exception { Context ctx = null; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); try { //System.setProperty("jmx.serial.form", "1.0"); /* From a WS admin article Properties clientProps = new Properties(); connectProps.setProperty(AdminClient.CONNECTOR_TYPE, AdminClient.CONNECTOR_TYPE_SOAP); connectProps.setProperty(AdminClient.CONNECTOR_HOST, "localhost"); connectProps.setProperty(AdminClient.CONNECTOR_PORT, "8879"); AdminClient adminClient = null; try { adminClient = AdminClientFactory.createAdminClient(clientProps); } catch (ConnectorException e) { System.out.println("Exception creating admin client: " + e); } */ Class adminClientClass = Class.forName("com.ibm.websphere.management.AdminClient", true, this.getClass().getClassLoader()); Class adminClientFactoryClass = Class.forName("com.ibm.websphere.management.AdminClientFactory"); // TODO GH: LATEST! This works from a SUN VM... // Autodetect the vm and suggest the correct factory // Hashtable env = new Hashtable(); // env.put(Context.INITIAL_CONTEXT_FACTORY, // "com.sun.jndi.cosnaming.CNCtxFactory"); // env.put(Context.PROVIDER_URL, "corbaname:iiop:localhost:2809/NameServiceServerRoot"); //env.put(Context.PROVIDER_URL, "iiop://localhost:2809/NameServiceServerRoot"); // ctx = new InitialContext(env); //this.mejb = retrieveMEJB(ctx); /* Properties orbprops = new Properties(); orbprops .put("org.omg.CORBA.ORBClass", "com.ibm.CORBA.iiop.ORB"); orbprops .put("com.ibm.CORBA.ORBInitRef.NameService", "corbaloc:iiop:localhost:2809/NameService"); orbprops .put("com.ibm.CORBA.ORBInitRef.NameServiceServerRoot", "corbaloc:iiop:localhost:2809/NameServiceServerRoot"); ORB _orb = ORB.init((String[])null, orbprops ); org.omg.CORBA.Object obj = _orb.resolve_initial_references("NameService"); NamingContextExt initCtx = NamingContextExtHelper.narrow(obj); Object objref = initCtx.resolve_str("java:comp/env/ejb/mgmt/MEJB"); ManagementHome home = (ManagementHome)PortableRemoteObject.narrow(objref,ManagementHome.class); this.mejb = home.create(); */ //props.put(Context.SECURITY_PRINCIPAL, connectionSettings.getPrincipal()); //props.put(Context.SECURITY_CREDENTIALS, connectionSettings.getCredentials()); Properties props = new Properties(); URI serverUrl = new URI(connectionSettings.getServerUrl()); if (serverUrl.getScheme().equalsIgnoreCase("http")) { System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager"); //Security.addProvider(new sun.security.provider.Sun()); System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol"); //System.setProperty("ssl.SocketFactory.provider", "javax.net.ssl.SSLSocketFactory"); props.put( getConstant(adminClientClass, "CONNECTOR_TYPE"), getConstant(adminClientClass, "CONNECTOR_TYPE_SOAP")); } else { props.put( getConstant(adminClientClass, "CONNECTOR_TYPE"), getConstant(adminClientClass, "CONNECTOR_TYPE_RMI")); } props.setProperty( getConstant(adminClientClass, "CONNECTOR_SECURITY_ENABLED"), "false"); props.put( getConstant(adminClientClass, "CONNECTOR_HOST"), serverUrl.getHost()); props.put( getConstant(adminClientClass, "CONNECTOR_PORT"), String.valueOf(serverUrl.getPort())); Method createMethod = adminClientFactoryClass.getMethod("createAdminClient",new Class[] { Properties.class }); Object adminClient = createMethod.invoke(null, new Object[] { props }); this.statsProxy = new GenericMBeanServerProxy(adminClient); this.mbeanServer = statsProxy.buildServerProxy(); //this.mejb = retrieveMEJB(ctx); super.connect(); // TODO GH: Customize exception and error messages to help // with typical problems (jsse jars missing, passwords, etc.) } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } public String getConstant(Class clazz, String name) throws Exception { Field field = clazz.getField(name); return (String) field.get(null); } // public Management getMEJB() { // return mejb; // } private Management retrieveMEJB(Context ic) { try { java.lang.Object objref = ic.lookup(MEJB_JNDI); // ManagementHome home = // (ManagementHome)PortableRemoteObject.narrow(objref,ManagementHome.class); // Management mejb = home.create(); return mejb; } catch(NamingException ne) { // ErrorManager.getDefault().notify(ne); // } catch(RemoteException re) { // ErrorManager.getDefault().notify(re); } catch(Exception ce) { // ErrorManager.getDefault().notify(ce); } return null; } public MBeanServer getMBeanServer() { return this.mbeanServer; } public long getRoundTrips() { return statsProxy.getRoundTrips(); } public long getFailures() { return statsProxy.getFailures(); } } --- NEW FILE: AbstractConnectionProvider.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.support.providers; import org.mc4j.ems.connection.EmsConnection; import org.mc4j.ems.connection.EmsConnectException; import org.mc4j.ems.connection.settings.ConnectionSettings; import org.mc4j.ems.connection.support.ConnectionProvider; import org.mc4j.ems.connection.support.ConnectionListener; import org.mc4j.ems.impl.jmx.connection.DConnection; import org.mc4j.ems.impl.jmx.connection.support.providers.proxy.StatsProxy; import javax.management.MBeanServer; import java.util.Timer; import java.util.List; import java.util.ArrayList; /** * This Node is the abstract node representing a connection to a JMX Server. * * @author Greg Hinkle (gh...@us...), January 2002 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public abstract class AbstractConnectionProvider implements ConnectionProvider { // Persistable settings protected ConnectionSettings connectionSettings; // Live information protected boolean connected = false; protected boolean connectionFailure = false; protected DConnection existingConnection; protected List<ConnectionListener> connectionListeners = new ArrayList<ConnectionListener>(); private Timer refreshTimer; private StatsProxy statsProxy; protected int connectionRoundTrips; public abstract MBeanServer getMBeanServer(); public Object getMEJB() { return null; } public ConnectionSettings getConnectionSettings() { return connectionSettings; } public int compareTo(Object o) { ConnectionProvider otherProvider = (ConnectionProvider) o; return this.connectionSettings.getConnectionName().compareTo(otherProvider.getConnectionSettings().getConnectionName()); } public void initialize(ConnectionSettings settings) { this.connectionSettings = settings; } public boolean isConnected() { return this.connected; } public void setConnected(boolean connected) throws Exception { if (this.connected) { disconnect(); } else { connect(); } } public final EmsConnection connect() { this.connected = true; this.connectionFailure = false; try { doConnect(); } catch (Exception e) { throw new EmsConnectException("Could not connect [" + connectionSettings.getServerUrl() + "] " + e.toString(), e); } if (existingConnection == null) { DConnection connection = new DConnection("unknown",this); this.existingConnection = connection; } else { this.existingConnection.setConnectionProvider(this); } for (ConnectionListener listener : connectionListeners) { listener.connect(); } return this.existingConnection; } protected abstract void doConnect() throws Exception; public final void disconnect() { if (this.refreshTimer != null) this.refreshTimer.cancel(); this.connected = false; this.connectionFailure = false; try { doDisconnect(); } catch (Exception e) { throw new EmsConnectException("Could not close connection " + e.toString(), e); } for (ConnectionListener listener : connectionListeners) { listener.disconnect(); } } // TODO Should this be abstract? protected void doDisconnect() throws Exception { } public void addConnectionListener(ConnectionListener connectionListener) { this.connectionListeners.add(connectionListener); } public void removeConnectionListener(ConnectionListener connectionListener) { this.connectionListeners.remove(connectionListener); } public long getRoundTrips() { if (statsProxy != null) return statsProxy.getRoundTrips(); else return 0; } public long getFailures() { if (statsProxy != null) return statsProxy.getFailures(); else return 0; } public StatsProxy getStatsProxy() { return statsProxy; } public void setStatsProxy(StatsProxy statsProxy) { this.statsProxy = statsProxy; } } --- NEW FILE: JMXRemotingConnectionProvider.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.support.providers; import org.mc4j.ems.connection.EmsConnectException; import org.mc4j.ems.connection.EmsException; import org.mc4j.ems.impl.jmx.connection.support.providers.proxy.JMXRemotingMBeanServerProxy; import org.mc4j.ems.impl.jmx.connection.support.providers.proxy.JSR77ManagementMBeanServerProxy; import org.mc4j.ems.impl.jmx.connection.support.providers.proxy.StatsProxy; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.management.remote.rmi.RMIConnector; import javax.management.remote.rmi.RMIServer; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.rmi.PortableRemoteObject; import javax.rmi.ssl.SslRMIClientSocketFactory; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Hashtable; import java.util.Map; import java.util.Set; /** * Represents a Connection to a JSR 160 compliant RMI server * * @author Greg Hinkle (gh...@us...), December 2003 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class JMXRemotingConnectionProvider extends AbstractConnectionProvider { private JMXConnector jmxConnector; private MBeanServerConnection serverConnection; private MBeanServer mbeanServer; private Object mejb; private static final String MEJB_JNDI = "ejb/mgmt/MEJB"; protected void doConnect() { try { ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); // Create an RMI connector client JMXServiceURL url = new JMXServiceURL(this.connectionSettings.getServerUrl()); Hashtable env = new Hashtable(); if ((connectionSettings.getInitialContextName() != null) && (connectionSettings.getInitialContextName().trim().length() > 0)) { env.put(Context.INITIAL_CONTEXT_FACTORY, connectionSettings.getInitialContextName()); } else { env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); } if (connectionSettings.getPrincipal() != null) env.put(Context.SECURITY_PRINCIPAL, connectionSettings.getPrincipal()); if (connectionSettings.getCredentials() != null) env.put(Context.SECURITY_CREDENTIALS, connectionSettings.getCredentials()); if (connectionSettings.getConnectionType().isUseManagementHome()) { InitialContext ctx = new InitialContext(env); this.mejb = retrieveMEJB(ctx); } /* Test crap ObjectName test = new ObjectName("*:Name=examplesServer,Type=ServerRuntime,*"); Set testResults = this.mejb.queryNames(test, null); for (Iterator iterator = testResults.iterator(); iterator.hasNext();) { ObjectName testName = (ObjectName) iterator.next(); System.out.println("MBean: " + testName.getCanonicalName()); MBeanInfo testInfo = this.mejb.getMBeanInfo(testName); MBeanAttributeInfo[] atts = testInfo.getAttributes(); for (int i = 0; i < atts.length; i++) { MBeanAttributeInfo att = atts[i]; System.out.println("\tAttribute: " + att.getName() + ":" + att.getType()); } } */ //env.put("jmx.remote.protocol.provider.pkgs","com.pramati.jmx.connector"); // Set and custom, advanced properties if (connectionSettings.getAdvancedProperties() != null) { Set<Map.Entry<Object,Object>> entries = connectionSettings.getAdvancedProperties().entrySet(); for (Map.Entry entry : entries) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); env.put(key, value); } } // Set the credential String[] credentials = new String[]{ this.connectionSettings.getPrincipal(), this.connectionSettings.getCredentials()}; env.put(JMXConnector.CREDENTIALS, credentials); testSsl(); if (ssl) { this.jmxConnector = new RMIConnector(sslStub, null); } else { this.jmxConnector = JMXConnectorFactory.connect(url, env); serverConnection = this.jmxConnector.getMBeanServerConnection(); } //serverConnection.queryNames(null,null); StatsProxy proxy = null; if (connectionSettings.getConnectionType().isUseManagementHome()) { proxy = new JSR77ManagementMBeanServerProxy(this.mejb); } else { proxy = new JMXRemotingMBeanServerProxy(serverConnection); } setStatsProxy(proxy); this.mbeanServer = proxy.buildServerProxy(); } catch (MalformedURLException e) { throw new EmsConnectException("Malformed url", e); } catch (IOException e) { throw new EmsConnectException("IOException: Check service availability",e); } catch (NamingException e) { throw new EmsConnectException("Naming failure",e); } } RMIServer sslStub; boolean ssl = false; private boolean testSsl() { JMXServiceURL url = null; String host = null; int port = 0; String start = "/jndi/rmi://"; String end = "/jmxrmi"; try { url = new JMXServiceURL(this.connectionSettings.getServerUrl()); String path = url.getURLPath(); if (path.startsWith(start)) { String hostAndPort = path.substring(start.length(), path.length() - end.length()); String[] hp = hostAndPort.split(":"); host = hp[0]; port = Integer.parseInt(hp[1]); } // Try SSL Registry registry = LocateRegistry.getRegistry(host,port, new SslRMIClientSocketFactory()); sslStub = (RMIServer) registry.lookup("jmxrmi"); ssl = true; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); // Try regular try { Registry registry = LocateRegistry.getRegistry(url.getHost(),url.getPort()); sslStub = (RMIServer) registry.lookup("jmxrmi"); } catch (RemoteException e1) { e1.printStackTrace(); } catch (NotBoundException e1) { e1.printStackTrace(); } } catch (NotBoundException e) { e.printStackTrace(); } return ssl; } public void doDisconnect() throws IOException { this.jmxConnector.close(); } private Object retrieveMEJB(Context ic) { try { java.lang.Object objref = ic.lookup(MEJB_JNDI); // ManagementHome home = // (ManagementHome) PortableRemoteObject.narrow(objref, ManagementHome.class); // Management mejb = home.create(); // return mejb; Class managementHomeClass = Class.forName("javax.management.j2ee.ManagementHome.class"); Object managementHome = PortableRemoteObject.narrow(objref, managementHomeClass); Method m = managementHomeClass.getMethod("create",new Class[] {}); Object managementEjb = m.invoke(managementHome); return managementEjb; } catch (NamingException ne) { throw new EmsException("",ne); }catch (Exception ce) { throw new EmsException("",ce); } } public MBeanServer getMBeanServer() { return this.mbeanServer; } } --- NEW FILE: JBossConnectionProvider.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.impl.jmx.connection.support.providers; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mc4j.ems.connection.ConnectionException; import org.mc4j.ems.impl.jmx.connection.support.providers.proxy.GenericMBeanServerProxy; import javax.management.MBeanServer; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessController; import java.security.Principal; import java.security.PrivilegedAction; import java.util.Properties; /** * Represents a Connection to a JBoss JMX Server. This connection * works against the JBoss RMI connector. * * @author Greg Hinkle (gh...@us...), January 2002 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class JBossConnectionProvider extends AbstractConnectionProvider { private MBeanServer mbeanServer; private GenericMBeanServerProxy proxy; // private Management mejb; private static final String MEJB_JNDI = "ejb/mgmt/MEJB"; private static Log log = LogFactory.getLog(JBossConnectionProvider.class); protected void doConnect() throws Exception { ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); try { System.setProperty("jmx.serial.form", "1.1"); // TODO: Used to need this, but it appears to work without now (verify) // Change the context classloader as the JBoss version of the // MBeanServerFactory uses it to find their class ClassLoader childLoader = this.getClass().getClassLoader(); Thread.currentThread().setContextClassLoader(childLoader); InitialContext context = getInitialContext(); Object rmiAdaptor = context.lookup(connectionSettings.getJndiName()); // GH: Works around a real strange "LinkageError: Duplicate class found" // by loading these classes in the main connection classloader //Class foo = RMINotificationListener.class; //foo = RMINotificationListenerMBean.class; // TODO GH!: I think this fixes notifications, but breaks compatibility with at least 3.0.8 //RMIConnectorImpl connector = new RMIConnectorImpl(rmiAdaptor); if (this.proxy != null) { // This is a reconnect proxy.setRemoteServer(rmiAdaptor); } else { this.proxy = new GenericMBeanServerProxy(rmiAdaptor); this.proxy.setProvider(this); setStatsProxy(proxy); this.mbeanServer = proxy.buildServerProxy(); } //this.mgmt = retrieveMEJB(); // Set the context classloader back to what it was } finally { Thread.currentThread().setContextClassLoader(currentLoader); } } public static final String JNDI_LOGIN_CONTEXT_FACTORY_CLASS = "org.jboss.security.jndi.JndiLoginInitialContextFactory"; private InitialContext getInitialContext() throws NamingException { Properties props = connectionSettings.getAdvancedProperties(); if (connectionSettings.getPrincipal() != null && connectionSettings.getPrincipal().length() != 0) { try { Class.forName(JNDI_LOGIN_CONTEXT_FACTORY_CLASS); log.debug("Utilizing JNDI Login Context Factory for secured access [" + JNDI_LOGIN_CONTEXT_FACTORY_CLASS + "]"); props.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_LOGIN_CONTEXT_FACTORY_CLASS); props.put(Context.SECURITY_PRINCIPAL, connectionSettings.getPrincipal()); props.put(Context.SECURITY_CREDENTIALS, connectionSettings.getCredentials()); } catch (ClassNotFoundException e) { log.debug("JNDI Login Context Factory not available, directly utilizing SecurityAssociation"); try { props.put(Context.INITIAL_CONTEXT_FACTORY, connectionSettings.getInitialContextName()); Class simplePrincipalClass = Class.forName("org.jboss.security.SimplePrincipal"); Principal p = (Principal) simplePrincipalClass.getConstructor(String.class).newInstance(connectionSettings.getPrincipal()); SetPrincipalInfoAction.setPrincipalInfo(p,connectionSettings.getCredentials()); } catch (ClassNotFoundException e1) { throw new ConnectionException("Secured connection not available with this version of JBoss " + e1.toString(),e1); } catch (Exception e1) { throw new ConnectionException("Unable to make secured connection to JBoss due to missing or unexpected security classes",e1); } } } else { props.put(Context.INITIAL_CONTEXT_FACTORY, connectionSettings.getInitialContextName()); } props.put(Context.PROVIDER_URL, connectionSettings.getServerUrl()); InitialContext context = new InitialContext(props); return context; } private static class SetPrincipalInfoAction implements PrivilegedAction { Principal principal; Object credential; public SetPrincipalInfoAction(Principal principal, Object credential) { this.principal = principal; this.credential = credential; } public Object run() { try { Class saClass = Class.forName("org.jboss.security.SecurityAssociation"); Method setCredentialMethod = saClass.getMethod("setCredential", Object.class); setCredentialMethod.invoke(null, credential); credential = null; Method setPrincipleMethod = saClass.getMethod("setPrincipal", Principal.class); setPrincipleMethod.invoke(null, principal); principal = null; return null; } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; } static void setPrincipalInfo(Principal principal, Object credential) { SetPrincipalInfoAction action = new SetPrincipalInfoAction(principal, credential); //noinspection unchecked AccessController.doPrivileged(action); } } /* GH: an aborted attempt at manually changing the polling type public class RMIAdaptorExtension extends RMIConnectorImpl { public RMIAdaptorExtension(RMIAdaptor rmiAdaptor) { super(rmiAdaptor); try { Field field = RMIConnectorImpl.class.getField("mEventType"); if (!Modifier.isPrivate(field.getModifiers())) { field.set(this, new Integer(RMIConnectorImpl.NOTIFICATION_TYPE_POLLING)); } } catch (NoSuchFieldException nsfe) { } catch (IllegalAccessException iae) { } } } */ public void doDisconnect() { } /* public Object getMEJB() { if (mejb == null) { mejb = retrieveMEJB(); } return mejb; } private Management retrieveMEJB() { try { Context ic = getInitialContext(); java.lang.Object objref = ic.lookup(MEJB_JNDI); ManagementHome home = (ManagementHome)PortableRemoteObject.narrow(objref,ManagementHome.class); Management mejb = home.create(); return mejb; } catch(NamingException ne) { ErrorManager.getDefault().notify(ne); } catch(RemoteException re) { ErrorManager.getDefault().notify(re); } catch(Exception ce) { ErrorManager.getDefault().notify(ce); } return null; } */ public MBeanServer getMBeanServer() { return this.mbeanServer; } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:42
|
Update of /cvsroot/mc4j/mc4j/modules/ems/lib/build In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/lib/build Added Files: objectprofiler.jar ognl-2.6.7.jar jboss-j2ee.jar javax77.jar mx4j-jmx.jar testng-4.1-jdk15.jar Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: mx4j-jmx.jar --- (This appears to be a binary file; contents omitted.) --- NEW FILE: ognl-2.6.7.jar --- (This appears to be a binary file; contents omitted.) --- NEW FILE: objectprofiler.jar --- (This appears to be a binary file; contents omitted.) --- NEW FILE: javax77.jar --- (This appears to be a binary file; contents omitted.) --- NEW FILE: testng-4.1-jdk15.jar --- (This appears to be a binary file; contents omitted.) --- NEW FILE: jboss-j2ee.jar --- (This appears to be a binary file; contents omitted.) |
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/connection/support/classloader In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/connection/support/classloader Added Files: DeepClassLoaderOrig.java ClassLoaderFactory.java DeepClassLoader.java ChildFirstClassloader.java NestedJarClassLoader.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: NestedJarClassLoader.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.classloader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.net.URL; import java.net.URLClassLoader; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.List; /** * <p>This classloader is able to load classes from the contents of jar files available * in the parent classloader. This mechanism creates support for nested jar file * deployment.</p> * <p/> * <p>To use this classloader, create a jar with other jars in it and put the main jar * in the parent classloader passed to the constructor of this classloader. In the * urls parameter, supply jars with the protocol "deepjar" and their path within the * parent classloader.</p> * <p/> * <p>Note: This class and the deepjar handler must currently reside in the application * classpath as the URL class will not be able to find the handler otherwise.</p> * * @author Greg Hinkle (gh...@us...), May 9, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class NestedJarClassLoader extends URLClassLoader { public final static String JAVA_PROTOCOL_HANDLER = "java.protocol.handler.pkgs"; public static Log log = LogFactory.getLog(NestedJarClassLoader.class); /** * TODO this is a hack because the JBoss NamingContext feels compelled to send * along the context classloader's URLs. Not having the deepjar handler on the * other side of course makes the server RMI side unhappy when it goes to * deserialize and reconstitute a deepjar URL. Stupid URL handler system. * Stupid JBoss. Boy, what a bitter moment. */ public URL[] getURLs() { URL[] all = super.getURLs(); List<URL> safe = new ArrayList<URL>(); for (URL url : all) { if (url.getProtocol().indexOf("deepjar") < 0) safe.add(url); } return safe.toArray(new URL[safe.size()]); } static { String handlerPackage = "org.mc4j.ems.connection.support.classloader"; String value = System.getProperty(JAVA_PROTOCOL_HANDLER); if (value == null) { value = handlerPackage; } else { value += "|" + handlerPackage; } System.setProperty("java.protocol.handler.pkgs", value); log.debug("Updated URL Handler Packages to: " + System.getProperty("java.protocol.handler.pkgs")); } // TODO synchronize me static Map<URL, ClassLoader> loadMap = new HashMap<URL, ClassLoader>(); public static NestedJarClassLoader newInstance(URL[] urls, final ClassLoader parent) { return new NestedJarClassLoader(urls, parent); } /* protected void addParentClassloaderArchive(String resource) throws IOException { File file = File.createTempFile("lib-",".jar"); InputStream is = getParent().getResourceAsStream(resource); FileOutputStream fos = new FileOutputStream(file); super.addURL(url); } */ protected Class<?> findClass(String string) throws ClassNotFoundException { if (string.indexOf("MBeanServer") >= 0) { log.debug("MBeanServer Class being loaded in ClassLoader " + this); } return super.findClass(string); } public NestedJarClassLoader(URL[] urls, ClassLoader parent) { super(urls, parent); for (URL url : urls) { if ("deepjar".equals(url.getProtocol())) loadMap.put(url, parent); } } public static ClassLoader getRunningLoader(URL url) { return loadMap.get(url); } public static void main(String[] args) throws Exception { //test long start = System.currentTimeMillis(); NestedJarClassLoader cl = NestedJarClassLoader.newInstance(new URL[]{ new URL("deepjar://org-mc4j-ems-impl.jar")}, NestedJarClassLoader.class.getClassLoader()); Class testClass = Class.forName("org.mc4j.ems.impl.jmx.connection.DConnection", false, cl); log.info(testClass); log.info("Time: " + (System.currentTimeMillis() - start) + "ns"); start = System.currentTimeMillis(); testClass = Class.forName("org.mc4j.ems.impl.jmx.connection.PooledConnectionTracker", false, cl); log.info(testClass); log.info("Time: " + (System.currentTimeMillis() - start) + "ns"); } } --- NEW FILE: DeepClassLoaderOrig.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.classloader; import org.mc4j.ems.connection.support.classloader.deepjar.Handler; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.Manifest; /** * @author Greg Hinkle (gh...@us...), May 9, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class DeepClassLoaderOrig extends ClassLoader { public final static String TMP = "tmp"; public final static String UNPACK = "unpack"; public final static String EXPAND = "One-Jar-Expand"; public final static String CLASS = ".class"; public final static String JAVA_PROTOCOL_HANDLER = "java.protocol.handler.pkgs"; protected String name; static { String handlerPackage = "org.mc4j.ems.connection.support.classloader.deepjar"; System.setProperty(JAVA_PROTOCOL_HANDLER, handlerPackage); } protected Map byteCode = new HashMap(); protected Map pdCache = Collections.synchronizedMap(new HashMap()); protected String jarName, mainJar, wrapDir; protected boolean delegateToParent; protected class ByteCode { public ByteCode(String $name, String $original, byte $bytes[], String $codebase) { name = $name; original = $original; bytes = $bytes; codebase = $codebase; } public byte bytes[]; public String name, original, codebase; } /** * Load a set of "deepjar" urls from the parent classloader * These deepjar urls represent relative paths within the parent classloader to * jar files that should be the basis for this classloader level * @param parent * @param jars */ public DeepClassLoaderOrig(ClassLoader parent, URL[] jars) { super(parent); } public String load(String mainClass) { return load(mainClass, null); } public String load(String mainClass, String jarName) { try { JarFile jarEnumeration = new JarFile(jarName); Enumeration enum = jarEnumeration.entries(); Manifest manifest = jarEnumeration.getManifest(); String expandPaths[] = null; // TODO: Allow a destination directory (relative or absolute) to // be specified like this: // One-Jar-Expand: build=../expanded String expand = manifest.getMainAttributes().getValue(EXPAND); if (expand != null) { VERBOSE(EXPAND + "=" + expand); expandPaths = expand.split(","); } while ( enum.hasMoreElements()) { JarEntry entry = (JarEntry) enum.nextElement(); if (entry.isDirectory()) continue; // The META-INF/MANIFEST.MF file can contain a property which names // directories in the JAR to be expanded (comma separated). For example: // Expand-Dirs: build,tmp,webapps boolean expanded = false; String name = entry.getName(); if (expandPaths != null) { // TODO: Can't think of a better way to do this right now. // This code really doesn't need to be optimized anyway. for (int i = 0; i < expandPaths.length; i++) { if (name.startsWith(expandPaths[i])) { File dest = new File(name); // Override if ZIP file is newer than existing. if (!dest.exists() || dest.lastModified() < entry.getTime()) { INFO("Expanding " + name); if (dest.exists()) INFO("Update because lastModified=" + new Date(dest.lastModified()) + ", entry=" + new Date(entry.getTime())); dest.getParentFile().mkdirs(); VERBOSE("using jarEnumeration.getInputStream(" + entry + ")"); InputStream is = jarEnumeration.getInputStream(entry); FileOutputStream os = new FileOutputStream(dest); copy(is, os); is.close(); os.close(); } else { VERBOSE(name + " already expanded"); } expanded = true; break; } } } if (expanded) continue; String jar = entry.getName(); if (wrapDir != null && jar.startsWith(wrapDir) || jar.startsWith(LIB_PREFIX) || jar.startsWith(MAIN_PREFIX)) { if (wrapDir != null && !entry.getName().startsWith(wrapDir)) continue; // Load it! INFO("caching " + jar); VERBOSE("using jarEnumeration.getInputStream(" + entry + ")"); { // Note: loadByteCode consumes the input stream, so make sure its scope // does not extend beyond here. InputStream is = jarEnumeration.getInputStream(entry); if (is == null) throw new IOException("Unable to load resource /" + jar + " using " + this); loadByteCode(is, jar); } // Do we need to look for a main class? if (jar.startsWith(MAIN_PREFIX)) { if (mainClass == null) { JarInputStream jis = new JarInputStream(jarEnumeration.getInputStream(entry)); mainClass = jis.getManifest().getMainAttributes().getValue(Attributes.Name.MAIN_CLASS); mainJar = jar; } else if (mainJar != null) { WARNING("A main class is defined in multiple jar files inside " + MAIN_PREFIX + mainJar + " and " + jar); WARNING("The main class " + mainClass + " from " + mainJar + " will be used"); } } } else if (wrapDir == null && name.startsWith(UNPACK)) { // Unpack into a temporary directory which is on the classpath of // the application classloader. Badly designed code which relies on the // application classloader can be made to work in this way. InputStream is = this.getClass().getResourceAsStream("/" + jar); if (is == null) throw new IOException(jar); // Make a sentinel. File dir = new File(TMP); File sentinel = new File(dir, jar.replace('/', '.')); if (!sentinel.exists()) { INFO("unpacking " + jar + " into " + dir.getCanonicalPath()); loadByteCode(is, jar, TMP); sentinel.getParentFile().mkdirs(); sentinel.createNewFile(); } } else if (name.endsWith(CLASS)) { // A plain vanilla class file rooted at the top of the jar file. loadBytes(entry, jarEnumeration.getInputStream(entry), "/", null); } } // If mainClass is still not defined, check the manifest of the jar file. if (mainClass == null) { mainClass = jarEnumeration.getManifest().getMainAttributes().getValue(Attributes.Name.MAIN_CLASS); } } catch (IOException iox) { System.err.println("Unable to load resource: " + iox); iox.printStackTrace(System.err); } return mainClass; } protected void loadByteCode(InputStream is, String jar) throws IOException { loadByteCode(is, jar, null); } protected void loadByteCode(InputStream is, String jar, String tmp) throws IOException { JarInputStream jis = new JarInputStream(is); JarEntry entry = null; // TODO: implement lazy loading of bytecode. while ((entry = jis.getNextJarEntry()) != null) { if (entry.isDirectory()) continue; loadBytes(entry, jis, jar, tmp); } } protected void loadBytes(JarEntry entry, InputStream is, String jar, String tmp) throws IOException { String entryName = entry.getName().replace('/', '.'); int index = entryName.lastIndexOf('.'); String type = entryName.substring(index + 1); // Because we are doing stream processing, we don't know what // the size of the entries is. So we store them dynamically. ByteArrayOutputStream baos = new ByteArrayOutputStream(); copy(is, baos); if (tmp != null) { // Unpack into a temporary working directory which is on the classpath. File file = new File(tmp, entry.getName()); file.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(file); fos.write(baos.toByteArray()); fos.close(); } else { // If entry is a class, check to see that it hasn't been defined // already. Class names must be unique within a classloader because // they are cached inside the VM until the classloader is released. byte[] bytes = baos.toByteArray(); if (type.equals("class")) { if (alreadyCached(entryName, jar, bytes)) return; byteCode.put(entryName, new ByteCode(entryName, entry.getName(), bytes, jar)); VERBOSE("cached bytes for class " + entryName); } else { // Another kind of resource. Cache this by name, and also prefixed // by the jar name. Don't duplicate the bytes. This allows us // to map resource lookups to either jar-local, or globally defined. String localname = jar + "/" + entryName; byteCode.put(localname, new ByteCode(localname, entry.getName(), bytes, jar)); VERBOSE("cached bytes for local name " + localname); if (alreadyCached(entryName, jar, bytes)) return; byteCode.put(entryName, new ByteCode(entryName, entry.getName(), bytes, jar)); VERBOSE("cached bytes for entry name " + entryName); } } } protected boolean classPool = false; /** * Locate the named class in a jar-file, contained inside the * jar file which was used to load <u>this</u> class. */ protected Class findClass(String name) throws ClassNotFoundException { // Make sure not to load duplicate classes. Class cls = findLoadedClass(name); if (cls != null) return cls; // Look up the class in the byte codes. String cache = name.replace('/', '.') + ".class"; ByteCode bytecode = (ByteCode) byteCode.get(cache); if (bytecode != null) { VERBOSE("found " + name + " in codebase '" + bytecode.codebase + "'"); if (record) { record(bytecode); } // Use a protectionDomain to associate the codebase with the // class. ProtectionDomain pd = (ProtectionDomain) pdCache.get(bytecode.codebase); if (pd == null) { ProtectionDomain cd = JarClassLoader.class.getProtectionDomain(); URL url = cd.getCodeSource().getLocation(); try { url = new URL("jar:" + url + "!/" + bytecode.codebase); } catch (MalformedURLException mux) { mux.printStackTrace(System.out); } CodeSource source = new CodeSource(url, null); pd = new ProtectionDomain(source, null, this, null); pdCache.put(bytecode.codebase, pd); } // Do it the simple way. byte bytes[] = bytecode.bytes; return defineClass(name, bytes, pd); } VERBOSE(name + " not found"); throw new ClassNotFoundException(name); } protected Class defineClass(String name, byte[] bytes, ProtectionDomain pd) throws ClassFormatError { // Simple, non wrapped class definition. return defineClass(name, bytes, 0, bytes.length, pd); } /** * Overriden to return resources from the appropriate codebase. * There are basically two ways this method will be called: most commonly * it will be called through the class of an object which wishes to * load a resource, i.e. this.getClass().getResourceAsStream(). Before * passing the call to us, java.lang.Class mangles the name. It * converts a file path such as foo/bar/Class.class into a name like foo.bar.Class, * and it strips leading '/' characters e.g. converting '/foo' to 'foo'. * All of which is a nuisance, since we wish to do a lookup on the original * name of the resource as present in the One-Jar jar files. * The other way is more direct, i.e. this.getClass().getClassLoader().getResourceAsStream(). * Then we get the name unmangled, and can deal with it directly. * <p/> * The problem is this: if one resource is called /foo/bar/data, and another * resource is called /foo.bar.data, both will have the same mangled name, * namely 'foo.bar.data' and only one of them will be visible. Perhaps the * best way to deal with this is to store the lookup names in mangled form, and * simply issue warnings if collisions occur. This is not very satisfactory, * but is consistent with the somewhat limiting design of the resource name mapping * strategy in Java today. */ public InputStream getByteStream(String resource) { InputStream result = null; // Look up without resolving first. This allows jar-local // resolution to take place. ByteCode bytecode = (ByteCode) byteCode.get(resource); if (bytecode == null) { // Try again with a resolved name. bytecode = (ByteCode) byteCode.get(resolve(resource)); } if (bytecode != null) result = new ByteArrayInputStream(bytecode.bytes); // Special case: if we are a wrapping classloader, look up to our // parent codebase. Logic is that the boot JarLoader will have // delegateToParent = false, the wrapping classloader will have // delegateToParent = true; if (result == null && delegateToParent) { result = ((JarClassLoader) getParent()).getByteStream(resource); } VERBOSE("getByteStream(" + resource + ") -> " + result); return result; } /** * Resolve a resource name. Look first in jar-relative, then in global scope. * * @param resource * @return */ protected String resolve(String $resource) { if ($resource.startsWith("/")) $resource = $resource.substring(1); $resource = $resource.replace('/', '.'); String resource = null; String caller = getCaller(); ByteCode callerCode = (ByteCode) byteCode.get(caller + ".class"); if (callerCode != null) { // Jar-local first, then global. String tmp = callerCode.codebase + "/" + $resource; if (byteCode.get(tmp) != null) { resource = tmp; } } if (resource == null) { // One last try. if (byteCode.get($resource) == null) { resource = null; } else { resource = $resource; } } VERBOSE("resource " + $resource + " resolved to " + resource); return resource; } protected boolean alreadyCached(String name, String jar, byte[] bytes) { // TODO: check resource map to see how we will map requests for this // resource from this jar file. Only a conflict if we are using a // global map and the resource is defined by more than // one jar file (default is to map to local jar). ByteCode existing = (ByteCode) byteCode.get(name); if (existing != null) { // If bytecodes are identical, no real problem. Likewise if it's in // META-INF. if (!Arrays.equals(existing.bytes, bytes) && !name.startsWith("/META-INF")) { INFO(existing.name + " in " + jar + " is hidden by " + existing.codebase + " (with different bytecode)"); } else { VERBOSE(existing.name + " in " + jar + " is hidden by " + existing.codebase + " (with same bytecode)"); } return true; } return false; } protected String getCaller() { StackTraceElement[] stack = new Throwable().getStackTrace(); // Search upward until we get to a known class, i.e. one with a non-null // codebase. String caller = null; for (int i = 0; i < stack.length; i++) { if (byteCode.get(stack[i].getClassName() + ".class") != null) { caller = stack[i].getClassName(); break; } } return caller; } /** * Sets the name of the used classes recording directory. * * @param $recording A value of "" will use the current working directory * (not recommended). A value of 'null' will use the default directory, which * is called 'recording' under the launch directory (recommended). */ public void setRecording(String $recording) { recording = $recording; if (recording == null) recording = RECORDING; } public String getRecording() { return recording; } public void setRecord(boolean $record) { record = $record; } public boolean getRecord() { return record; } public void setFlatten(boolean $flatten) { flatten = $flatten; } public boolean isFlatten() { return flatten; } public void setVerbose(boolean $verbose) { verbose = $verbose; info = verbose; } public boolean getVerbose() { return verbose; } public void setInfo(boolean $info) { info = $info; } public boolean getInfo() { return info; } /* (non-Javadoc) * @see java.lang.ClassLoader#findResource(java.lang.String) */ protected URL findResource(String $resource) { try { INFO("findResource(" + $resource + ")"); // Do we have the named resource in our cache? If so, construct a // 'onejar:' URL so that a later attempt to access the resource // will be redirected to our Handler class, and thence to this class. String resource = resolve($resource); if (resource != null) { // We know how to handle it. INFO("findResource() found: " + $resource); return new URL(Handler.PROTOCOL + ":" + resource); } INFO("findResource(): unable to locate " + $resource); // If all else fails, return null. return null; } catch (MalformedURLException mux) { WARNING("unable to locate " + $resource + " due to " + mux); } return null; } /** * Utility to assist with copying InputStream to OutputStream. All * bytes are copied, but both streams are left open. * * @param in Source of bytes to copy. * @param out Destination of bytes to copy. * @throws IOException */ protected void copy(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[1024]; while (true) { int len = in.read(buf); if (len < 0) break; out.write(buf, 0, len); } } public String toString() { return super.toString() + (name != null ? "(" + name + ")" : ""); } /** * Returns name of the classloader. * * @return */ public String getName() { return name; } /** * Sets name of the classloader. Default is null. * * @param string */ public void setName(String string) { name = string; } } --- NEW FILE: DeepClassLoader.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.classloader; import org.mc4j.ems.connection.support.classloader.deepjar.Handler; import java.net.MalformedURLException; import java.net.URL; import java.security.CodeSigner; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.Map; /** * @author Greg Hinkle (gh...@us...), May 17, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class DeepClassLoader extends ClassLoader { private URL[] searchPaths; private Map<String, ByteCode> codeMap; private Map<String, ProtectionDomain> protectionDomainMap; public final static String JAVA_PROTOCOL_HANDLER = "java.protocol.handler.pkgs"; static { // Register a protocol handler so that deepjar:// references will look in jars in // the classloader String handlerPackage = "org.mc4j.ems.connection.support.classloader.deepjar"; String existingHandlers = System.getProperty(JAVA_PROTOCOL_HANDLER); String newHandlers = null; if (existingHandlers != null && existingHandlers.length() > 0) newHandlers = handlerPackage + "|" + existingHandlers; else newHandlers = handlerPackage; System.setProperty(JAVA_PROTOCOL_HANDLER, newHandlers); } public DeepClassLoader(ClassLoader parent, URL[] urls) { super(parent); } protected Class<?> findClass(String name) throws ClassNotFoundException { Class cls = findLoadedClass(name); if (cls != null) return cls; // Look up the class in the byte codes. String cache = name.replace('/', '.') + ".class"; ByteCode bytecode = (ByteCode) codeMap.get(cache); if (bytecode != null) { // Use a protectionDomain to associate the codebase with the // class. // Associate the codebase with the class with a protection domain ProtectionDomain pd = (ProtectionDomain) protectionDomainMap.get(bytecode.codebase); if (pd == null) { ProtectionDomain cd = this.getClass().getProtectionDomain(); URL url = cd.getCodeSource().getLocation(); try { url = new URL("jar:" + url + "!/" + bytecode.codebase); } catch (MalformedURLException mux) { mux.printStackTrace(System.out); } CodeSource source = new CodeSource(url, (CodeSigner[]) null); pd = new ProtectionDomain(source, null, this, null); protectionDomainMap.put(bytecode.codebase, pd); } return defineClass(name, bytecode.bytes, 0, bytecode.length, pd); } throw new ClassNotFoundException(name); } protected URL findResource(String resourceName) { try { // Do we have the named resource in our cache? If so, construct a // 'onejar:' URL so that a later attempt to access the resource // will be redirected to our Handler class, and thence to this class. String resource = resolve(resourceName); if (resource != null) { // We know how to handle it. return new URL(Handler.PROTOCOL + ":" + resource); } // If all else fails, return null. return null; } catch (MalformedURLException mux) { System.out.println("Unable to find resource " + resourceName); } return null; } protected String resolve(String resourceName) { if (resourceName.startsWith("/")) resourceName = resourceName.substring(1); resourceName = resourceName.replace('/', '.'); String resource = null; if (resource == null) { // One last try. if (codeMap.get(resourceName) == null) { resource = null; } else { resource = resourceName; } } return resource; } protected class ByteCode { public byte bytes[]; public int length; public String name, original, codebase; public ByteCode(String name, String $original, byte bytes[], int length, String codebase) { this.name = name; original = $original; this.bytes = bytes; this.codebase = codebase; } } } --- NEW FILE: ChildFirstClassloader.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.classloader; import java.net.URL; import java.net.URLClassLoader; /** * WARNING: GH - DISGUSTING HACK * This is an aweful little hack that allows us to execute under jdk 1.5 (which includes jmx) * while utilizing the jmx classes we load from somewhere else. We just override the classloader * delegation for cases of the "javax.management" classes. * * @author Greg Hinkle (gh...@us...), Apr 5, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class ChildFirstClassloader extends URLClassLoader { public ChildFirstClassloader(URL[] urls, ClassLoader parent) { super(urls, parent); } protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { Class c = findLoadedClass(name); if (c == null) { if (name.indexOf("javax.management") >= 0) { try { try { c = findClass(name); } catch (SecurityException se) { int i = name.lastIndexOf('.'); String pkgname = name.substring(0, i); // Check if package already loaded. Package pkg = getPackage(pkgname); if (pkg == null) { definePackage(pkgname, null, null, null, null, null, null, null); } } if (resolve) { resolveClass(c); } } catch (ClassNotFoundException cnfe) { c = super.loadClass(name, resolve); } } else { c = super.loadClass(name, resolve); } } return c; } /* private Class defineClass(String name, Resource res) throws IOException { int i = name.lastIndexOf('.'); URL url = res.getCodeSourceURL(); if (i != -1) { String pkgname = name.substring(0, i); // Check if package already loaded. Package pkg = getPackage(pkgname); Manifest man = res.getManifest(); if (pkg != null) { // Package found, so check package sealing. if (pkg.isSealed()) { // Verify that code source URL is the same. if (!pkg.isSealed(url)) { throw new SecurityException( "sealing violation: package " + pkgname + " is sealed"); } } else { // Make sure we are not attempting to seal the package // at this code source URL. if ((man != null) && isSealed(pkgname, man)) { throw new SecurityException( "sealing violation: can't seal package " + pkgname + ": already loaded"); } } } else { if (man != null) { definePackage(pkgname, man, url); } else { definePackage(pkgname, null, null, null, null, null, null, null); } } }*/ } --- NEW FILE: ClassLoaderFactory.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.classloader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mc4j.ems.connection.EmsConnectException; import org.mc4j.ems.connection.EmsException; import org.mc4j.ems.connection.settings.ConnectionSettings; import org.mc4j.ems.connection.support.metadata.JSR160ConnectionTypeDescriptor; import org.mc4j.ems.connection.support.metadata.WeblogicConnectionTypeDescriptor; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; /** * @author Greg Hinkle (gh...@us...), Apr 5, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:35 $) */ public class ClassLoaderFactory { private static ClassLoaderFactory INSTANCE; private static Log log = LogFactory.getLog(ClassLoaderFactory.class); private static Map<String, File> jarCache = new HashMap<String, File>(); static { String className = System.getProperty("org.mc4j.ems.classloaderfactory"); if (className != null) { try { INSTANCE = ((Class<ClassLoaderFactory>) Class.forName(className)).newInstance(); } catch (Exception e) { throw new EmsException("Unable to load custom classloader factory " + className, e); } } if (INSTANCE == null) { INSTANCE = new ClassLoaderFactory(); } } /** * Retrieves the configured classloader factory for EMS. This can be customized by * setting the system property "org.mc4j.ems.classloaderfactory". * * @return the Classloader Factory used to build the connection classloader */ public static ClassLoaderFactory getInstance() { return INSTANCE; } /** * TODO GH: Implement a special classloader that can load classes from * within a jar inside another jar or perhaps just ship the impl jar separately... */ protected URL storeImplToTemp(String archiveResource) { try { if (jarCache.containsKey(archiveResource)) { return jarCache.get(archiveResource).toURI().toURL(); } InputStream is = ClassLoaderFactory.class.getClassLoader().getResourceAsStream(archiveResource); if (is == null) { throw new EmsException("Unable to find resource to store [" + archiveResource + "]"); } // String tmpPath = System.getProperty("java.io.tmpdir"); String jarName = new File(archiveResource).getName(); jarName = jarName.substring(0, jarName.length() - 4); File tmpFile = File.createTempFile(jarName, ".jar"); tmpFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tmpFile); byte[] buffer = new byte[4096]; int size = is.read(buffer); while (size != -1) { fos.write(buffer, 0, size); size = is.read(buffer); } fos.close(); is.close(); jarCache.put(archiveResource, tmpFile); return tmpFile.toURI().toURL(); } catch (FileNotFoundException e) { throw new EmsException("Unable to make temporary file store",e); } catch (IOException e) { throw new EmsException("Unable to make temporary file store",e); } } public ClassLoader buildClassLoader(ConnectionSettings settings) { // TODO GH: Implement configurable system to point at jar instead of creating temporary version List<URL> entries = new ArrayList<URL>(); if (settings.getClassPathEntries() != null) { for (File file : settings.getClassPathEntries()) { try { entries.add(file.toURI().toURL()); } catch (MalformedURLException e) { throw new EmsConnectException("Unable to read class path library url", e); } } } // Now load in the implementation jar // URL implURL = new URL(null, "deepjar://org-mc4j-ems-impl.jar", new Handler()); URL implURL = storeImplToTemp("org-mc4j-ems-impl.jar"); entries.add(implURL); // Add internal support jars for JSR160 on < jdk5 if ((settings.getConnectionType() instanceof JSR160ConnectionTypeDescriptor) && settings.getConnectionType().getConnectionClasspathEntries() == null && Double.parseDouble(System.getProperty("java.version").substring(0, 3)) < 1.5) { entries.add(storeImplToTemp("lib/jsr160-includes/mx4j.jar")); entries.add(storeImplToTemp("lib/jsr160-includes/mx4j-remote.jar")); } // TODO: Check if file exists, log warning if not URL[] entryArray = entries.toArray(new URL[entries.size()]); // TODO - WARNING: GH - DISGUSTING HACK URLClassLoader loader = null; if ((settings.getConnectionType() instanceof WeblogicConnectionTypeDescriptor)) { loader = new ChildFirstClassloader(entryArray, ClassLoaderFactory.class.getClassLoader()); } else { // TODO was NestedJarClassLoader //loader = new ChildFirstClassloader(entryArray, ClassLoaderFactory.class.getClassLoader()); loader = new URLClassLoader(entryArray, ClassLoaderFactory.class.getClassLoader()); //loader = new NestedJarClassLoader(entryArray, ClassLoaderFactory.class.getClassLoader()); } if (log.isDebugEnabled()) { StringBuffer buf = new StringBuffer("Classloader built with: \n"); for (URL url : entries) { buf.append("\t").append(url).append("\n"); } log.debug(buf.toString()); } return loader; } } |
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/connection/support/metadata In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/connection/support/metadata Added Files: WeblogicConnectionTypeDescriptor.java WebsphereConnectionTypeDescriptor.java Weblogic9Jsr77ConnectionTypeDescriptor.java PramatiConnectionTypeDescriptor.java ConnectionTypeDescriptor.java Weblogic9ConnectionTypeDescriptor.java JBossConnectionTypeDescriptor.java AbstractConnectionTypeDescriptor.java Oc4jConnectionTypeDescriptor.java JSR160ConnectionTypeDescriptor.java JDMKConnectionTypeDescriptor.java Mx4jConnectionTypeDescriptor.java SJSASConnectionTypeDescriptor.java Tomcat55ConnectionTypeDescriptor.java J2SE5ConnectionTypeDescriptor.java GeronimoConnectionTypeDescriptor.java WebsphereStudioConnectionTypeDescriptor.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: JSR160ConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class JSR160ConnectionTypeDescriptor extends AbstractConnectionTypeDescriptor { public boolean isMEJBCompliant() { return true; } public String getDisplayName() { return "JSR160"; } public String getRecongnitionPath() { return null; } public String getDefaultServerUrl() { return "service:jmx:rmi:///jndi/rmi://localhost:9999/server"; } public String getDefaultPrincipal() { return ""; } public String getDefaultCredentials() { return ""; } public String getDefaultInitialContext() { return "com.sun.jndi.rmi.registry.RegistryContextFactory"; } public String getDefaultJndiName() { return null; } public String getConnectionType() { return "JSR160"; } public String getConnectionMessage() { return null; } public String[] getConnectionClasspathEntries() { return null; } public String getConnectionNodeClassName() { return "org.mc4j.ems.impl.jmx.connection.support.providers.JMXRemotingConnectionProvider"; } public String getExtrasLibrary() { return "JSR160"; } } --- NEW FILE: J2SE5ConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class J2SE5ConnectionTypeDescriptor extends JSR160ConnectionTypeDescriptor { public boolean isMEJBCompliant() { return false; } public String getDisplayName() { return "J2SE 5.0"; } public String getDefaultServerUrl() { return "service:jmx:rmi:///jndi/rmi://localhost:8999/jmxrmi"; } public String getConnectionType() { return "J2SE5"; } } --- NEW FILE: Weblogic9Jsr77ConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; import java.net.MalformedURLException; import java.util.Properties; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class Weblogic9Jsr77ConnectionTypeDescriptor extends JSR160ConnectionTypeDescriptor { public static void main(String[] args) throws MalformedURLException { // String protocol = "t3"; // String jndiroot = "/jndi/"; // String mserver = "weblogic.management.mbeanservers.domainruntime"; // JMXServiceURL serviceURL = new JMXServiceURL(protocol, "localhost", 7001, // jndiroot + mserver); // System.out.println("URL: " + serviceURL); } public boolean isMEJBCompliant() { return true; } public boolean isUseManagementHome() { return true; } public String getDisplayName() { return "WebLogic 9 via JSR 77"; } public String getConnectionMessage() { return "Displays WebLogic 9 JSR 77 capabilities only. Not all runtime mbeans are available with this view."; } public String getDefaultServerUrl() { return "service:jmx:t3://localhost:7001/jndi/weblogic.management.mbeanservers.domainruntime"; } public String getConnectionType() { return "weblogic"; } public Properties getDefaultAdvancedProperties() { Properties props = super.getDefaultAdvancedProperties(); // Don't want runtime dependency on JMX classes at this level props.put("jmx.remote.protocol.provider.pkgs" /*JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES*/, "weblogic.management.remote"); return props; } public String getRecongnitionPath() { return "server/lib/weblogic.jar"; } public String getDefaultInitialContext() { return "weblogic.jndi.WLInitialContextFactory"; } public String[] getConnectionClasspathEntries() { return new String[] { "server/lib/weblogic.jar", // their doco is wrong... says the provider pkg is in wlclient.jar... it isn't "server/lib/wlclient.jar" }; } } --- NEW FILE: PramatiConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Properties; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class PramatiConnectionTypeDescriptor extends AbstractConnectionTypeDescriptor { public boolean isMEJBCompliant() { return false; } public String getDisplayName() { return "Pramati 3.5+"; } public String getRecongnitionPath() { return "server/lib/pramati/version.jar"; } public String getServerVersion(File recognitionFile) { try { String version = null; URLClassLoader ld = new URLClassLoader(new URL[] { recognitionFile.toURL() }); InputStream is = ld.getResourceAsStream("Version.props"); if (is != null) { Properties props = new Properties(); props.load(is); version = props.getProperty("PRODUCT_VERSION"); } return version; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public String getDefaultServerUrl() { return "service:jmx:rmi:///jndi/rmi://localhost:9191/rmi-client-connector"; } public String getDefaultPrincipal() { return ""; } public String getDefaultCredentials() { return ""; } public String getDefaultInitialContext() { return "com.sun.jndi.rmi.registry.RegistryContextFactory"; } public String getDefaultJndiName() { return null; } public String getConnectionType() { return "Pramati"; } public String getConnectionMessage() { return null; } public String[] getConnectionClasspathEntries() { return new String[] { "pramati_client_all.jar" }; } public String getConnectionNodeClassName() { return "org.mc4j.console.connection.PramatiConnectionProvider"; } } --- NEW FILE: WebsphereConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class WebsphereConnectionTypeDescriptor extends AbstractConnectionTypeDescriptor { public boolean isMEJBCompliant() { return true; } public String getDefaultServerUrl() { return "http://localhost:8880"; } public String getDefaultPrincipal() { return "admin"; } public String getDefaultCredentials() { return ""; } public String getDefaultJndiName() { return null; } public String getDefaultInitialContext() { return null; } public String getConnectionType() { return "WebSphere"; } public String getConnectionMessage() { return "You must use the IBM JVM for MC4J when connection to WebSphere 5.x. The Sun JVM " + "can only be used for WS 6."; } public String[] getConnectionClasspathEntries() { return new String[] { "AppServer/lib/*", "AppServer/deploytool/itp/plugins/com.ibm.etools.jsse/ibmjsse.jar", "AppServer/java/jre/lib/ext/mail.jar", "AppServer/deploytool/itp/plugins/org.apache.xerces_4.0.13/xercesImpl.jar", "AppServer/deploytool/itp/plugins/org.apache.xerces_4.0.13/xmlParserAPIs.jar", }; } public String getConnectionNodeClassName() { return "org.mc4j.console.connection.WebsphereConnectionProvider"; } public String getDisplayName() { return "WebSphere 5.x+"; } public String getRecongnitionPath() { return "AppServer/lib/runtime.jar"; } } --- NEW FILE: JBossConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; import javax.naming.Context; import java.util.Properties; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class JBossConnectionTypeDescriptor extends AbstractConnectionTypeDescriptor implements ConnectionTypeDescriptor { public boolean isMEJBCompliant() { return true; } public String getDisplayName() { return "JBoss"; } public String getRecongnitionPath() { return "server/*/lib/jboss.jar"; } public String getDefaultServerUrl() { return "jnp://localhost:1099"; } public String getDefaultJndiName() { return "jmx/rmi/RMIAdaptor"; } public String getDefaultInitialContext() { return "org.jnp.interfaces.NamingContextFactory"; } public String getDefaultPrincipal() { return ""; } public String getDefaultCredentials() { return ""; } public String getConnectionType() { return "JBoss"; } public String getConnectionMessage() { return null; } public Properties getDefaultAdvancedProperties() { Properties props = super.getDefaultAdvancedProperties(); props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces" ); props.put("jnp.disableDiscovery", "True"); return props; } public String[] getConnectionClasspathEntries() { return new String[] { // 3.x + jars "lib/jboss-jmx.jar", "client/jboss-common.jar", "lib/jboss-system.jar", "client/jbossall-client.jar", "client/log4j.jar", "*/*/lib/jboss.jar", "client/concurrent.jar", "client/jboss-jsr77-client.jar", // 3.2.3 jars "*/*/lib/jboss-transaction.jar", "lib/xercesImpl.jar", "lib/xml-apis.jar", // 4.0 jars "lib/dom4j.jar", "client/jnp-client.jar", "client/jmx-rmi-connector-client.jar", "client/jboss-j2ee.jar", "*/*/lib/jboss-management.jar", "client/jbosssx.jar", "lib/endorsed/xercesImpl.jar", "lib/endorsed/xml-apis.jar" }; } public String getConnectionNodeClassName() { return "org.mc4j.ems.impl.jmx.connection.support.providers.JBossConnectionProvider"; } } --- NEW FILE: Weblogic9ConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; import java.net.MalformedURLException; import java.util.Properties; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class Weblogic9ConnectionTypeDescriptor extends JSR160ConnectionTypeDescriptor { public static void main(String[] args) throws MalformedURLException { // String protocol = "t3"; // String jndiroot = "/jndi/"; // String mserver = "weblogic.management.mbeanservers.domainruntime"; // JMXServiceURL serviceURL = new JMXServiceURL(protocol, "localhost", 7001, // jndiroot + mserver); // System.out.println("URL: " + serviceURL); } public boolean isMEJBCompliant() { return false; } public boolean isUseManagementHome() { return false; } public String getDisplayName() { return "WebLogic 9"; } public String getConnectionMessage() { return "Has only been tested against Diablo Beta. No JSR 77 MBeans are available with this view. " + "Select the WebLogic 9 JSR 77 connection type to view those."; } public String getDefaultServerUrl() { return "service:jmx:t3://localhost:7001/jndi/weblogic.management.mbeanservers.domainruntime"; } public String getConnectionType() { return "weblogic"; } public Properties getDefaultAdvancedProperties() { Properties props = super.getDefaultAdvancedProperties(); props.put("jmx.remote.protocol.provider.pkgs", "weblogic.management.remote"); return props; } public String getRecongnitionPath() { return "server/lib/weblogic.jar"; } public String getDefaultInitialContext() { return "weblogic.jndi.WLInitialContextFactory"; } public String[] getConnectionClasspathEntries() { return new String[] { "server/lib/weblogic.jar", // their doco is wrong... says the provider pkg is in wlclient.jar... it isn't "server/lib/wlclient.jar" }; } } --- NEW FILE: JDMKConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class JDMKConnectionTypeDescriptor extends AbstractConnectionTypeDescriptor { public boolean isMEJBCompliant() { return false; //To change body of implemented methods use File | Settings | File Templates. } public String getDisplayName() { return "JDMK"; } public String getRecongnitionPath() { return null; } public String getDefaultServerUrl() { return "localhost:8086"; } public String getDefaultJndiName() { return "name=RmiConnectorServer"; } public String getDefaultInitialContext() { return null; } public String getDefaultPrincipal() { return null; } public String getDefaultCredentials() { return null; } public String getConnectionType() { return "JDMK"; } public String getConnectionMessage() { return null; } public String[] getConnectionClasspathEntries() { return null; } public String getConnectionNodeClassName() { return null; } public String getExtrasLibrary() { return "JDMK"; } } --- NEW FILE: WebsphereStudioConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class WebsphereStudioConnectionTypeDescriptor extends WebsphereConnectionTypeDescriptor { public String getConnectionMessage() { return "You must use the IBM JVM for MC4J when connection to WebSphere Test Server 5.x. The Sun JVM " + "can only be used for WS 6."; } public String[] getConnectionClasspathEntries() { return new String[] { "runtimes/base_v51/lib/*", "runtimes/base_v51/java/jre/lib/ext/ibmjsse.jar", "runtimes/base_v51/java/jre/lib/ext/mail.jar", "runtimes/base_v51/deploytool/itp/plugins/org.apache.xerces_4.0.13/xercesImpl.jar", "runtimes/base_v51/deploytool/itp/plugins/org.apache.xerces_4.0.13/xmlParserAPIs.jar", }; } public String getDisplayName() { return "WSAD Test Environment 5.x+"; } public String getRecongnitionPath() { return "runtimes/base_v51/lib/runtime.jar"; } } --- NEW FILE: ConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; import java.io.File; import java.io.Serializable; import java.util.Properties; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public interface ConnectionTypeDescriptor extends Serializable { String getDefaultServerUrl(); String getDefaultJndiName(); String getDefaultInitialContext(); String getDefaultPrincipal(); String getDefaultCredentials(); String getConnectionType(); String getConnectionMessage(); String[] getConnectionClasspathEntries(); String getConnectionNodeClassName(); boolean isMEJBCompliant(); boolean isUseManagementHome(); String getDisplayName(); String getRecongnitionPath(); String getServerVersion(File recognitionFile); String getExtrasLibrary(); Properties getDefaultAdvancedProperties(); } --- NEW FILE: AbstractConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.File; import java.io.IOException; import java.util.jar.JarFile; import java.util.jar.Attributes; import java.util.Map; import java.util.Iterator; import java.util.Properties; import java.net.MalformedURLException; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public abstract class AbstractConnectionTypeDescriptor implements ConnectionTypeDescriptor { private static Log log = LogFactory.getLog(AbstractConnectionTypeDescriptor.class); public String toString() { return getDisplayName(); } public boolean isUseManagementHome() { return false; } public String getServerVersion(File recognitionFile) { try { String version; JarFile recJarFile = new JarFile(recognitionFile); version = recJarFile.getManifest().getMainAttributes().getValue("Implementation-Version"); if (version == null) { Map attrMap = recJarFile.getManifest().getEntries(); for (Iterator iterator = attrMap.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); Attributes attr = (Attributes) entry.getValue(); version = attr.getValue("Implementation-Version"); } } return version; } catch (MalformedURLException e) { log.warn("Could not determine server version from matched file " + recognitionFile.getAbsolutePath(),e); } catch (IOException e) { log.warn("Could not determine server version from matched file " + recognitionFile.getAbsolutePath(),e); } return null; } public String getExtrasLibrary() { return null; } public Properties getDefaultAdvancedProperties() { return new Properties(); } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof AbstractConnectionTypeDescriptor)) return false; final AbstractConnectionTypeDescriptor other = (AbstractConnectionTypeDescriptor) o; if (getDisplayName() != null ? !getDisplayName().equals(other.getDisplayName()) : other.getDisplayName() != null) return false; return true; } public int hashCode() { return (getDisplayName() != null ? getDisplayName().hashCode() : 0); } } --- NEW FILE: Oc4jConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class Oc4jConnectionTypeDescriptor extends AbstractConnectionTypeDescriptor { public boolean isMEJBCompliant() { return true; } public String getDisplayName() { return "OC4J"; } public String getRecongnitionPath() { return "j2ee/home/oc4j.jar"; } public String getDefaultServerUrl() { return "ormi://localhost:23791/default"; } public String getDefaultJndiName() { return "java:comp/env/ejb/mgmt/MEJB"; } public String getDefaultInitialContext() { return "com.evermind.server.ApplicationClientInitialContextFactory"; } public String getDefaultPrincipal() { return "admin"; } public String getDefaultCredentials() { return ""; } public String getConnectionType() { return "OC4J"; } public String getConnectionMessage() { return null; } public String[] getConnectionClasspathEntries() { return new String[] { "adminclient.jar", "ejb.jar", "oc4j-internal.jar", "admin_client.jar" }; } public String getConnectionNodeClassName() { return "org.mc4j.console.connection.Oc4jConnectionProvider"; } } --- NEW FILE: GeronimoConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; /** * @author Greg Hinkle (gh...@us...), Oct 4, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class GeronimoConnectionTypeDescriptor extends JSR160ConnectionTypeDescriptor { public String getDisplayName() { return "Geronimo"; } public String getConnectionType() { return "Geronimo"; } public String getDefaultServerUrl() { return "service:jmx:rmi:///jndi/rmi://localhost/JMXConnector"; //"service:jmx:rmi://localhost/jndi/rmi:/JMXConnector" } } --- NEW FILE: Tomcat55ConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class Tomcat55ConnectionTypeDescriptor extends J2SE5ConnectionTypeDescriptor { public boolean isMEJBCompliant() { return true; } public String getDisplayName() { return "Tomcat 5.5+"; } public String[] getConnectionClasspathEntries() { return new String[] { "catalina.jar", "catalina-cluster.jar", "catalina-optional.jar" }; } public String getRecongnitionPath() { return "server/lib/catalina.jar"; } public String getConnectionType() { return "Tomcat55"; } public String getServerVersion(File recognitionFile) { try { String version; URLClassLoader ld = new URLClassLoader(new URL[] { recognitionFile.toURL() }); Class serverInfoClass = Class.forName("org.apache.catalina.util.ServerInfo",true,ld); Method m = serverInfoClass.getMethod("getServerInfo",new Class[] {}); version = (String) m.invoke(null,(Object[]) null); return version; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; } } --- NEW FILE: Mx4jConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class Mx4jConnectionTypeDescriptor extends AbstractConnectionTypeDescriptor { public boolean isMEJBCompliant() { return false; //To change body of implemented methods use File | Settings | File Templates. } public String getDisplayName() { return "MX4J 1.x"; } public String getRecongnitionPath() { return null; } public String getDefaultServerUrl() { return "rmi://localhost:1099"; } public String getDefaultJndiName() { return "jrmp"; } public String getDefaultInitialContext() { return "com.sun.jndi.rmi.registry.RegistryContextFactory"; } public String getConnectionMessage() { return "This connection type is for connections to MX4J 1.x. For versions 2.x of MX4J " + "use the JSR 160 connection type above."; } public String getDefaultPrincipal() { return null; } public String getDefaultCredentials() { return null; } public String getConnectionType() { return "MX4J"; } public String[] getConnectionClasspathEntries() { return null; } public String getConnectionNodeClassName() { return "org.mc4j.console.connection.Mx4jConnectionNode"; } public String getExtrasLibrary() { return "MX4J"; } } --- NEW FILE: WeblogicConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; /** * @author Greg Hinkle (gh...@us...), Sep 30, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class WeblogicConnectionTypeDescriptor extends AbstractConnectionTypeDescriptor { public boolean isMEJBCompliant() { return false; //To change body of implemented methods use File | Settings | File Templates. } public String getDefaultServerUrl() { return "t3://localhost:7001"; } public String getDefaultJndiName() { return "weblogic.management.adminhome"; } public String getDefaultInitialContext() { return "weblogic.jndi.WLInitialContextFactory"; } public String getDefaultPrincipal() { return "admin"; } public String getConnectionType() { return "weblogic"; } public String getConnectionMessage() { return null; } public String[] getConnectionClasspathEntries() { return new String[] { "weblogic.jar" }; } public String getConnectionNodeClassName() { return "org.mc4j.ems.impl.jmx.connection.support.providers.WeblogicConnectionProvider"; } public String getDisplayName() { return "WebLogic"; } public String getRecongnitionPath() { return "server/lib/weblogic.jar"; } public String getDefaultCredentials() { return ""; } } --- NEW FILE: SJSASConnectionTypeDescriptor.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.connection.support.metadata; /** * @author Greg Hinkle (gh...@us...), Oct 4, 2004 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:33 $) */ public class SJSASConnectionTypeDescriptor extends JSR160ConnectionTypeDescriptor { public String getDisplayName() { return "Sun JSAS"; } public String getConnectionType() { return "SJSAS"; } public String getDefaultServerUrl() { return "service:jmx:rmi:///jndi/rmi://localhost:8686/management/rmi-jmx-connector"; } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:40
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/test/org/mc4j/ems/test/notifications In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/test/org/mc4j/ems/test/notifications Added Files: NotificationTest.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: NotificationTest.java --- /* * Copyright 2002-2005 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.test.notifications; import org.mc4j.ems.connection.ConnectionFactory; import org.mc4j.ems.connection.EmsConnection; import org.mc4j.ems.connection.bean.EmsBean; import org.mc4j.ems.connection.bean.notification.EmsNotification; import org.mc4j.ems.connection.settings.ConnectionSettings; import org.mc4j.ems.connection.support.metadata.JSR160ConnectionTypeDescriptor; import org.mc4j.ems.test.beans.MyTestBean; import org.testng.annotations.Configuration; import org.testng.annotations.Test; import java.util.SortedSet; /** * @author Greg Hinkle (gh...@us...), Nov 10, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:36 $) */ public class NotificationTest { String testMBeanName = "ems.test:type=test,name=MyTestMBean"; EmsConnection connection; EmsBean testBean; @Configuration(beforeTestClass = true) public void testSetup() { System.out.println("Here"); ConnectionSettings settings = new ConnectionSettings(); settings.initializeConnectionType(new JSR160ConnectionTypeDescriptor()); settings.setServerUrl("service:jmx:rmi:///jndi/rmi://localhost:9999/server"); ConnectionFactory factory = new ConnectionFactory(); connection = factory.connect(settings); connection.loadSynchronous(true); } @Test(groups= {"registration"}) public void testRegistration() { testBean = connection.registerBean(MyTestBean.class.getName(), testMBeanName); } @Test(groups = { "functest" }) public void testNotificationRegister() { SortedSet<EmsNotification> notifications = testBean.getNotifications(); for (EmsNotification notification : notifications) { System.out.println("Notif: " + notification); notification.startListening(); } } } |
From: Greg H. <gh...@us...> - 2006-04-12 19:11:40
|
Update of /cvsroot/mc4j/mc4j/modules/ems/src/ems/org/mc4j/ems/store In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18666/modules/ems/src/ems/org/mc4j/ems/store Added Files: CompleteValueHistory.java ValueHistory.java Value.java Log Message: Merging EMS into head for the 2.0 release work --- NEW FILE: CompleteValueHistory.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.store; import java.util.List; import java.util.LinkedList; import java.util.Collections; /** * @author Greg Hinkle (gh...@us...), Apr 6, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:34 $) */ public class CompleteValueHistory implements ValueHistory { /** * Newer values are added at the end of the list. Oldest values first. */ protected List<Value> values = new LinkedList<Value>(); protected int historySize; public CompleteValueHistory() { this(-1); } public CompleteValueHistory(int historySize) { this.historySize = historySize; } public int getHistorySize() { return values.size(); } public void setMaximumHistorySize(int historySize) { this.historySize = historySize; } public List<Value> getValues() { return Collections.unmodifiableList(values); } public void addValue(Value value) { values.add(value); if (historySize > 0 && historySize < values.size()) { values.remove(0); } } } --- NEW FILE: ValueHistory.java --- package org.mc4j.ems.store; import java.util.List; /** * @author Greg Hinkle (gh...@us...), Apr 12, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:34 $) */ public interface ValueHistory { int getHistorySize(); List<Value> getValues(); void addValue(Value value); } --- NEW FILE: Value.java --- /* * Copyright 2002-2004 Greg Hinkle * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mc4j.ems.store; /** * @author Greg Hinkle (gh...@us...), Apr 12, 2005 * @version $Revision: 1.2 $($Author: ghinkl $ / $Date: 2006/04/12 19:11:34 $) */ public class Value { private Object value; private long recorded; public Value(Object value, long recorded) { this.value = value; this.recorded = recorded; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public long getRecorded() { return recorded; } public void setRecorded(long recorded) { this.recorded = recorded; } } |