diff options
| author | Stephen D. Huston <shuston@apache.org> | 2011-10-21 01:19:00 +0000 |
|---|---|---|
| committer | Stephen D. Huston <shuston@apache.org> | 2011-10-21 01:19:00 +0000 |
| commit | ebfd9ff053b04ab379acfc0fefedee5a31b6d8a5 (patch) | |
| tree | dcfb94e75656c6c239fc3dcb754cd2015126424d /java/management/client/src/test | |
| parent | 5eb354b338bb8d8fcd35b6ac3fb33f8103e757c3 (diff) | |
| download | qpid-python-ebfd9ff053b04ab379acfc0fefedee5a31b6d8a5.tar.gz | |
Undo bad merge from trunk - merged at wrong level.
git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/QPID-2519@1187150 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'java/management/client/src/test')
36 files changed, 5642 insertions, 0 deletions
diff --git a/java/management/client/src/test/java/org/apache/qpid/management/TestConstants.java b/java/management/client/src/test/java/org/apache/qpid/management/TestConstants.java new file mode 100644 index 0000000000..9abcd08eef --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/TestConstants.java @@ -0,0 +1,67 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.qpid.management.domain.handler.impl.MethodOrEventDataTransferObject; +import org.apache.qpid.management.domain.model.DomainModel; +import org.apache.qpid.management.domain.model.type.Binary; + +/** + * Collects all literal constants used in test cases. + */ +public interface TestConstants +{ + UUID BROKER_ID = UUID.randomUUID(); + Binary OBJECT_ID = new Binary(new byte []{1,2,3,2,1,1,2,3}); + + DomainModel DOMAIN_MODEL = new DomainModel(BROKER_ID); + + String AGE_ATTRIBUTE_NAME = "age"; + String AGE_ATTRIBUTE_DESCRIPTION = "The age of a person."; + String SURNAME_ATTRIBUTE_NAME = "surname"; + String SURNAME_ATTRIBUTE_DESCRIPTION = "The surname of a person."; + Integer _1 = new Integer(1); + + byte [] TEST_RAW_DATA= new byte []{1,4,5,7,8,9,4,44}; + long NOW = System.currentTimeMillis(); + int SEVERITY = _1; + + String QPID_PACKAGE_NAME = "qpid"; + String EXCHANGE_CLASS_NAME = "exchange"; + String BIND_EVENT_NAME = "bind"; + Binary HASH = new Binary(new byte []{1,2,3,4,5,6,7,8,9}); + int VALID_CODE = _1; + + List<Map<String, Object>> EMPTY_PROPERTIES_SCHEMA = new LinkedList<Map<String,Object>>(); + List<Map<String, Object>> EMPTY_STATISTICS_SCHEMA = new LinkedList<Map<String,Object>>(); + List<MethodOrEventDataTransferObject> EMPTY_METHODS_SCHEMA = new LinkedList<MethodOrEventDataTransferObject>(); + List<Map<String, Object>> EMPTY_ARGUMENTS_SCHEMA = new LinkedList<Map<String,Object>>(); + int _0 = 0; + int SAMPLE_ACCESS_CODE = 1; + String YEARS = "years"; + int SAMPLE_MIN_VALUE = 1; + int SAMPLE_MAX_VALUE = 120; +}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/configuration/ConfigurationTest.java b/java/management/client/src/test/java/org/apache/qpid/management/configuration/ConfigurationTest.java new file mode 100644 index 0000000000..72bd45f70f --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/configuration/ConfigurationTest.java @@ -0,0 +1,181 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.configuration; + +import java.util.Map; +import java.util.UUID; + +import junit.framework.TestCase; + +import org.apache.qpid.management.TestConstants; +import org.apache.qpid.management.domain.handler.base.IMessageHandler; +import org.apache.qpid.management.domain.handler.impl.ConfigurationMessageHandler; +import org.apache.qpid.management.domain.handler.impl.InstrumentationMessageHandler; +import org.apache.qpid.management.domain.handler.impl.SchemaResponseMessageHandler; + +/** + * Test case for Configuration singleton. + */ +public class ConfigurationTest extends TestCase +{ + /** + * Tests the singleton behaviour of the configuration object. + */ + public void testSingleton() + { + assertSame(Configuration.getInstance(),Configuration.getInstance()); + } + + /** + * Tests the execution of getType() method when a unknown code is supplied. + * + * <br>precondition : the requested type doesn't exist on the configuration. + * <br>postcondition : an exception is thrown indicating the failure. + */ + public void testGetTypeKO() + { + try + { + Configuration.getInstance().getType(TestConstants.VALID_CODE*10001); + fail("If an unknwon code is supplied an exception must be thrown."); + } catch (UnknownTypeCodeException expected) + { + assertEquals(TestConstants.VALID_CODE*10001,expected.getCode()); + } + } + + /** + * Tests the execution of getAccessMode() method when a unknown code is supplied. + * + * <br>precondition : the requested access mode doesn't exist on the configuration. + * <br>postcondition : an exception is thrown indicating the failure. + */ + public void testGetAccessModeKO() + { + try + { + Configuration.getInstance().getAccessMode(TestConstants.VALID_CODE*1528); + fail("If an unknwon code is supplied an exception must be thrown."); + } catch (UnknownAccessCodeException expected) + { + assertEquals(TestConstants.VALID_CODE*1528,expected.getCode()); + } + } + + /** + * Tests the execution of the getBrokerConnectionData when a valid broker id is supplied. + * + * <br>precondition : on configuration a connection data is stored and associated with the supplied id. + * <br>postcondition : the requested connection data is returned and no exception is thrown. + */ + public void testGetBrokerConnectionDataOK() throws Exception + { + BrokerConnectionData connectionData = new BrokerConnectionData(); + connectionData.setHost("host"); + connectionData.setPort("7001"); + connectionData.setInitialPoolCapacity("0"); + connectionData.setMaxPoolCapacity("10"); + connectionData.setMaxWaitTimeout("1"); + Configuration.getInstance().addBrokerConnectionData(TestConstants.BROKER_ID, connectionData); + + BrokerConnectionData result = Configuration.getInstance().getBrokerConnectionData(TestConstants.BROKER_ID); + assertSame(connectionData, result); + } + + /** + * Tests the execution of the getBrokerConnectionData when a unknown broker id is supplied. + * + * <br>precondition : on configuration there's no connection data associated with the supplied id. + * <br>postcondition : an exception is thrown indicating the failure. + */ + public void testGetBrokerConnectionDataKO_withUnknownBrokerId() + { + UUID brokerId = UUID.randomUUID(); + try + { + Configuration.getInstance().getBrokerConnectionData(brokerId); + fail("If an unknown broker id is supplied then an exception must be thrown."); + } catch(UnknownBrokerException expected) + { + assertEquals(brokerId.toString(),expected.getMessage()); + } + } + + /** + * Tests the execution of the getBrokerConnectionData when a null id is supplied. + * + * <br>precondition : a null broker is given. + * <br>postcondition : an exception is thrown indicating the failure. + */ + public void testGetBrokerConnectionDataKO_withNullBrokerId() + { + try + { + Configuration.getInstance().getBrokerConnectionData(null); + fail("If a null broker id is supplied then an exception must be thrown."); + } catch(UnknownBrokerException expected) + { + } + } + + /** + * Tests the behaviour of the getManagementQueueHandlers() method. + * + * <br>precondition: 2 management handlers are in stored configuration + * <br>postcondition : 2 management handlers are returned. + */ + public void testGetManagementQueueHandlersOk() + { + IMessageHandler instrMessageHandler = new InstrumentationMessageHandler(); + IMessageHandler configMessageHandler = new ConfigurationMessageHandler(); + + MessageHandlerMapping instrMapping = new MessageHandlerMapping('i',instrMessageHandler); + MessageHandlerMapping configMapping = new MessageHandlerMapping('c',configMessageHandler); + + Configuration.getInstance().addManagementMessageHandlerMapping(instrMapping); + Configuration.getInstance().addManagementMessageHandlerMapping(configMapping); + + Map<Character, IMessageHandler> handlerMappings = Configuration.getInstance().getManagementQueueHandlers(); + + assertEquals(2,handlerMappings.size()); + assertEquals(instrMessageHandler,handlerMappings.get(instrMapping.getOpcode())); + assertEquals(configMessageHandler,handlerMappings.get(configMapping.getOpcode())); + } + + /** + * Tests the behaviour of the getManagementQueueHandlers() method. + * + * <br>precondition: 2 management handlers are in stored configuration + * <br>postcondition : 2 management handlers are returned. + */ + public void testGetMethodReplyQueueHandlersOk() + { + IMessageHandler schemaMessageHandler = new SchemaResponseMessageHandler(); + + MessageHandlerMapping schemaMapping = new MessageHandlerMapping('s',schemaMessageHandler); + + Configuration.getInstance().addMethodReplyMessageHandlerMapping(schemaMapping); + + Map<Character, IMessageHandler> handlerMappings = Configuration.getInstance().getMethodReplyQueueHandlers(); + + assertEquals(schemaMessageHandler,handlerMappings.get(schemaMapping.getOpcode())); + } +} diff --git a/java/management/client/src/test/java/org/apache/qpid/management/configuration/ConfiguratorTest.java b/java/management/client/src/test/java/org/apache/qpid/management/configuration/ConfiguratorTest.java new file mode 100644 index 0000000000..1e464bf6ae --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/configuration/ConfiguratorTest.java @@ -0,0 +1,163 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.configuration; + +import java.util.Map; +import java.util.UUID; + +import junit.framework.TestCase; + +import org.apache.qpid.management.Protocol; +import org.apache.qpid.management.domain.handler.base.IMessageHandler; +import org.apache.qpid.management.domain.handler.impl.ConfigurationMessageHandler; +import org.apache.qpid.management.domain.handler.impl.EventContentMessageHandler; +import org.apache.qpid.management.domain.handler.impl.HeartBeatIndicationMessageHandler; +import org.apache.qpid.management.domain.handler.impl.InstrumentationMessageHandler; +import org.apache.qpid.management.domain.handler.impl.MethodResponseMessageHandler; +import org.apache.qpid.management.domain.handler.impl.SchemaResponseMessageHandler; +import org.apache.qpid.management.domain.model.AccessMode; +import org.apache.qpid.management.domain.model.type.AbsTime; +import org.apache.qpid.management.domain.model.type.DeltaTime; +import org.apache.qpid.management.domain.model.type.ObjectReference; +import org.apache.qpid.management.domain.model.type.Str16; +import org.apache.qpid.management.domain.model.type.Str8; +import org.apache.qpid.management.domain.model.type.Uint16; +import org.apache.qpid.management.domain.model.type.Uint32; +import org.apache.qpid.management.domain.model.type.Uint64; +import org.apache.qpid.management.domain.model.type.Uint8; +import org.xml.sax.SAXException; + +/** + * Test case for configurator. + * + * @author Andrea Gazzarini + * + */ +public class ConfiguratorTest extends TestCase +{ + /** + * Tests the execution of the configure() method when no configuration file is given. + * + * <br>precondition : configuration file option is not set + * <br>postcondition : no exception is thrown, the configuration is holding no broker data and the predefined mappings are + * stored in configuration. + */ + public void testConfigureOK_WithNoConfigurationFile() throws Exception + { + Configurator configurator = new Configurator(); + configurator.configure(); + Configuration configuration = Configuration.getInstance(); + + assertEquals(new Uint8(), configuration.getType(1)); + assertEquals(new Uint16(), configuration.getType(2)); + assertEquals(new Uint32(), configuration.getType(3)); + assertEquals(new Uint64(), configuration.getType(4)); + assertEquals(new Str8(), configuration.getType(6)); + assertEquals(new Str16(), configuration.getType(7)); + assertEquals(new AbsTime(), configuration.getType(8)); + assertEquals(new DeltaTime(), configuration.getType(9)); + assertEquals(new ObjectReference(), configuration.getType(10)); + assertEquals(new org.apache.qpid.management.domain.model.type.Boolean(), configuration.getType(11)); + assertEquals(new org.apache.qpid.management.domain.model.type.Uuid(), configuration.getType(14)); + assertEquals(new org.apache.qpid.management.domain.model.type.Map(), configuration.getType(15)); + + assertEquals(AccessMode.RC,configuration.getAccessMode(1)); + assertEquals(AccessMode.RW,configuration.getAccessMode(2)); + assertEquals(AccessMode.RO,configuration.getAccessMode(3)); + + Map<Character, IMessageHandler> managementHandlers = configuration.getManagementQueueHandlers(); + assertEquals(4,managementHandlers.size()); + assertEquals( + InstrumentationMessageHandler.class, + managementHandlers.get(Protocol.INSTRUMENTATION_CONTENT_RESPONSE_OPCODE).getClass()); + + assertEquals( + ConfigurationMessageHandler.class, + managementHandlers.get(Protocol.CONFIGURATION_CONTENT_RESPONSE_OPCDE).getClass()); + + assertEquals( + EventContentMessageHandler.class, + managementHandlers.get(Protocol.EVENT_CONTENT_RESPONSE_OPCDE).getClass()); + + assertEquals( + HeartBeatIndicationMessageHandler.class, + managementHandlers.get(Protocol.HEARTBEAT_INDICATION_RESPONSE_OPCODE).getClass()); + + Map<Character, IMessageHandler> methodReplyHandlers = configuration.getMethodReplyQueueHandlers(); + assertEquals(2, methodReplyHandlers.size()); + + assertEquals( + MethodResponseMessageHandler.class, + methodReplyHandlers.get(Protocol.OPERATION_INVOCATION_RESPONSE_OPCODE).getClass()); + + assertEquals( + SchemaResponseMessageHandler.class, + methodReplyHandlers.get(Protocol.SCHEMA_RESPONSE_OPCODE).getClass()); + } + + /** + * Tests the changes of the configurator internal state while configuration file is parsed. + * + * <br>precondition: N.A. + * <br>postcondition: N.A. + */ + public void testDirectorParsing() throws SAXException{ + Configurator configurator = new Configurator(); + + assertSame(Configurator.DEFAULT_PARSER,configurator._currentParser); + + configurator.startElement(null, null, Tag.BROKERS.toString(), null); + assertSame(configurator._brokerConfigurationParser,configurator._currentParser); + } + + /** + * It's not possibile to add twice the same broker connection data. + * Is so an exception must be thrown indicating that the given broker is already connected. + * + * <br>precondition : the given data identifies an already connected broker. + * <br>postcondition : an exception is thrown indicating the failure. + */ + public void testAddTwoIdenticalBrokers() throws ConfigurationException, BrokerConnectionException + { + Configurator configurator = new Configurator(); + configurator.configure(); + + BrokerConnectionData data = new BrokerConnectionData("sofia.gazzax.com",5672,"virtualHost","user","pwd",1,4,-1); + + Configuration.getInstance()._brokerConnectionInfos.put(UUID.randomUUID(),data); + + try { + configurator.createAndReturnBrokerConnectionData( + UUID.randomUUID(), + data.getHost(), + data.getPort(), + "anotherUser", + "anotherPassword", + data.getVirtualHost(), + 33, + 12, + 1000); + fail("If a broker is added twice an exception must be thrown."); + } catch (BrokerAlreadyConnectedException expected) { + assertEquals(data,expected.getBrokerConnectionData()); + } + } +} diff --git a/java/management/client/src/test/java/org/apache/qpid/management/configuration/MappingParsersTest.java b/java/management/client/src/test/java/org/apache/qpid/management/configuration/MappingParsersTest.java new file mode 100644 index 0000000000..af261024bd --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/configuration/MappingParsersTest.java @@ -0,0 +1,79 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.configuration; + +import java.util.UUID; + +import junit.framework.TestCase; + +import org.apache.qpid.management.TestConstants; + +/** + * Test case for mapping parsers. + * + * @author Andrea Gazzarini. + */ +public class MappingParsersTest extends TestCase +{ + /** + * Tests the execution of the broker connection data mapping parser. + * + * <br>precondition: A broker connection datamapping is built by the parser; + * <br>postcondition: the corresponding connection data is available on the configuration. + */ + public void testBrokerConnectionDataParser() throws UnknownBrokerException + { + String host = "127.0.0.1"; + String port = "7001"; + String virtualHost = "test"; + String username = "username_guest"; + String password ="password_guest"; + + BrokerConnectionDataParser parser = new BrokerConnectionDataParser() + { + @Override + UUID getUUId () + { + return TestConstants.BROKER_ID; + } + }; + + parser.setCurrrentAttributeValue(host); + parser.setCurrentAttributeName(Tag.HOST.toString()); + parser.setCurrrentAttributeValue(port); + parser.setCurrentAttributeName(Tag.PORT.toString()); + parser.setCurrrentAttributeValue(virtualHost); + parser.setCurrentAttributeName(Tag.VIRTUAL_HOST.toString()); + parser.setCurrrentAttributeValue(username); + parser.setCurrentAttributeName(Tag.USER.toString()); + parser.setCurrrentAttributeValue(password); + parser.setCurrentAttributeName(Tag.PASSWORD.toString()); + parser.setCurrentAttributeName(Tag.BROKER.toString()); + + BrokerConnectionData result = Configuration.getInstance().getBrokerConnectionData(TestConstants.BROKER_ID); + + assertEquals(host,result.getHost()); + assertEquals(Integer.parseInt(port),result.getPort()); + assertEquals(virtualHost,result.getVirtualHost()); + assertEquals(username,result.getUsername()); + assertEquals(password,result.getPassword()); + } +} diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/handler/base/ContentIndicationMessageHandlerTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/handler/base/ContentIndicationMessageHandlerTest.java new file mode 100644 index 0000000000..d6b51b64fc --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/handler/base/ContentIndicationMessageHandlerTest.java @@ -0,0 +1,59 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.handler.base; + +import junit.framework.TestCase; + +import org.apache.qpid.management.domain.model.type.Binary; + +/** + * Test case for Content indication message handler (base class). + * + * @author Andrea Gazzarini + */ +public class ContentIndicationMessageHandlerTest extends TestCase +{ + /** + * Tests the behaviour of the objectHasBeenRemoved method(). + */ + public void testObjectHasBeenRemoved() + { + ContentIndicationMessageHandler mockHandler = new ContentIndicationMessageHandler() + { + @Override + protected void updateDomainModel (String packageName, String className, Binary classHash, Binary objectId, + long timeStampOfCurrentSample, long timeObjectWasCreated, long timeObjectWasDeleted, byte[] contentData) + { + } + }; + + long deletionTimestamp = 0; + long now = System.currentTimeMillis(); + + assertFalse(mockHandler.objectHasBeenRemoved(deletionTimestamp, now)); + + deletionTimestamp = now + 1000; + assertFalse(mockHandler.objectHasBeenRemoved(deletionTimestamp, now)); + + deletionTimestamp = now - 1000; + assertTrue(mockHandler.objectHasBeenRemoved(deletionTimestamp, now)); + } +}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/BaseDomainModelTestCase.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/BaseDomainModelTestCase.java new file mode 100644 index 0000000000..c528392a93 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/BaseDomainModelTestCase.java @@ -0,0 +1,44 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model; + +import org.apache.qpid.management.configuration.Configurator; + +import junit.framework.TestCase; + +/** + * Layer supertype for all domain model related test cases. + * + * @author Andrea Gazzarini + */ +public abstract class BaseDomainModelTestCase extends TestCase +{ + /** + * Set up fixture for this test case. + * In order to execute tests on domain model we need to build the configuration. + */ + @Override + protected void setUp () throws Exception + { + Configurator configurator = new Configurator(); + configurator.configure(); + } +}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/BaseQpidFeatureBuilderTestCase.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/BaseQpidFeatureBuilderTestCase.java new file mode 100644 index 0000000000..3d3783eb04 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/BaseQpidFeatureBuilderTestCase.java @@ -0,0 +1,96 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model; + +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.desc; +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.name; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.apache.qpid.management.configuration.Configurator; +import org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute; + +/** + * Layer supertype for feature builder test cases. + * + * @author Andrea Gazzarini + */ +public abstract class BaseQpidFeatureBuilderTestCase extends TestCase +{ + protected final static String NAME = "aName"; + + protected final static String DESCRIPTION = "A description."; + + protected Map <String,Object> _featureDefinition; + protected QpidFeatureBuilder _builder; + + /** + * Set up fixture for all concrete builder test cases. + */ + @Override + protected void setUp () throws Exception + { + Configurator configurator = new Configurator(); + configurator.configure(); + _featureDefinition = new HashMap<String, Object>(); + _featureDefinition.put(name.name(),NAME); + _featureDefinition.put(desc.name(), DESCRIPTION); + } + + // Internal test used to avoid code duplication. + protected void internalTestForMissingMandatoryAttribute(Attribute ...toBeRemoved) + { + try + { + for (Attribute attribute : toBeRemoved) + { + _featureDefinition.remove(attribute.name()); + } + _builder.build(); + fail("If a mandatory attribute is missing an exception must be thrown!"); + } catch (UnableToBuildFeatureException expected) + { + assertTrue(expected instanceof MissingFeatureAttributesException); + for (Attribute attribute : toBeRemoved) + { + assertTrue(expected.getMessage().contains(attribute.name())); + } + } + } + + // Internal test used to avoid code duplication. + protected void internalTestForMissingOptionalAttribute(Attribute ...toBeRemoved) throws UnableToBuildFeatureException + { + for (Attribute attribute : toBeRemoved) + { + _featureDefinition.remove(attribute.name()); + } + _builder.build(); + + assertNotNull(_builder.getQpidFeature()); + assertNotNull(_builder.getManagementFeature()); + } + + +} diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/DomainModelTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/DomainModelTest.java new file mode 100644 index 0000000000..578fa36bc7 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/DomainModelTest.java @@ -0,0 +1,55 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model; + +import java.util.UUID; + +import org.apache.qpid.management.TestConstants; + +/** + * Test case for domain model entity. + * + * @author Andrea Gazzarini + */ +public class DomainModelTest extends BaseDomainModelTestCase +{ + private DomainModel _model; + + @Override + protected void setUp () throws Exception + { + _model = new DomainModel(UUID.randomUUID()); + } + + /** + * Tests the execution of the getPackage() method. + */ + public void testGetPackage() + { + assertFalse(_model.containsPackage(TestConstants.QPID_PACKAGE_NAME)); + + QpidPackage qpidPackage = _model.getPackageByName(TestConstants.QPID_PACKAGE_NAME); + assertEquals(TestConstants.QPID_PACKAGE_NAME,qpidPackage.getName()); + + QpidPackage theSameAsPreviousOne = _model.getPackageByName(TestConstants.QPID_PACKAGE_NAME); + assertSame(qpidPackage, theSameAsPreviousOne); + } +}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/OptionalPropertiesTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/OptionalPropertiesTest.java new file mode 100644 index 0000000000..553c1c21de --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/OptionalPropertiesTest.java @@ -0,0 +1,187 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model; + +import java.nio.ByteBuffer; +import java.util.LinkedList; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.qpid.management.domain.model.type.Uint64; +import org.apache.qpid.transport.codec.BBDecoder; + +public class OptionalPropertiesTest extends TestCase +{ + public void testDecoderStateChange() + { + QpidProperty property = new QpidProperty(); + assertSame( + "Default decoder for properties is the one for mandatory properties.", + property._mandatoryPropertyDecoder, + property._decoder); + + property.markAsOptional(1); + assertSame( + "After a property has been marked as optional the corresponding decoder must be installed.", + property._optionalPropertyDecoder, + property._decoder); + } + + /** + * Tests the execution of the decode() method when the current property is optional but in the presence bitmask + * there's no the corresponding bit set. + * + * <br>precondition : property is optional and corresponding presence bit is not set. + * <br>postcondition : result must be null. + */ + public void testDecodeValueWithOptionalPropertyAndMissingValue() + { + byte [] presenceBytes = {2}; + + QpidProperty property = new QpidProperty(); + + // We don't need a decoder so in order to be sure that it won't be invoked set it to null. + BBDecoder nullDecoder = null; + + for (int i = 0; i < 8; i++) + { + // Property number 1 is declaring a value so skip it! + if (i != 1) + { + property.markAsOptional(i); + assertNull(property.decodeValue(nullDecoder, presenceBytes)); + } + } + } + + /** + * Tests the execution of the decode() method when the current property is optional but in the presence bitmask + * there's no the corresponding bit set. + * + * <br>precondition : property is optional and corresponding presence bit is not set. + * <br>postcondition : result must be null. + */ + public void testDecodeValueWithOptionalPropertyAndDeclaredValue() + { + byte [] presenceBytes = {4}; + Long _44 = new Long(44); + + QpidProperty property = new QpidProperty(); + property.setType(new Uint64()); + property.markAsOptional(2); + + ByteBuffer buffer = ByteBuffer.allocate(8); + buffer.putLong(_44); + buffer.rewind(); + BBDecoder decoder = new BBDecoder(); + + decoder.init(buffer); + assertEquals(_44,property.decodeValue(decoder, presenceBytes)); + } + + /** + * Tests the execution of the decode() method with a real scenario where there are mandatory and optional + * properties. + */ + public void testDecodeValueWithOptionalAndMandatoryProperties() + { + // With this bitset : + // + // 1th opt property is null; + // 2th opt property is null; + // 3th opt property is not null; + // 4th opt property is null; + // 5th opt propertyis null; + // 6th opt property is null; + // 7th opt property is null; + // 8th opt property is not null; + byte [] presenceBytes = {4,1}; + + List<QpidProperty> properties = new LinkedList<QpidProperty>(); + + properties.add(createProperty(false, -1)); + properties.add(createProperty(false, -1)); + properties.add(createProperty(true, 0)); + properties.add(createProperty(false, -1)); + properties.add(createProperty(false, -1)); + properties.add(createProperty(true, 1)); + properties.add(createProperty(false, -1)); + properties.add(createProperty(false, -1)); + properties.add(createProperty(true, 2)); + properties.add(createProperty(true, 3)); + properties.add(createProperty(true, 4)); + properties.add(createProperty(true, 5)); + properties.add(createProperty(true, 6)); + properties.add(createProperty(true, 7)); + properties.add(createProperty(false, -1)); + properties.add(createProperty(true, 8)); + + Long expectedResults [] = { + 1L, // p1 + 22L, // p2 + null, // p3 + 232L, // p4 + 211L, // p5 + null, // p6 + 232L, // p7 + 211L, // p8 + 999L, // p9 + null, // p10 + null, // p11 + null, // p12 + null, // p13 + null, // p14 + 626L, // p15 + 969L // p16 + }; + + + ByteBuffer buffer = ByteBuffer.allocate(expectedResults.length * 8); + for (Long expected : expectedResults) + { + if (expected != null) + { + buffer.putLong(expected); + } + } + buffer.rewind(); + BBDecoder decoder = new BBDecoder(); + + decoder.init(buffer); + int index = 0; + for (QpidProperty property : properties) + { + assertEquals(expectedResults[index++],property.decodeValue(decoder, presenceBytes)); + } + } + + private QpidProperty createProperty(boolean isOptional, int optionalIndex) + { + QpidProperty property = new QpidProperty(); + property.setType(new Uint64()); + if (isOptional) + { + property.markAsOptional(optionalIndex); + } + return property; + } +}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidClassTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidClassTest.java new file mode 100644 index 0000000000..9d6e176912 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidClassTest.java @@ -0,0 +1,408 @@ +/* +* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.management.MBeanAttributeInfo; +import javax.management.MBeanInfo; + +import junit.framework.TestCase; + +import org.apache.qpid.management.TestConstants; +import org.apache.qpid.management.configuration.ConfigurationException; +import org.apache.qpid.management.configuration.Configurator; +import org.apache.qpid.management.domain.handler.impl.MethodOrEventDataTransferObject; +import org.apache.qpid.management.domain.model.QpidClass.QManManagedObject; + +/** + * Test case for Qpid Class. + * + * @author Andrea Gazzarini + */ +public class QpidClassTest extends TestCase +{ + private QpidClass _class; + private QpidPackage _package; + + @Override + protected void setUp () throws ConfigurationException + { + Configurator configurator = new Configurator(); + configurator.configure(); + _package = new QpidPackage(TestConstants.QPID_PACKAGE_NAME,TestConstants.DOMAIN_MODEL); + _class = new QpidClass(TestConstants.EXCHANGE_CLASS_NAME,TestConstants.HASH,_package); + } + + /** + * Tests the execution of the getObjectInstance() method. + * Basically it tests the addition of a new object instance. + * + * <br>precondition: class has no object instances. + * <br>precondition : class contains the added object instance. + */ + public void testGetObjectInstance() + { + assertFalse ( + "Nobody set instance #"+TestConstants.OBJECT_ID+" into this class so why is it there?", + _class._objectInstances.containsKey(TestConstants.OBJECT_ID)); + + QManManagedObject instance = _class.getObjectInstance(TestConstants.OBJECT_ID, false); + + assertTrue ( + "Now the instance #"+TestConstants.OBJECT_ID+" should be there...", + _class._objectInstances.containsKey(TestConstants.OBJECT_ID)); + + assertEquals(instance,_class.getObjectInstance(TestConstants.OBJECT_ID, false)); + } + + /** + * Tests the injection of instrumentation and configuration data (related to a specific object instance) before the + * schema is installed. + * + * <br>precondition : the schema hasn't yet installed on this class. + * <br>postcondition : incoming configuration & instrumentation data is stored into the corresponding object instance. + */ + public void testAddInstrumentationAndConfigurationDataBeforeSchemaInstallation() + { + _class._state = _class._schemaRequestedButNotYetInjected; + QManManagedObject objectInstance = _class.getObjectInstance(TestConstants.OBJECT_ID,false); + + assertTrue( + "This object instance is a new one so how is it possible that it has already instrumentation data? ", + objectInstance._rawInstrumentationData.isEmpty()); + assertTrue( + "This object instance is a new one so how is it possible that it has already configuration data? ", + objectInstance._rawConfigurationData.isEmpty()); + + byte [] dummyConfigurationData = {1,2,3,4,5,6,7,8}; + byte [] dummyInstrumentationData = {11,21,31,41,51,61,71,81}; + + _class.addConfigurationData(TestConstants.OBJECT_ID, dummyConfigurationData); + _class.addInstrumentationData(TestConstants.OBJECT_ID, dummyInstrumentationData); + + assertEquals("Now configuration data should be there...",1,objectInstance._rawConfigurationData.size()); + assertEquals("Now instrumentation data should be there...",1,objectInstance._rawInstrumentationData.size()); + + assertTrue( + "Object instance configuration data should be the previously set...", + Arrays.equals(objectInstance._rawConfigurationData.get(0), + dummyConfigurationData)); + + assertTrue( + "Object instance instrumentation data should be the previously set...", + Arrays.equals(objectInstance._rawInstrumentationData.get(0), + dummyInstrumentationData)); + } + + /** + * Tests the internal state change of a class definition. + */ + public void testStateChange() throws UnableToBuildFeatureException + { + _class = new QpidClass(TestConstants.EXCHANGE_CLASS_NAME,TestConstants.HASH,_package) + { + @Override + void requestSchema() throws Exception { + _state = _schemaRequestedButNotYetInjected; + } + + @Override + void setSchema(List<Map<String, Object>> propertyDefinitions, + List<Map<String, Object>> statisticDefinitions, + List<MethodOrEventDataTransferObject> methodDefinitions) throws UnableToBuildFeatureException { + _state = _schemaInjected; + } + }; + + assertSame( + "Initial state doesn't match.", + _class._schemaNotRequested, + _class._state); + + _class.addConfigurationData(TestConstants.OBJECT_ID, TestConstants.TEST_RAW_DATA); + _class.addInstrumentationData(TestConstants.OBJECT_ID, TestConstants.TEST_RAW_DATA); + + assertSame( + "Request schema has been requested but not yet injected. The current state is not indicating that!", + _class._schemaRequestedButNotYetInjected, + _class._state); + + _class.setSchema( + TestConstants.EMPTY_PROPERTIES_SCHEMA, + TestConstants.EMPTY_STATISTICS_SCHEMA, + new LinkedList<MethodOrEventDataTransferObject>()); + + assertSame( + "Request schema has been injected. The current state is not indicating that!", + _class._schemaInjected, + _class._state); + } + + /** + * Tests the injection of a valid schema on a QpidClass. + * + * <br>precondition : a valid arguments is injected on the qpid class. + * <br>postcondition : class definition is built successfully. + */ + public void testSchemaInjectionOk() throws UnableToBuildFeatureException + { + _class = new QpidClass(TestConstants.EXCHANGE_CLASS_NAME,TestConstants.HASH,_package) + { + @Override + void requestSchema() throws Exception + { + // DO NOTHING : QMan is not running and therefore the schema will be manually injected. + } + + @Override + void updateInstanceWithConfigurationData(QManManagedObject instance, byte[] rawData) + { + // DO NOTHING Given raw data is not valid so it cannot be converted. + } + }; + + // Incoming configuration data : that will fire the schema request and a state change + // from schema-not-requested to schema-requested-but-not-injected + _class.addConfigurationData(TestConstants.OBJECT_ID, TestConstants.TEST_RAW_DATA); + + // I must be sure that what is obvious for me it's obvious for QMan... :) + assertSame( + "Request schema has been requested but not yet injected. The current state is not indicating that!", + _class._schemaRequestedButNotYetInjected, + _class._state); + + List<Map<String,Object>> propertyDefinitions = new ArrayList<Map<String,Object>>(2); + propertyDefinitions.add( + createProperty( + TestConstants.AGE_ATTRIBUTE_NAME, + 1, + TestConstants.YEARS, + TestConstants.SAMPLE_MIN_VALUE, + TestConstants.SAMPLE_MAX_VALUE, + null, + TestConstants.AGE_ATTRIBUTE_DESCRIPTION, + TestConstants._1, + false, + TestConstants._0)); + + propertyDefinitions.add( + createProperty( + TestConstants.SURNAME_ATTRIBUTE_NAME, + TestConstants.SAMPLE_ACCESS_CODE, + null, + null, + null, + TestConstants.SAMPLE_MAX_VALUE, + TestConstants.SURNAME_ATTRIBUTE_DESCRIPTION, + TestConstants._1, + true, + TestConstants._1)); + + _class.setSchema(propertyDefinitions, TestConstants.EMPTY_STATISTICS_SCHEMA, TestConstants.EMPTY_METHODS_SCHEMA); + + assertEquals(2,_class._properties.size()); + + QpidProperty property = _class._properties.get(TestConstants.AGE_ATTRIBUTE_NAME); + assertEquals(TestConstants.AGE_ATTRIBUTE_NAME,property.getName()); + assertEquals(AccessMode.RC,property.getAccessMode()); + assertEquals(TestConstants.YEARS,property.getUnit()); + assertEquals(TestConstants.SAMPLE_MIN_VALUE,property.getMinValue()); + assertEquals(TestConstants.SAMPLE_MAX_VALUE,property.getMaxValue()); + assertEquals(Integer.MIN_VALUE,property.getMaxLength()); + assertEquals(TestConstants.AGE_ATTRIBUTE_DESCRIPTION,property.getDescription()); + assertEquals(Short.class,property.getJavaType()); + assertFalse(property.isOptional()); + + property = _class._properties.get(TestConstants.SURNAME_ATTRIBUTE_NAME); + assertEquals(TestConstants.SURNAME_ATTRIBUTE_NAME,property.getName()); + assertEquals(AccessMode.RC,property.getAccessMode()); + assertNull(property.getUnit()); + assertEquals(Integer.MIN_VALUE,property.getMinValue()); + assertEquals(Integer.MIN_VALUE,property.getMaxValue()); + assertEquals(TestConstants.SAMPLE_MAX_VALUE,property.getMaxLength()); + assertEquals(TestConstants.SURNAME_ATTRIBUTE_DESCRIPTION,property.getDescription()); + assertEquals(Short.class,property.getJavaType()); + assertTrue(property.isOptional()); + + MBeanInfo mbeanInfo = _class._metadata; + assertEquals(TestConstants.EXCHANGE_CLASS_NAME,mbeanInfo.getClassName()); + + MBeanAttributeInfo [] attributes = mbeanInfo.getAttributes(); + assertEquals(2,attributes.length); + + MBeanAttributeInfo attribute = attributes[0]; + assertEquals(TestConstants.AGE_ATTRIBUTE_NAME,attribute.getName()); + assertEquals(TestConstants.AGE_ATTRIBUTE_DESCRIPTION,attribute.getDescription()); + assertFalse(attribute.isWritable()); + assertTrue(attribute.isReadable()); + assertEquals(Short.class.getName(),attribute.getType()); + + attribute = attributes[1]; + assertEquals(TestConstants.SURNAME_ATTRIBUTE_NAME,attribute.getName()); + assertEquals(TestConstants.SURNAME_ATTRIBUTE_DESCRIPTION,attribute.getDescription()); + assertFalse(attribute.isWritable()); + assertTrue(attribute.isReadable()); + assertEquals(Short.class.getName(),attribute.getType()); + } + + /** + * Tests the behaviour of the class when a schema request can't be made. + * + * <br>precondition : class must be in "schema-not-requested" state when incoming data arrives. + * <br>postcondition : no exception is thrown and no state transition happens. + */ + public void testStateChange_withRequestSchemaFailure() + { + _class= new QpidClass(TestConstants.EXCHANGE_CLASS_NAME,TestConstants.HASH,_package) + { + @Override + void requestSchema() throws Exception { + throw new Exception(); + } + + @Override + void setSchema( + List<Map<String, Object>> propertyDefinitions, + List<Map<String, Object>> statisticDefinitions, + List<MethodOrEventDataTransferObject> methodDefinitions) throws UnableToBuildFeatureException + { + } + }; + + assertSame( + "Initial state must be schema-not-requested.", + _class._schemaNotRequested, + _class._state); + + _class.addInstrumentationData(TestConstants.OBJECT_ID, TestConstants.TEST_RAW_DATA); + + assertSame( + "Current state must be still schema-not-requested.", + _class._schemaNotRequested, + _class._state); + } + + /** + * Tests the behaviour of the class when a schema injection fails. + * + * <br>precondition : class must be in "schema-not-requested" state when incoming data arrives. + * <br>postcondition : an exception is thrown and no state transition happens. + */ + public void testStateChange_withSchemaInjectionFailure() + { + _class = new QpidClass(TestConstants.EXCHANGE_CLASS_NAME,TestConstants.HASH,_package) + { + @Override + void requestSchema() throws Exception + { + // DO NOTHING. + } + + @Override + void setSchema(List<Map<String, Object>> propertyDefinitions, + List<Map<String, Object>> statisticDefinitions, + List<MethodOrEventDataTransferObject> methodDefinitions) + throws UnableToBuildFeatureException + { + throw new UnableToBuildFeatureException(""); + } + }; + + assertSame( + "Initial state must be schema-not-requested.", + _class._schemaNotRequested, + _class._state); + + _class.addInstrumentationData(TestConstants.OBJECT_ID, TestConstants.TEST_RAW_DATA); + + assertSame( + "Request schema has been requested but not yet injected. The current state is not indicating that!", + _class._schemaRequestedButNotYetInjected, + _class._state); + + try { + _class.setSchema( + TestConstants.EMPTY_PROPERTIES_SCHEMA, + TestConstants.EMPTY_STATISTICS_SCHEMA, + TestConstants.EMPTY_METHODS_SCHEMA); + fail("If we are here something was wrong becuase the setSchema() of this event is throwing an exception..."); + } catch (UnableToBuildFeatureException expected) { + assertSame( + "Request schema has been requested but not yet injected. The current state is not indicating that!", + _class._schemaRequestedButNotYetInjected, + _class._state); + } + } + + private Map<String,Object> createProperty( + String name, + Integer accessCode, + String unit, + Integer min, + Integer max, + Integer maxLength, + String description, + Integer type, + boolean optional, + Integer index) + { + Map <String,Object> result = new HashMap<String, Object>(); + result.put(QpidFeatureBuilder.Attribute.name.name(),name); + result.put(QpidFeatureBuilder.Attribute.access.name(), accessCode); + + if (unit != null) + { + result.put(QpidFeatureBuilder.Attribute.unit.name(),unit); + } + + if (min != null) + { + result.put(QpidFeatureBuilder.Attribute.min.name(), min); + } + + if (max != null) + { + result.put(QpidFeatureBuilder.Attribute.max.name(),max); + } + + if (maxLength != null) + { + result.put(QpidFeatureBuilder.Attribute.maxlen.name(),maxLength); + } + + result.put(QpidFeatureBuilder.Attribute.desc.name(), description); + result.put(QpidFeatureBuilder.Attribute.type.name(), type); + result.put(QpidFeatureBuilder.Attribute.optional.name(),optional ? 1 : 0); + + if (index != null) + { + result.put(QpidFeatureBuilder.Attribute.index.name(), index); + } + return result; + } +} diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidEventTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidEventTest.java new file mode 100644 index 0000000000..4b36d9e5cc --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidEventTest.java @@ -0,0 +1,293 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.domain.model;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanException;
+import javax.management.ObjectName;
+import javax.management.ReflectionException;
+
+import junit.framework.TestCase;
+
+import org.apache.qpid.management.TestConstants;
+import org.apache.qpid.management.configuration.ConfigurationException;
+import org.apache.qpid.management.configuration.Configurator;
+import org.apache.qpid.management.domain.model.QpidEvent.QManManagedEvent;
+
+/**
+ * Test case for qpid class entity.
+ *
+ * @author Andrea Gazzarini
+ */
+public class QpidEventTest extends TestCase
+{
+ private QpidEvent _event;
+ private QpidPackage _qpidPackage;
+
+ @Override
+ protected void setUp () throws Exception
+ {
+ _qpidPackage = new QpidPackage(TestConstants.QPID_PACKAGE_NAME,TestConstants.DOMAIN_MODEL);
+ _event = new QpidEvent(TestConstants.BIND_EVENT_NAME,TestConstants.HASH,_qpidPackage);
+ }
+
+ /**
+ * Tests the execution of the createEventInstance() method.
+ * Basically it tests the addition of a new event instance.
+ *
+ * <br>precondition: event deifinition has no object instances.
+ * <br>precondition : event definition contains the new object instance.
+ */
+ public void testCreateEventInstance()
+ {
+ assertTrue(
+ "A just created event should be empty. I mean there shouldn't be event instances inside.",
+ _event.hasNoInstances());
+
+ QManManagedEvent instance = createEventInstance();
+
+ assertFalse (
+ "Now a new instance should be there...",
+ _event.hasNoInstances());
+
+ assertEquals(TestConstants.TEST_RAW_DATA,instance._rawEventData);
+ assertEquals(TestConstants.NOW,instance._timestamp);
+ assertEquals(TestConstants.SEVERITY, instance._severity);
+ }
+
+ /**
+ * Tests the internal state change of an event definition.
+ */
+ public void testStateChange() throws UnableToBuildFeatureException
+ {
+ // Let's override this class because this is not an online tests and therefore
+ // QMan is not supposed to be up.
+ _event = new QpidEvent(TestConstants.BIND_EVENT_NAME,TestConstants.HASH,_qpidPackage)
+ {
+ @Override
+ void requestSchema() throws Exception {
+ // Do Nothing.
+ }
+
+ @Override
+ void setSchema(List<Map<String, Object>> argumentDefinitions)throws UnableToBuildFeatureException {
+ _state = _schemaInjected;
+ }
+ };
+
+ assertSame(
+ "Initial state doesn't match.",
+ _event._schemaNotRequested,
+ _event._state);
+
+ _event.addEventData(TestConstants.TEST_RAW_DATA, TestConstants.NOW, TestConstants.SEVERITY);
+
+ assertSame(
+ "Request schema has been requested but not yet injected. The current state is not indicating that!",
+ _event._schemaRequestedButNotYetInjected,
+ _event._state);
+
+ _event.setSchema(TestConstants.EMPTY_ARGUMENTS_SCHEMA);
+
+ assertSame(
+ "Request schema has been injected. The current state is not indicating that!",
+ _event._schemaInjected,
+ _event._state);
+ }
+
+ /**
+ * Tests the injection of a valid schema on a QpidEvent.
+ *
+ * <br>precondition : a valid arguments is injected on the qpid event.
+ * <br>postcondition : event definition is built successfully.
+ */
+ public void testSchemaInjectionOK() throws UnableToBuildFeatureException, ConfigurationException, InstanceNotFoundException, MBeanException, ReflectionException
+ {
+ _event = new QpidEvent(TestConstants.BIND_EVENT_NAME,TestConstants.HASH,_qpidPackage)
+ {
+ @Override
+ void requestSchema() throws Exception
+ {
+ // DO NOTHING : QMan is not running and therefore the schema will be manually injected.
+ }
+
+ @Override
+ void updateEventInstanceWithData(QManManagedEvent instance)
+ {
+ // DO NOTHING : otherwise we should supply a valid raw data to be converted. ;-)
+ }
+ };
+
+ Configurator configurator = new Configurator();
+ configurator.configure();
+
+ List<Map<String,Object>> arguments = new ArrayList<Map<String, Object>>();
+ arguments.add(createArgument(TestConstants.AGE_ATTRIBUTE_NAME, TestConstants.AGE_ATTRIBUTE_DESCRIPTION));
+ arguments.add(createArgument(TestConstants.SURNAME_ATTRIBUTE_NAME, TestConstants.SURNAME_ATTRIBUTE_DESCRIPTION));
+
+ // Incoming data : that will fire the schema request and a state change from schema-not-requested to schema-requested-but-not-injected
+ _event.addEventData(TestConstants.TEST_RAW_DATA, TestConstants.NOW, TestConstants.SEVERITY);
+
+ // I must be sure that what is obvious for me it's obvious for QMan... :)
+ assertSame(
+ "Request schema has been requested but not yet injected. The current state is not indicating that!",
+ _event._schemaRequestedButNotYetInjected,
+ _event._state);
+
+ // Inject schema
+ _event.setSchema(arguments);
+
+ // Arguments must be 2 + 2 (severity)
+ assertEquals(2,_event._arguments.size());
+
+ QpidProperty argument = _event._arguments.get(TestConstants.AGE_ATTRIBUTE_NAME);
+ assertEquals(TestConstants.AGE_ATTRIBUTE_NAME,argument.getName());
+ assertEquals(AccessMode.RO,argument.getAccessMode());
+ assertEquals(TestConstants.AGE_ATTRIBUTE_DESCRIPTION,argument.getDescription());
+ assertEquals(Short.class,argument.getJavaType());
+ assertFalse(argument.isOptional());
+
+ argument = _event._arguments.get(TestConstants.SURNAME_ATTRIBUTE_NAME);
+ assertEquals(TestConstants.SURNAME_ATTRIBUTE_NAME,argument.getName());
+ assertEquals(AccessMode.RO,argument.getAccessMode());
+ assertEquals(TestConstants.SURNAME_ATTRIBUTE_DESCRIPTION,argument.getDescription());
+ assertEquals(Short.class,argument.getJavaType());
+ assertFalse(argument.isOptional());
+
+ assertEquals(1,_event._eventInstances.size());
+
+ JmxService service = new JmxService();
+ Set<ObjectName> objectNames = service.getEventMBeans();
+
+ assertEquals(1,objectNames.size());
+ }
+
+ /**
+ * Tests the behaviour of the event class when a schema request can't be made.
+ *
+ * <br>precondition : event must be in "schema-not-requested" state when incoming data arrives.
+ * <br>postcondition : no exception is thrown and no state transition happens.
+ */
+ public void testStateChange_withRequestSchemaFailure()
+ {
+ _event = new QpidEvent(TestConstants.BIND_EVENT_NAME,TestConstants.HASH,_qpidPackage)
+ {
+ @Override
+ void requestSchema() throws Exception {
+ throw new Exception();
+ }
+
+ @Override
+ void setSchema(List<Map<String, Object>> argumentDefinitions)throws UnableToBuildFeatureException {
+ _state = _schemaInjected;
+ }
+ };
+
+ assertSame(
+ "Initial state must be schema-not-requested.",
+ _event._schemaNotRequested,
+ _event._state);
+
+ _event.addEventData(TestConstants.TEST_RAW_DATA, TestConstants.NOW, TestConstants.SEVERITY);
+
+ assertSame(
+ "Current state must be still schema-not-requested.",
+ _event._schemaNotRequested,
+ _event._state);
+ }
+
+ /**
+ * Tests the behaviour of the event class when a schema injection fails.
+ *
+ * <br>precondition : event must be in "schema-not-requested" state when incoming data arrives.
+ * <br>postcondition : an exception is thrown and no state transition happens.
+ */
+ public void testStateChange_withSchemaInjectionFailure()
+ {
+ _event = new QpidEvent(TestConstants.BIND_EVENT_NAME,TestConstants.HASH,_qpidPackage)
+ {
+ @Override
+ void requestSchema() throws Exception {
+ // DO NOTHING.
+ }
+
+ @Override
+ void setSchema(List<Map<String, Object>> argumentDefinitions)throws UnableToBuildFeatureException {
+ throw new UnableToBuildFeatureException("");
+ }
+ };
+
+ assertSame(
+ "Initial state must be schema-not-requested.",
+ _event._schemaNotRequested,
+ _event._state);
+
+ _event.addEventData(TestConstants.TEST_RAW_DATA, TestConstants.NOW, TestConstants.SEVERITY);
+
+ assertSame(
+ "Request schema has been requested but not yet injected. The current state is not indicating that!",
+ _event._schemaRequestedButNotYetInjected,
+ _event._state);
+
+ try {
+ _event.setSchema(TestConstants.EMPTY_ARGUMENTS_SCHEMA);
+ fail("If we are here something was wrong becuase the setSchema() of this event is throwing an exception...");
+ } catch (UnableToBuildFeatureException expected) {
+ assertSame(
+ "Request schema has been requested but not yet injected. The current state is not indicating that!",
+ _event._schemaRequestedButNotYetInjected,
+ _event._state);
+ }
+ }
+
+ /**
+ * Factory method for qpid managed event instances.
+ *
+ * @return a new QpidManagedEvent with test data inside.
+ */
+ private QManManagedEvent createEventInstance()
+ {
+ return _event.createEventInstance(
+ TestConstants.TEST_RAW_DATA,
+ TestConstants.NOW,
+ TestConstants.SEVERITY);
+ }
+
+ /**
+ * Factory method for event argument.
+ *
+ * @return a new argument metadata.
+ */
+ private Map<String,Object> createArgument(String name,String desc)
+ {
+ Map <String,Object> argument = new HashMap<String, Object>();
+ argument.put(QpidFeatureBuilder.Attribute.name.name(),name);
+ argument.put(QpidFeatureBuilder.Attribute.desc.name(), desc);
+ argument.put(QpidFeatureBuilder.Attribute.type.name(), TestConstants._1);
+ return argument;
+ }
+}
diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidMethodBuilderTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidMethodBuilderTest.java new file mode 100644 index 0000000000..06dc35b0b1 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidMethodBuilderTest.java @@ -0,0 +1,147 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model; + +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.dir; +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.name; +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.type; +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.unit; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.management.MBeanOperationInfo; + +import org.apache.qpid.management.Names; +import org.apache.qpid.management.domain.handler.impl.MethodOrEventDataTransferObject; +import org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute; + +/** + * Test case for Qpid Statistic builder. + * + * @author Andrea Gazzarini + */ +public class QpidMethodBuilderTest extends BaseQpidFeatureBuilderTestCase +{ + private final static Integer ARG_COUNT = 3; + private MethodOrEventDataTransferObject _methodDefinition; + + private List<Map<String,Object>> _argumentsDefinitons = new ArrayList<Map<String, Object>>(); + + @Override + protected void setUp () throws Exception + { + super.setUp(); + _featureDefinition.put(Names.ARG_COUNT_PARAM_NAME, ARG_COUNT); + + Map<String,Object> arg1 = new HashMap<String,Object>(); + arg1.put(name.name(), "arg1"); + arg1.put(type.name(),1); + arg1.put(dir.name(),Direction.I.name()); + arg1.put(unit.name(), "bytes"); + + Map<String,Object> arg2 = new HashMap<String,Object>(); + arg2.put(name.name(), "arg2"); + arg2.put(type.name(),1); + arg2.put(dir.name(),Direction.O.name()); + arg2.put(unit.name(), "bytes"); + + Map<String,Object> arg3 = new HashMap<String,Object>(); + arg3.put(name.name(), "arg3"); + arg3.put(type.name(),1); + arg3.put(dir.name(),Direction.IO.name()); + arg3.put(unit.name(), "bytes"); + + /* + dir yes no yes Direction code for method arguments + unit yes yes yes Units for numeric values (i.e. seconds, bytes, etc.) + min yes no yes Minimum value for numerics + max yes no yes Maximum value for numerics + maxlen yes no yes Maximum length for strings + desc yes yes yes Description of the argument + default yes no yes Default value for the argument + */ + _argumentsDefinitons.add(arg1); + _argumentsDefinitons.add(arg2); + + _methodDefinition = new MethodOrEventDataTransferObject(_featureDefinition,_argumentsDefinitons); + _builder = QpidFeatureBuilder.createMethodBuilder(_methodDefinition); + } + + /** + * Tests the build process for a statistic when the definition map doesn't contains type attribute. + * + * <br>precondition: definition map doesn't contains type attribute. + * <br>postcondition : an exception should be thrown indicating the failure. That exception must contain the name of the + * missing attribute. + */ + public void testMethodBuilderKO_WithMissingName() + { + internalTestForMissingMandatoryAttribute(Attribute.name); + } + + /** + * Tests the build process for a statistic when the definition map doesn't contain type, name, index & optional attributes. + * + * <br>precondition: definition map doesn't contain type, name, index & optional attributes. + * <br>postcondition : an exception should be thrown indicating the failure. That exception must contain the name of the + * missing attributes. + */ + public void testMethodBuilderOK_WithMissingUnit() throws UnableToBuildFeatureException + { + internalTestForMissingOptionalAttribute(Attribute.unit); + } + + /** + * Tests the build process for a statistic when the definition map doesn't unit attribute. + * Note that this attribute is optional and therefore the build must succeed. + * + * <br>precondition: definition map doesn't contain unit attribute. + * <br>postcondition : no exception is thrown and the statistic is built. + */ + public void testMethodBuilderOK_WithMissingDescription() throws UnableToBuildFeatureException + { + internalTestForMissingOptionalAttribute(Attribute.desc); + } + + /** + * Tests the build process for a statistic when the definition map contains valid values. + * + * <br>precondition : the statistic definiton map contains valid values. + * <br>postcondition : no exception is thrown and the statistisc is built as expected. + */ + public void testMethodBuilderOK() throws UnableToBuildFeatureException + { + _builder.build(); + + QpidMethod method = (QpidMethod) _builder.getQpidFeature(); + MBeanOperationInfo info = (MBeanOperationInfo) _builder.getManagementFeature(); + + assertEquals(NAME,method.getName()); + + assertEquals(DESCRIPTION,method.getDescription()); + + assertEquals(method.getDescription(),info.getDescription()); + assertEquals(method.getName(),info.getName()); + } +} diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidNumberPropertyTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidNumberPropertyTest.java new file mode 100644 index 0000000000..374011d150 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidNumberPropertyTest.java @@ -0,0 +1,171 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model; + +import junit.framework.TestCase; + +import org.apache.qpid.management.configuration.Configurator; +import org.apache.qpid.management.domain.model.type.Uint8; + +public class QpidNumberPropertyTest extends TestCase +{ + private QpidProperty _property; + private Long _value = 55432L; + + @Override + protected void setUp () throws Exception + { + Configurator configurator = new Configurator(); + configurator.configure(); + _property = new QpidProperty(); + _property.setName("average"); + _property.setAccessMode(AccessMode.RW); + _property.setType(new Uint8()); + } + + /** + * Tests the validation of a qpid property when the type is a number and no constraint has been set. + * + * <br>precondition : property type is a string, no constraint has been set. + * <br>postcondition : no exception is thrown and the validation succeeds. + */ + public void testValidationWithoutConstraints() { + try + { + _property.validate(_value); + } catch (ValidationException notExpected) + { + fail("If no constraint has been set on this property why the validation is failing?"); + } + } + + /** + * Tests the validation of a qpid property when the type is a number and a max value constraint has been set. + * + * <br>precondition : property type is a number, max value has been set and property value is greater than max value. + * <br>postcondition : an exception is thrown indicating the validation failure. + */ + public void testValidationKO_withMaxValue() { + int maxValue = (int)(_value-1); + _property.setMaxValue(maxValue); + + try + { + _property.validate(_value); + fail("The given value is violating the installed constraint so an exception must be thrown."); + } catch (ValidationException expected) + { + assertEquals(ValidationException.MAX_VALUE,expected.getConstraintName()); + assertEquals(maxValue,expected.getConstraintValue()); + assertEquals((double)_value,expected.getFeatureValue()); + assertEquals(_property.getName(),expected.getFeatureName()); + } + } + + /** + * Tests the validation of a qpid property when the type is a number and a min value constraint has been set. + * + * <br>precondition : property type is a number, min value has been set and property value is lesser than min value. + * <br>postcondition : an exception is thrown indicating the validation failure. + */ + public void testValidationKO_withMinValue() { + int minValue = (int)(_value+1); + _property.setMinValue(minValue); + + try + { + _property.validate(_value); + fail("The given value is violating the installed constraint so an exception must be thrown."); + } catch (ValidationException expected) + { + assertEquals(ValidationException.MIN_VALUE,expected.getConstraintName()); + assertEquals(minValue,expected.getConstraintValue()); + assertEquals((double)_value,expected.getFeatureValue()); + assertEquals(_property.getName(),expected.getFeatureName()); + } + } + + + /** + * Tests the validation of a qpid property when the number is a string and the property value is null. + * + * <br>precondition : property type is a number and property value is null.. + * <br>postcondition : no exception is thrown. That is : the validation succeeds. + */ + public void testValidationOK_withNullValue() { + try + { + _property.validate(null); + } catch (ValidationException notExpected) + { + fail("No constraint has been violated so validate() shouldn't raise an exception."); + } + + _property.setMinValue(1); + _property.setMaxValue(10); + + try + { + _property.validate(null); + } catch (ValidationException notExpected) + { + fail("No constraint has been violated so validate() shouldn't raise an exception."); + } + } + + /** + * Tests the validation of a qpid property when the type is a number and a max / min constraints have been set. + * + * <br>precondition : property type is a number, max / min constraint have been set and property value is wrong. + * <br>postcondition : an exception is thrown indicating the validation failure. + */ + public void testValidationOK_withMinAndMaxConstraint() { + int minValue = (int)(_value+1); + int maxValue = (int)(_value-1); + _property.setMinValue(minValue); + _property.setMaxValue(maxValue); + + try + { + _property.validate(_value); + fail("The given value is violating the installed constraint so an exception must be thrown."); + } catch (ValidationException expected) + { + assertEquals(ValidationException.MIN_VALUE,expected.getConstraintName()); + assertEquals(minValue,expected.getConstraintValue()); + assertEquals((double)_value,expected.getFeatureValue()); + assertEquals(_property.getName(),expected.getFeatureName()); + } + + _property.setMinValue(0); + try + { + _property.validate(_value); + fail("The given value is violating the installed constraint so an exception must be thrown."); + } catch (ValidationException expected) + { + assertEquals(ValidationException.MAX_VALUE,expected.getConstraintName()); + assertEquals(maxValue,expected.getConstraintValue()); + assertEquals((double)_value,expected.getFeatureValue()); + assertEquals(_property.getName(),expected.getFeatureName()); + } + } +} diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidPackageTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidPackageTest.java new file mode 100644 index 0000000000..b7eb9055ba --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidPackageTest.java @@ -0,0 +1,53 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model; + +import org.apache.qpid.management.TestConstants; + +/** + * Test case for Qpid package entity. + * + * @author Andrea Gazzarini + */ +public class QpidPackageTest extends BaseDomainModelTestCase +{ + private QpidPackage _qpidPackage; + + @Override + protected void setUp () throws Exception + { + _qpidPackage = new QpidPackage(TestConstants.QPID_PACKAGE_NAME, TestConstants.DOMAIN_MODEL); + } + + /** + * Tests the association of a new class with a qpid package. + * + * <br>precondition : the package is not associated with any class. + * <br>postcondition : the package is now associated with the given class. + */ + public void testAddClass() throws UnableToBuildFeatureException { + assertFalse(_qpidPackage.alreadyContainsClassDefinition(TestConstants.EXCHANGE_CLASS_NAME, TestConstants.HASH)); + + _qpidPackage.getQpidClass(TestConstants.EXCHANGE_CLASS_NAME, TestConstants.HASH, true); + + assertTrue(_qpidPackage.alreadyContainsClassDefinition(TestConstants.EXCHANGE_CLASS_NAME, TestConstants.HASH)); + } +}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidPropertyBuilderTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidPropertyBuilderTest.java new file mode 100644 index 0000000000..8ad177645c --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidPropertyBuilderTest.java @@ -0,0 +1,269 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model; + +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.access; +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.index; +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.max; +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.min; +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.optional; +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.type; +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.unit; + +import javax.management.MBeanAttributeInfo; + +import org.apache.qpid.management.configuration.UnknownTypeCodeException; +import org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute; + +/** + * Test case for Qpid Property builder. + * + * @author Andrea Gazzarini + */ +public class QpidPropertyBuilderTest extends BaseQpidFeatureBuilderTestCase +{ + private final static Integer MIN = 0; + private final static Integer MAX = 120; + private final static String UNIT = "bytes"; + + private Integer _access; + + @Override + protected void setUp () throws Exception + { + super.setUp(); + + _access = 1; + _featureDefinition.put(access.name(), _access); + _featureDefinition.put(unit.name(),UNIT); + _featureDefinition.put(min.name(), MIN); + _featureDefinition.put(max.name(),MAX); + + _featureDefinition.put(type.name(), 1); + _featureDefinition.put(optional.name(),0); + _featureDefinition.put(index.name(), 0); + + _builder = QpidFeatureBuilder.createPropertyBuilder(_featureDefinition); + } + + /** + * Tests the build process for a statistic when the definition map contains an unknown type code. + * + * <br>precondition : the statistic definiton map contains an unknown type code. + * <br>postcondition : an exception is thrown indicating the failure. + */ + public void testStatisticBuilderKO_WithUnknownType() + { + int unknownTypeCode =999; + try + { + _featureDefinition.put(type.name(), unknownTypeCode); + _builder.build(); + fail("An unknown type code should raise an exception to indicate a failure."); + } catch (UnableToBuildFeatureException expected) + { + assertEquals(unknownTypeCode,((UnknownTypeCodeException)expected.getCause()).getCode()); + } + } + + /** + * Tests the build process for a statistic when the definition map contains a null value for a metadata attribute. + * + * <br>precondition : the statistic definiton map contains a null value for a metadata attribute. + * <br>postcondition : an exception is thrown indicating the failure. + */ + public void testMethodBuilderKO_WithNullMetadataValue() + { + try + { + _featureDefinition.put(type.name(), null); + _builder.build(); + fail("An null value for a metadata attribute should raise an exception to indicate a failure."); + } catch (UnableToBuildFeatureException expected) + { + assertTrue(expected.getCause() instanceof NullPointerException); + } + } + + /** + * Tests the build process for a property when the definition map contains an invalid metadata type. + * + * <br>precondition : the property definiton map contains a wrong type for a metadata attribute. + * <br>postcondition : an exception is thrown indicating the failure. + */ + public void testPropertyBuilderKO_WithClassCastException() + { + try + { + _featureDefinition.put(access.name(), new String("a")); + _builder.build(); + fail("A wrong metadata attribute type should raise an exception to indicate a failure."); + } catch (UnableToBuildFeatureException expected) + { + assertTrue(expected.getCause() instanceof ClassCastException); + } + } + + /** + * Tests the build process for a property when the definition map contains an unknown type code. + * + * <br>precondition : the property definiton map contains an unknown type code. + * <br>postcondition : an exception is thrown indicating the failure. + */ + public void testPropertyBuilderKO_WithUnknownType() + { + int unknownTypeCode = 999; + try + { + _featureDefinition.put(type.name(), unknownTypeCode); + _builder.build(); + fail("An unknown type code should raise an exception to indicate a failure."); + } catch (UnableToBuildFeatureException expected) + { + assertEquals(unknownTypeCode,((UnknownTypeCodeException)expected.getCause()).getCode()); + } + } + + /** + * Tests the build process for a property when the definition map doesn't contains type attribute. + * + * <br>precondition: definition map doesn't contains type attribute. + * <br>postcondition : an exception should be thrown indicating the failure. That exception must contain the name of the + * missing attribute. + */ + public void testPropertyBuilderKO_WithMissingType() + { + internalTestForMissingMandatoryAttribute(Attribute.type); + } + + /** + * Tests the build process for a property when the definition map doesn't contain type & name attributes. + * + * <br>precondition: definition map doesn't contain type & name attributes. + * <br>postcondition : an exception should be thrown indicating the failure. That exception must contain the name of the + * missing attributes. + */ + public void testPropertyBuilderKO_WithMissingTypeAndName() + { + internalTestForMissingMandatoryAttribute(Attribute.type, Attribute.name); + } + + /** + * Tests the build process for a property when the definition map doesn't contain type & name & index attributes. + * + * <br>precondition: definition map doesn't contain type & name & index attributes. + * <br>postcondition : an exception should be thrown indicating the failure. That exception must contain the name of the + * missing attributes. + */ + public void testPropertyBuilderKO_WithMissingTypeAndNameAndIndex() + { + internalTestForMissingMandatoryAttribute(Attribute.type, Attribute.name,Attribute.index); + } + + /** + * Tests the build process for a property when the definition map doesn't contain type, name, index & optional attributes. + * + * <br>precondition: definition map doesn't contain type, name, index & optional attributes. + * <br>postcondition : an exception should be thrown indicating the failure. That exception must contain the name of the + * missing attributes. + */ + public void testPropertyBuilderKO_WithMissingTypeAndNameAndIndexAndOptional() + { + internalTestForMissingMandatoryAttribute(Attribute.type, Attribute.name,Attribute.index,Attribute.optional); + } + + /** + * Tests the build process for a property when the definition map doesn't contain type, name, index, optional and access + * attributes. + * + * <br>precondition: definition map doesn't contain type, name, index, optional and access attributes. + * <br>postcondition : an exception should be thrown indicating the failure. That exception must contain the name of the + * missing attributes. + */ + public void testPropertyBuilderKO_WithMissingTypeAndNameAndIndexAndOptionalAndAccess() + { + internalTestForMissingMandatoryAttribute(Attribute.type, Attribute.name,Attribute.index,Attribute.optional,Attribute.access); + } + + /** + * Tests the build process for a property when the definition map doesn't unit attribute. + * Note that this attribute is optional and therefore the build must succeed. + * + * <br>precondition: definition map doesn't contain unit attribute. + * <br>postcondition : no exception is thrown and the property is built. + */ + public void testBuilderOK_WithMissingUnit() throws UnableToBuildFeatureException + { + internalTestForMissingOptionalAttribute(Attribute.unit); + } + + /** + * Tests the build process for a property when the definition map doesn't min and max attributes. + * Note that those attributes are optional and therefore the build must succeed. + * + * <br>precondition: definition map doesn't contain min and max attributes. + * <br>postcondition : no exception is thrown and the property is built. + */ + public void testBuilderOK_WithMissingMinAndMax() throws UnableToBuildFeatureException + { + internalTestForMissingOptionalAttribute(Attribute.min,Attribute.max); + } + + /** + * Tests the build process for a property when the definition map doesn't description attribute. + * Note that this attribute is optional and therefore the build must succeed. + * + * <br>precondition: definition map doesn't contain description attribute. + * <br>postcondition : no exception is thrown and the property is built. + */ + public void testBuilderOK_WithMissingDescription() throws UnableToBuildFeatureException + { + internalTestForMissingOptionalAttribute(Attribute.desc); + } + + /** + * Tests the build process for a property when the definition map contains valid values. + * + * <br>precondition : the property definiton map contains valid values. + * <br>postcondition : no exception is thrown and the property is built as expected. + */ + public void testPropertyBuilderOK() throws UnableToBuildFeatureException + { + _builder.build(); + + QpidProperty property = (QpidProperty) _builder.getQpidFeature(); + MBeanAttributeInfo info = (MBeanAttributeInfo) _builder.getManagementFeature(); + + assertEquals(NAME,property.getName()); + assertEquals(AccessMode.RC,property.getAccessMode()); + assertEquals(UNIT,property.getUnit()); + assertEquals(MIN.intValue(),property.getMinValue()); + assertEquals(MAX.intValue(),property.getMaxValue()); + assertEquals(Integer.MIN_VALUE,property.getMaxLength()); + assertEquals(DESCRIPTION,property.getDescription()); + assertEquals(Short.class,property.getJavaType()); + assertFalse(property.isOptional()); + + assertEquals(property.getDescription(),info.getDescription()); + assertEquals(property.getName(),info.getName()); + assertEquals(property.getJavaType().getName(),info.getType()); + } +} diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidStatisticBuilderTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidStatisticBuilderTest.java new file mode 100644 index 0000000000..b7a8540b2d --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidStatisticBuilderTest.java @@ -0,0 +1,159 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model; + +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.type; +import static org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute.unit; + +import javax.management.MBeanAttributeInfo; + +import org.apache.qpid.management.configuration.UnknownTypeCodeException; +import org.apache.qpid.management.domain.model.QpidFeatureBuilder.Attribute; + +/** + * Test case for Qpid Statistic builder. + * + * @author Andrea Gazzarini + */ +public class QpidStatisticBuilderTest extends BaseQpidFeatureBuilderTestCase +{ + private final static String UNIT = "bytes"; + + @Override + protected void setUp () throws Exception + { + super.setUp(); + _featureDefinition.put(unit.name(),UNIT); + _featureDefinition.put(type.name(), 1); + + _builder = QpidFeatureBuilder.createStatisticBuilder(_featureDefinition); + } + + /** + * Tests the build process for a statistic when the definition map contains an unknown type code. + * + * <br>precondition : the statistic definiton map contains an unknown type code. + * <br>postcondition : an exception is thrown indicating the failure. + */ + public void testStatisticBuilderKO_WithUnknownType() + { + int unknownTypeCode = 999; + try + { + _featureDefinition.put(type.name(), unknownTypeCode); + _builder.build(); + fail("An unknown type code should raise an exception to indicate a failure."); + } catch (UnableToBuildFeatureException expected) + { + assertEquals(unknownTypeCode,((UnknownTypeCodeException)expected.getCause()).getCode()); + } + } + + /** + * Tests the build process for a statistic when the definition map contains a null value for a metadata attribute. + * + * <br>precondition : the statistic definiton map contains a null value for a metadata attribute. + * <br>postcondition : an exception is thrown indicating the failure. + */ + public void testMethodBuilderKO_WithNullMetadataValue() + { + try + { + _featureDefinition.put(type.name(), null); + _builder.build(); + fail("An null value for a metadata attribute should raise an exception to indicate a failure."); + } catch (UnableToBuildFeatureException expected) + { + assertTrue(expected.getCause() instanceof NullPointerException); + } + } + + /** + * Tests the build process for a statistic when the definition map doesn't contains type attribute. + * + * <br>precondition: definition map doesn't contains type attribute. + * <br>postcondition : an exception should be thrown indicating the failure. That exception must contain the name of the + * missing attribute. + */ + public void testStatisticBuilderKO_WithMissingType() + { + internalTestForMissingMandatoryAttribute(Attribute.type); + } + + /** + * Tests the build process for a statistic when the definition map doesn't contain type & name attributes. + * + * <br>precondition: definition map doesn't contain type & name attributes. + * <br>postcondition : an exception should be thrown indicating the failure. That exception must contain the name of the + * missing attributes. + */ + public void testStatisticBuilderKO_WithMissingTypeAndName() + { + internalTestForMissingMandatoryAttribute(Attribute.type, Attribute.name); + } + + /** + * Tests the build process for a statistic when the definition map doesn't contain type, name, index & optional attributes. + * + * <br>precondition: definition map doesn't contain type, name, index & optional attributes. + * <br>postcondition : an exception should be thrown indicating the failure. That exception must contain the name of the + * missing attributes. + */ + public void testStatisticBuilderOK_WithMissingUnit() throws UnableToBuildFeatureException + { + internalTestForMissingOptionalAttribute(Attribute.unit); + } + + /** + * Tests the build process for a statistic when the definition map doesn't unit attribute. + * Note that this attribute is optional and therefore the build must succeed. + * + * <br>precondition: definition map doesn't contain unit attribute. + * <br>postcondition : no exception is thrown and the statistic is built. + */ + public void testBuilderOK_WithMissingDescription() throws UnableToBuildFeatureException + { + internalTestForMissingOptionalAttribute(Attribute.desc); + } + + /** + * Tests the build process for a statistic when the definition map contains valid values. + * + * <br>precondition : the statistic definiton map contains valid values. + * <br>postcondition : no exception is thrown and the statistisc is built as expected. + */ + public void testStatisticBuilderOK() throws UnableToBuildFeatureException + { + _builder.build(); + + QpidStatistic statistic= (QpidStatistic) _builder.getQpidFeature(); + MBeanAttributeInfo info = (MBeanAttributeInfo) _builder.getManagementFeature(); + + assertEquals(NAME,statistic.getName()); + assertEquals(UNIT,statistic.getUnit()); + assertEquals(DESCRIPTION,statistic.getDescription()); + assertEquals(Short.class,statistic.getJavaType()); + + assertEquals(statistic.getDescription(),info.getDescription()); + assertEquals(statistic.getName(),info.getName()); + assertEquals(statistic.getJavaType().getName(),info.getType()); + } +} diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidStringPropertyTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidStringPropertyTest.java new file mode 100644 index 0000000000..8aeb7c8550 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/QpidStringPropertyTest.java @@ -0,0 +1,127 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model; + +import junit.framework.TestCase; + +import org.apache.qpid.management.configuration.Configurator; +import org.apache.qpid.management.domain.model.type.Str16; + +public class QpidStringPropertyTest extends TestCase +{ + private QpidProperty _property; + private final String _5LettersString = "12345"; + + @Override + protected void setUp () throws Exception + { + Configurator configurator = new Configurator(); + configurator.configure(); + _property = new QpidProperty(); + _property.setName("name"); + _property.setAccessMode(AccessMode.RW); + _property.setType(new Str16()); + } + + /** + * Tests the validation of a qpid property when the type is a string and a max length constraint hasn't been set. + * + * <br>precondition : property type is a string, max length hasn't been set. + * <br>postcondition : no exception is thrown. That is : the validation succeeds. + */ + public void testValidationWithoutMaxLength() { + try + { + _property.validate(_5LettersString); + } catch (ValidationException notExpected) + { + fail("No max length has been set on property so validation must succeed."); + } + } + + /** + * Tests the validation of a qpid property when the type is a string and a max length constraint has been set. + * + * <br>precondition : property type is a string, max length has been set and property value is longer than max length. + * <br>postcondition : an exception is thrown indicating the validation failure. + */ + public void testValidationKO_withMaxLength() { + int maxLength = 2; + _property.setMaxLength(maxLength); + + try + { + _property.validate(_5LettersString); + fail("No max length has been set on property so validation must proceed."); + } catch (ValidationException expected) + { + assertEquals(ValidationException.MAX_LENGTH,expected.getConstraintName()); + assertEquals(maxLength,expected.getConstraintValue()); + assertEquals(_5LettersString.length(),expected.getFeatureValue()); + assertEquals(_property.getName(),expected.getFeatureName()); + } + } + + /** + * Tests the validation of a qpid property when the type is a string and the property value is null. + * + * <br>precondition : property type is a string and property value is null.. + * <br>postcondition : no exception is thrown. That is : the validation succeeds. + */ + public void testValidationOK_withNullValue() { + try + { + _property.validate(null); + } catch (ValidationException notExpected) + { + fail("No constraint has been violated so validate() shouldn't raise an exception."); + } + + _property.setMaxLength(1); + + try + { + _property.validate(null); + } catch (ValidationException notExpected) + { + fail("No constraint has been violated so validate() shouldn't raise an exception."); + } + } + + /** + * Tests the validation of a qpid property when the type is a string and a max length constraint has been set. + * + * <br>precondition : property type is a string, max length has been set and property value is not violating that. + * <br>postcondition : no exception is thrown. That is : the validation succeeds. + */ + public void testValidationOK_withMaxLength() { + int maxLength = (_5LettersString.length()+1); + _property.setMaxLength(maxLength); + + try + { + _property.validate(_5LettersString); + } catch (ValidationException notExpected) + { + fail("No constraint has been violated so validate() shouldn't raise an exception."); + } + } +} diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/model/type/BinaryTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/type/BinaryTest.java new file mode 100644 index 0000000000..6636c08710 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/model/type/BinaryTest.java @@ -0,0 +1,59 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.model.type; + +import junit.framework.TestCase; + +/** + * Test case for "Binary" type. + * + * @author Andrea Gazzarini + */ +public class BinaryTest extends TestCase +{ + /** + * Tests the lazy & once hash code computation behaviour of the binary type. + */ + public void testHashCodeComputation(){ + Binary binary = new Binary(new byte[]{1,2,3,4,5,6,7,6,3,3}); + assertSame(binary.state,binary.hashCodeNotYetComputed); + + int firstResult = binary.hashCode(); + assertSame(binary.state,binary.hashCodeAlreadyComputed); + + int secondResult = binary.hashCode(); + assertSame(binary.state,binary.hashCodeAlreadyComputed); + assertEquals(firstResult,secondResult); + } + + /** + * Tests the equals() method of the binary class. + * Two binary must be equals only if they contain the same array (that is, two arrays with the same size & content) + */ + public void testIdentity() { + Binary binary = new Binary(new byte[]{1,2,3,4,5,6,7,6,3,3}); + Binary theSame= new Binary(new byte[]{1,2,3,4,5,6,7,6,3,3}); + Binary aDifferentOne = new Binary(new byte[]{4,2,3,3,4,4,5,3,3,2}); + + assertTrue(binary.equals(theSame)); + assertFalse(binary.equals(aDifferentOne)); + } +}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/services/BrokerMessageListenerTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/services/BrokerMessageListenerTest.java new file mode 100644 index 0000000000..805c039a6f --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/services/BrokerMessageListenerTest.java @@ -0,0 +1,241 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.qpid.management.domain.services; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import junit.framework.TestCase; + +import org.apache.qpid.api.Message; +import org.apache.qpid.management.TestConstants; +import org.apache.qpid.management.domain.handler.base.IMessageHandler; +import org.apache.qpid.management.domain.model.DomainModel; +import org.apache.qpid.nclient.util.ByteBufferMessage; +import org.apache.qpid.transport.codec.Decoder; + +/** + * Test case for Broker Message Listener. + * + * @author Andrea Gazzarini + */ +public class BrokerMessageListenerTest extends TestCase +{ + // An empty message handler user for test. + private IMessageHandler _emptyMessageHandler = new IMessageHandler() + { + public void process (Decoder decoder, int sequenceNumber) + { + } + public void setDomainModel (DomainModel domainModel) + { + } + }; + + // Another empty message handler user for test. + private IMessageHandler _anotherEmptyMessageHandler = new IMessageHandler() + { + public void process (Decoder decoder, int sequenceNumber) + { + } + public void setDomainModel (DomainModel domainModel) + { + } + }; + + private Map<Character,IMessageHandler> _handlers = new HashMap<Character, IMessageHandler>(); + private BrokerMessageListener _listener; + private final char opcode1 = 'x'; + private final char opcode2 = 'y'; + + + @Override + protected void setUp () throws Exception + { + DomainModel domainModel = new DomainModel(TestConstants.BROKER_ID); + _listener = new BrokerMessageListener(domainModel); + + _handlers.put(opcode1, _emptyMessageHandler); + _handlers.put(opcode2, _anotherEmptyMessageHandler); + } + + /** + * Tests the installation of message handlers on a broker message listener. + * + * <br>precondition : no message handler has been installed on message listener. + * <br>postcondition : two message handlers are installed on message listener. + */ + public void testSetHandlersOK() + { + assertTrue( + "No handler has yet been installed so how is it possible that the handlers map is not empty?", + _listener._handlers.isEmpty()); + + _listener.setHandlers(_handlers); + + assertEquals("Now we should have two handlers configured.",2,_listener._handlers.size()); + assertSame(_listener._handlers.get(opcode1),_emptyMessageHandler); + assertSame(_listener._handlers.get(opcode2),_anotherEmptyMessageHandler); + } + + /** + * Tests the installation of message handlers on a broker message listener. + * Specifically it tries to install three message handlers and one of them is throwing an exception at installation time. + * + * <br>precondition : no message handler has been installed on message listener. + * <br>postcondition : two message handlers are installed on message listener. (the one that thrown exception has been + * discarded). + */ + public void testSetHandlerOK() + { + IMessageHandler wrongMessageHandler = new IMessageHandler() + { + + public void process (Decoder decoder, int sequenceNumber) + { + } + + public void setDomainModel (DomainModel domainModel) + { + throw new RuntimeException(); + } + }; + + char opcodeForWrongHandler = 'k'; + + assertTrue( + "No handler has yet been installed so how is it possible that the handlers map is not empty?", + _listener._handlers.isEmpty()); + + _handlers.put(opcodeForWrongHandler,wrongMessageHandler); + + _listener.setHandlers(_handlers); + + assertEquals("Now we should have two handlers configured.",2,_listener._handlers.size()); + assertSame(_listener._handlers.get(opcode1),_emptyMessageHandler); + assertSame(_listener._handlers.get(opcode2),_anotherEmptyMessageHandler); + assertNull(_listener._handlers.get(opcodeForWrongHandler)); + } + + /** + * Tests the execution of the onMessage() method when a message with a bad magic number is received. + * + * <br>precondition : a message with a bad magic number is received. + * <br>postcondition : the processing of the incoming message is skipped and therefore no handler will be called. + */ + public void testOnMessageKO_withBadMagicNumber() throws IOException + { + IMessageHandler neverCallMe = new IMessageHandler() + { + + public void process (Decoder decoder, int sequenceNumber) + { + fail("This test shouldn't never arrive at this point..."); + } + + public void setDomainModel (DomainModel domainModel) + { + } + }; + + String opcodeForNeverCallMeHandler = "w"; + + _handlers.put('w',neverCallMe); + _listener.setHandlers(_handlers); + + Message message = new ByteBufferMessage(); + message.appendData( ("AMG"+opcodeForNeverCallMeHandler).getBytes()); + + _listener.onMessage(message); + } + + /** + * Tests the execution of the onMessage() method when the incoming message is a compound message. + * + * <br>precondition : the incoming message is a compound message. + * <br>postcondition : each tokenized message is forwarded to the appropriate handler. + */ + public void testOnMessageOK_WithCompoundMessage() throws Exception + { + final Map<Character,IMessageHandler> handlersMap = new HashMap<Character,IMessageHandler>(); + char [] opcodes = {'a','b','c','d','e'}; + + class MockMessageHandler implements IMessageHandler + { + private final char _opcode; + + public MockMessageHandler(char opcode) + { + this._opcode = opcode; + } + + public void process (Decoder decoder, int sequenceNumber) + { + handlersMap.remove(_opcode); + } + + public void setDomainModel (DomainModel domainModel) + { + // Do nothing here. It's just a mock handler. + } + }; + + for (char opcode : opcodes) + { + handlersMap.put(opcode, new MockMessageHandler(opcode)); + } + + // Removes previously injected handlers (i.e. x & y) + _listener._handlers.clear(); + _listener.setHandlers(handlersMap); + + Message compoundMessage = createCompoundMessage(opcodes); + _listener.onMessage(compoundMessage); + + assertTrue(handlersMap.isEmpty()); + } + + // Creates a (non valid) compound message. + private Message createCompoundMessage(char[] opcodes) throws IOException { + byte [] compoundMessageData = new byte [12 * opcodes.length]; + Random randomizer = new Random(); + int position = 0; + + for (char opcode : opcodes) { + System.arraycopy(MessageTokenizer.MAGIC_NUMBER_BYTES, 0, compoundMessageData, position, MessageTokenizer.MAGIC_NUMBER_BYTES.length); + position+=MessageTokenizer.MAGIC_NUMBER_BYTES.length; + + compoundMessageData[position++] = (byte)opcode; + + for (int c = 4; c < 12; c++) + { + byte aByte = (byte)randomizer.nextInt(127); + compoundMessageData[position++] = aByte; + } + } + + Message compoundMessage = new ByteBufferMessage(); + compoundMessage.appendData(compoundMessageData); + return compoundMessage; + } +} diff --git a/java/management/client/src/test/java/org/apache/qpid/management/domain/services/MessageTokenizerTest.java b/java/management/client/src/test/java/org/apache/qpid/management/domain/services/MessageTokenizerTest.java new file mode 100644 index 0000000000..55b8b17f9d --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/domain/services/MessageTokenizerTest.java @@ -0,0 +1,140 @@ +/*
+*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.domain.services;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.*;
+
+import junit.framework.TestCase;
+
+import org.apache.qpid.api.Message;
+import org.apache.qpid.nclient.util.ByteBufferMessage;
+import org.apache.qpid.transport.codec.BBDecoder;
+
+/**
+ * Tests case for messaeg tokenizer.
+ *
+ * @author Andrea Gazzarini
+ */
+public class MessageTokenizerTest extends TestCase {
+
+ /**
+ * Tests the execution of the message tokenizer when the given message is not a valid AMQP message.
+ *
+ * <br>precondition : the incoming message is not a valid AMQP message.
+ * <br>postcondition : no exception is thrown and there will be exactly one token with the given message.
+ */
+ public void testOK_WithNoMessage() throws IOException{
+ byte [] noMessage = {2,10,120,23,23,23,4,10,11,12,2,1,3,-22};
+
+ Message multiMessage = new ByteBufferMessage();
+ multiMessage.appendData(noMessage);
+ MessageTokenizer tokenizer = new MessageTokenizer(multiMessage);
+
+ assertEquals(1, tokenizer.countTokens());
+ assertEquals(tokenizer.nextElement(),noMessage);
+ assertFalse(tokenizer.hasMoreElements());
+ }
+
+ /**
+ * Tests the execution of the message tokenizer when the given message contains only one message.
+ *
+ * <br>precondition : the incoming message contains only one message.
+ * <br>postcondition : no exception is thrown and there will be exactly one token with the given message.
+ */
+ public void testOK_WithOneMessage() throws IOException{
+ byte [] oneEncodedMessage = {'A','M','2',23,23,23,4,10,11,12,2,1,3,-22};
+
+ Message multiMessage = new ByteBufferMessage();
+ multiMessage.appendData(oneEncodedMessage);
+ MessageTokenizer tokenizer = new MessageTokenizer(multiMessage);
+
+ assertEquals(1, tokenizer.countTokens());
+ assertEquals(tokenizer.nextElement(),oneEncodedMessage);
+ assertFalse(tokenizer.hasMoreElements());
+ }
+
+ /**
+ * Tests the execution of the message tokenizer when the given message contains a random number of messages.
+ *
+ * <br>precondition : the incoming message contains a random number of messages.
+ * <br>postcondition : no exception is thrown and each built token is a valid message starting with right header.
+ */
+ public void testOK_WithRandomNUmberOfMessages() throws IOException{
+ Random randomizer = new Random();
+
+ int howManyLoops = randomizer.nextInt(10000);
+ howManyLoops = (howManyLoops == 0) ? 10 : howManyLoops;
+ byte [] compoundMessageData = new byte [12 * howManyLoops];
+
+ List<byte []> messages = new ArrayList<byte[]>(howManyLoops);
+
+ int position = 0;
+ for (int i = 0; i < howManyLoops; i++)
+ {
+ byte [] message = new byte[12];
+ System.arraycopy(MessageTokenizer.MAGIC_NUMBER_BYTES, 0, compoundMessageData, position, MessageTokenizer.MAGIC_NUMBER_BYTES.length);
+ System.arraycopy(MessageTokenizer.MAGIC_NUMBER_BYTES, 0, message, 0, MessageTokenizer.MAGIC_NUMBER_BYTES.length);
+ position+=MessageTokenizer.MAGIC_NUMBER_BYTES.length;
+
+ for (int c = 3; c < 12; c++)
+ {
+ byte aByte = (byte)randomizer.nextInt(127);
+ aByte = (aByte == 77) ? (byte)c : aByte;
+ compoundMessageData[position++] = aByte;
+ message[c] = aByte;
+ }
+ messages.add(message);
+ }
+
+ Message multiMessage = new ByteBufferMessage();
+ multiMessage.appendData(compoundMessageData);
+ MessageTokenizer tokenizer = new MessageTokenizer(multiMessage);
+
+ int howManyTokens = tokenizer.countTokens();
+ assertEquals(howManyLoops, howManyTokens);
+
+ int index = 0;
+ while (tokenizer.hasMoreElements())
+ {
+ assertEquals(tokenizer.nextElement(),messages.get(index++));
+ }
+
+ assertEquals((index),howManyTokens);
+ }
+
+ /**
+ * Internal method used for comparison of two messages.
+ *
+ * @param message the token message just built by the tokenizer.
+ * @param expected the expected result.
+ */
+ private void assertEquals(Message message, byte [] expected) throws IOException
+ {
+ ByteBuffer messageContent = message.readData();
+ BBDecoder decoder = new BBDecoder();
+ decoder.init(messageContent);
+ byte [] content = decoder.readReaminingBytes();
+ assertTrue(Arrays.equals(content, expected));
+ }
+}
diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/BaseWsDmAdapterTestCase.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/BaseWsDmAdapterTestCase.java new file mode 100644 index 0000000000..900d14c72e --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/BaseWsDmAdapterTestCase.java @@ -0,0 +1,143 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm;
+
+import java.lang.management.ManagementFactory;
+import java.net.URI;
+import java.util.UUID;
+
+import javax.management.MBeanInfo;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+
+import junit.framework.TestCase;
+
+import org.apache.muse.ws.addressing.EndpointReference;
+import org.apache.muse.ws.resource.remote.WsResourceClient;
+import org.apache.muse.ws.resource.sg.remote.ServiceGroupClient;
+import org.apache.qpid.management.Names;
+import org.apache.qpid.management.Protocol;
+import org.apache.qpid.management.TestConstants;
+
+/**
+ * Test case for WS-Resource lifecycle management.
+ *
+ * @author Andrea Gazzarini
+ */
+public abstract class BaseWsDmAdapterTestCase extends TestCase implements TestConstants{
+
+ protected MBeanServer _managementServer;
+ protected ObjectName _resourceObjectName;
+
+ protected WsResourceClient _resourceClient;
+ protected MBeanInfo _mbeanInfo;
+
+ /**
+ * Set up fixture for this test case.
+ *
+ * @throws Exception when the test case intialization fails.
+ */
+ protected void setUp() throws Exception
+ {
+ _managementServer = ManagementFactory.getPlatformMBeanServer();
+
+ ServiceGroupClient serviceGroup = getServiceGroupClient();
+ WsResourceClient [] members = serviceGroup.getMembers();
+
+ assertEquals(
+ "No resource has been yet created so how is " +
+ "it possible that service group children list is not empty?",
+ 0,
+ members.length);
+
+ _managementServer.invoke(
+ Names.QPID_EMULATOR_OBJECT_NAME,
+ "createQueue",
+ new Object[]{_resourceObjectName = createResourceName()},
+ new String[]{ObjectName.class.getName()});
+
+ members = serviceGroup.getMembers();
+ assertEquals(
+ "One resource has just been created so " +
+ "I expect to find it on service group children list...",
+ 1,
+ members.length);
+
+ _resourceClient = members[0];
+ _mbeanInfo = _managementServer.getMBeanInfo(_resourceObjectName);
+ }
+
+ /**
+ * Shutdown procedure for this test case.
+ *
+ * @throws Exception when either the server or some resource fails to shutdown.
+ */
+ @Override
+ protected void tearDown() throws Exception
+ {
+ ServiceGroupClient serviceGroup = getServiceGroupClient();
+ WsResourceClient [] members = serviceGroup.getMembers();
+
+ _managementServer.invoke(
+ Names.QPID_EMULATOR_OBJECT_NAME,
+ "unregister",
+ new Object[]{_resourceObjectName},
+ new String[]{ObjectName.class.getName()});
+
+ members = serviceGroup.getMembers();
+
+ assertEquals(
+ "No resource has been yet created so how is it possible that service group children list is not empty?",
+ 0,
+ members.length);
+ }
+
+ /**
+ * Creates a service group client reference.
+ *
+ * @return a service group client reference.
+ */
+ private ServiceGroupClient getServiceGroupClient()
+ {
+ URI address = URI.create(
+ Protocol.DEFAULT_ENDPOINT_URI.replaceFirst("8080",System.getProperty(Names.ADAPTER_PORT_PROPERTY_NAME)));
+ return new ServiceGroupClient(new EndpointReference(address));
+ }
+
+ /**
+ * In order to test the behaviour of the WS-DM adapter, at
+ * least one resource must be created. This is the method that
+ * returns the name (ObjectName on JMX side, Resource-ID on WSDM side)
+ * of that resource
+ *
+ * @return the name of the MBean instance that will be created.
+ * @throws Exception when the name if malformed. Practically never.
+ */
+ private ObjectName createResourceName() throws Exception
+ {
+ return new ObjectName(
+ "Q-MAN:objectId="+UUID.randomUUID()+
+ ", brokerID="+UUID.randomUUID()+
+ ",class=queue"+
+ ",package=org.apache.qpid"+
+ ",name="+System.currentTimeMillis());
+ }
+}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/EnhancedReflectionProxyHandler.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/EnhancedReflectionProxyHandler.java new file mode 100644 index 0000000000..615d744546 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/EnhancedReflectionProxyHandler.java @@ -0,0 +1,72 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm;
+
+import javax.xml.namespace.QName;
+
+import org.apache.muse.core.proxy.ReflectionProxyHandler;
+import org.apache.muse.util.xml.XmlUtils;
+import org.apache.muse.ws.addressing.soap.SoapFault;
+import org.apache.qpid.management.wsdm.muse.serializer.ByteArraySerializer;
+import org.w3c.dom.Element;
+
+/**
+ * Custom implementation of Muse ReflectionProxyHandler
+ * that uses a base64 serializer for byte arrays.
+ * Note that this proxy handler is only needed for tests because it provides
+ * client side Base64 serializer capability.
+ * In a concrete scenario we don't mind what instrument the client is using in order to
+ * propertly serialize byte arrays.
+ *
+ * @author Andrea Gazzarini
+ */
+public class EnhancedReflectionProxyHandler extends ReflectionProxyHandler
+{
+ @Override
+ protected Element serialize(Object obj, QName qname) throws SoapFault
+ {
+ if (obj == null)
+ {
+ return XmlUtils.createElement(qname);
+ }
+
+ if (obj.getClass() == byte[].class)
+ {
+ return new ByteArraySerializer().toXML(obj, qname);
+ } else
+ {
+ return super.serialize(obj, qname);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ protected Object deserialize(Element xml, Class theClass) throws SoapFault
+ {
+ if (theClass == byte[].class)
+ {
+ return new ByteArraySerializer().fromXML(xml);
+ } else
+ {
+ return super.deserialize(xml, theClass);
+ }
+ }
+}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetMultipleResourcePropertiesTestCase.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetMultipleResourcePropertiesTestCase.java new file mode 100644 index 0000000000..d59e7a39e5 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetMultipleResourcePropertiesTestCase.java @@ -0,0 +1,125 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm;
+
+import java.util.Date;
+import java.util.UUID;
+
+import javax.management.MBeanAttributeInfo;
+import javax.xml.namespace.QName;
+
+import org.apache.muse.ws.addressing.soap.SoapFault;
+import org.apache.muse.ws.resource.WsrfConstants;
+import org.apache.qpid.management.Names;
+import org.w3c.dom.Element;
+
+/**
+ * Test case for Web Service Resource Properties interfaces.
+ * Those interfaces are defined on http://docs.oasis-open.org/wsrf/wsrf-ws_resource_properties-1.2-spec-os.pdf
+ * (Web Services Resource Properties 1.2 - (WS-ResourceProperties).
+ * For a better explanation see chapter 5 of the specification above.
+ *
+ * @author Andrea Gazzarini
+ */
+public class GetMultipleResourcePropertiesTestCase extends BaseWsDmAdapterTestCase
+{
+ /**
+ * Tests the GetMultipleResourceProperties interface when the request contains
+ * an unknwon target resource.
+ *
+ * <br>precondition : the GetMultipleResourceProperties request contains an unknwon resource.
+ * <br>postcondition : a SoapFault is thrown and the corresponding detail contains an
+ * UnknownResourceFault element.
+ */
+ public void testGetMultipleResourcePropertiesKO_WithUnknownResourceFault() throws Exception
+ {
+ try
+ {
+ _resourceClient.getEndpointReference().removeParameter(Names.RESOURCE_ID_QNAME);
+ _resourceClient.getEndpointReference().addParameter(Names.RESOURCE_ID_QNAME,"lablabalbal");
+
+ _resourceClient.getMultipleResourceProperties(new QName[]{});
+ } catch(SoapFault expected)
+ {
+ assertEquals(
+ WsrfConstants.RESOURCE_UNKNOWN_QNAME.getLocalPart(),
+ expected.getDetail().getLocalName());
+ }
+ }
+
+ /**
+ * Test the WS-RP GetResourceProperties interface of the WS-DM adapter.
+ *
+ * <br>precondition : a ws resource exists and is registered.
+ * <br>postcondition : Properties are correctly returned according to WSRP interface and they (their value)
+ * are matching with corresponding MBean properties.
+ */
+ public void testGetMultipleResourcePropertiesOK() throws Exception
+ {
+ MBeanAttributeInfo [] attributesMetadata = _mbeanInfo.getAttributes();
+ QName[] names = new QName[attributesMetadata.length];
+
+ int index = 0;
+ for (MBeanAttributeInfo attributeMetadata : _mbeanInfo.getAttributes())
+ {
+ QName qname = new QName(Names.NAMESPACE_URI,attributeMetadata.getName(),Names.PREFIX);
+ names[index++] = qname;
+ }
+
+ Element[] properties =_resourceClient.getMultipleResourceProperties(names);
+ for (Element element : properties)
+ {
+ String name = element.getLocalName();
+ Object value = _managementServer.getAttribute(_resourceObjectName, name);
+ if ("Name".equals(name))
+ {
+ assertEquals(
+ value,
+ element.getTextContent());
+ } else if ("Durable".equals(name))
+ {
+ assertEquals(
+ value,
+ Boolean.valueOf(element.getTextContent()));
+ } else if ("ExpireTime".equals(name))
+ {
+ assertEquals(
+ value,
+ new Date(Long.valueOf(element.getTextContent())));
+ } else if ("MsgTotalEnqueues".equals(name))
+ {
+ assertEquals(
+ value,
+ Long.valueOf(element.getTextContent()));
+ } else if ("ConsumerCount".equals(name))
+ {
+ assertEquals(
+ value,
+ Integer.valueOf(element.getTextContent()));
+ }else if ("VhostRef".equals(name))
+ {
+ assertEquals(
+ value,
+ UUID.fromString(element.getTextContent()));
+ }
+ }
+ }
+}
diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetResourcePropertiesTestCase.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetResourcePropertiesTestCase.java new file mode 100644 index 0000000000..e18e928cf4 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetResourcePropertiesTestCase.java @@ -0,0 +1,105 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm;
+
+import java.lang.reflect.Array;
+
+import javax.management.MBeanAttributeInfo;
+import javax.xml.namespace.QName;
+
+import org.apache.muse.ws.addressing.soap.SoapFault;
+import org.apache.muse.ws.resource.WsrfConstants;
+import org.apache.qpid.management.Names;
+
+/**
+ * Test case for Web Service Resource Properties interfaces.
+ * Those interfaces are defined on http://docs.oasis-open.org/wsrf/wsrf-ws_resource_properties-1.2-spec-os.pdf
+ * (Web Services Resource Properties 1.2 - (WS-ResourceProperties).
+ * For a better explanation see chapter 5 of the specification above.
+ *
+ * @author Andrea Gazzarini
+ */
+public class GetResourcePropertiesTestCase extends BaseWsDmAdapterTestCase
+{
+
+ /**
+ * Test the WS-RP GetResourceProperty interface of the WS-DM adapter.
+ *
+ * <br>precondition : a ws resource exists and is registered.
+ * <br>postcondition : property values coming from WS-DM resource are the same of the JMX interface.
+ */
+ public void testGetResourcePropertiesOK() throws Exception
+ {
+ MBeanAttributeInfo [] attributesMetadata = _mbeanInfo.getAttributes();
+ for (MBeanAttributeInfo attributeMetadata : attributesMetadata)
+ {
+ String name = attributeMetadata.getName();
+ Object propertyValues = _resourceClient.getPropertyAsObject(
+ new QName(
+ Names.NAMESPACE_URI,
+ name,
+ Names.PREFIX),
+ Class.forName(attributeMetadata.getType()));
+
+ int length = Array.getLength(propertyValues);
+ if (length != 0)
+ {
+ Object propertyValue = Array.get(propertyValues, 0);
+
+ assertEquals(
+ "Comparison failed for property "+name,
+ _managementServer.getAttribute(_resourceObjectName,name),
+ propertyValue);
+ } else {
+ assertNull(
+ String.format(
+ "\"%s\" property value shouldn't be null. Its value is %s",
+ name,
+ _managementServer.getAttribute(_resourceObjectName,name)),
+ _managementServer.getAttribute(_resourceObjectName,name));
+ }
+ }
+ }
+
+ /**
+ * Tests the GetMultipleResourceProperties interface when the request contains
+ * an unknwon target resource.
+ *
+ * <br>precondition : the GetMultipleResourceProperties request contains an unknwon resource.
+ * <br>postcondition : a SoapFault is thrown and the corresponding detail contains an
+ * UnknownResourceFault element.
+ */
+ public void testGetResourcePropertiesKO_WithUnknownResourceFault() throws Exception
+ {
+ try
+ {
+ _resourceClient.getEndpointReference().removeParameter(Names.RESOURCE_ID_QNAME);
+ _resourceClient.getEndpointReference().addParameter(Names.RESOURCE_ID_QNAME,"lablabalbal");
+
+ _resourceClient.getResourceProperty(new QName("a","b","c"));
+ } catch(SoapFault expected)
+ {
+ assertEquals(
+ WsrfConstants.RESOURCE_UNKNOWN_QNAME.getLocalPart(),
+ expected.getDetail().getLocalName());
+ }
+ }
+}
diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetResourcePropertyDocumentTestCase.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetResourcePropertyDocumentTestCase.java new file mode 100644 index 0000000000..862115f841 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetResourcePropertyDocumentTestCase.java @@ -0,0 +1,134 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm;
+
+import javax.xml.namespace.QName;
+
+import org.apache.muse.util.xml.XmlUtils;
+import org.apache.muse.ws.addressing.soap.SoapFault;
+import org.apache.muse.ws.resource.WsrfConstants;
+import org.apache.qpid.management.Names;
+import org.w3c.dom.Element;
+
+/**
+ * Test case for Web Service Resource Properties interfaces.
+ * Those interfaces are defined on http://docs.oasis-open.org/wsrf/wsrf-ws_resource_properties-1.2-spec-os.pdf
+ * (Web Services Resource Properties 1.2 - (WS-ResourceProperties).
+ * For a better explanation see chapter 5 of the specification above.
+ *
+ * @author Andrea Gazzarini
+ */
+public class GetResourcePropertyDocumentTestCase extends BaseWsDmAdapterTestCase
+{
+ /**
+ * Tests the GetResourcePropertyDocument interface when the request contains
+ * an unknwon target resource.
+ *
+ * <br>precondition : the GetResourcePropertyDocument contains an unknwon resource.
+ * <br>postcondition : a SoapFault is thrown and the corresponding detail contains an
+ * UnknownResourceFault element.
+ */
+ public void testGetResourcePropertyDocumentKO_WithUnknownResourceFault() throws Exception
+ {
+ try
+ {
+ _resourceClient.getEndpointReference().removeParameter(Names.RESOURCE_ID_QNAME);
+ _resourceClient.getEndpointReference().addParameter(Names.RESOURCE_ID_QNAME,"lablabalbal");
+ _resourceClient.setTrace(true);
+
+ _resourceClient.getResourcePropertyDocument();
+ } catch(SoapFault expected)
+ {
+ assertEquals(
+ WsrfConstants.RESOURCE_UNKNOWN_QNAME.getLocalPart(),
+ expected.getDetail().getLocalName());
+ }
+ }
+
+ /**
+ * Tests the WS-RP PutResourcePropertyDocument interface of the WS-DM adapter.
+ *
+ * <br>precondition : a ws resource exists and is registered.
+ * <br>postcondition : A read / write property is correctly set according to WSRP interface.
+ */
+ public void testGetAndPutResourcePropertyDocumentOK() throws Exception
+ {
+ String expectedMgmtPubIntervalValue = "4321";
+ String propertyName = "MgmtPubInterval";
+
+ Element propertiesDocument = _resourceClient.getResourcePropertyDocument();
+ Element [] properties = XmlUtils.getAllElements(propertiesDocument);
+
+ for (Element element : properties)
+ {
+ if (propertyName.equals(element.getLocalName())) {
+ element.setTextContent(expectedMgmtPubIntervalValue);
+ } else {
+ propertiesDocument.removeChild(element);
+ }
+ }
+
+ _resourceClient.putResourcePropertyDocument(propertiesDocument);
+
+ Element newProperties = _resourceClient.getResourcePropertyDocument();
+
+ Element mgmtPubInterval = XmlUtils.getElement(
+ newProperties, new QName(
+ Names.NAMESPACE_URI,
+ propertyName,
+ Names.PREFIX));
+
+ assertEquals(expectedMgmtPubIntervalValue,mgmtPubInterval.getTextContent());
+ }
+
+ /**
+ * Tests the WS-RP PutResourcePropertyDocument interface of the WS-DM adapter.
+ * Specifically it tries to update the value of a read-only property.
+ *
+ * <br>precondition : a ws resource exists, it is registered and has at least one read-only property.
+ * <br>postcondition : An exception is thrown indicating the failure.
+ */
+ public void testGetAndPutResourcePropertyDocumentKO_WithReadOnlyProperty() throws Exception
+ {
+ String propertyName = "Name";
+
+ Element propertiesDocument = _resourceClient.getResourcePropertyDocument();
+ Element [] properties = XmlUtils.getAllElements(propertiesDocument);
+
+ for (Element element : properties)
+ {
+ if (propertyName.equals(element.getLocalName())) {
+ element.setTextContent("ThisIsTheNewValueOfNameProperty");
+ } else {
+ propertiesDocument.removeChild(element);
+ }
+ }
+
+ try
+ {
+ _resourceClient.putResourcePropertyDocument(propertiesDocument);
+ fail("It's not possible to update the value of a read-only property.");
+ } catch (SoapFault expected)
+ {
+
+ }
+ }
+}
diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/MetadataExchangeInterfaceTestCase.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/MetadataExchangeInterfaceTestCase.java new file mode 100644 index 0000000000..046f2226e6 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/MetadataExchangeInterfaceTestCase.java @@ -0,0 +1,169 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm;
+
+import javax.xml.namespace.QName;
+
+import org.apache.muse.core.proxy.ProxyHandler;
+import org.apache.muse.core.proxy.ReflectionProxyHandler;
+import org.apache.muse.util.xml.XmlUtils;
+import org.apache.muse.ws.addressing.soap.SoapFault;
+import org.apache.muse.ws.metadata.WsxConstants;
+import org.apache.muse.ws.resource.WsrfConstants;
+import org.apache.muse.ws.resource.metadata.WsrmdConstants;
+import org.apache.qpid.management.Names;
+import org.w3c.dom.Element;
+
+/**
+ * Test case for QMan metadata exchange interface.
+ *
+ * @author Andrea Gazzarini
+ */
+public class MetadataExchangeInterfaceTestCase extends BaseWsDmAdapterTestCase
+{
+ /**
+ * Test the MetadataExchange interface when the corresponding
+ * request doesn't contain a dialect. According to WS-MetadataExchange specs this should be
+ * intended as a "give-me-all-metadata" for that resource.
+ *
+ * <br>precondition : the GetMetadata request doesn't contain a dialect.
+ * <br>postcondition : the whole metadata document is returned with all metadata .
+ * It will contain both WSDL and RMD.
+ */
+ @SuppressWarnings("unchecked")
+ public void testGetMetadataOK_WithoutDialect() throws Exception
+ {
+ Element[] result = (Element[]) _resourceClient.invoke(
+ getProxyHandler(),
+ new Object[]{""});
+
+ assertEquals(2,result.length);
+
+ Element rmdMetadataSection = result[0];
+ Element wsdlMetadataSection = result[1];
+
+ Element rmd = XmlUtils.getFirstElement(rmdMetadataSection);
+ Element wsdl = XmlUtils.getFirstElement(wsdlMetadataSection);
+
+ assertEquals("MetadataDescriptor",rmd.getLocalName());
+ assertEquals("definitions",wsdl.getLocalName());
+ }
+
+ /**
+ * Test the MetadataExchange interface when the WSDL dialect is specified on the request.
+ *
+ * <br>precondition : the GetMetadata request contains WSDL dialect.
+ * <br>postcondition : the resource WSDL metadata document is returned.
+ */
+ @SuppressWarnings("unchecked")
+ public void testGetMetadataOK_WithWSDLDialect() throws Exception
+ {
+ Element[] result = (Element[]) _resourceClient.invoke(
+ getProxyHandler(),
+ new Object[]{WsxConstants.WSDL_DIALECT});
+
+ assertEquals(1,result.length);
+
+ Element wsdlMetadataSection = result[0];
+
+ Element wsdl = XmlUtils.getFirstElement(wsdlMetadataSection);
+
+ assertEquals("definitions",wsdl.getLocalName());
+ }
+
+ /**
+ * Test the MetadataExchange interface when the RMD dialect is specified on the request.
+ *
+ * <br>precondition : the GetMetadata request contains RMD dialect.
+ * <br>postcondition : the RMD metadata document is returned.
+ */
+ @SuppressWarnings("unchecked")
+ public void testGetMetadataOK_WithRMDDialect() throws Exception
+ {
+ Element[] result = (Element[]) _resourceClient.invoke(
+ getProxyHandler(),
+ new Object[]{WsrmdConstants.NAMESPACE_URI});
+
+ assertEquals(1,result.length);
+
+ Element rmdMetadataSection = result[0];
+
+ Element wsdl = XmlUtils.getFirstElement(rmdMetadataSection);
+
+ assertEquals("MetadataDescriptor",wsdl.getLocalName());
+ }
+
+ /**
+ * Test the MetadataExchange interface with an unknown metadata dialect.
+ *
+ * <br>precondition : the GetMetadata request contains an unknown dialect.
+ * <br>postcondition : the returned metadata section is empty.
+ */
+ @SuppressWarnings("unchecked")
+ public void testGetMetadataKO_WithoutUnknownDialect() throws Exception
+ {
+ Element [] metadata = (Element[]) _resourceClient.invoke(
+ getProxyHandler(),
+ new Object[]{"HopeThisIsAnUnknownDialect"});
+
+ assertEquals(0,metadata.length);
+ }
+
+ /**
+ * Test the MetadataExchange interface with an unknown metadata dialect.
+ *
+ * <br>precondition : the GetMetadata request contains an unknown dialect.
+ * <br>postcondition : the returned metadata section is empty.
+ */
+ @SuppressWarnings("unchecked")
+ public void testGetMetadataKO_WithoutUnknownResourceFault() throws Exception
+ {
+ try
+ {
+ _resourceClient.getEndpointReference().removeParameter(Names.RESOURCE_ID_QNAME);
+ _resourceClient.getEndpointReference().addParameter(Names.RESOURCE_ID_QNAME,"lablabalbal");
+
+ _resourceClient.invoke(getProxyHandler(), new Object[]{""});
+ } catch(SoapFault expected)
+ {
+ assertEquals(
+ WsrfConstants.RESOURCE_UNKNOWN_QNAME.getLocalPart(),
+ expected.getDetail().getLocalName());
+ }
+ }
+
+ /**
+ * Returns a proxy handler used for working with metadata exchange
+ * interface.
+ *
+ * @return a metadata proxy handler.
+ */
+ private ProxyHandler getProxyHandler()
+ {
+ ProxyHandler getMetadataHandler = new ReflectionProxyHandler();
+ getMetadataHandler.setAction("http://schemas.xmlsoap.org/ws/2004/09/mex/GetMetadata");
+ getMetadataHandler.setRequestName(new QName("http://schemas.xmlsoap.org/ws/2004/09/mex", "GetMetadata", "wsx"));
+ getMetadataHandler.setRequestParameterNames(new QName[]{new QName("http://schemas.xmlsoap.org/ws/2004/09/mex", "Dialect", "wsx")});
+ getMetadataHandler.setResponseName(new QName("http://schemas.xmlsoap.org/ws/2004/09/mex", "Metadata", "wsx"));
+ getMetadataHandler.setReturnType(Element[].class);
+ return getMetadataHandler;
+ }
+}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/OperationInvocationInterfaceTestCase.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/OperationInvocationInterfaceTestCase.java new file mode 100644 index 0000000000..afc4a62085 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/OperationInvocationInterfaceTestCase.java @@ -0,0 +1,580 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.Method;
+import java.net.URI;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.xml.namespace.QName;
+
+import org.apache.muse.core.proxy.ProxyHandler;
+import org.apache.muse.core.proxy.ReflectionProxyHandler;
+import org.apache.muse.ws.addressing.soap.SoapFault;
+import org.apache.qpid.management.Names;
+import org.apache.qpid.management.wsdm.capabilities.Result;
+
+/**
+ * Test case for QMan operation invocation interface.
+ *
+ * @author Andrea Gazzarini
+ */
+public class OperationInvocationInterfaceTestCase extends BaseWsDmAdapterTestCase
+{
+ private Map<String, ProxyHandler> _invocationHandlers = createInvocationHandlers();
+
+ /**
+ * Test operation invocation on WS-Resource.
+ * This method tests the exchange of a byte type array between requestor
+ * and service provider.
+ *
+ * <br>precondition : a WS-Resource exists and is registered and the requested
+ * operation is available on that.
+ * <br>postcondition : invocations are executed successfully, no exception is thrown
+ * and byte array are correctly returned.
+ */
+ @SuppressWarnings("unchecked")
+ public void testOperationInvocationOK_withByteArray() throws Exception
+ {
+ byte [] expectedByteResult = {1,3,4,2,2,44,22,3,3,55,66};
+
+ Object result = _resourceClient.invoke(
+ _invocationHandlers.get("echoWithByteArray"),
+ new Object[]{expectedByteResult});
+
+ Method getOutputParameters = result.getClass().getMethod("getOutputParameters");
+
+ Map<String,Object> out = (Map<String, Object>) getOutputParameters.invoke(result);
+
+ assertEquals("Output parameters must be 1.",1,out.size());
+ assertArrayEquals(expectedByteResult, out.get(byte[].class.getName()));
+ }
+
+ /**
+ * Test a simple operation invocation on a WS-Resource.
+ * This method tests a simple operation without any input and output parameters.
+ *
+ * <br>precondition : a ws resource exists and is registered and the requested operation
+ * is available on that.
+ * <br>postcondition : invocations are executed successfully an no exception is thrown.
+ */
+ @SuppressWarnings("unchecked")
+ public void testSimpleOperationInvocationOK() throws Exception
+ {
+ Object result = _resourceClient.invoke(
+ _invocationHandlers.get("voidWithoutArguments"),
+ null);
+
+ assertNotNull(result);
+ }
+
+ /**
+ * Test a the invocation on a WS-Resource with a method that throws an exception..
+ *
+ * <br>precondition : a ws resource exists and is registered and the requested
+ * operation is available on that.
+ * <br>postcondition : an exception is thrown by the requested method.
+ */
+ @SuppressWarnings("unchecked")
+ public void testInvocationException_OK() throws Exception
+ {
+ try
+ {
+ _resourceClient.invoke(
+ _invocationHandlers.get("throwsException"),
+ null);
+ fail("The requested operation has thrown an exception so a Soap Fault is expected...");
+ } catch(SoapFault expected)
+ {
+ }
+ }
+
+ /**
+ * Test operation invocation on WS-Resource.
+ * This method tests the exchange of UUID type between requestor and service provider.
+ *
+ * <br>precondition : a WS-Resource exists and is registered and the requested operation
+ * is available on that.
+ * <br>postcondition : invocations are executed successfully, no exception is thrown
+ * and parameters are correctly returned.
+ */
+ @SuppressWarnings("unchecked")
+ public void testOperationInvocationOK_withUUID() throws Exception
+ {
+ UUID expectedUuid = UUID.randomUUID();
+
+ Object result = _resourceClient.invoke(
+ _invocationHandlers.get("echoWithUUID"),
+ new Object[]{expectedUuid});
+
+ Method getOutputParameters = result.getClass().getMethod("getOutputParameters");
+
+ Map<String,Object> out = (Map<String, Object>) getOutputParameters.invoke(result);
+
+ assertEquals("Output parameters must be 1.",1,out.size());
+ assertEquals(expectedUuid, out.get("uuid"));
+ }
+
+ /**
+ * Test operation invocation on WS-Resource.
+ * This method tests the exchange of Map type between requestor and service provider.
+ * For this test exchanged arrays contain :
+ *
+ * <br>precondition : a ws resource exists and is registered and the requested
+ * operation is available on that.
+ * <br>postcondition : invocations are executed successfully, no exception is
+ * thrown and parameters are correctly returned.
+ */
+ @SuppressWarnings("unchecked")
+ public void testOperationInvocationOK_withMap() throws Exception
+ {
+ Map<String,Object> expectedMap = new HashMap<String, Object>();
+ expectedMap.put("p1", new Long(1));
+ expectedMap.put("p2", Boolean.TRUE);
+ expectedMap.put("p3", 1234d);
+ expectedMap.put("p4", 11.2f);
+ expectedMap.put("p5", 1272);
+ expectedMap.put("p6", (short)12);
+ expectedMap.put("p7", "aString");
+ expectedMap.put("p8", "http://qpid.apache.org");
+ expectedMap.put("p9", new Date(12383137128L));
+ expectedMap.put("p10", new byte[]{1,2,2,3,3,4});
+
+ Object result = _resourceClient.invoke(
+ _invocationHandlers.get("echoWithMap"),
+ new Object[]{expectedMap});
+
+ Method getOutputParameters = result.getClass().getMethod("getOutputParameters");
+
+ Map<String,Object> out = (Map<String, Object>) ((Map<String, Object>) getOutputParameters.invoke(result)).get("map");
+
+ assertEquals("Output parameters must be 10.",10,out.size());
+ assertEquals(expectedMap.get("p1"),out.get("p1"));
+ assertEquals(expectedMap.get("p2"),out.get("p2"));
+ assertEquals(expectedMap.get("p3"),out.get("p3"));
+ assertEquals(expectedMap.get("p4"),out.get("p4"));
+ assertEquals(expectedMap.get("p5"),out.get("p5"));
+ assertEquals(expectedMap.get("p6"),out.get("p6"));
+ assertEquals(expectedMap.get("p7"),out.get("p7"));
+ assertEquals(expectedMap.get("p8"),out.get("p8"));
+ assertEquals(expectedMap.get("p9"),out.get("p9"));
+ assertTrue( Arrays.equals((byte[])expectedMap.get("p10"),(byte[])out.get("p10")));
+ }
+
+ /**
+ * Test operation invocation on WS-Resource.
+ * This method tests the exchange of simple types between requestor and
+ * service provider.
+ *
+ * With simple types we mean :
+ *
+ * <ul>
+ * <li>java.lang.Long / long (xsd:long)
+ * <li>java.lang.Integer / int (xsd:int / xsd:integer)
+ * <li>java.lang.Double/ double (xsd:double)
+ * <li>java.lang.Float / float (xsd:float)
+ * <li>java.lang.Short / short (xsd:short)
+ * <li>java.lang.Boolean / boolean (xsd:boolean)
+ * <li>java.lang.String (xsd:string)
+ * <li>java.net.URI (xsd:anyURI)
+ * <li>java.util.Date(xsd:dateTime)
+ * </ul>
+ *
+ * <br>precondition : a ws resource exists and is registered and the requested operation is
+ * available on that.
+ * <br>postcondition : invocations are executed successfully, no exception is thrown and
+ * parameters are correctly returned.
+ */
+ @SuppressWarnings("unchecked")
+ public void testOperationInvocationOK_withSimpleTypes() throws Exception
+ {
+ Long expectedLongResult = new Long(1373);
+ Boolean expectedBooleanResult = Boolean.TRUE;
+ Double expectedDoubleResult = new Double(12763.44);
+ Float expectedFloatResult = new Float(2727.233f);
+ Integer expectedIntegerResult = new Integer(28292);
+ Short expectedShortResult = new Short((short)227);
+ String expectedStringResult = "expectedStringResult";
+ URI expectedUriResult = URI.create("http://qpid.apache.org/");
+ Date expectedDateResult = new Date();
+
+ Object result = _resourceClient.invoke(
+ _invocationHandlers.get("echoWithSimpleTypes"),
+ new Object[]{
+ expectedLongResult,
+ expectedBooleanResult,
+ expectedDoubleResult,
+ expectedFloatResult,
+ expectedIntegerResult,
+ expectedShortResult,
+ expectedStringResult,
+ expectedUriResult,
+ expectedDateResult});
+
+ Method getOutputParameters = result.getClass().getMethod("getOutputParameters");
+ Map<String,Object> out = (Map<String, Object>) getOutputParameters.invoke(result);
+
+ assertEquals("Output parameters must be 9.",9,out.size());
+ assertTrue("Long output parameter not found on result object.",out.containsValue(expectedLongResult));
+ assertTrue("Boolean output parameter not found on result object.",out.containsValue(expectedBooleanResult));
+ assertTrue("Double output parameter not found on result object.",out.containsValue(expectedDoubleResult));
+ assertTrue("Float output parameter not found on result object.",out.containsValue(expectedFloatResult));
+ assertTrue("Integer output parameter not found on result object.",out.containsValue(expectedIntegerResult));
+ assertTrue("Short output parameter not found on result object.",out.containsValue(expectedShortResult));
+ assertTrue("String output parameter not found on result object.",out.containsValue(expectedStringResult));
+ assertTrue("URI output parameter not found on result object.",out.containsValue(expectedUriResult));
+ assertTrue("Date output parameter not found on result object.",out.containsValue(expectedDateResult));
+ }
+
+ /**
+ * Test operation invocation on WS-Resource.
+ * This method tests the exchange of arrays between requestor and service provider.
+ * For this test exchanged arrays contain :
+ *
+ * <ul>
+ * <li>java.lang.Long (xsd:long)
+ * <li>java.lang.Integer (xsd:int / xsd:integer)
+ * <li>java.lang.Double (xsd:double)
+ * <li>java.lang.Float (xsd:float)
+ * <li>java.lang.Short (xsd:short)
+ * <li>java.lang.Boolean (xsd:boolean)
+ * <li>java.lang.String (xsd:string)
+ * <li>java.net.URI (xsd:anyURI)
+ * <li>java.util.Date(xsd:dateTime)
+ * </ul>
+ *
+ * <br>precondition : a ws resource exists and is registered and the requested operation is available on that.
+ * <br>postcondition : invocations are executed successfully, no exception is thrown and parameters are correctly returned.
+ */
+ @SuppressWarnings("unchecked")
+ public void testOperationInvocationOK_withWrapperArrays() throws Exception
+ {
+ Long [] expectedLongResult = {new Long(2),new Long(1),new Long(3),new Long(4)};
+ Boolean [] expectedBooleanResult = { Boolean.TRUE,Boolean.FALSE,Boolean.FALSE};
+ Double [] expectedDoubleResult = {12763.44d,2832.33d,2292.33d,22293.22d};
+ Float [] expectedFloatResult = {2727.233f,1f,2f,4f,5.4f,33.2f};
+ Integer [] expectedIntegerResult = {1,2,3,4,55,66,77,88,99};
+ Short [] expectedShortResult = {(short)227,(short)23,(short)9};
+ String [] expectedStringResult = {"s1","s2","s333","s4"};
+ URI [] expectedUriResult = {
+ URI.create("http://qpid.apache.org/"),
+ URI.create("http://www.apache.org"),
+ URI.create("http://projects.apache.org")};
+
+ Date [] expectedDateResult = {
+ new Date(),
+ new Date(38211897),
+ new Date(903820382)};
+
+ Object result = _resourceClient.invoke(
+ _invocationHandlers.get("echoWithArrays"),
+ new Object[]{
+ expectedLongResult,
+ expectedBooleanResult,
+ expectedDoubleResult,
+ expectedFloatResult,
+ expectedIntegerResult,
+ expectedShortResult,
+ expectedStringResult,
+ expectedUriResult,
+ expectedDateResult});
+
+ Method getOutputParameters = result.getClass().getMethod("getOutputParameters");
+ Map<String,Object> out = (Map<String, Object>) getOutputParameters.invoke(result);
+
+ assertEquals("Output parameters must be 9.",9,out.size());
+ assertTrue("Long array doesn't match.",Arrays.equals(expectedLongResult, (Long[])out.get(Long.class.getName())));
+ assertTrue("Boolean array doesn't match.",Arrays.equals(expectedBooleanResult, (Boolean[])out.get(Boolean.class.getName())));
+ assertTrue("Double array doesn't match.",Arrays.equals(expectedDoubleResult, (Double[])out.get(Double.class.getName())));
+ assertTrue("Float array doesn't match.",Arrays.equals(expectedFloatResult, (Float[])out.get(Float.class.getName())));
+ assertTrue("Integer array doesn't match.", Arrays.equals(expectedIntegerResult, (Integer[])out.get(Integer.class.getName())));
+ assertTrue("Short array doesn't match.",Arrays.equals(expectedShortResult, (Short[])out.get(Short.class.getName())));
+ assertTrue("String array doesn't match.",Arrays.equals(expectedStringResult, (String[])out.get(String.class.getName())));
+ assertTrue("URI array doesn't match.",Arrays.equals(expectedUriResult, (URI[])out.get(URI.class.getName())));
+ assertTrue("Date array doesn't match.",Arrays.equals(expectedDateResult, (Date[])out.get(Date.class.getName())));
+ }
+
+ /**
+ * Test operation invocation on WS-Resource.
+ * This method tests the exchange of primitive type arrays between requestor and service provider.
+ * NOte that even the sent array contain primtiive type QMan deals only with objects so in the result
+ * object you will find the corresponding wrapper types.
+ *
+ * For this test exchanged arrays contain :
+ *
+ * <ul>
+ * <li>java.lang.Long / long (xsd:long)
+ * <li>java.lang.Integer / int (xsd:int / xsd:integer)
+ * <li>java.lang.Double/ double (xsd:double)
+ * <li>java.lang.Float / float (xsd:float)
+ * <li>java.lang.Short / short (xsd:short)
+ * <li>java.lang.Boolean / boolean (xsd:boolean)
+ * </ul>
+ *
+ * <br>precondition : a ws resource exists and is registered and the requested operation is available on that.
+ * <br>postcondition : invocations are executed successfully, no exception is thrown and parameters are correctly returned.
+ */
+ @SuppressWarnings("unchecked")
+ public void testOperationInvocationOK_withPrimitiveArrays() throws Exception
+ {
+ long [] expectedLongResult = {1L,2L,3L,4L};
+ boolean [] expectedBooleanResult = { true,false,false};
+ double [] expectedDoubleResult = {12763.44d,2832.33d,2292.33d,22293.22d};
+ float [] expectedFloatResult = {2727.233f,1f,2f,4f,5.4f,33.2f};
+ int [] expectedIntegerResult = {1,2,3,4,55,66,77,88,99};
+ short [] expectedShortResult = {(short)227,(short)23,(short)9};
+
+ Object result = _resourceClient.invoke(
+ _invocationHandlers.get("echoWithSimpleTypeArrays"),
+ new Object[]{
+ expectedLongResult,
+ expectedBooleanResult,
+ expectedDoubleResult,
+ expectedFloatResult,
+ expectedIntegerResult,
+ expectedShortResult});
+
+ Method getOutputParameters = result.getClass().getMethod("getOutputParameters");
+ Map<String,Object> out = (Map<String, Object>) getOutputParameters.invoke(result);
+
+ assertEquals("Output parameters must be 6.",6,out.size());
+ assertArrayEquals(expectedLongResult, out.get(long.class.getName()));
+ assertArrayEquals(expectedBooleanResult, out.get(boolean.class.getName()));
+ assertArrayEquals(expectedDoubleResult, out.get(double.class.getName()));
+ assertArrayEquals(expectedFloatResult, out.get(float.class.getName()));
+ assertArrayEquals(expectedIntegerResult, out.get(int.class.getName()));
+ assertArrayEquals(expectedShortResult, out.get(short.class.getName()));
+ }
+
+ /**
+ * Internal method used for array comparison using reflection.
+ *
+ * @param expectedArray the expected array.
+ * @param resultArray the array that must match the expected one.
+ */
+ private void assertArrayEquals(Object expectedArray, Object resultArray)
+ {
+ int expectedArrayLength = Array.getLength(expectedArray);
+ int resultArrayLength = Array.getLength(resultArray);
+
+ assertEquals(expectedArrayLength,resultArrayLength);
+
+ for (int index = 0; index < expectedArrayLength; index++)
+ {
+ Object expected = Array.get(expectedArray, index);
+ Object result = Array.get(resultArray, index);
+
+ assertEquals(expected,result);
+ }
+ }
+
+ private Map<String,ProxyHandler> createInvocationHandlers()
+ {
+ Map<String, ProxyHandler> handlers = new HashMap<String, ProxyHandler>();
+
+ ProxyHandler handler = new ReflectionProxyHandler();
+ handler.setAction(Names.NAMESPACE_URI+"/"+"voidWithoutArguments");
+ handler.setRequestName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "voidWithoutArgumentsRequest",
+ Names.PREFIX));
+ handler.setRequestParameterNames(new QName[]{});
+ handler.setResponseName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "voidWithoutArgumentsResponse",
+ Names.PREFIX));
+ handler.setReturnType(Result.class);
+
+ ProxyHandler exceptionHandler = new ReflectionProxyHandler();
+ exceptionHandler.setAction(Names.NAMESPACE_URI+"/"+"throwsException");
+ exceptionHandler.setRequestName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "throwsExceptionRequest",
+ Names.PREFIX));
+
+ exceptionHandler.setRequestParameterNames(new QName[]{});
+ exceptionHandler.setResponseName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "throwsExceptionResponse",
+ Names.PREFIX));
+
+ exceptionHandler.setReturnType(Result.class);
+
+ ProxyHandler echoWithWrapperTypesHandler = new ReflectionProxyHandler();
+ echoWithWrapperTypesHandler.setAction(Names.NAMESPACE_URI+"/"+"echoWithSimpleTypes");
+ echoWithWrapperTypesHandler.setRequestName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithSimpleTypesRequest",
+ Names.PREFIX));
+
+ echoWithWrapperTypesHandler.setRequestParameterNames(new QName[]{
+ new QName(Names.NAMESPACE_URI,"p1",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p2",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p3",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p4",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p5",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p6",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p7",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p8",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p9",Names.PREFIX),
+ });
+
+ echoWithWrapperTypesHandler.setResponseName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithSimpleTypesResponse",
+ Names.PREFIX));
+
+ echoWithWrapperTypesHandler.setReturnType(Result.class);
+
+ ProxyHandler echoWithArrayOfWrapperTypes = new ReflectionProxyHandler();
+ echoWithArrayOfWrapperTypes.setAction(Names.NAMESPACE_URI+"/"+"echoWithArrays");
+ echoWithArrayOfWrapperTypes.setRequestName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithArraysRequest",
+ Names.PREFIX));
+
+ echoWithArrayOfWrapperTypes.setRequestParameterNames(new QName[]{
+ new QName(Names.NAMESPACE_URI,"p1",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p2",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p3",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p4",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p5",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p6",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p7",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p8",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p9",Names.PREFIX),
+ });
+
+ echoWithArrayOfWrapperTypes.setResponseName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithArraysResponse",
+ Names.PREFIX));
+
+ echoWithArrayOfWrapperTypes.setReturnType(Result.class);
+
+ ProxyHandler echoWithArrayOfPrimitiveTypes = new ReflectionProxyHandler();
+ echoWithArrayOfPrimitiveTypes.setAction(Names.NAMESPACE_URI+"/"+"echoWithSimpleTypeArrays");
+ echoWithArrayOfPrimitiveTypes.setRequestName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithSimpleTypeArraysRequest",
+ Names.PREFIX));
+
+ echoWithArrayOfPrimitiveTypes.setRequestParameterNames(new QName[]{
+ new QName(Names.NAMESPACE_URI,"p1",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p2",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p3",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p4",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p5",Names.PREFIX),
+ new QName(Names.NAMESPACE_URI,"p6",Names.PREFIX)});
+
+ echoWithArrayOfPrimitiveTypes.setResponseName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithSimpleTypeArraysResponse",
+ Names.PREFIX));
+
+ echoWithArrayOfPrimitiveTypes.setReturnType(Result.class);
+
+ ProxyHandler echoWithByteArray = new EnhancedReflectionProxyHandler();
+ echoWithByteArray.setAction(Names.NAMESPACE_URI+"/"+"echoWithByteArray");
+ echoWithByteArray.setRequestName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithByteArrayRequest",
+ Names.PREFIX));
+
+ echoWithByteArray.setRequestParameterNames(
+ new QName[]{
+ new QName(Names.NAMESPACE_URI,"p1",Names.PREFIX)});
+
+ echoWithByteArray.setResponseName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithByteArrayResponse",
+ Names.PREFIX));
+
+ echoWithByteArray.setReturnType(Result.class);
+
+ ProxyHandler echoWithUUID = new EnhancedReflectionProxyHandler();
+ echoWithUUID.setAction(Names.NAMESPACE_URI+"/"+"echoWithUUID");
+ echoWithUUID.setRequestName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithUUIDRequest",
+ Names.PREFIX));
+
+ echoWithUUID.setRequestParameterNames(
+ new QName[]{
+ new QName(Names.NAMESPACE_URI,"p1",Names.PREFIX)});
+
+ echoWithUUID.setResponseName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithUUIDResponse",
+ Names.PREFIX));
+
+ echoWithUUID.setReturnType(Result.class);
+
+ ProxyHandler echoWithMap = new EnhancedReflectionProxyHandler();
+ echoWithMap.setAction(Names.NAMESPACE_URI+"/"+"echoWithMap");
+ echoWithMap.setRequestName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithMapRequest",
+ Names.PREFIX));
+
+ echoWithMap.setRequestParameterNames(
+ new QName[]{
+ new QName(Names.NAMESPACE_URI,"p1",Names.PREFIX)});
+
+ echoWithMap.setResponseName(
+ new QName(
+ Names.NAMESPACE_URI,
+ "echoWithMapResponse",
+ Names.PREFIX));
+
+ echoWithMap.setReturnType(Result.class);
+
+ handlers.put("voidWithoutArguments",handler);
+ handlers.put("echoWithSimpleTypes",echoWithWrapperTypesHandler);
+ handlers.put("echoWithArrays",echoWithArrayOfWrapperTypes);
+ handlers.put("echoWithSimpleTypeArrays", echoWithArrayOfPrimitiveTypes);
+ handlers.put("echoWithByteArray", echoWithByteArray);
+ handlers.put("echoWithUUID", echoWithUUID);
+ handlers.put("echoWithMap", echoWithMap);
+ handlers.put("throwsException",exceptionHandler);
+ return handlers;
+ }
+}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/ServerThread.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/ServerThread.java new file mode 100644 index 0000000000..6574c278ff --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/ServerThread.java @@ -0,0 +1,118 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm;
+
+import java.io.File;
+
+import org.apache.qpid.management.Names;
+import org.mortbay.component.LifeCycle.Listener;
+import org.mortbay.jetty.Connector;
+import org.mortbay.jetty.Server;
+import org.mortbay.jetty.nio.SelectChannelConnector;
+import org.mortbay.jetty.webapp.WebAppContext;
+import org.mortbay.start.Monitor;
+
+/**
+ * Web Server startup thread.
+ * It is used on adapter test case in order to start the embedded
+ * web server as a separated thread.
+ *
+ * @author Andrea Gazzarini
+ */
+class ServerThread extends Thread
+{
+ private final Listener _lifecycleListener;
+ private Server _server;
+
+ private SelectChannelConnector _connector;
+
+ /**
+ * Builds a new server thread with the given lifecycle listener.
+ *
+ * @param listener the lifecycle listener.
+ */
+ ServerThread(Listener listener)
+ {
+ this._lifecycleListener = listener;
+ }
+
+ /**
+ * Starts the server.
+ */
+ @Override
+ public void run()
+ {
+ try
+ {
+ Monitor.monitor();
+ _server = new Server();
+ _server.setStopAtShutdown(true);
+
+ _connector=new SelectChannelConnector();
+ _connector.setPort(Integer.parseInt(System.getProperty(Names.ADAPTER_PORT_PROPERTY_NAME)));
+ _connector.setHost(System.getProperty(Names.ADAPTER_HOST_PROPERTY_NAME));
+
+
+ _server.setConnectors(new Connector[]{_connector});
+
+ WebAppContext webapp = new WebAppContext();
+ webapp.setContextPath("/qman");
+
+ // Additional web application descriptor containing test components.
+ webapp.setDefaultsDescriptor("/org/apache/qpid/management/wsdm/web.xml");
+
+ String webApplicationPath = System.getProperty("qman.war");
+ File rootFolderPath = (webApplicationPath != null) ? new File(webApplicationPath) : new File(".");
+
+ webapp.setWar(rootFolderPath.toURI().toURL().toExternalForm());
+ webapp.addLifeCycleListener(_lifecycleListener);
+ _server.setHandler(webapp);
+ _server.start();
+ System.setProperty(Names.ADAPTER_PORT_PROPERTY_NAME,String.valueOf( _connector.getLocalPort()));
+ _server.join();
+
+ } catch(Exception exception)
+ {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ /**
+ * Shutdown the server.
+ *
+ * @throws Exception when a problem is encountered during shutdown.
+ */
+ void shutdown() throws Exception
+ {
+ _server.stop();
+ }
+
+ /**
+ * Returns the port number where the server is running.
+ *
+ * @return the port number where the server is running.
+ */
+ int getPort()
+ {
+ return _connector.getLocalPort();
+ }
+
+}
diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/SetResourcePropertiesTestCase.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/SetResourcePropertiesTestCase.java new file mode 100644 index 0000000000..87f8905e01 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/SetResourcePropertiesTestCase.java @@ -0,0 +1,219 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm;
+
+import java.lang.reflect.Array;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.management.MBeanAttributeInfo;
+import javax.xml.namespace.QName;
+
+import org.apache.muse.ws.addressing.soap.SoapFault;
+import org.apache.muse.ws.resource.WsrfConstants;
+import org.apache.qpid.management.Names;
+
+/**
+ * Test case for Set Resource Properties interfaces.
+ *
+ * @author Andrea Gazzarini
+ */
+public class SetResourcePropertiesTestCase extends BaseWsDmAdapterTestCase
+{
+ /**
+ * Test the WS-RP SetResourceProperty interface of the WS-DM adapter.
+ *
+ * <br>precondition : a WS-Resource exists and is registered.
+ * <br>postcondition : property values are correctly updated on the target WS-Resource..
+ */
+ public void testSetResourcePropertiesOK() throws Exception
+ {
+ Map<String, Object> sampleMap = new HashMap<String, Object>();
+ sampleMap.put("Key1", "BLABALABLABALBAL");
+ sampleMap.put("Key2", 182838484l);
+ sampleMap.put("Key3", -928376362);
+ sampleMap.put("Key4", 23762736276.33D);
+ sampleMap.put("Key4", 2327363.2F);
+
+ Map<String, Object> sampleValues = new HashMap<String, Object>();
+ sampleValues.put(String.class.getName(),"SAMPLE_STRING");
+ sampleValues.put(UUID.class.getName(),UUID.randomUUID());
+ sampleValues.put(Boolean.class.getName(),Boolean.FALSE);
+ sampleValues.put(Map.class.getName(),sampleMap);
+ sampleValues.put(Long.class.getName(),283781273L);
+ sampleValues.put(Integer.class.getName(),12727);
+ sampleValues.put(Short.class.getName(),new Short((short)22));
+ sampleValues.put(Date.class.getName(),new Date());
+
+ MBeanAttributeInfo [] attributesMetadata = _mbeanInfo.getAttributes();
+ boolean atLeastThereIsOneWritableProperty = false;
+
+ for (MBeanAttributeInfo attributeMetadata : attributesMetadata)
+ {
+ String name = attributeMetadata.getName();
+
+ if (attributeMetadata.isWritable())
+ {
+ atLeastThereIsOneWritableProperty = true;
+ Object sampleValue = sampleValues.get(attributeMetadata.getType());
+ Object []values = new Object[]{sampleValue};
+
+ Object result = _managementServer.getAttribute(_resourceObjectName, name);
+ if (result == null)
+ {
+ _resourceClient.insertResourceProperty(
+ new QName(
+ Names.NAMESPACE_URI,
+ name,
+ Names.PREFIX),
+ values);
+ } else
+ {
+ _resourceClient.updateResourceProperty(
+ new QName(
+ Names.NAMESPACE_URI,
+ name,
+ Names.PREFIX),
+ values);
+ }
+
+ Object propertyValues = _resourceClient.getPropertyAsObject(
+ new QName(
+ Names.NAMESPACE_URI,
+ name,
+ Names.PREFIX),
+ Class.forName(attributeMetadata.getType()));
+ int length = Array.getLength(propertyValues);
+ if (length != 0)
+ {
+ Object propertyValue = Array.get(propertyValues, 0);
+
+ assertEquals(
+ "Comparison failed for property "+name,
+ sampleValue,
+ propertyValue);
+ } else {
+ assertNull(
+ String.format(
+ "\"%s\" property value shouldn't be null. Its value is %s",
+ name,
+ _managementServer.getAttribute(_resourceObjectName,name)),
+ sampleValue);
+ }
+ }
+ }
+ assertTrue(
+ "It's not possibile to run successfully this test case if " +
+ "the target WS-Resource has no at least one writable property",
+ atLeastThereIsOneWritableProperty);
+ }
+
+ /**
+ * Test the WS-RP SetResourceProperty interface of the WS-DM adapter when the
+ * target property is null.
+ * According to WS-RP specs this operation is not allowed because in this case a SetResourceProperty with an "Insert"
+ * message should be sent in order to initialize the property.
+ *
+ * <br>precondition : a ws resource exists and is registered. The value of the target property is null.
+ * <br>postcondition : a Soap fault is received indicating the failuire.
+ */
+ public void testSetResourcePropertiesKO() throws Exception
+ {
+ Object typePropertyValue = _managementServer.getAttribute(_resourceObjectName, "Type");
+ assertNull(typePropertyValue);
+
+ try
+ {
+ _resourceClient.updateResourceProperty(
+ new QName(
+ Names.NAMESPACE_URI,
+ "Type",
+ Names.PREFIX),
+ new Object[]{"sampleValue"});
+ fail(
+ "If the property is null on the target ws resource, according " +
+ "to WS-RP specs, an update of its value is not possible.");
+ } catch(SoapFault expected)
+ {
+
+ }
+ }
+
+ /**
+ * Tests the SetResourceProperties (update) interface when the request contains
+ * an unknwon target resource.
+ *
+ * <br>precondition : the SetResourceProperties contains an unknwon resource.
+ * <br>postcondition : a SoapFault is thrown and the corresponding detail contains an
+ * UnknownResourceFault element.
+ */
+ public void testUpdateResourcePropertiesKO_WithUnknownResourceFault() throws Exception
+ {
+ try
+ {
+ _resourceClient.getEndpointReference().removeParameter(Names.RESOURCE_ID_QNAME);
+ _resourceClient.getEndpointReference().addParameter(Names.RESOURCE_ID_QNAME,"lablabalbal");
+
+ _resourceClient.updateResourceProperty(
+ new QName(
+ Names.NAMESPACE_URI,
+ "Type",
+ Names.PREFIX),
+ new Object[]{"sampleValue"});
+ } catch(SoapFault expected)
+ {
+ assertEquals(
+ WsrfConstants.RESOURCE_UNKNOWN_QNAME.getLocalPart(),
+ expected.getDetail().getLocalName());
+ }
+ }
+
+ /**
+ * Tests the SetResourceProperties (insert) interface when the request contains
+ * an unknwon target resource.
+ *
+ * <br>precondition : the SetResourceProperties contains an unknwon resource.
+ * <br>postcondition : a SoapFault is thrown and the corresponding detail contains an
+ * UnknownResourceFault element.
+ */
+ public void testInsertResourcePropertiesKO_WithUnknownResourceFault() throws Exception
+ {
+ try
+ {
+ _resourceClient.getEndpointReference().removeParameter(Names.RESOURCE_ID_QNAME);
+ _resourceClient.getEndpointReference().addParameter(Names.RESOURCE_ID_QNAME,"lablabalbal");
+
+ _resourceClient.insertResourceProperty(
+ new QName(
+ Names.NAMESPACE_URI,
+ "Type",
+ Names.PREFIX),
+ new Object[]{"sampleValue"});
+ } catch(SoapFault expected)
+ {
+ assertEquals(
+ WsrfConstants.RESOURCE_UNKNOWN_QNAME.getLocalPart(),
+ expected.getDetail().getLocalName());
+ }
+ }
+}
diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/WebApplicationLifeCycleListener.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/WebApplicationLifeCycleListener.java new file mode 100644 index 0000000000..91c646467e --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/WebApplicationLifeCycleListener.java @@ -0,0 +1,61 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm;
+
+import org.mortbay.component.LifeCycle;
+import org.mortbay.component.LifeCycle.Listener;
+
+/**
+ * Adapter class used to provide an empty (base) implementation of
+ * Lifecycle listener interface.
+ *
+ * Adapter test case needs to be informed about the lifecycle of the
+ * deployed QMan application. Only when its deployment is completed the test
+ * case can run successfully.
+ *
+ * So, following the same logic of Swng event model, this is an adapter that provides
+ * empty implementation of the listener interface (see for example MouseAdapter
+ * for mouse events listener)
+ *
+ * @author Andrea Gazzarini
+ */
+public class WebApplicationLifeCycleListener implements Listener
+{
+ public void lifeCycleFailure(LifeCycle event, Throwable cause)
+ {
+ }
+
+ public void lifeCycleStarted(LifeCycle event)
+ {
+ }
+
+ public void lifeCycleStarting(LifeCycle event)
+ {
+ }
+
+ public void lifeCycleStopped(LifeCycle event)
+ {
+ }
+
+ public void lifeCycleStopping(LifeCycle event)
+ {
+ }
+}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/WsDmAdapterTest.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/WsDmAdapterTest.java new file mode 100644 index 0000000000..f12288c91d --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/WsDmAdapterTest.java @@ -0,0 +1,156 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import org.apache.muse.core.serializer.SerializerRegistry;
+import org.apache.qpid.management.Names;
+import org.apache.qpid.management.Protocol;
+import org.apache.qpid.management.wsdm.capabilities.Result;
+import org.apache.qpid.management.wsdm.muse.serializer.DateSerializer;
+import org.apache.qpid.management.wsdm.muse.serializer.InvocationResultSerializer;
+import org.apache.qpid.management.wsdm.muse.serializer.MapSerializer;
+import org.apache.qpid.management.wsdm.muse.serializer.ObjectSerializer;
+import org.apache.qpid.management.wsdm.muse.serializer.UUIDSerializer;
+import org.mortbay.component.LifeCycle;
+import org.mortbay.component.LifeCycle.Listener;
+
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+public class WsDmAdapterTest
+{
+
+ /**
+ * Test case wide set up.
+ * Provides Server startup & shutdown global procedure.
+ *
+ * @author Andrea Gazzarini
+ */
+ private static class WsDmAdapterTestSetup extends TestSetup
+ {
+ private Object _serverMonitor = new Object();
+
+ Listener listener = new WebApplicationLifeCycleListener()
+ {
+ public void lifeCycleStarted(LifeCycle event)
+ {
+ synchronized (_serverMonitor)
+ {
+ _serverMonitor.notify();
+ }
+ }
+ };
+
+ private ServerThread _server;
+
+ /**
+ * Builds a new test setup with for the given test.
+ *
+ * @param test the decorated test.
+ */
+ public WsDmAdapterTestSetup(Test test)
+ {
+ super(test);
+ }
+
+ /**
+ * Starts up Web server.
+ *
+ * @throws Exception when the server startup fails.
+ */
+ @Override
+ protected void setUp() throws Exception
+ {
+ SerializerRegistry.getInstance().registerSerializer(Object.class, new ObjectSerializer());
+ SerializerRegistry.getInstance().registerSerializer(Date.class, new DateSerializer());
+ SerializerRegistry.getInstance().registerSerializer(Map.class, new MapSerializer());
+ SerializerRegistry.getInstance().registerSerializer(HashMap.class, new MapSerializer());
+ SerializerRegistry.getInstance().registerSerializer(UUID.class, new UUIDSerializer());
+ SerializerRegistry.getInstance().registerSerializer(Result.class, new InvocationResultSerializer());
+
+ System.setProperty(
+ Names.ADAPTER_HOST_PROPERTY_NAME,
+ Protocol.DEFAULT_QMAN_HOSTNAME);
+
+ System.setProperty(
+ Names.ADAPTER_PORT_PROPERTY_NAME,
+ String.valueOf(getFreePort()));
+
+ _server = new ServerThread(listener);
+ _server.start();
+
+ synchronized(_serverMonitor) {
+ _serverMonitor.wait();
+ Thread.sleep(2000);
+ }
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ _server.shutdown();
+ }
+ };
+
+ /**
+ * Gets the test suite composition.
+ *
+ * @return the test suite composition.
+ */
+ public static Test suite()
+ {
+ TestSuite suite = new TestSuite("Test suite for QMan WS-DM.");
+ /*suite.addTestSuite(MetadataExchangeInterfaceTestCase.class);
+ suite.addTestSuite(OperationInvocationInterfaceTestCase.class);
+ suite.addTestSuite(GetResourcePropertyDocumentTestCase.class);
+ suite.addTestSuite(SetResourcePropertiesTestCase.class);
+ suite.addTestSuite(GetMultipleResourcePropertiesTestCase.class);
+ suite.addTestSuite(GetResourcePropertiesTestCase.class); */
+ return new WsDmAdapterTestSetup(suite);
+ }
+
+ /**
+ * Finds a free port that will be used to run the embedded
+ * web server.
+ *
+ * @return a free port that will be used to run the
+ * embedded web server.
+ */
+ private static int getFreePort() throws IOException {
+ ServerSocket server = null;
+ try
+ {
+ server = new ServerSocket(0);
+ return server.getLocalPort();
+ } finally
+ {
+ server.close();
+ }
+ }
+}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapabilityBuilderTest.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapabilityBuilderTest.java new file mode 100644 index 0000000000..68c9930ecd --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapabilityBuilderTest.java @@ -0,0 +1,335 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm.capabilities;
+
+import java.lang.management.ManagementFactory;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javassist.CtClass;
+import javassist.CtMethod;
+
+import javax.management.MBeanAttributeInfo;
+import javax.management.MBeanInfo;
+import javax.management.MBeanOperationInfo;
+import javax.management.MBeanParameterInfo;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+import javax.xml.namespace.QName;
+
+import junit.framework.TestCase;
+
+import org.apache.qpid.management.domain.handler.impl.QpidDomainObject;
+import org.apache.qpid.management.wsdm.common.EntityInstanceNotFoundFault;
+import org.apache.qpid.management.wsdm.common.MethodInvocationFault;
+import org.apache.qpid.management.wsdm.common.NoSuchAttributeFault;
+import org.apache.qpid.management.wsdm.common.QManFault;
+
+/**
+ * Test case for MBean capability builder.
+ *
+ * @author Andrea Gazzarini
+ */
+public class MBeanCapabilityBuilderTest extends TestCase
+{
+
+ /**
+ * Management interface for an mbean that has no properties and no
+ * methods.
+ *
+ * @author Andrea Gazzarini
+ */
+ public interface NoPropertiesNoMethodsMBean
+ {
+ }
+
+ /**
+ * Implementation of the managenent interface described above.
+ *
+ * @author Andrea Gazzarini
+ */
+ public class NoPropertiesNoMethods implements NoPropertiesNoMethodsMBean
+ {
+ }
+
+ private MBeanCapabilityBuilder _builder;
+ private ObjectName _objectName;
+
+ /**
+ * Set up fixture for this test case.
+ */
+ protected void setUp() throws Exception
+ {
+ _builder = new MBeanCapabilityBuilder();
+ _objectName = new ObjectName("Test:Name=aName,class=DomainObject");
+ }
+
+ /**
+ * Tests that state change that occcurs on the begin() method when the requested
+ * class has not been defined.
+ */
+ public void testBegin_withClassNotYetDefined() throws Exception
+ {
+ _builder.begin(_objectName);
+ assertEquals(_builder._state,_builder._classNotAvailable);
+ }
+
+ /**
+ * Tests that state change that occcurs on the begin() method when the requested
+ * class has not been defined.
+ */
+ public void testBegin_withClassAlreadyDefined() throws Exception
+ {
+ _objectName = new ObjectName("Test:Name=aString,class=MBeanCapabilityBuilder");
+ _builder.begin(_objectName);
+
+ assertTrue(_builder._state instanceof DummyCapabilityBuilder);
+ assertSame(_builder._endAttributeHandler, _builder._noPropertyHasBeenDefined);
+ }
+
+ /**
+ * Tests the generateGetter method().
+ */
+ public void testGenerateGetter()
+ {
+ String name ="MyProperty";
+ String type = Long.class.getName();
+ String expected =
+ "public "+
+ type+
+ " get"+
+ name+
+ "() throws NoSuchAttributeFault,EntityInstanceNotFoundFault,QManFault { return ("+
+ type+
+ ") getAttribute(\""+
+ name+
+ "\"); }";
+
+ String result = _builder.generateGetter(type, name,name);
+ assertEquals(expected,result);
+ }
+
+ /**
+ * Tests the generateGetter method().
+ */
+ public void testGenerateSetter()
+ {
+ String name ="MyProperty";
+ String type = Long.class.getName();
+ String expected =
+ "public void setMyProperty("+
+ type+
+ " newValue) throws NoSuchAttributeFault,EntityInstanceNotFoundFault,QManFault { setAttribute(\""+
+ name+
+ "\", newValue); }";
+
+ String result = _builder.generateSetter(type, name,name);
+ assertEquals(expected,result);
+ }
+
+ /**
+ * Tests buils of a capability that has no properties and methods
+ *
+ * <br>precondition : the incoming entity definition is empty (no properties and no methods)
+ * <br>postcondition : the capability class is built successfully and has no props and methods.
+ * The getPropertyNames returns an empty QName array.
+ */
+ public void testOK_WithNoPropertiesNoMethods() throws Exception {
+
+ ObjectName name = new ObjectName("Test:Name=NoPropertiesNoMethods");
+
+ MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+ server.registerMBean(new NoPropertiesNoMethods(), name);
+
+ _builder.begin(name);
+ _builder.endAttributes();
+ _builder.endOperations();
+ Class<MBeanCapability> capabilityClass = _builder.getCapabilityClass();
+
+ Field[] fields = capabilityClass.getDeclaredFields();
+ Method [] methods = capabilityClass.getDeclaredMethods();
+
+ assertEquals(Arrays.toString(fields),0,fields.length);
+ assertEquals(Arrays.toString(methods),1,methods.length);
+
+ Method getPropertyNames = methods[0];
+ assertEquals("getPropertyNames",getPropertyNames.getName());
+
+
+ MBeanCapability capability = capabilityClass.newInstance();
+ QName [] properties = (QName[]) getPropertyNames.invoke(capability);
+ assertEquals(0,properties.length);
+ }
+
+ /**
+ * Tests the whole execution of the builder.
+ */
+ @SuppressWarnings("unchecked")
+ public void testBuildOK() throws Exception
+ {
+ MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+ QpidDomainObject mbean = new QpidDomainObject();
+ server.registerMBean(mbean, _objectName);
+
+ _builder.begin(_objectName);
+
+ CtClass definition = _builder._capabilityClassDefinition;
+ assertEquals(
+ MBeanCapability.class.getName(),
+ definition.getSuperclass().getName());
+
+ MBeanInfo metadata = server.getMBeanInfo(_objectName);
+
+ for (MBeanAttributeInfo attribute : metadata.getAttributes())
+ {
+ _builder.onAttribute(attribute);
+ checkAttribute(attribute, definition);
+
+ assertSame(
+ _builder._endAttributeHandler,
+ _builder._atLeastThereIsOneProperty);
+ }
+
+ for (MBeanOperationInfo operation : metadata.getOperations())
+ {
+ _builder.onOperation(operation);
+ checkOperation(operation,definition);
+ }
+
+ _builder.endAttributes();
+ _builder.endOperations();
+
+ assertNotNull(_builder.getCapabilityClass());
+ }
+
+ /**
+ * Checks an operation / method after that it has been declared on
+ * capability definition.
+ *
+ * @param operation the (JMX) operation metadata.
+ * @param definition the capability class definition.
+ * @throws Exception when something goes wrong during introspection.
+ */
+ private void checkOperation(MBeanOperationInfo operation, CtClass definition) throws Exception
+ {
+ CtMethod method = definition.getDeclaredMethod(operation.getName());
+ assertNotNull(method);
+
+ checkExceptionTypes(
+ method.getExceptionTypes(),
+ new String[]{
+ QManFault.class.getName(),
+ EntityInstanceNotFoundFault.class.getName(),
+ MethodInvocationFault.class.getName()});
+
+ assertEquals(Result.class.getName(),method.getReturnType().getName());
+
+ CtClass [] parameterTypes = method.getParameterTypes();
+ MBeanParameterInfo [] parameterMetadata = operation.getSignature();
+
+ assertEquals(parameterTypes.length, parameterMetadata.length);
+ for (int i = 0; i < parameterMetadata.length; i++)
+ {
+ assertEquals(
+ parameterTypes[i].getName(),
+ Class.forName(parameterMetadata[i].getType()).getCanonicalName());
+ }
+ }
+
+ /**
+ * Checks the exception types associated with a method.
+ *
+ * @param exceptionTypes the exception types actually thrown.
+ * @param expectedExceptionNames the expected exception types (as strings).
+ */
+ private void checkExceptionTypes(CtClass [] exceptionTypes, String [] expectedExceptionNames)
+ {
+ List<String> exceptionNames = new ArrayList<String>(exceptionTypes.length);
+ for (CtClass exception : exceptionTypes)
+ {
+ exceptionNames.add(exception.getName());
+ }
+
+ for (String expectedExceptionName : expectedExceptionNames)
+ {
+ exceptionNames.remove(expectedExceptionName);
+ }
+
+ assertTrue(exceptionNames.isEmpty());
+ }
+
+ /**
+ * Checks an attribute after that it has been declared on capability definition.
+ *
+ * @param attribute the (JMX) attribute metadata.
+ * @param definition the capability class definition.
+ * @throws Exception when something goes wrong during introspection.
+ */
+ private void checkAttribute(MBeanAttributeInfo attribute, CtClass definition) throws Exception
+ {
+ String name = _builder.getNameForAccessors(attribute.getName());
+
+ String newPropertyDeclaration =
+ new StringBuilder("new QName(Names.NAMESPACE_URI, \"")
+ .append(attribute.getName())
+ .append("\", Names.PREFIX),")
+ .toString();
+ assertTrue(_builder._properties.indexOf(newPropertyDeclaration) != -1);
+
+ if (attribute.isReadable())
+ {
+ CtMethod getter = definition.getDeclaredMethod("get"+name);
+ assertNotNull(getter);
+
+ checkExceptionTypes(
+ getter.getExceptionTypes(),
+ new String[]{
+ QManFault.class.getName(),
+ NoSuchAttributeFault.class.getName(),
+ EntityInstanceNotFoundFault.class.getName()});
+
+ assertEquals(0,getter.getParameterTypes().length);
+ assertEquals(attribute.getType(),getter.getReturnType().getName());
+ }
+
+ if (attribute.isWritable())
+ {
+ CtMethod setter = definition.getDeclaredMethod("set"+name);
+ assertNotNull(setter);
+
+ checkExceptionTypes(
+ setter.getExceptionTypes(),
+ new String[]{
+ QManFault.class.getName(),
+ NoSuchAttributeFault.class.getName(),
+ EntityInstanceNotFoundFault.class.getName()});
+
+ CtClass [] parameterTypes = setter.getParameterTypes();
+
+ assertEquals(1,parameterTypes.length);
+ assertEquals(attribute.getType(),parameterTypes[0].getName());
+ assertEquals(void.class.getName(),setter.getReturnType().getName());
+ }
+ }
+}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapabilityTest.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapabilityTest.java new file mode 100644 index 0000000000..a9a6491209 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapabilityTest.java @@ -0,0 +1,204 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm.capabilities;
+
+import java.lang.management.ManagementFactory;
+import java.net.URI;
+
+import javax.management.ObjectName;
+
+import junit.framework.TestCase;
+
+import org.apache.muse.ws.addressing.EndpointReference;
+import org.apache.muse.ws.resource.WsResource;
+import org.apache.muse.ws.resource.impl.SimpleWsResource;
+import org.apache.qpid.management.domain.handler.impl.QpidDomainObject;
+import org.apache.qpid.management.wsdm.common.EntityInstanceNotFoundFault;
+import org.apache.qpid.management.wsdm.common.NoSuchAttributeFault;
+import org.apache.qpid.management.wsdm.common.QManFault;
+
+/**
+ * Test case for MBeanCapability supertype layer..
+ *
+ * @author Andrea Gazzarini
+ */
+public class MBeanCapabilityTest extends TestCase
+{
+ private final String _typeAttributeName = "Type";
+ private final String _newTypeValue = "DomainObject";
+
+ private ObjectName _objectName;
+ private ObjectName _unknownObjectName;
+
+ private MBeanCapability _capability;
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ _objectName = new ObjectName("Test:Name=aName");
+ _unknownObjectName = new ObjectName("Test:Type=unknown");
+
+ _capability = new MBeanCapability(){
+ @Override
+ public WsResource getWsResource()
+ {
+ return new SimpleWsResource(){
+ @Override
+ public EndpointReference getEndpointReference()
+ {
+ return new EndpointReference(URI.create("http://qpid.apache.org/qman"));
+ }
+ };
+ }
+ };
+ _capability.setResourceObjectName(_objectName);
+ ManagementFactory.getPlatformMBeanServer().registerMBean(new QpidDomainObject(), _objectName);
+ }
+
+ /**
+ * Tests the execution of the getAttribute() and setAttribute() method.
+ *
+ * <br>precondition : the mbean is registered and a _capability is associated with it.
+ * <br>postcondition : the set value of the requested attribute is correctly returned.
+ */
+ public void testGetAndSetAttributeOK() throws Exception
+ {
+ Object name = _capability.getAttribute(_typeAttributeName);
+ assertNull("Name has an initial value of null so how is possibile that is not null?",name);
+
+ _capability.setAttribute(_typeAttributeName,_newTypeValue);
+
+ name = _capability.getAttribute(_typeAttributeName);
+ assertEquals("Now the name attribute must be set to \""+_newTypeValue+"\"",_newTypeValue,name);
+ }
+
+ /**
+ * Tests the execution of the getAttribute() and setAttribte() methods when an unknown attribute is given..
+ *
+ * <br>precondition : the mbean is registered, a _capability is associated with it and the requested attribute doesn't exist.
+ * <br>postcondition : an exception is thrown indicating the failure.
+ */
+ public void testNoSuchAttributeFault() throws Exception
+ {
+ // I suppose that we shouldn't have an attribute with this name...
+ String unknownAttribute = String.valueOf(System.currentTimeMillis());
+
+ try
+ {
+ _capability.getAttribute(unknownAttribute);
+ fail("An exception must be thrown here in order to indicate that the attribute is unknown.");
+ } catch(NoSuchAttributeFault expected)
+ {
+ }
+
+ try
+ {
+ _capability.setAttribute(unknownAttribute,null);
+ fail("An exception must be thrown here in order to indicate that the attribute is unknown.");
+ } catch(NoSuchAttributeFault expected)
+ {
+ }
+ }
+
+ /**
+ * Tests the execution of the setAttribute,getAttribute and invoke methods when the target mbean
+ * doesn't exists.
+ *
+ * <br>precondition : the object name associated with the capability is not pointing to an existent MBean.
+ * <br>postcondition : an exception is thrown indicating the failure.
+ */
+ public void testEntityInstanceNotFoundFault() throws Exception
+ {
+ _capability.setResourceObjectName(_unknownObjectName);
+
+ try
+ {
+ _capability.getAttribute(_typeAttributeName);
+ fail("An exception must be thrown here in order to indicate that the attribute is unknown.");
+ } catch(EntityInstanceNotFoundFault expected)
+ {
+ }
+
+ try
+ {
+ _capability.setAttribute(_typeAttributeName,_newTypeValue);
+ fail("An exception must be thrown here in order to indicate that the attribute is unknown.");
+ } catch(EntityInstanceNotFoundFault expected)
+ {
+ }
+
+ try
+ {
+ _capability.invoke("operationName", null,null);
+ fail("An exception must be thrown here in order to indicate that the attribute is unknown.");
+ } catch(EntityInstanceNotFoundFault expected)
+ {
+ }
+ }
+
+ /**
+ * Tests the execution of the setAttribute,getAttribute and invoke methods when an unknown / unexpected
+ * exception is thrown.
+ *
+ * <br>precondition : the mbean is registered and a capability is associated with it. Something
+ * unexpected happens during method invocation.
+ * <br>postcondition : an exception is thrown indicating the failure.
+ */
+ public void testQManFault() throws Exception
+ {
+ // Emulate a RuntimeException (which is the best example of uncaught exception... :) )
+ _capability.setResourceObjectName(null);
+
+ try
+ {
+ _capability.getAttribute(_typeAttributeName);
+ fail("An exception must be thrown here in order to indicate that the attribute is unknown.");
+ } catch(QManFault expected)
+ {
+ }
+
+ try
+ {
+ _capability.setAttribute(_typeAttributeName,_newTypeValue);
+ fail("An exception must be thrown here in order to indicate that the attribute is unknown.");
+ } catch(QManFault expected)
+ {
+ }
+
+ try
+ {
+ _capability.invoke("operationName", null,null);
+ fail("An exception must be thrown here in order to indicate that the attribute is unknown.");
+ } catch(QManFault expected)
+ {
+ }
+ }
+
+
+ /**
+ * Shutdown procedure for this test case.
+ */
+ @Override
+ protected void tearDown() throws Exception
+ {
+ ManagementFactory.getPlatformMBeanServer().unregisterMBean(_objectName);
+ }
+}
diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/QManAdapterCapabilityTest.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/QManAdapterCapabilityTest.java new file mode 100644 index 0000000000..648c7b2f60 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/QManAdapterCapabilityTest.java @@ -0,0 +1,81 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm.capabilities;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+import org.apache.muse.ws.notification.NotificationProducer;
+import org.apache.qpid.management.Names;
+
+import junit.framework.TestCase;
+
+/**
+ * Test case for QMan adapter capability.
+ *
+ * @author Andrea Gazzarini
+ */
+public class QManAdapterCapabilityTest extends TestCase
+{
+ /**
+ * Tests the execution of the getTopicName() method.
+ *
+ * <br>precondition : an object type is given to the method (null is allowed).
+ * <br>postcondition : according to getTopicName() specs, the name of the
+ * topic associated with the given object type must be returned.
+ */
+ public void testGetTopicName()
+ {
+ final InvocationHandler invocationHandler = new InvocationHandler(){
+
+ public Object invoke(Object proxy, Method method, Object[] args)
+ {
+ return null;
+ }
+ };
+
+ QManAdapterCapability capability = new QManAdapterCapability(){
+ @Override
+ NotificationProducer getPublisherCapability()
+ {
+ return (NotificationProducer) Proxy.newProxyInstance(
+ getClass().getClassLoader(),
+ new Class[]{NotificationProducer.class},
+ invocationHandler);
+ }
+ };
+
+ capability.createLifeCycleTopics();
+
+ assertEquals(
+ Names.EVENTS_LIFECYLE_TOPIC_NAME,
+ capability.getTopicName(Names.EVENT));
+
+ assertEquals(
+ Names.OBJECTS_LIFECYLE_TOPIC_NAME,
+ capability.getTopicName(Names.CLASS));
+
+ assertEquals(
+ Names.UNKNOWN_OBJECT_TYPE_LIFECYLE_TOPIC_NAME,
+ capability.getTopicName("This is an unknown object Type @#!--!!@#"));
+ }
+}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/RmdBuilderTest.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/RmdBuilderTest.java new file mode 100644 index 0000000000..77cda1c2c1 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/capabilities/RmdBuilderTest.java @@ -0,0 +1,110 @@ +/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.qpid.management.wsdm.capabilities;
+
+import java.lang.management.ManagementFactory;
+
+import javax.management.MBeanAttributeInfo;
+import javax.management.MBeanInfo;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+
+import org.apache.qpid.management.Names;
+import org.apache.qpid.management.domain.handler.impl.QpidDomainObject;
+import org.w3c.dom.Element;
+
+import junit.framework.TestCase;
+
+/**
+ * Test case for Resource Metadata Descriptor Builder.
+ *
+ * @author Andrea Gazzarini
+ */
+public class RmdBuilderTest extends TestCase
+{
+ private MBeanInfo _metadata;
+ private RmdBuilder _builder;
+ private ObjectName _objectName;
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+ _objectName = new ObjectName("Test:Name=QpidDomainObject");
+
+ server.registerMBean(new QpidDomainObject(), _objectName);
+ _metadata = server.getMBeanInfo(_objectName);
+
+ _builder = new RmdBuilder();
+ _builder.begin(_objectName);
+
+ assertEquals(_objectName,_builder._objectName);
+ }
+
+ /**
+ * Tests the execution of the onOperation() method.
+ */
+ public void testOnOperation() throws Exception
+ {
+ MBeanAttributeInfo [] attributes = _metadata.getAttributes();
+ for (MBeanAttributeInfo attribute : attributes)
+ {
+ _builder.onAttribute(attribute);
+ }
+
+ Element [] rmd = _builder.getResourceMetadataDescriptor();
+
+ assertEquals(attributes.length,rmd.length);
+
+ for (MBeanAttributeInfo attribute: _metadata.getAttributes())
+ {
+ Element propertyMetadataDescriptor = getPropertyMetadatDescriptor(attribute.getName(), rmd);
+
+ String modifiability = propertyMetadataDescriptor.getAttribute(Names.MODIFIABILITY);
+ String expectedValue =
+ attribute.isWritable()
+ ? Names.READ_WRITE
+ : Names.READ_ONLY;
+ assertEquals(expectedValue,modifiability);
+ }
+ }
+
+ /**
+ * Returns the property metadata descriptor associated with the given attribute name.
+ *
+ * @param name the attribute name.
+ * @param rmd the resource metadata descriptor.
+ * @return the property metadata descriptor associated with the given attribute name.
+ * @throws RuntimeException if metadata for the given attribute is not found.
+ */
+ private Element getPropertyMetadatDescriptor(String name, Element [] rmd)
+ {
+ for (Element propertyMetadataDescriptor : rmd)
+ {
+ if ((Names.PREFIX+":"+name).equals(
+ propertyMetadataDescriptor.getAttribute(Names.NAME_ATTRIBUTE)))
+ {
+ return propertyMetadataDescriptor;
+ }
+ }
+ throw new RuntimeException("Property MetadataDescriptor not found for attribute "+name);
+ }
+}
\ No newline at end of file diff --git a/java/management/client/src/test/java/org/apache/qpid/management/wsdm/web.xml b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/web.xml new file mode 100644 index 0000000000..df273bd841 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/web.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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. + +--> + +<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> + <servlet> + <display-name>Qpid emulator startip</display-name> + <servlet-name>QEmu</servlet-name> + <servlet-class>org.apache.qpid.management.wsdm.QEmuInitializer</servlet-class> + <load-on-startup>1</load-on-startup> + </servlet> +</web-app> |
