Merge branch 'master' into jetty-9.4.x-Feature

This commit is contained in:
Greg Wilkins 2016-03-10 16:52:43 +11:00
commit 2f15c3e4f9
20 changed files with 1144 additions and 84 deletions

View File

@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-project</artifactId>
@ -34,6 +35,13 @@
<artifactId>jetty-util</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.openpojo</groupId>
<artifactId>openpojo</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -74,8 +74,8 @@ public class MBeanContainer implements Container.InheritedListener, Dumpable
{
for (Map.Entry<Object, ObjectName> entry : _beans.entrySet())
{
if (entry.getKey().equals(objectName))
return entry.getValue();
if (entry.getValue().equals(objectName))
return entry.getKey();
}
return null;
}

View File

@ -25,7 +25,7 @@ public class Base extends AbstractLifeCycle
String name;
int value;
String[] messages;
/* ------------------------------------------------------------ */
/**
* @return Returns the messages.
@ -34,14 +34,17 @@ public class Base extends AbstractLifeCycle
{
return messages;
}
/* ------------------------------------------------------------ */
/**
* @param messages The messages to set.
* @param messages
* The messages to set.
*/
public void setMessages(String[] messages)
{
this.messages = messages;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the name.
@ -50,14 +53,17 @@ public class Base extends AbstractLifeCycle
{
return name;
}
/* ------------------------------------------------------------ */
/**
* @param name The name to set.
* @param name
* The name to set.
*/
public void setName(String name)
{
this.name = name;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the value.
@ -66,10 +72,11 @@ public class Base extends AbstractLifeCycle
{
return value;
}
/* ------------------------------------------------------------ */
/**
* @param value The value to set.
* @param value
* The value to set.
*/
public void setValue(int value)
{
@ -79,14 +86,13 @@ public class Base extends AbstractLifeCycle
/* ------------------------------------------------------------ */
public void doSomething(int arg)
{
System.err.println("doSomething "+arg);
System.err.println("doSomething " + arg);
}
/* ------------------------------------------------------------ */
public String findSomething(int arg)
{
return ("found "+arg);
return ("found " + arg);
}
}

View File

@ -23,16 +23,16 @@ import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
import org.eclipse.jetty.util.annotation.Name;
@ManagedObject(value="Test the mbean stuff")
@ManagedObject(value = "Test the mbean stuff")
public class Derived extends Base implements Signature
{
String fname="Full Name";
String fname = "Full Name";
Managed managedInstance = new Managed();
SuperManaged superManagedInstance = new SuperManaged();
@ManagedAttribute(value="The full name of something", name="fname", setter="setFullName")
@ManagedAttribute(value = "The full name of something", name = "fname", setter = "setFullName")
public String getFullName()
{
return fname;
@ -40,7 +40,7 @@ public class Derived extends Base implements Signature
public void setFullName(String name)
{
fname=name;
fname = name;
}
@ManagedOperation("publish something")
@ -48,11 +48,11 @@ public class Derived extends Base implements Signature
{
System.err.println("publish");
}
@ManagedOperation("Doodle something")
public void doodle(@Name(value="doodle", description="A description of the argument") String doodle)
public void doodle(@Name(value = "doodle", description = "A description of the argument") String doodle)
{
System.err.println("doodle "+doodle);
System.err.println("doodle " + doodle);
}
public String bad()
@ -70,8 +70,7 @@ public class Derived extends Base implements Signature
{
this.managedInstance = managedInstance;
}
@ManagedAttribute("sample super managed object")
public SuperManaged getSuperManagedInstance()
{

View File

@ -0,0 +1,55 @@
//
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package com.acme;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
@ManagedObject(value = "Test the mbean extended stuff")
public class DerivedExtended extends Derived
{
private String doodle4 = "doodle4";
@ManagedAttribute(value = "The doodle4 name of something", name = "doodle4", setter = "setDoodle4")
public String getDoodle4()
{
throw new IllegalAccessError();
}
public void setDoodle4(String doodle4)
{
this.doodle4 = doodle4;
}
@ManagedOperation("Doodle2 something")
private void doodle2()
{
System.err.println("doodle2");
// this is just for a test case perspective
}
@ManagedOperation("Doodle1 something")
public void doodle1()
{
// this is just for a test case perspective
throw new IllegalAccessError();
}
}

View File

@ -0,0 +1,97 @@
//
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package com.acme;
import java.util.ArrayList;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
import org.eclipse.jetty.util.annotation.Name;
@ManagedObject(value = "Test the mbean stuff")
public class DerivedManaged extends Base implements Signature
{
String fname = "Full Name";
Derived[] addresses = new Derived[3];
ArrayList<Derived> aliasNames = new ArrayList<Derived>();
Derived derived = new Derived();
@ManagedAttribute("sample managed address object")
public Derived[] getAddresses()
{
return addresses;
}
@ManagedAttribute("sample managed derived object")
public Derived getDerived()
{
return derived;
}
public void setDerived(Derived derived)
{
this.derived = derived;
}
public void setAddresses(Derived[] addresses)
{
this.addresses = addresses;
}
@ManagedOperation(value = "Doodle something", impact = "ACTION_INFO")
public void doodle(@Name(value = "doodle", description = "A description of the argument") String doodle)
{
System.err.println("doodle " + doodle);
}
@ManagedOperation(value = "google something", impact = "")
public void google(@Name(value = "google", description = "A description of the argument") String google)
{
System.err.println("google " + google);
}
@ManagedAttribute("sample managed alias object")
public ArrayList<Derived> getAliasNames()
{
return aliasNames;
}
public void setAliasNames(ArrayList<Derived> aliasNames)
{
this.aliasNames = aliasNames;
}
@ManagedAttribute(value = "The full name of something", name = "fname", setter = "setFullName")
public String getFullName()
{
return fname;
}
public void setFullName(String name)
{
fname = name;
}
@ManagedOperation("publish something")
public void publish()
{
System.err.println("publish");
}
}

View File

@ -21,11 +21,11 @@ package com.acme;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
@ManagedObject(value="Managed Object")
@ManagedObject(value = "Managed Object")
public class Managed
{
String managed = "foo";
@ManagedAttribute("Managed Attribute")
public String getManaged()
{
@ -36,11 +36,10 @@ public class Managed
{
this.managed = managed;
}
public String bad()
{
return "bad";
}
}

View File

@ -21,6 +21,6 @@ package com.acme;
public interface Signature
{
String getFullName();
void publish();
}

View File

@ -20,10 +20,10 @@ package com.acme;
public class SuperManaged extends Managed
{
public String superized()
{
return "super";
}
}

View File

@ -43,7 +43,7 @@ public class DerivedMBean extends ObjectMBean
return "not " + ((Derived)_managed).bad();
}
@ManagedAttribute(value="test of proxy attributes", proxied=true)
@ManagedAttribute(value = "test of proxy attributes", proxied = true)
public String goop()
{
return "goop";

View File

@ -39,7 +39,7 @@ public class ManagedMBean extends ObjectMBean
return "not managed " + ((Managed)_managed).bad();
}
@ManagedAttribute(value="test of proxy attributes", proxied=true)
@ManagedAttribute(value = "test of proxy attributes", proxied = true)
public String goop()
{
return "goop";

View File

@ -18,20 +18,94 @@
package org.eclipse.jetty.jmx;
import java.net.InetAddress;
import java.rmi.registry.LocateRegistry;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import javax.management.remote.JMXServiceURL;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.AnyOf.anyOf;
public class ConnectorServerTest
{
private ConnectorServer connectorServer;
@After
public void tearDown() throws Exception
{
if (connectorServer != null)
{
connectorServer.doStop();
}
}
@Test
public void randomPortTest() throws Exception
{
ConnectorServer srv = new ConnectorServer(
new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:0/jettytest"),
// given
connectorServer = new ConnectorServer(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:0/jettytest"),
"org.eclipse.jetty:name=rmiconnectorserver");
srv.start();
Thread.sleep(5000);
// if port is not available then the server value is null
if (connectorServer != null)
{
// when
connectorServer.start();
// then
assertThat("Server status must be in started or starting",connectorServer.getState(),
anyOf(is(ConnectorServer.STARTED),is(ConnectorServer.STARTING)));
}
}
@Test
public void testConnServerWithRmiDefaultPort() throws Exception
{
// given
LocateRegistry.createRegistry(1099);
JMXServiceURL serviceURLWithOutPort = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
connectorServer = new ConnectorServer(serviceURLWithOutPort," domain: key3 = value3");
// when
connectorServer.start();
// then
assertThat("Server status must be in started or starting",connectorServer.getState(),anyOf(is(ConnectorServer.STARTED),is(ConnectorServer.STARTING)));
}
@Test
public void testConnServerWithRmiRandomPort() throws Exception
{
// given
JMXServiceURL serviceURLWithOutPort = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi");
connectorServer = new ConnectorServer(serviceURLWithOutPort," domain: key4 = value4");
// if port is not available then the server value is null
if (connectorServer != null)
{
// when
connectorServer.start();
connectorServer.stop();
// then
assertThat("Server status must be in started or starting",connectorServer.getState(),
anyOf(is(ConnectorServer.STOPPING),is(ConnectorServer.STOPPED)));
}
}
@Test
@Ignore
public void testIsLoopbackAddressWithWrongValue() throws Exception
{
// given
JMXServiceURL serviceURLWithOutPort = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + InetAddress.getLocalHost() + ":1199/jmxrmi");
// when
connectorServer = new ConnectorServer(serviceURLWithOutPort," domain: key5 = value5");
// then
assertNull("As loopback address returns false...registry must be null",connectorServer._registry);
}
}

View File

@ -0,0 +1,240 @@
//
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.jmx;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.eclipse.jetty.util.component.Container;
import org.eclipse.jetty.util.component.ContainerLifeCycle;
import org.eclipse.jetty.util.log.Log;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.acme.Managed;
public class MBeanContainerTest
{
private MBeanContainer mbeanContainer;
private MBeanServer mbeanServer;
private String domain;
private String beanName;
private Managed managed;
private ObjectName objectName;
private Integer mbeanCount;
@Before
public void setUp()
{
mbeanServer = ManagementFactory.getPlatformMBeanServer();
mbeanContainer = new MBeanContainer(mbeanServer);
}
@Test
public void testMakeName()
{
// given
beanName = "mngd:bean";
// when
beanName = mbeanContainer.makeName(beanName);
// then
assertEquals("Bean name should be mngd_bean","mngd_bean",beanName);
}
@Test
public void testFindBean()
{
// given
managed = getManaged();
// when
objectName = mbeanContainer.findMBean(managed);
assertNotNull(objectName);
// then
assertEquals("Bean must be added",managed,mbeanContainer.findBean(objectName));
assertNull("It must return null as there is no bean with the name null",mbeanContainer.findBean(null));
}
private Managed getManaged()
{
beanName = "mngd:bean";
beanName = mbeanContainer.makeName(beanName);
Managed managed = new Managed();
managed.setManaged(beanName);
mbeanContainer.beanAdded(null,managed);
return managed;
}
@Test
public void testMBeanContainer()
{
assertNotNull("Container shouldn't be null",mbeanContainer);
}
@Test
public void testGetMBeanServer()
{
assertEquals("MBean server Instance must be equal",mbeanServer,mbeanContainer.getMBeanServer());
}
@Test
public void testDomain()
{
// given
domain = "Test";
// when
mbeanContainer.setDomain(domain);
// then
assertEquals("Domain name must be Test",domain,mbeanContainer.getDomain());
}
@Test
public void testBeanAdded() throws Exception
{
// given
setBeanAdded();
// when
objectName = mbeanContainer.findMBean(managed);
// then
assertTrue("Bean must have been registered",mbeanServer.isRegistered(objectName));
}
@Test
public void testBeanAddedNullCheck() throws Exception
{
// given
setBeanAdded();
mbeanCount = mbeanServer.getMBeanCount();
// when
mbeanContainer.beanAdded(null,null);
// then
assertEquals("Mbean count must not change after beanAdded(null, null) call",mbeanCount,mbeanServer.getMBeanCount());
}
private void setBeanAdded()
{
managed = new Managed();
Container container = new ContainerLifeCycle();
mbeanContainer.beanAdded(container,managed);
mbeanServer = mbeanContainer.getMBeanServer();
}
@Test
public void testBeanRemoved() throws Exception
{
// given
setUpBeanRemoved();
// when
mbeanContainer.beanRemoved(null,managed);
// then
assertNull("Bean shouldn't be registed with container as we removed the bean",mbeanContainer.findMBean(managed));
}
private void setUpBeanRemoved()
{
managed = new Managed();
mbeanContainer.beanRemoved(null,managed);
mbeanContainer.beanAdded(null,managed);
}
@Test
public void testBeanRemovedInstanceNotFoundException() throws Exception
{
// given
setUpBeanRemoved();
objectName = mbeanContainer.findMBean(managed);
// when
mbeanContainer.getMBeanServer().unregisterMBean(objectName);
// then
assertFalse("Bean must not have been registered as we unregisted the bean",mbeanServer.isRegistered(objectName));
// this flow covers InstanceNotFoundException. Actual code just eating
// the exception. i.e Actual code just printing the stacktrace, whenever
// an exception of type InstanceNotFoundException occurs.
mbeanContainer.beanRemoved(null,managed);
}
@Test
public void testDump()
{
assertNotNull("Dump operation shouldn't return null if operation is success",mbeanContainer.dump());
}
private void setUpDestoy()
{
managed = new Managed();
mbeanContainer.beanAdded(null,managed);
}
@Test
public void testDestroy() throws Exception
{
// given
setUpDestoy();
// when
mbeanContainer.destroy();
objectName = mbeanContainer.findMBean(managed);
// then
assertFalse("Unregisted bean- managed",mbeanContainer.getMBeanServer().isRegistered(objectName));
}
@Test
public void testDestroyInstanceNotFoundException() throws Exception
{
// given
setUpDestoy();
objectName = mbeanContainer.findMBean(managed);
// when
mbeanContainer.getMBeanServer().unregisterMBean(objectName);
// then
assertFalse("Unregisted bean- managed",mbeanContainer.getMBeanServer().isRegistered(objectName));
// this flow covers InstanceNotFoundException. Actual code just eating
// the exception. i.e Actual code just printing the stacktrace, whenever
// an exception of type InstanceNotFoundException occurs.
mbeanContainer.destroy();
}
}

View File

@ -36,7 +36,6 @@ import org.junit.Test;
import com.acme.Derived;
public class ObjectMBeanTest
{
private static final Logger LOG = Log.getLogger(ObjectMBeanTest.class);
@ -78,28 +77,28 @@ public class ObjectMBeanTest
MBeanInfo info = mbean.getMBeanInfo();
Assert.assertEquals("name does not match", "com.acme.Derived", info.getClassName());
Assert.assertEquals("description does not match", "Test the mbean stuff", info.getDescription());
Assert.assertEquals("name does not match","com.acme.Derived",info.getClassName());
Assert.assertEquals("description does not match","Test the mbean stuff",info.getDescription());
//for ( MBeanAttributeInfo i : info.getAttributes())
//{
// LOG.debug(i.toString());
//}
// for ( MBeanAttributeInfo i : info.getAttributes())
// {
// LOG.debug(i.toString());
// }
/*
* 2 attributes from lifecycle and 2 from Derived and 1 from MBean
*/
Assert.assertEquals("attribute count does not match", 6, info.getAttributes().length);
Assert.assertEquals("attribute count does not match",6,info.getAttributes().length);
Assert.assertEquals("attribute values does not match", "Full Name", mbean.getAttribute("fname") );
Assert.assertEquals("attribute values does not match","Full Name",mbean.getAttribute("fname"));
mbean.setAttribute( new Attribute("fname","Fuller Name"));
mbean.setAttribute(new Attribute("fname","Fuller Name"));
Assert.assertEquals("set attribute value does not match", "Fuller Name", mbean.getAttribute("fname") );
Assert.assertEquals("set attribute value does not match","Fuller Name",mbean.getAttribute("fname"));
Assert.assertEquals("proxy attribute values do not match", "goop", mbean.getAttribute("goop") );
Assert.assertEquals("proxy attribute values do not match","goop",mbean.getAttribute("goop"));
//Thread.sleep(100000);
// Thread.sleep(100000);
}
@Test
@ -114,31 +113,31 @@ public class ObjectMBeanTest
MBeanInfo info = mbean.getMBeanInfo();
Assert.assertEquals("operation count does not match", 5, info.getOperations().length);
Assert.assertEquals("operation count does not match",5,info.getOperations().length);
MBeanOperationInfo[] opinfos = info.getOperations();
boolean publish = false;
boolean doodle = false;
boolean good = false;
for ( int i = 0 ; i < opinfos.length; ++i )
for (int i = 0; i < opinfos.length; ++i)
{
MBeanOperationInfo opinfo = opinfos[i];
if ("publish".equals(opinfo.getName()))
{
publish = true;
Assert.assertEquals("description doesn't match", "publish something", opinfo.getDescription());
Assert.assertEquals("description doesn't match","publish something",opinfo.getDescription());
}
if ("doodle".equals(opinfo.getName()))
{
doodle = true;
Assert.assertEquals("description doesn't match", "Doodle something", opinfo.getDescription());
Assert.assertEquals("description doesn't match","Doodle something",opinfo.getDescription());
MBeanParameterInfo[] pinfos = opinfo.getSignature();
Assert.assertEquals("parameter description doesn't match", "A description of the argument", pinfos[0].getDescription());
Assert.assertEquals("parameter name doesn't match", "doodle", pinfos[0].getName());
Assert.assertEquals("parameter description doesn't match","A description of the argument",pinfos[0].getDescription());
Assert.assertEquals("parameter name doesn't match","doodle",pinfos[0].getName());
}
// This is a proxied operation on the JMX wrapper
@ -146,14 +145,14 @@ public class ObjectMBeanTest
{
good = true;
Assert.assertEquals("description does not match", "test of proxy operations", opinfo.getDescription());
Assert.assertEquals("execution contexts wrong", "not bad", mbean.invoke("good", new Object[] {}, new String[] {}));
Assert.assertEquals("description does not match","test of proxy operations",opinfo.getDescription());
Assert.assertEquals("execution contexts wrong","not bad",mbean.invoke("good",new Object[] {},new String[] {}));
}
}
Assert.assertTrue("publish operation was not not found", publish);
Assert.assertTrue("doodle operation was not not found", doodle);
Assert.assertTrue("good operation was not not found", good);
Assert.assertTrue("publish operation was not not found",publish);
Assert.assertTrue("doodle operation was not not found",doodle);
Assert.assertTrue("good operation was not not found",good);
}
@ -174,11 +173,9 @@ public class ObjectMBeanTest
container.beanAdded(null,mbean);
container.beanAdded(null,managed);
//Managed managedInstance = (Managed)mbean.getAttribute("managedInstance");
//Assert.assertNotNull(managedInstance);
//Assert.assertEquals("managed instance returning nonsense", "foo", managedInstance.getManaged());
// Managed managedInstance = (Managed)mbean.getAttribute("managedInstance");
// Assert.assertNotNull(managedInstance);
// Assert.assertEquals("managed instance returning nonsense", "foo", managedInstance.getManaged());
}
@ -206,7 +203,6 @@ public class ObjectMBeanTest
container.beanAdded(null,managed);
container.beanAdded(null,qtp);
Thread.sleep(10000000);
}
@ -226,6 +222,4 @@ public class ObjectMBeanTest
Assert.assertEquals("fullName",mbean.toVariableName("fullName"));
}
}

View File

@ -0,0 +1,352 @@
//
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.jmx;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Arrays;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.ReflectionException;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.log.StdErrLog;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.acme.Derived;
import com.acme.DerivedExtended;
import com.acme.DerivedManaged;
public class ObjectMBeanUtilTest
{
private ObjectMBean objectMBean;
private DerivedExtended derivedExtended;
private MBeanContainer container;
private MBeanInfo objectMBeanInfo;
private Object mBean;
private String value;
private Attribute attribute;
private AttributeList attributes;
private ObjectMBean mBeanDerivedManaged;
private Derived[] derivedes;
private ArrayList<Derived> aliasNames;
private DerivedManaged derivedManaged;
private static final int EMPTY = 0;
@BeforeClass
public static void beforeClass()
{
Logger ombLog = Log.getLogger(ObjectMBean.class);
if (ombLog instanceof StdErrLog && !ombLog.isDebugEnabled())
((StdErrLog)ombLog).setHideStacks(true);
}
@AfterClass
public static void afterClass()
{
Logger ombLog = Log.getLogger(ObjectMBean.class);
if (ombLog instanceof StdErrLog)
((StdErrLog)ombLog).setHideStacks(false);
}
@Before
public void setUp()
{
derivedExtended = new DerivedExtended();
objectMBean = new ObjectMBean(derivedExtended);
container = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
objectMBean.setMBeanContainer(container);
objectMBeanInfo = objectMBean.getMBeanInfo();
}
@Test
public void testBasicOperations()
{
assertEquals("Managed objects should be equal",derivedExtended,objectMBean.getManagedObject());
assertNull("This method call always returns null in the actual code",objectMBean.getObjectName());
assertNull("This method call always returns null in the actual code",objectMBean.getObjectNameBasis());
assertNull("This method call always returns null in the actual code",objectMBean.getObjectContextBasis());
assertEquals("Mbean container should be equal",container,objectMBean.getMBeanContainer());
assertEquals("Mbean description must be equal to : Test the mbean extended stuff","Test the mbean extended stuff",objectMBeanInfo.getDescription());
}
@Test
public void testMbeanForNullCheck()
{
// when
mBean = ObjectMBean.mbeanFor(null);
// then
assertNull("As we are passing null value the output should be null",mBean);
}
@Test(expected = ReflectionException.class)
public void testGetAttributeReflectionException() throws Exception
{
// given
setUpGetAttribute("doodle4","charu");
// when
objectMBean.getAttribute("doodle4");
// then
fail("An InvocationTargetException must have occured by now as doodle4() internally throwing exception");
}
private void setUpGetAttribute(String property, String value) throws Exception
{
Attribute attribute = new Attribute(property,value);
objectMBean.setAttribute(attribute);
}
@Test(expected = AttributeNotFoundException.class)
public void testGetAttributeAttributeNotFoundException() throws Exception
{
// when
objectMBean.getAttribute("ffname");
// then
fail("An AttributeNotFoundException must have occured by now as there is no " + "attribute with the name ffname in bean");
}
@Test
public void testSetAttributeWithCorrectAttrName() throws Exception
{
// given
setUpGetAttribute("fname","charu");
// when
value = (String)objectMBean.getAttribute("fname");
// then
assertEquals("Attribute(fname) value must be equl to charu","charu",value);
}
@Test(expected = AttributeNotFoundException.class)
public void testSetAttributeNullCheck() throws Exception
{
// given
objectMBean.setAttribute(null);
// when
objectMBean.getAttribute(null);
// then
fail("An AttributeNotFoundException must have occured by now as there is no attribute with the name null");
}
@Test(expected = AttributeNotFoundException.class)
public void testSetAttributeAttributeWithWrongAttrName() throws Exception
{
// given
attribute = new Attribute("fnameee","charu");
// when
objectMBean.setAttribute(attribute);
// then
fail("An AttributeNotFoundException must have occured by now as there is no attribute " + "with the name ffname in bean");
}
@Test
public void testSetAttributesWithCorrectValues() throws Exception
{
// given
attributes = getAttributes("fname","vijay");
attributes = objectMBean.setAttributes(attributes);
// when
attributes = objectMBean.getAttributes(new String[]
{ "fname" });
// then
assertEquals("Fname value must be equal to vijay","vijay",((Attribute)(attributes.get(0))).getValue());
}
@Test
public void testSetAttributesForArrayTypeAttribue() throws Exception
{
// given
derivedes = getArrayTypeAttribute();
// when
derivedManaged.setAddresses(derivedes);
mBeanDerivedManaged.getMBeanInfo();
// then
assertNotNull("Address object shouldn't be null",mBeanDerivedManaged.getAttribute("addresses"));
}
@Test
public void testSetAttributesForCollectionTypeAttribue() throws Exception
{
// given
aliasNames = getCollectionTypeAttribute();
// when
derivedManaged.setAliasNames(aliasNames);
mBeanDerivedManaged.getMBeanInfo();
// then
assertNotNull("Address object shouldn't be null",mBeanDerivedManaged.getAttribute("aliasNames"));
assertNull("Derived object shouldn't registerd with container so its value will be null",mBeanDerivedManaged.getAttribute("derived"));
}
private Derived[] getArrayTypeAttribute()
{
derivedManaged = new DerivedManaged();
mBeanDerivedManaged = new ObjectMBean(derivedManaged);
MBeanContainer mBeanDerivedManagedContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
mBeanDerivedManaged.setMBeanContainer(mBeanDerivedManagedContainer);
Derived derived0 = new Derived();
mBeanDerivedManagedContainer.beanAdded(null,derived0);
Derived[] derivedes = new Derived[3];
for (int i = 0; i < 3; i++)
{
derivedes[i] = new Derived();
}
derivedManaged.setAddresses(derivedes);
mBeanDerivedManaged.getMBeanInfo();
ArrayList<Derived> aliasNames = new ArrayList<Derived>(Arrays.asList(derivedes));
derivedManaged.setAliasNames(aliasNames);
return derivedes;
}
private ArrayList<Derived> getCollectionTypeAttribute()
{
ArrayList<Derived> aliasNames = new ArrayList<Derived>(Arrays.asList(getArrayTypeAttribute()));
return aliasNames;
}
@Test
public void testSetAttributesException()
{
// given
attributes = getAttributes("fnameee","charu");
// when
attributes = objectMBean.setAttributes(attributes);
// then
// Original code eating the exception and returning zero size list
assertEquals("As there is no attribute with the name fnameee, this should return empty",EMPTY,attributes.size());
}
private AttributeList getAttributes(String name, String value)
{
Attribute attribute = new Attribute(name,value);
AttributeList attributes = new AttributeList();
attributes.add(attribute);
return attributes;
}
@Test(expected = MBeanException.class)
public void testInvokeMBeanException() throws Exception
{
// given
setMBeanInfoForInvoke();
// when
objectMBean.invoke("doodle2",new Object[] {},new String[] {});
// then
fail("An MBeanException must have occured by now as doodle2() in Derived bean throwing exception");
}
@Test(expected = ReflectionException.class)
public void testInvokeReflectionException() throws Exception
{
// given
setMBeanInfoForInvoke();
// when
objectMBean.invoke("doodle1",new Object[] {},new String[] {});
// then
fail("An ReflectionException must have occured by now as doodle1() has private access in Derived bean");
}
@Test
public void testInvoke() throws Exception
{
// given
setMBeanInfoForInvoke();
// when
value = (String)objectMBean.invoke("good",new Object[] {},new String[] {});
// then
assertEquals("Method(good) invocation on objectMBean must return not bad","not bad",value);
}
@Test(expected = ReflectionException.class)
public void testInvokeNoSuchMethodException() throws Exception
{
// given
setMBeanInfoForInvoke();
// when
// DerivedMBean contains a managed method with the name good,we must
// call this method without any arguments
objectMBean.invoke("good",new Object[] {},new String[]
{ "int aone" });
// then
fail("An ReflectionException must have occured by now as we cannot call a methow with wrong signature");
}
private void setMBeanInfoForInvoke()
{
objectMBean = (ObjectMBean)ObjectMBean.mbeanFor(derivedExtended);
container.beanAdded(null,derivedExtended);
objectMBean.getMBeanInfo();
}
@Test
public void testToVariableName()
{
assertEquals("fullName",objectMBean.toVariableName("isfullName"));
}
}

View File

@ -0,0 +1,49 @@
//
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.jmx;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jetty.util.log.jmx.LogMBean;
import org.junit.Test;
import com.openpojo.reflection.impl.PojoClassFactory;
import com.openpojo.validation.Validator;
import com.openpojo.validation.ValidatorBuilder;
import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
/*
* This class tests all the getters and setters for a given list of classes.
*/
public class PojoTest
{
private Validator validator;
@Test
public void testOpenPojo()
{
validator = ValidatorBuilder.create().with(new SetterTester()).with(new GetterTester()).build();
List<Class> classes = Arrays.asList(MBeanContainer.class,ObjectMBean.class,LogMBean.class);
for (Class clazz : classes)
{
validator.validate(PojoClassFactory.getPojoClass(clazz));
}
}
}

View File

@ -0,0 +1,56 @@
//
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.util.log.jmx;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Before;
import org.junit.Test;
import com.acme.Managed;
public class LogMBeanTest
{
private Managed managed;
private LogMBean logMBean;
private static final String MANAGED_CLASS = "Managed";
@Before
public void setUp()
{
managed = new Managed();
logMBean = new LogMBean(managed);
}
@Test
public void testKeySet()
{
// given
assertFalse("Managed is not registered with loggers",logMBean.getLoggers().contains(MANAGED_CLASS));
// when
logMBean.setDebugEnabled(MANAGED_CLASS,true);
// then
assertTrue("Managed must be registered with loggers",logMBean.getLoggers().contains(MANAGED_CLASS));
assertTrue("This must return true as debug is enabled for this class",logMBean.isDebugEnabled(MANAGED_CLASS));
}
}

View File

@ -77,6 +77,7 @@ import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.AttributesMap;
import org.eclipse.jetty.util.FutureCallback;
import org.eclipse.jetty.util.Loader;
import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
@ -195,6 +196,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
private final List<EventListener> _eventListeners=new CopyOnWriteArrayList<>();
private final List<EventListener> _programmaticListeners=new CopyOnWriteArrayList<>();
private final List<ServletContextListener> _servletContextListeners=new CopyOnWriteArrayList<>();
private final List<ServletContextListener> _destroySerletContextListeners=new ArrayList<>();
private final List<ServletContextAttributeListener> _servletContextAttributeListeners=new CopyOnWriteArrayList<>();
private final List<ServletRequestListener> _servletRequestListeners=new CopyOnWriteArrayList<>();
private final List<ServletRequestAttributeListener> _servletRequestAttributeListeners=new CopyOnWriteArrayList<>();
@ -776,6 +778,8 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
}
finally
{
if (_availability==Availability.STARTING)
_availability=Availability.UNAVAILABLE;
exitScope(null);
__context.set(old_context);
// reset the classloader
@ -801,15 +805,18 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
super.doStart();
// Call context listeners
_destroySerletContextListeners.clear();
if (!_servletContextListeners.isEmpty())
{
ServletContextEvent event = new ServletContextEvent(_scontext);
for (ServletContextListener listener:_servletContextListeners)
{
callContextInitialized(listener, event);
_destroySerletContextListeners.add(listener);
}
}
}
/* ------------------------------------------------------------ */
protected void stopContext () throws Exception
{
@ -817,12 +824,21 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
super.doStop();
//Call the context listeners
if (!_servletContextListeners.isEmpty())
ServletContextEvent event = new ServletContextEvent(_scontext);
Collections.reverse(_destroySerletContextListeners);
MultiException ex = new MultiException();
for (ServletContextListener listener:_destroySerletContextListeners)
{
ServletContextEvent event = new ServletContextEvent(_scontext);
for (int i = _servletContextListeners.size(); i-->0;)
callContextDestroyed(_servletContextListeners.get(i),event);
try
{
callContextDestroyed(listener,event);
}
catch(Exception x)
{
ex.add(x);
}
}
ex.ifExceptionThrow();
}

View File

@ -62,8 +62,10 @@ public class HotSwapHandler extends AbstractHandlerContainer
@Override
public Handler[] getHandlers()
{
return new Handler[]
{ _handler };
Handler handler=_handler;
if (handler==null)
return new Handler[0];
return new Handler[] { handler };
}
/* ------------------------------------------------------------ */
@ -73,14 +75,13 @@ public class HotSwapHandler extends AbstractHandlerContainer
*/
public void setHandler(Handler handler)
{
if (handler == null)
throw new IllegalArgumentException("Parameter handler is null.");
try
{
Server server = getServer();
if (handler!=null)
handler.setServer(server);
updateBean(_handler,handler,true);
_handler=handler;
Server server = getServer();
handler.setServer(server);
}
catch (Exception e)
@ -116,9 +117,10 @@ public class HotSwapHandler extends AbstractHandlerContainer
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
if (_handler != null && isStarted())
Handler handler=_handler;
if (handler != null && isStarted() && handler.isStarted())
{
_handler.handle(target,baseRequest,request,response);
handler.handle(target,baseRequest,request,response);
}
}
@ -126,7 +128,9 @@ public class HotSwapHandler extends AbstractHandlerContainer
@Override
protected void expandChildren(List<Handler> list, Class<?> byClass)
{
expandHandler(_handler,list,byClass);
Handler handler=_handler;
if (handler!=null)
expandHandler(handler,list,byClass);
}
/* ------------------------------------------------------------ */

View File

@ -27,11 +27,15 @@ import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.List;
import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@ -40,6 +44,8 @@ import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.HotSwapHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceCollection;
import org.hamcrest.Matchers;
@ -225,4 +231,109 @@ public class WebAppContextTest
this.getServletContext().getContext("/B/s");
}
}
@Test
public void testServletContextListener() throws Exception
{
Server server = new Server();
HotSwapHandler swap = new HotSwapHandler();
server.setHandler(swap);
server.start();
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.setResourceBase(System.getProperty("java.io.tmpdir"));
final List<String> history=new ArrayList<>();
context.addEventListener(new ServletContextListener()
{
@Override
public void contextInitialized(ServletContextEvent servletContextEvent)
{
history.add("I0");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent)
{
history.add("D0");
}
});
context.addEventListener(new ServletContextListener()
{
@Override
public void contextInitialized(ServletContextEvent servletContextEvent)
{
history.add("I1");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent)
{
history.add("D1");
throw new RuntimeException("Listener1 destroy broken");
}
});
context.addEventListener(new ServletContextListener()
{
@Override
public void contextInitialized(ServletContextEvent servletContextEvent)
{
history.add("I2");
throw new RuntimeException("Listener2 init broken");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent)
{
history.add("D2");
}
});
context.addEventListener(new ServletContextListener()
{
@Override
public void contextInitialized(ServletContextEvent servletContextEvent)
{
history.add("I3");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent)
{
history.add("D3");
}
});
try
{
swap.setHandler(context);
context.start();
}
catch(Exception e)
{
history.add(e.getMessage());
}
finally
{
try
{
swap.setHandler(null);
}
catch(Exception e)
{
while(e.getCause() instanceof Exception)
e=(Exception)e.getCause();
history.add(e.getMessage());
}
finally
{
}
}
Assert.assertThat(history,Matchers.contains("I0","I1","I2","Listener2 init broken","D1","D0","Listener1 destroy broken"));
server.stop();
}
}