From 244c8e31c6073d7db5b79cccf1decba830a0c85e Mon Sep 17 00:00:00 2001 From: Andrea Gazzarini Date: Thu, 26 Feb 2009 13:52:33 +0000 Subject: QPID-1579 : Instead of having one huge WSDM test case now WS-DM Adapter test is a suite that contains different test cases ( one for each interface) git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk/qpid@748154 13f79535-47bb-0310-9956-ffa450edef68 --- java/management/client/build.xml | 6 +- .../example/ConsumerAndProducerExample.java | 47 +- java/management/client/src/main/java/muse.xml | 2 +- .../java/org/apache/qpid/management/Messages.java | 2 +- .../java/org/apache/qpid/management/Names.java | 4 +- .../configuration/AccessModeMapping.java | 83 -- .../management/configuration/Configuration.java | 94 +- .../management/configuration/Configurator.java | 45 - .../qpid/management/configuration/TypeMapping.java | 90 -- .../qpid/management/domain/model/JmxService.java | 28 +- .../qpid/management/domain/services/QMan.java | 86 +- .../qpid/management/wsdm/QEmuInitializer.java | 8 +- .../management/wsdm/capabilities/Constants.java | 44 + .../wsdm/capabilities/ConsumerCapability.java | 2 + .../wsdm/capabilities/DummyCapabilityBuilder.java | 37 +- .../wsdm/capabilities/MBeanCapability.java | 5 +- .../wsdm/capabilities/MBeanCapabilityBuilder.java | 8 + .../QManMetadataExchangeCapability.java | 36 + .../management/wsdm/capabilities/RmdBuilder.java | 3 +- .../wsdm/capabilities/WSDMArtifactsDirector.java | 5 +- .../wsdm/capabilities/WsArtifactsFactory.java | 9 +- .../management/wsdm/capabilities/WsdlBuilder.java | 414 ++++----- .../wsdm/common/EntityInstanceNotFoundFault.java | 5 +- .../qpid/management/wsdm/common/ThreadSession.java | 8 +- .../wsdm/muse/engine/WSDMAdapterEnvironment.java | 15 + .../client/src/main/java/wsdl/QManWsResource.wsdl | 30 +- .../main/java/wsdl/WS-ServiceGroupEntry-1_2.wsdl | 2 +- .../org/apache/qpid/management/TestConstants.java | 2 +- .../configuration/ConfigurationTest.java | 39 +- .../management/wsdm/BaseWsDmAdapterTestCase.java | 185 ++++ .../GetMultipleResourcePropertiesTestCase.java | 126 +++ .../wsdm/GetResourcePropertyDocumentTestCase.java | 134 +++ .../wsdm/MetadataExchangeInterfaceTestCase.java | 143 +++ .../wsdm/OperationInvocationInterfaceTestCase.java | 597 +++++++++++++ .../wsdm/SetResourcePropertiesTestCase.java | 221 +++++ .../qpid/management/wsdm/WsDmAdapterTest.java | 974 +-------------------- 36 files changed, 1987 insertions(+), 1552 deletions(-) delete mode 100644 java/management/client/src/main/java/org/apache/qpid/management/configuration/AccessModeMapping.java delete mode 100644 java/management/client/src/main/java/org/apache/qpid/management/configuration/TypeMapping.java create mode 100644 java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/Constants.java create mode 100644 java/management/client/src/test/java/org/apache/qpid/management/wsdm/BaseWsDmAdapterTestCase.java create mode 100644 java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetMultipleResourcePropertiesTestCase.java create mode 100644 java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetResourcePropertyDocumentTestCase.java create mode 100644 java/management/client/src/test/java/org/apache/qpid/management/wsdm/MetadataExchangeInterfaceTestCase.java create mode 100644 java/management/client/src/test/java/org/apache/qpid/management/wsdm/OperationInvocationInterfaceTestCase.java create mode 100644 java/management/client/src/test/java/org/apache/qpid/management/wsdm/SetResourcePropertiesTestCase.java (limited to 'java') diff --git a/java/management/client/build.xml b/java/management/client/build.xml index 6543a569ee..729c15e2a6 100644 --- a/java/management/client/build.xml +++ b/java/management/client/build.xml @@ -25,7 +25,6 @@ - @@ -49,7 +48,6 @@ - @@ -59,6 +57,8 @@ + + @@ -195,7 +195,7 @@ - + diff --git a/java/management/client/src/example/org/apache/qpid/management/example/ConsumerAndProducerExample.java b/java/management/client/src/example/org/apache/qpid/management/example/ConsumerAndProducerExample.java index 93e78707e9..9b4a24e2ae 100644 --- a/java/management/client/src/example/org/apache/qpid/management/example/ConsumerAndProducerExample.java +++ b/java/management/client/src/example/org/apache/qpid/management/example/ConsumerAndProducerExample.java @@ -26,7 +26,9 @@ import java.util.Date; import org.apache.muse.util.xml.XPathUtils; import org.apache.muse.ws.addressing.EndpointReference; import org.apache.muse.ws.addressing.soap.SoapFault; +import org.apache.muse.ws.notification.impl.FilterCollection; import org.apache.muse.ws.notification.impl.MessagePatternFilter; +import org.apache.muse.ws.notification.impl.ProducerPropertiesFilter; import org.apache.muse.ws.notification.impl.TopicFilter; import org.apache.muse.ws.notification.remote.NotificationProducerClient; import org.apache.qpid.management.Names; @@ -93,8 +95,11 @@ public class ConsumerAndProducerExample extends AbstractQManExample // Example 6: a MessageFilter is installed in order to listen only for connection events // (connections created or removed). The subscription will expire in 10 seconds. allMessagesWithMessageFilterAndTerminationTime(producerEPR,consumerEPR); + + // Example 7 : a subscription with more than one filter. + complexSubscription(producerEPR, consumerEPR); } - + /** * Makes a subscription on all topics / all messages without an expiry date. * @@ -223,6 +228,41 @@ public class ConsumerAndProducerExample extends AbstractQManExample new Date(System.currentTimeMillis() + 10000)); // Termination Time } + /** + * Makes a subscription on a specifc topic with an expiry date. + * Only messages published on the given topic will be delivered to the given consumer. + * The subscription will end after 10 seconds + * + * @param producer the producer endpoint reference. + * @param consumer the consumer endpoint reference . + * @throws SoapFault when the subscription cannot be made. + */ + private void complexSubscription(EndpointReference producer, EndpointReference consumer) throws SoapFault + { + NotificationProducerClient producerClient = new NotificationProducerClient(producer); + producerClient.setTrace(true); + + FilterCollection filter = new FilterCollection(); + + TopicFilter topicFilter = new TopicFilter(Names.EVENTS_LIFECYLE_TOPIC_NAME); + MessagePatternFilter messageFilter= new MessagePatternFilter( + "/wsnt:NotificationMessage/wsnt:Message/qman:LifeCycleEvent/qman:Resource/qman:Name/text()='connection'", // expression (XPath) + XPathUtils.NAMESPACE_URI); // Dialect : the only supported dialect is XPath 1.0 + + ProducerPropertiesFilter producerFilter = new ProducerPropertiesFilter( + "boolean(/*/MgtPubInterval > 100 and /*/MsgTotalEnqueues > 56272)", + XPathUtils.NAMESPACE_URI); + + filter.addFilter(topicFilter); + filter.addFilter(messageFilter); + filter.addFilter(producerFilter); + + producerClient.subscribe( + consumer, // Consumer Endpoint reference + filter, // Topic Filter + new Date(System.currentTimeMillis() + 10000)); // Termination Time + } + @Override void printOutExampleDescription() { @@ -245,4 +285,9 @@ public class ConsumerAndProducerExample extends AbstractQManExample System.out.println("A subscription with a termination time will have a predefined expiry"); System.out.println("date while if there's no termination the subscription will never expire."); } + + public static void main(String[] args) + { + new ConsumerAndProducerExample().execute(new String[]{"localhost","8080"}); + } } diff --git a/java/management/client/src/main/java/muse.xml b/java/management/client/src/main/java/muse.xml index d2f499cef9..cf651c34ac 100644 --- a/java/management/client/src/main/java/muse.xml +++ b/java/management/client/src/main/java/muse.xml @@ -29,7 +29,7 @@ org.apache.qpid.management.wsdm.muse.serializer.DateSerializer - org.apache.muse.core.routing.SimpleResourceRouter + org.apache.muse.ws.resource.impl.WsResourceRouter log/muse.log SEVERE diff --git a/java/management/client/src/main/java/org/apache/qpid/management/Messages.java b/java/management/client/src/main/java/org/apache/qpid/management/Messages.java index 3d208835f0..4f84128fb3 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/Messages.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/Messages.java @@ -170,6 +170,6 @@ public interface Messages String QMAN_100037_INVOKE_OPERATION_FAILURE = " : Operation Invocation failure for operation."; String QMAN_100038_UNABLE_TO_SEND_WS_NOTIFICATION = " : Unable to send notification."; String QMAN_100039_UNABLE_TO_CONFIGURE_PROPERLY_WORKER_MANAGER = " : Unable to properly configure WorkManager. A malformed property (NaN) was given as input parameter."; - + String QMAN_100040_UNABLE_TO_LOCATE_WSRP_PROPERTIES = " : Unable to evaluate the WSRP XPath expression on resource WSDL."; } \ No newline at end of file diff --git a/java/management/client/src/main/java/org/apache/qpid/management/Names.java b/java/management/client/src/main/java/org/apache/qpid/management/Names.java index 808cafb6a7..d3ce711d5d 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/Names.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/Names.java @@ -45,7 +45,7 @@ public abstract class Names public static String CLASS = "class"; public static String EVENT = "event"; public static String OBJECT_ID="objectId"; - public static String BROKER_ID = "brokerID"; + public static String BROKER_ID = "brokerId"; public static String DOMAIN_NAME = "Q-MAN"; public static String ARG_COUNT_PARAM_NAME = "argCount"; @@ -86,7 +86,7 @@ public abstract class Names new StringBuilder() .append(DOMAIN_NAME) .append(':') - .append("Type=Service") + .append("Name=QMan,Type=Service") .toString()); } catch(Exception exception) { diff --git a/java/management/client/src/main/java/org/apache/qpid/management/configuration/AccessModeMapping.java b/java/management/client/src/main/java/org/apache/qpid/management/configuration/AccessModeMapping.java deleted file mode 100644 index af6aaa36bf..0000000000 --- a/java/management/client/src/main/java/org/apache/qpid/management/configuration/AccessModeMapping.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * - * 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 org.apache.qpid.management.domain.model.AccessMode; - -/** - * Class used to encapsulate a mapping between an access mode and a code. - * - * @author Andrea Gazzarini - */ -class AccessModeMapping -{ - private final int _code; - private final AccessMode _accessMode; - - /** - * Builds a new access mode mapping with the given parameters. - * - * @param code the access code. - * @param accessMode the access mode. - */ - AccessModeMapping(int code, AccessMode accessMode) - { - this._code = code; - this._accessMode = accessMode; - } - - /** - * Returns the access mode of this mapping. - * - * @return the access mode of this mapping. - */ - AccessMode getAccessMode () - { - return _accessMode; - } - - /** - * Returns the code of this mapping. - * - * @return the code of this mapping. - */ - int getCode () - { - return _code; - } - - /** - * Returns a string representation of this mapping. - * The returned string is indicating the code and the corresponding access mode. - * - * @return a string representation of this mapping. - */ - @Override - public String toString () - { - return new StringBuilder() - .append("AccessMode mapping (") - .append(_code) - .append(',') - .append(_accessMode) - .append(')').toString(); - } -} diff --git a/java/management/client/src/main/java/org/apache/qpid/management/configuration/Configuration.java b/java/management/client/src/main/java/org/apache/qpid/management/configuration/Configuration.java index c9d45c5023..51dc62f4fa 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/configuration/Configuration.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/configuration/Configuration.java @@ -30,7 +30,16 @@ import org.apache.qpid.management.Messages; import org.apache.qpid.management.Names; import org.apache.qpid.management.domain.handler.base.IMessageHandler; 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.Type; +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.apache.qpid.transport.DeliveryProperties; import org.apache.qpid.transport.Header; import org.apache.qpid.transport.MessageProperties; @@ -71,7 +80,12 @@ public final class Configuration private Configuration() { defineQueueNames(); + createHeaderForCommandMessages(); + + addAccessModeMappings(); + + addTypeMappings(); } void clean() @@ -90,9 +104,11 @@ public final class Configuration } /** - * Returns true if this configuration has at least one broker connection data. + * Returns true if this configuration has at least + * one broker configured. * - * @return true if this configuration has at least one broker connection data. + * @return true if this configuration has at least one + * broker configured. */ public boolean hasOneOrMoreBrokersDefined() { @@ -245,26 +261,46 @@ public final class Configuration /** * Adds a new type mapping to this configuration. * - * @param mapping the type mapping that will be added. + * @param code the code that will be associated with the declared type. + * @param type the type. + * @param vailidatorClassName the FQN of the validator class that will be + * associated with the given type. */ - void addTypeMapping(TypeMapping mapping) { - int code = mapping.getCode(); - Type type = mapping.getType(); - String validatorClassName = mapping.getValidatorClassName(); - _typeMappings.put(code, type); + void addTypeMapping(int code, Type type, String validatorClassName) { + _typeMappings.put(code, type); _validators.put(type, validatorClassName); - LOGGER.info(Messages.QMAN_000005_TYPE_MAPPING_CONFIGURED, code,type,validatorClassName); + LOGGER.info( + Messages.QMAN_000005_TYPE_MAPPING_CONFIGURED, + code, + type, + validatorClassName); } - + + + /** + * Adds a new type mapping to this configuration. + * + * @param code the code that will be associated with the declared type. + * @param type the type. + */ + void addTypeMapping(int code, Type type) { + _typeMappings.put(code, type); + + LOGGER.info( + Messages.QMAN_000005_TYPE_MAPPING_CONFIGURED, + code, + type, + "not configured for this type."); + } + /** * Adds a new access mode mapping to this configuration. * - * @param mapping the mapping that will be added. + * @param code the code that will be associated with the access mode, + * @param accessMode the accessMode. */ - void addAccessModeMapping(AccessModeMapping mapping){ - int code = mapping.getCode(); - AccessMode accessMode = mapping.getAccessMode(); + void addAccessModeMapping(int code, AccessMode accessMode){ _accessModes.put(code, accessMode); LOGGER.info(Messages.QMAN_000006_ACCESS_MODE_MAPPING_CONFIGURED, code,accessMode); @@ -420,4 +456,34 @@ public final class Configuration { this._keepAliveTime = keepAliveTime; } + + /** + * Configures access mode mappings. + * An access mode mapping is an association between a code and an access mode. + */ + private void addAccessModeMappings() { + addAccessModeMapping(1,AccessMode.RC); + addAccessModeMapping(2,AccessMode.RW); + addAccessModeMapping(3,AccessMode.RO); + } + + /** + * Configures type mappings. + * A type mapping is an association between a code and a management type. + */ + private void addTypeMappings() + { + addTypeMapping(1,new Uint8(),Names.NUMBER_VALIDATOR); + addTypeMapping(2,new Uint16(),Names.NUMBER_VALIDATOR); + addTypeMapping(3,new Uint32(),Names.NUMBER_VALIDATOR); + addTypeMapping(4,new Uint64(),Names.NUMBER_VALIDATOR); + addTypeMapping(6,new Str8(),Names.STRING_VALIDATOR); + addTypeMapping(7,new Str16(),Names.STRING_VALIDATOR); + addTypeMapping(8,new AbsTime()); + addTypeMapping(9,new DeltaTime()); + addTypeMapping(10,new ObjectReference()); + addTypeMapping(11,new org.apache.qpid.management.domain.model.type.Boolean()); + addTypeMapping(14,new org.apache.qpid.management.domain.model.type.Uuid()); + addTypeMapping(15,new org.apache.qpid.management.domain.model.type.Map()); + } } \ No newline at end of file diff --git a/java/management/client/src/main/java/org/apache/qpid/management/configuration/Configurator.java b/java/management/client/src/main/java/org/apache/qpid/management/configuration/Configurator.java index 1cde9d5f88..fe44c6aff7 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/configuration/Configurator.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/configuration/Configurator.java @@ -38,16 +38,6 @@ import org.apache.qpid.management.domain.handler.impl.HeartBeatIndicationMessage 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.apache.qpid.transport.util.Logger; import org.xml.sax.Attributes; import org.xml.sax.InputSource; @@ -148,9 +138,6 @@ public class Configurator extends DefaultHandler } } - addTypeMappings(); - addAccessModeMappings(); - addMandatoryManagementMessageHandlers(); addMandatoryMethodReplyMessageHandlers(); } catch (Exception exception) @@ -209,38 +196,6 @@ public class Configurator extends DefaultHandler return data; } - /** - * Configures access mode mappings. - * An access mode mapping is an association between a code and an access mode. - */ - private void addAccessModeMappings() { - Configuration configuration = Configuration.getInstance(); - configuration.addAccessModeMapping(new AccessModeMapping(1,AccessMode.RC)); - configuration.addAccessModeMapping(new AccessModeMapping(2,AccessMode.RW)); - configuration.addAccessModeMapping(new AccessModeMapping(3,AccessMode.RO)); - } - - /** - * Configures type mappings. - * A type mapping is an association between a code and a management type. - */ - private void addTypeMappings() - { - Configuration configuration = Configuration.getInstance(); - configuration.addTypeMapping(new TypeMapping(1,new Uint8(),Names.NUMBER_VALIDATOR)); - configuration.addTypeMapping(new TypeMapping(2,new Uint16(),Names.NUMBER_VALIDATOR)); - configuration.addTypeMapping(new TypeMapping(3,new Uint32(),Names.NUMBER_VALIDATOR)); - configuration.addTypeMapping(new TypeMapping(4,new Uint64(),Names.NUMBER_VALIDATOR)); - configuration.addTypeMapping(new TypeMapping(6,new Str8(),Names.STRING_VALIDATOR)); - configuration.addTypeMapping(new TypeMapping(7,new Str16(),Names.STRING_VALIDATOR)); - configuration.addTypeMapping(new TypeMapping(8,new AbsTime())); - configuration.addTypeMapping(new TypeMapping(9,new DeltaTime())); - configuration.addTypeMapping(new TypeMapping(10,new ObjectReference())); - configuration.addTypeMapping(new TypeMapping(11,new org.apache.qpid.management.domain.model.type.Boolean())); - configuration.addTypeMapping(new TypeMapping(14,new org.apache.qpid.management.domain.model.type.Uuid())); - configuration.addTypeMapping(new TypeMapping(15,new org.apache.qpid.management.domain.model.type.Map())); - } - /** * Configures the mandatory management message handlers. */ diff --git a/java/management/client/src/main/java/org/apache/qpid/management/configuration/TypeMapping.java b/java/management/client/src/main/java/org/apache/qpid/management/configuration/TypeMapping.java deleted file mode 100644 index 2c0a460c1a..0000000000 --- a/java/management/client/src/main/java/org/apache/qpid/management/configuration/TypeMapping.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * - * 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 org.apache.qpid.management.domain.model.type.Type; - -/** - * Type Mapping used for associating a code with a management type. - * - * @author Andrea Gazzarini - */ -class TypeMapping -{ - private final int _code; - private final Type _type; - private final String _validatorClass; - - /** - * Builds a new type mapping with the given parameters and no validator. - * - * @param code the code. - * @param type the management type. - */ - TypeMapping(int code, Type type) - { - this(code,type,null); - } - - /** - * Builds a new type mapping with the given parameters. - * - * @param code the code. - * @param type the management type. - * @param validatorClassName the class name of the validator to be used. - */ - TypeMapping(int code, Type type, String validatorClassName) - { - this._code = code; - this._type = type; - this._validatorClass = validatorClassName; - } - - /** - * Returns the code of this mapping. - * - * @return the code of this mapping. - */ - int getCode () - { - return _code; - } - - /** - * Returns the type for this mapping. - * - * @return the type for this mapping. - */ - Type getType () - { - return _type; - } - - /** - * Returns the validator class of this mapping. - * - * @return the validator class (as a string) of this mapping. - */ - public String getValidatorClassName() - { - return _validatorClass; - } -} diff --git a/java/management/client/src/main/java/org/apache/qpid/management/domain/model/JmxService.java b/java/management/client/src/main/java/org/apache/qpid/management/domain/model/JmxService.java index 176cec451e..657d7e6210 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/domain/model/JmxService.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/domain/model/JmxService.java @@ -54,11 +54,10 @@ public class JmxService */ public void registerQManService(QMan qman) throws MBeanException { - ObjectName name = createQManName(); - if (!_mxServer.isRegistered(name)) + if (!_mxServer.isRegistered(Names.QMAN_OBJECT_NAME)) { try { - _mxServer.registerMBean(qman, name); + _mxServer.registerMBean(qman, Names.QMAN_OBJECT_NAME); } catch (Exception exception) { throw new MBeanException(exception); } @@ -358,27 +357,6 @@ public class JmxService throw new RuntimeException(exception); } } - - /** - * Creates the QMan object name. - * - * @return the QMan object name. - */ - private ObjectName createQManName() - { - String asString = new StringBuilder() - .append(Names.DOMAIN_NAME) - .append(':') - .append("Type=Service") - .toString(); - try - { - return new ObjectName(asString); - } catch (MalformedObjectNameException exception) - { - throw new RuntimeException(exception); - } - } ObjectName createEntityDefinitionName(String packageName, String className, String type) { @@ -407,7 +385,7 @@ public class JmxService { if (!_mxServer.isRegistered(name)) _mxServer.registerMBean(entity, name); - _mxServer.addNotificationListener(name, createQManName(), null, null); + _mxServer.addNotificationListener(name, Names.QMAN_OBJECT_NAME, null, null); } catch(Exception exception) { throw new RuntimeException(exception); diff --git a/java/management/client/src/main/java/org/apache/qpid/management/domain/services/QMan.java b/java/management/client/src/main/java/org/apache/qpid/management/domain/services/QMan.java index d124593472..c4c0ce5e74 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/domain/services/QMan.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/domain/services/QMan.java @@ -26,6 +26,9 @@ import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.UUID; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import javax.management.Attribute; import javax.management.AttributeList; @@ -45,6 +48,7 @@ import org.apache.qpid.management.Names; import org.apache.qpid.management.configuration.BrokerAlreadyConnectedException; import org.apache.qpid.management.configuration.BrokerConnectionData; import org.apache.qpid.management.configuration.BrokerConnectionException; +import org.apache.qpid.management.configuration.Configuration; import org.apache.qpid.management.configuration.Configurator; import org.apache.qpid.management.domain.model.JmxService; import org.apache.qpid.transport.util.Logger; @@ -58,6 +62,7 @@ public class QMan extends NotificationBroadcasterSupport implements DynamicMBean private final List managementClients = new ArrayList(); private Configurator _configurator = new Configurator(); + private ThreadPoolExecutor _workManager; /** * Starts QMan. @@ -74,6 +79,8 @@ public class QMan extends NotificationBroadcasterSupport implements DynamicMBean _configurator.configure(); + configureWorkManager(); + LOGGER.info(Messages.QMAN_000019_QMAN_STARTED); } catch(Exception exception) { LOGGER.error(exception,Messages.QMAN_100018_UNABLE_TO_STARTUP_CORRECTLY ); @@ -143,6 +150,36 @@ public class QMan extends NotificationBroadcasterSupport implements DynamicMBean LOGGER.info(Messages.QMAN_000021_SHUT_DOWN); } + /** + * Creates a management client using the given data. + * + * @param brokerId the broker identifier. + * @param data the broker connection data. + */ + public void createManagementClient(UUID brokerId, BrokerConnectionData data) + { + try + { + ManagementClient client = new ManagementClient(brokerId,data); + client.estabilishFirstConnectionWithBroker(); + managementClients.add(client); + + LOGGER.info(Messages.QMAN_000004_MANAGEMENT_CLIENT_CONNECTED,brokerId); + } catch(StartupFailureException exception) { + LOGGER.error(exception, Messages.QMAN_100017_UNABLE_TO_CONNECT,brokerId,data); + } + } + + /** + * Returns the list of management clients currently handled by QMan. + * + * @return the list of management clients currently handled by QMan. + */ + public List getManagementClients() + { + return managementClients; + } + /** * Injects the configurator on this QMan instance. * That configutator later will be responsible to manage the configuration. @@ -330,13 +367,20 @@ public class QMan extends NotificationBroadcasterSupport implements DynamicMBean /** * Simply dispatches the incoming notification to registered listeners. + * Consider that the notification is sent asynchronously so the QMan current thread is not + * waiting for completion of receiver task. * * @param notification the incoming notification. * @param handback the context associated to this notification. */ - public void handleNotification(Notification notification, Object handback) + public void handleNotification(final Notification notification, Object handback) { - sendNotification(notification); + _workManager.execute(new Runnable(){ + public void run() + { + sendNotification(notification); + } + }); } /** @@ -352,33 +396,17 @@ public class QMan extends NotificationBroadcasterSupport implements DynamicMBean LOGGER.info(Messages.QMAN_000023_QMAN_REGISTERED_AS_MBEAN); } - /** - * Creates a management client using the given data. - * - * @param brokerId the broker identifier. - * @param data the broker connection data. - */ - public void createManagementClient(UUID brokerId, BrokerConnectionData data) - { - try - { - ManagementClient client = new ManagementClient(brokerId,data); - client.estabilishFirstConnectionWithBroker(); - managementClients.add(client); - - LOGGER.info(Messages.QMAN_000004_MANAGEMENT_CLIENT_CONNECTED,brokerId); - } catch(StartupFailureException exception) { - LOGGER.error(exception, Messages.QMAN_100017_UNABLE_TO_CONNECT,brokerId,data); - } - } - /** - * Returns the list of management clients currently handled by QMan. - * - * @return the list of management clients currently handled by QMan. + * Configures work manager component. */ - public List getManagementClients() - { - return managementClients; - } + private void configureWorkManager() + { + Configuration configuration = Configuration.getInstance(); + _workManager = new ThreadPoolExecutor( + configuration.getWorkerManagerPoolSize(), + configuration.getWorkerManagerMaxPoolSize(), + configuration.getWorkerManagerKeepAliveTime(), + TimeUnit.MILLISECONDS, + new ArrayBlockingQueue(30)); + } } diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/QEmuInitializer.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/QEmuInitializer.java index 545e587f79..47aa4ea681 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/QEmuInitializer.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/QEmuInitializer.java @@ -57,7 +57,9 @@ public class QEmuInitializer extends HttpServlet Names.QPID_EMULATOR_OBJECT_NAME); } catch(Exception exception) { - LOGGER.warn(exception,Messages.QMAN_300005_QEMU_INITIALIZATION_FAILURE); + LOGGER.warn( + exception, + Messages.QMAN_300005_QEMU_INITIALIZATION_FAILURE); throw new ServletException(exception); } } @@ -84,8 +86,8 @@ public class QEmuInitializer extends HttpServlet { try { - ManagementFactory.getPlatformMBeanServer() - .unregisterMBean(Names.QPID_EMULATOR_OBJECT_NAME); + ManagementFactory.getPlatformMBeanServer().unregisterMBean( + Names.QPID_EMULATOR_OBJECT_NAME); } catch (Exception exception) { } diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/Constants.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/Constants.java new file mode 100644 index 0000000000..59a5801505 --- /dev/null +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/Constants.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.wsdm.capabilities; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; + +public interface Constants +{ + String WSRP_PROPERTIES_XPATH = "/wsdl:definitions/wsdl:types/xsd:schema[" + + "@targetNamespace='http://amqp.apache.org/qpid/management/qman']" + + "/xsd:element[@name='QManWsResourceProperties']/xsd:complexType/xsd:sequence"; + + String SERVICE_LOCATION_XPATH = "/wsdl:definitions/wsdl:service/wsdl:port/wsdl-soap:address/@location"; + String QMAN_SCHEMA_XPATH = "/wsdl:definitions/wsdl:types/xsd:schema[@targetNamespace='http://amqp.apache.org/qpid/management/qman']"; + + String MIN_OCCURS = "minOccurs"; + String REF_ATTRIBUTE = "ref"; + String NAME_ATTRIBUTE = "name"; + String TYPE_ATTRIBUTE ="type"; + + QName XSD_ELEMENT_QNAME = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI,"element","xsd"); + QName XSD_COMPLEX_TYPE_QNAME = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI,"complexType","xsd"); + QName XSD_SEQUENCE_QNAME = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI,"sequence","xsd"); + +} \ No newline at end of file diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/ConsumerCapability.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/ConsumerCapability.java index dd5eb523c1..bde98092a0 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/ConsumerCapability.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/ConsumerCapability.java @@ -29,6 +29,8 @@ import org.apache.muse.ws.notification.WsnConstants; /** * WS-Notifications consumer capability. + * At the moment QMan is not a consumer of itself so this capability is here only + * for test purposes. * * @author Andrea Gazzarini */ diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/DummyCapabilityBuilder.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/DummyCapabilityBuilder.java index 0676b4ac49..370cf3086d 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/DummyCapabilityBuilder.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/DummyCapabilityBuilder.java @@ -29,32 +29,57 @@ import org.apache.muse.core.Environment; /** * Dummy capability builder used for avoid duplicated builds for the * same class. + * Basically it acts likes a Null Object when the target capability class has been + * already built. * * @author Andrea Gazzarini */ public class DummyCapabilityBuilder implements IArtifactBuilder { - - public void begin(ObjectName objectName) throws BuilderException + /** + * Director callback. + * Do nothing here (see class comments above.) + */ + public void begin(ObjectName objectName) { } - public void endAttributes() throws BuilderException + /** + * Director callback. + * Do nothing here (see class comments above.) + */ + public void endAttributes() { } - public void endOperations() throws BuilderException + /** + * Director callback. + * Do nothing here (see class comments above.) + */ + public void endOperations() { } - public void onAttribute(MBeanAttributeInfo attributeMetadata) throws BuilderException + /** + * Director callback. + * Do nothing here (see class comments above.) + */ + public void onAttribute(MBeanAttributeInfo attributeMetadata) { } - public void onOperation(MBeanOperationInfo operationMetadata) throws BuilderException + /** + * Director callback. + * Do nothing here (see class comments above.) + */ + public void onOperation(MBeanOperationInfo operationMetadata) { } + /** + * Director callback. + * Do nothing here (see class comments above.) + */ public void setEnvironment(Environment environment) { } diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapability.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapability.java index 82d8e97d37..b3ce0f0587 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapability.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapability.java @@ -179,12 +179,11 @@ public abstract class MBeanCapability extends AbstractWsResourceCapability params, signature); - Result result = new Result( + return new Result( output.getReturnCode(), output.getStatusText(), output.getOutputSection()); - - return result; + } catch (InstanceNotFoundException exception) { throw new EntityInstanceNotFoundFault( diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapabilityBuilder.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapabilityBuilder.java index ea623138a4..ea67bdf9e1 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapabilityBuilder.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/MBeanCapabilityBuilder.java @@ -178,6 +178,14 @@ public class MBeanCapabilityBuilder implements IArtifactBuilder{ } } + /** + * Director callback. + * All attributes have been notified. + * + * This builder is using this callback in order to create the initial + * properties QNames declaration. + * + */ public void endAttributes() throws BuilderException { _endAttributeHandler.endAttributes(); diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/QManMetadataExchangeCapability.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/QManMetadataExchangeCapability.java index 7e58992540..d6255d0bed 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/QManMetadataExchangeCapability.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/QManMetadataExchangeCapability.java @@ -21,6 +21,10 @@ package org.apache.qpid.management.wsdm.capabilities; import org.apache.muse.util.xml.XmlUtils; +import org.apache.muse.ws.metadata.WsxConstants; +import org.apache.muse.ws.resource.WsResource; +import org.apache.muse.ws.resource.metadata.MetadataDescriptor; +import org.apache.muse.ws.resource.metadata.WsrmdConstants; import org.apache.muse.ws.resource.metadata.ext.WsrfMetadataExchange; import org.apache.muse.ws.wsdl.WsdlUtils; import org.apache.qpid.management.wsdm.muse.resources.QManWsResource; @@ -60,4 +64,36 @@ public class QManMetadataExchangeCapability extends WsrfMetadataExchange return wsdl; } + + /** + * Returns the resource metadata descriptor associated with the owenr + * resource of thi capability. + * + * @return the resource metadata descriptor. + */ + protected Element getResourceMetadataDescriptor() + { + WsResource resource = (WsResource)getResource(); + MetadataDescriptor metadataDescriptor = resource.getPropertyCollection().getMetadata(); + return metadataDescriptor.toXML(); + } + + public Element[] getMetadata(String dialect) + { + if (dialect == null) + { + return new Element[]{ + getResourceMetadataDescriptor(), + getWSDL()}; + } else { + if (WsrmdConstants.NAMESPACE_URI.equals(dialect)) + { + return new Element[]{getResourceMetadataDescriptor()}; + } else if (WsxConstants.WSDL_DIALECT.equals(dialect)) + { + return new Element[]{getWSDL()}; + } + } + return super.getMetadata(dialect); + } } \ No newline at end of file diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/RmdBuilder.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/RmdBuilder.java index 86aba0e5bb..c1678eb43f 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/RmdBuilder.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/RmdBuilder.java @@ -128,7 +128,8 @@ class RmdBuilder implements IArtifactBuilder */ public Element[] getResourceMetadataDescriptor() { - Element [] properties = _metadataDescriptor.toArray(new Element[0]); + Element [] properties = _metadataDescriptor.toArray( + new Element[_metadataDescriptor.size()]); return properties; } } \ No newline at end of file diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WSDMArtifactsDirector.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WSDMArtifactsDirector.java index c9ffd5eac0..35a919c295 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WSDMArtifactsDirector.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WSDMArtifactsDirector.java @@ -35,7 +35,7 @@ import org.w3c.dom.Element; * * @author Andrea Gazzarini */ -class WSDMArtifactsDirector +final class WSDMArtifactsDirector { private final ObjectName _eventSourceObjectName; private final MBeanInfo _metadata; @@ -189,7 +189,8 @@ class WSDMArtifactsDirector * * @param resource the ws resource. */ - public void setResource(Resource resource) { + public void setResource(Resource resource) + { _wsdlBuilder.setWsdlPath(resource.getWsdlPath()); } } \ No newline at end of file diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WsArtifactsFactory.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WsArtifactsFactory.java index 2a1bf059c3..94505d28f7 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WsArtifactsFactory.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WsArtifactsFactory.java @@ -105,13 +105,18 @@ class WsArtifactsFactory _cache.put(searchKey, result); - LOGGER.debug(Messages.QMAN_200040_WS_ARTIFACTS_CACHED,searchKey); + LOGGER.debug( + Messages.QMAN_200040_WS_ARTIFACTS_CACHED, + searchKey); } return result; } catch(Exception exception) { - throw new ArtifactsNotAvailableException(result,exception,objectName); + throw new ArtifactsNotAvailableException( + result, + exception, + objectName); } } diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WsdlBuilder.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WsdlBuilder.java index 02b25eb02f..6bfccda1ce 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WsdlBuilder.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WsdlBuilder.java @@ -23,20 +23,22 @@ package org.apache.qpid.management.wsdm.capabilities; import java.net.InetAddress; import java.util.HashMap; import java.util.Map; +import java.util.UUID; import javax.management.MBeanAttributeInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.ObjectName; -import javax.xml.XMLConstants; -import javax.xml.namespace.QName; +import javax.xml.transform.TransformerException; import org.apache.muse.core.Environment; +import org.apache.muse.core.serializer.SerializerRegistry; import org.apache.muse.util.ReflectUtils; import org.apache.muse.util.xml.XmlUtils; import org.apache.muse.ws.wsdl.WsdlUtils; import org.apache.qpid.management.Messages; import org.apache.qpid.management.Names; +import org.apache.qpid.management.wsdm.muse.engine.WSDMAdapterEnvironment; import org.apache.qpid.management.wsdm.muse.serializer.ObjectSerializer; import org.apache.qpid.qman.debug.WsdlDebugger; import org.apache.qpid.transport.util.Logger; @@ -49,126 +51,61 @@ import org.w3c.dom.Element; * * @author Andrea Gazzarini */ -class WsdlBuilder implements IArtifactBuilder { +class WsdlBuilder implements IArtifactBuilder,Constants { private final static Logger LOGGER = Logger.get(WsdlBuilder.class); - private Environment _environment; + private WSDMAdapterEnvironment _environment; private Document _document; private Element schema; - - private ObjectSerializer serializer = new ObjectSerializer(); - + private Element _wsrpProperties; + private ObjectSerializer _serializer; private ObjectName _objectName; - - private boolean mapTypeHasBeenDeclared; - private boolean uuidTypeHasBeenDeclared; private Map arrayTypesAlreadyDeclared = new HashMap(); + private Element _arrayComplexType; + private Element _nestedArrayType; + + /** + * For each attibute the corresponding xml type definition must be inserted on the QMan + * schema related section. + * After that, a reference to that definition must be declared on the wsrp element . + * + * @param attributeMetadata the attribute metadata. + * @throws BuilderException only if this builder wasn't able to get a reference (via XPath) + * to QMan schema section. + */ public void onAttribute(MBeanAttributeInfo attributeMetadata) throws BuilderException { try { - /* - - - - - - - - - - - - - - -*/ - schema.appendChild(defineSchemaFor(attributeMetadata.getType(), attributeMetadata.getName())); - Element wsrpProperties = (Element) XPathAPI.selectSingleNode( - _document, - "/wsdl:definitions/wsdl:types/xsd:schema[" + - "@targetNamespace='http://amqp.apache.org/qpid/management/qman']" + - "/xsd:element[@name='QManWsResourceProperties']/xsd:complexType/xsd:sequence"); + String attributeName = attributeMetadata.getName(); + schema.appendChild(defineSchemaFor(attributeMetadata.getType(), attributeName)); Element propertyRef= XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); + propertyRef.setAttribute(MIN_OCCURS, "0"); propertyRef.setAttribute( - "ref", - Names.PREFIX+":"+attributeMetadata.getName()); - propertyRef.setAttribute("minOccurs", "0"); - wsrpProperties.appendChild(propertyRef); - + REF_ATTRIBUTE, + Names.PREFIX+":"+attributeName); + + _wsrpProperties.appendChild(propertyRef); } catch(Exception exception) { throw new BuilderException(exception); } } - private final static QName XSD_ELEMENT_QNAME = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI,"element","xsd"); - private final static QName XSD_COMPLEX_TYPE_QNAME = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI,"complexType","xsd"); - private final static QName XSD_SEQUENCE_QNAME = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI,"sequence","xsd"); - @SuppressWarnings("unchecked") private Element defineSchemaFor(String type, String attributeName) throws Exception { - if (type.equals("java.util.Map")) + Element propertyDeclaration = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); + String xmlType = null; + if (type.equals(Map.class.getName())) { - if (!mapTypeHasBeenDeclared) - { - Element complexType = XmlUtils.createElement(_document, XSD_COMPLEX_TYPE_QNAME); - complexType.setAttribute("name","map"); - Element sequence = XmlUtils.createElement(_document, XSD_SEQUENCE_QNAME); - - Element entry = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); - entry.setAttribute("name", "entry"); - entry.setAttribute("minOccurs", "0"); - entry.setAttribute("maxOccurs", "unbounded"); - - Element complexType2 = XmlUtils.createElement(_document, XSD_COMPLEX_TYPE_QNAME); - Element sequence2 = XmlUtils.createElement(_document, XSD_SEQUENCE_QNAME); - - Element key = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); - key.setAttribute("name", "key"); - key.setAttribute("type", "xsd:string"); - - Element value = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); - value.setAttribute("name", "value"); - value.setAttribute("type", "xsd:anyType"); - - sequence2.appendChild(key); - sequence2.appendChild(value); - complexType2.appendChild(sequence2); - entry.appendChild(complexType2); - sequence.appendChild(entry); - complexType.appendChild(sequence); - schema.appendChild(complexType); - mapTypeHasBeenDeclared = true; - } - Element propertyDeclaration = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); - propertyDeclaration.setAttribute("name",attributeName); - propertyDeclaration.setAttribute("type", "qman:map"); - return propertyDeclaration; - - } else if ("java.util.UUID".equals(type)) - { - if (!uuidTypeHasBeenDeclared) - { - Element complexType = XmlUtils.createElement(_document, XSD_COMPLEX_TYPE_QNAME); - complexType.setAttribute("name", "uuid"); - Element sequence = XmlUtils.createElement(_document, XSD_SEQUENCE_QNAME); - Element uuid = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); - uuid.setAttribute("name", "uuid"); - uuid.setAttribute("type", "xsd:string"); - sequence.appendChild(uuid); - complexType.appendChild(sequence); - schema.appendChild(complexType); - uuidTypeHasBeenDeclared = true; - } - Element propertyDeclaration = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); - propertyDeclaration.setAttribute("name",attributeName); - propertyDeclaration.setAttribute("type", "qman:uuid"); - return propertyDeclaration; + xmlType="qman:map"; + } else if (UUID.class.getName().equals(type)) + { + xmlType = "qman:uuid"; } else if (type.startsWith("[")) { Class arrayClass = Class.forName(type); @@ -177,143 +114,40 @@ class WsdlBuilder implements IArtifactBuilder { arrayType = Character.toUpperCase(arrayType.charAt(0))+arrayType.substring(1); if (!arrayTypesAlreadyDeclared.containsKey(type)) { - Element complexType = XmlUtils.createElement(_document, XSD_COMPLEX_TYPE_QNAME); - complexType.setAttribute("name", "arrayOf"+arrayType); - Element sequence = XmlUtils.createElement(_document, XSD_SEQUENCE_QNAME); - Element entry = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); - entry.setAttribute("name", "entry"); - entry.setAttribute("type", serializer.getXmlType(clazz)); - sequence.appendChild(entry); - complexType.appendChild(sequence); - schema.appendChild(complexType); + _arrayComplexType.setAttribute(NAME_ATTRIBUTE, "arrayOf"+arrayType); + _nestedArrayType.setAttribute(TYPE_ATTRIBUTE, _serializer.getXmlType(clazz)); + schema.appendChild(_arrayComplexType); arrayTypesAlreadyDeclared.put(type, arrayType); } - Element propertyDeclaration = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); - propertyDeclaration.setAttribute("name",attributeName); - propertyDeclaration.setAttribute("type", "qman:arrayOf"+arrayTypesAlreadyDeclared.get(type)); - return propertyDeclaration; + xmlType = "qman:arrayOf"+arrayTypesAlreadyDeclared.get(type); } - else { - Element propertyDeclaration = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); - propertyDeclaration.setAttribute("name",attributeName); - propertyDeclaration.setAttribute("type", serializer.getXmlType(Class.forName(type))); - - return propertyDeclaration; + else + { + xmlType = _serializer.getXmlType(Class.forName(type)); } + propertyDeclaration.setAttribute(NAME_ATTRIBUTE,attributeName); + propertyDeclaration.setAttribute(TYPE_ATTRIBUTE, xmlType); + return propertyDeclaration; } - + + /** + * Initializes this builder. + * + * @param objectName the name of the current JMX entity. + * @throws BuilderException when it's not possible to proceed with the initialization. + */ public void begin(ObjectName objectName) throws BuilderException { this._objectName = objectName; - try - { - Attr location = (Attr) XPathAPI.selectSingleNode( - _document, - "/wsdl:definitions/wsdl:service/wsdl:port/wsdl-soap:address/@location"); - - StringBuilder builder = new StringBuilder("http://") - .append(InetAddress.getLocalHost().getHostName()) - .append(':') - .append(System.getProperty(Names.ADAPTER_PORT_PROPERTY_NAME,"8080")) - .append('/') - .append("qman") - .append('/') - .append("services/QManWsResource"); - location.setValue(builder.toString()); - } catch(Exception exception) - { - LOGGER.error( - exception, - Messages.QMAN_100026_SOAP_ADDRESS_REPLACEMENT_FAILURE); - throw new BuilderException(exception); - } - - try - { - schema = (Element) XPathAPI.selectSingleNode( - _document.getDocumentElement(), - "/wsdl:definitions/wsdl:types/xsd:schema[@targetNamespace='http://amqp.apache.org/qpid/management/qman']"); - } catch(Exception exception) - { - LOGGER.error( - exception, - Messages.QMAN_100034_WSDL_SCHEMA_SECTION_NOT_FOUND); - throw new BuilderException(exception); - } -/* - - - - - - - - - - - - - - - - - - - - - -*/ - Element complexTypeResult = _document.createElement("xsd:complexType"); - complexTypeResult.setAttribute("name", "result"); - Element sequence = _document.createElement("xsd:sequence"); - complexTypeResult.appendChild(sequence); - - Element statusCode = _document.createElement("xsd:element"); - statusCode.setAttribute("name", "statusCode"); - statusCode.setAttribute("type", "xsd:long"); - - Element statusText = _document.createElement("xsd:element"); - statusText.setAttribute("name", "statusText"); - statusText.setAttribute("type", "xsd:string"); - - sequence.appendChild(statusCode); - sequence.appendChild(statusText); - - Element outputParams = _document.createElement("xsd:complexType"); - outputParams.setAttribute("name", "outputParameters"); - sequence.appendChild(outputParams); - - Element complexTypeOutput = _document.createElement("xsd:complexType"); - Element outputSequence = _document.createElement("xsd:sequence"); + this._serializer = (ObjectSerializer) SerializerRegistry.getInstance().getSerializer(Object.class); - outputParams.appendChild(complexTypeOutput); - complexTypeOutput.appendChild(outputSequence); + createWsrpPropertiesElement(); - Element entry = _document.createElement("xsd:element"); - entry.setAttribute("maxOccurs", "unbounded"); - entry.setAttribute("minOccurs", "0"); - entry.setAttribute("name", "entry"); + createReusableArrayComplextType(); - outputSequence.appendChild(entry); + replaceDummyServiceLocationOnWsdl(); - Element entryComplexType = _document.createElement("xsd:complexType"); - Element entrySequence = _document.createElement("xsd:sequence"); - entryComplexType.appendChild(entrySequence); - entry.appendChild(entryComplexType); - - Element name = _document.createElement("xsd:name"); - name.setAttribute("name", "key"); - name.setAttribute("type", "xsd:string"); - - Element value = _document.createElement("xsd:element"); - value.setAttribute("name", "value"); - value.setAttribute("type", "xsd:anyType"); - - entrySequence.appendChild(name); - entrySequence.appendChild(value); - - schema.appendChild(complexTypeResult); + createSchemaElement(); } public void onOperation(MBeanOperationInfo operationMetadata) throws BuilderException @@ -350,9 +184,9 @@ class WsdlBuilder implements IArtifactBuilder { */ + try { - // // Element methodRequestElement= _document.createElement("xsd:element"); @@ -361,13 +195,13 @@ class WsdlBuilder implements IArtifactBuilder { methodRequestElement.setAttribute("type", "qman:"+methodNameRequest); // - Element methodResponseElement= _document.createElement("xsd:element"); +// Element methodResponseElement= _document.createElement("xsd:element"); String methodNameResponse= operationMetadata.getName()+"Response"; - methodResponseElement.setAttribute("name", methodNameResponse); - methodResponseElement.setAttribute("type", "qman:"+methodNameResponse); +// methodResponseElement.setAttribute("name", methodNameResponse); +// methodResponseElement.setAttribute("type", "qman:result");//+methodNameResponse); schema.appendChild(methodRequestElement); - schema.appendChild(methodResponseElement); +// schema.appendChild(methodResponseElement); /* @@ -391,19 +225,6 @@ class WsdlBuilder implements IArtifactBuilder { methodNameRequestComplexType.appendChild(methodNameRequestComplexTypeSequence); schema.appendChild(methodNameRequestComplexType); - Element methodNameResponseComplexType = _document.createElement("xsd:complexType"); - methodNameResponseComplexType.setAttribute("name", methodNameResponse); - - Element methodNameResponseSequence = _document.createElement("xsd:sequence"); - methodNameResponseComplexType.appendChild(methodNameResponseSequence); - - Element result = _document.createElement("xsd:element"); - result.setAttribute("name", "result"); - result.setAttribute("type", "qman:result"); - methodNameResponseSequence.appendChild(result); - - schema.appendChild(methodNameResponseComplexType); - /* @@ -428,7 +249,7 @@ class WsdlBuilder implements IArtifactBuilder { Element responseMessage = _document.createElement("wsdl:message"); responseMessage.setAttribute("name", responseMessageName); Element responsePart = _document.createElement("wsdl:part"); - responsePart.setAttribute("element", "qman:"+methodNameResponse); + responsePart.setAttribute("element", "qman:result");//+methodNameResponse); responsePart.setAttribute("name", methodNameResponse); responseMessage.appendChild(responsePart); @@ -506,29 +327,134 @@ class WsdlBuilder implements IArtifactBuilder { } } + /** + * Director callback : all attributes have been notified. + * Nothing to do here. + */ public void endAttributes() { // N.A. } + /** + * Director callback : all operations have been notified. + * Nothing to do here. + */ public void endOperations() { - + // N.A. } + /** + * Returns the WSDL built by this builder. + * + * @return the WSDL built by this builder. + */ public Document getWsdl() { WsdlDebugger.debug(_objectName,_document); return _document; } + /** + * Injects the application context environment + * on this builder. + * + * @param environment the application context environment. + */ public void setEnvironment(Environment environment) { - this._environment = environment; + this._environment = (WSDMAdapterEnvironment)environment; } + /** + * Injects the path of the wsdl document. + * + * @param wsdlPath the path of the wsdl document. + */ public void setWsdlPath(String wsdlPath) { _document = WsdlUtils.createWSDL(_environment, wsdlPath, true); } -} + + /** + * Create a reference to the WSRP properties element. + * + * @throws BuilderException in case of XPath evaluation problem. + */ + private void createWsrpPropertiesElement() throws BuilderException + { + try + { + _wsrpProperties = (Element) XPathAPI.selectSingleNode( + _document, + WSRP_PROPERTIES_XPATH); + } catch (TransformerException exception) + { + LOGGER.error(Messages.QMAN_100040_UNABLE_TO_LOCATE_WSRP_PROPERTIES); + throw new BuilderException(exception); + } + } + + /** + * Creates a template element that will be used for array + * type schema declaration(s). + */ + private void createReusableArrayComplextType() + { + _arrayComplexType = XmlUtils.createElement(_document, XSD_COMPLEX_TYPE_QNAME); + Element sequence = XmlUtils.createElement(_document, XSD_SEQUENCE_QNAME); + _nestedArrayType = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME); + _nestedArrayType.setAttribute(NAME_ATTRIBUTE, "entry"); + sequence.appendChild(_nestedArrayType); + _arrayComplexType.appendChild(sequence); + } + + private void createSchemaElement() throws BuilderException + { + try + { + schema = (Element) XPathAPI.selectSingleNode( + _document.getDocumentElement(), + QMAN_SCHEMA_XPATH); + } catch(Exception exception) + { + LOGGER.error( + exception, + Messages.QMAN_100034_WSDL_SCHEMA_SECTION_NOT_FOUND); + throw new BuilderException(exception); + } + } + + /** + * The template WSDL contains a dummy URL as service location that + * needs to be replaced with the real service address. + * + * @throws BuilderException when replacement fails (XPath problem). + */ + private void replaceDummyServiceLocationOnWsdl() throws BuilderException + { + try + { + Attr location = (Attr) XPathAPI.selectSingleNode( + _document, + SERVICE_LOCATION_XPATH); + + StringBuilder builder = new StringBuilder("http://") + .append(InetAddress.getLocalHost().getHostName()) + .append(':') + .append(System.getProperty(Names.ADAPTER_PORT_PROPERTY_NAME,"8080")) + .append('/') + .append(_environment.getContextPath()) + .append('/') + .append("services/QManWsResource"); + location.setValue(builder.toString()); + } catch(Exception exception) + { + LOGGER.error( + exception, + Messages.QMAN_100026_SOAP_ADDRESS_REPLACEMENT_FAILURE); + throw new BuilderException(exception); + } + } +} \ No newline at end of file diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/common/EntityInstanceNotFoundFault.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/common/EntityInstanceNotFoundFault.java index 25bb871e75..116d74727a 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/common/EntityInstanceNotFoundFault.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/common/EntityInstanceNotFoundFault.java @@ -50,6 +50,9 @@ public class EntityInstanceNotFoundFault extends QManFault */ public EntityInstanceNotFoundFault(EndpointReference endpointReference, ObjectName targetEntityName) { - super(endpointReference,EXCEPTION_QNAME, targetEntityName.getCanonicalName()); + super( + endpointReference, + EXCEPTION_QNAME, + targetEntityName.getCanonicalName()); } } \ No newline at end of file diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/common/ThreadSession.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/common/ThreadSession.java index bc214b8b25..588879b951 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/common/ThreadSession.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/common/ThreadSession.java @@ -25,7 +25,6 @@ import javax.management.ObjectName; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * Thread-scoped session. * @@ -35,7 +34,8 @@ public class ThreadSession { private ObjectName _objectName; private Document _wsdl; - private Element [] additionalProperties; + private Element [] _wsrmdProperties; + /** * Empty constructor. */ @@ -90,7 +90,7 @@ public class ThreadSession */ public Element[] getResourceMetadataDescriptor() { - return additionalProperties; + return _wsrmdProperties; } /** @@ -100,6 +100,6 @@ public class ThreadSession */ public void setResourceMetadataDescriptor(Element[] rmd) { - this.additionalProperties = rmd; + this._wsrmdProperties = rmd; } } \ No newline at end of file diff --git a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/muse/engine/WSDMAdapterEnvironment.java b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/muse/engine/WSDMAdapterEnvironment.java index f47a587830..b5d978e0e5 100644 --- a/java/management/client/src/main/java/org/apache/qpid/management/wsdm/muse/engine/WSDMAdapterEnvironment.java +++ b/java/management/client/src/main/java/org/apache/qpid/management/wsdm/muse/engine/WSDMAdapterEnvironment.java @@ -64,6 +64,11 @@ public class WSDMAdapterEnvironment extends AbstractEnvironment return _realDirectory; } + /** + * Returns the default endpoint reference URI. + * + * @return the default endpoint reference URI. + */ public String getDefaultURIPrefix() { return new StringBuilder() @@ -79,4 +84,14 @@ public class WSDMAdapterEnvironment extends AbstractEnvironment .append("/services/") .toString(); } + + /** + * Returns the context path name of QMan application. + * + * @return the context path name of QMan application. + */ + public String getContextPath() + { + return _servletContext.getContextPath(); + } } \ No newline at end of file diff --git a/java/management/client/src/main/java/wsdl/QManWsResource.wsdl b/java/management/client/src/main/java/wsdl/QManWsResource.wsdl index 69647521ba..20df95e2b1 100644 --- a/java/management/client/src/main/java/wsdl/QManWsResource.wsdl +++ b/java/management/client/src/main/java/wsdl/QManWsResource.wsdl @@ -93,7 +93,35 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/management/client/src/main/java/wsdl/WS-ServiceGroupEntry-1_2.wsdl b/java/management/client/src/main/java/wsdl/WS-ServiceGroupEntry-1_2.wsdl index dc4581d8a8..379382c18d 100644 --- a/java/management/client/src/main/java/wsdl/WS-ServiceGroupEntry-1_2.wsdl +++ b/java/management/client/src/main/java/wsdl/WS-ServiceGroupEntry-1_2.wsdl @@ -200,7 +200,7 @@ - + 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 index 12ba1fab73..9abcd08eef 100644 --- 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 @@ -63,5 +63,5 @@ public interface TestConstants int SAMPLE_ACCESS_CODE = 1; String YEARS = "years"; int SAMPLE_MIN_VALUE = 1; - int SAMPLE_MAX_VALUE = 120; + 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 index 8e9c3ccd6b..72bd45f70f 100644 --- 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 @@ -23,16 +23,13 @@ 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; -import org.apache.qpid.management.domain.model.AccessMode; -import org.apache.qpid.management.domain.model.type.Type; -import org.apache.qpid.management.domain.model.type.Uint8; - -import junit.framework.TestCase; /** * Test case for Configuration singleton. @@ -46,22 +43,7 @@ public class ConfigurationTest extends TestCase { assertSame(Configuration.getInstance(),Configuration.getInstance()); } - - /** - * Tests the execution of getType() method when a valid code is supplied. - * - *
precondition : the requested type already exist on the configuration. - *
postcondition : the requested type is returned and no exception is thrown. - */ - public void testGetTypeOk() throws UnknownTypeCodeException - { - TypeMapping mapping = new TypeMapping(TestConstants.VALID_CODE,new Uint8()); - Configuration.getInstance().addTypeMapping(mapping); - Type type = Configuration.getInstance().getType(TestConstants.VALID_CODE); - assertTrue(type instanceof Uint8); - } - /** * Tests the execution of getType() method when a unknown code is supplied. * @@ -79,22 +61,7 @@ public class ConfigurationTest extends TestCase assertEquals(TestConstants.VALID_CODE*10001,expected.getCode()); } } - - /** - * Tests the execution of getAccessMode() method when a valid code is supplied. - * - *
precondition : the requested access mode already exist on the configuration. - *
postcondition : the requested access mode is returned and no exception is thrown. - */ - public void testGetAccessModeOk() throws UnknownAccessCodeException - { - AccessModeMapping mapping = new AccessModeMapping(TestConstants.VALID_CODE,AccessMode.RW); - Configuration.getInstance().addAccessModeMapping(mapping); - AccessMode accessMode = Configuration.getInstance().getAccessMode(TestConstants.VALID_CODE); - - assertSame(AccessMode.RW,accessMode); - } - + /** * Tests the execution of getAccessMode() method when a unknown code is supplied. * 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..34f359e56b --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/BaseWsDmAdapterTestCase.java @@ -0,0 +1,185 @@ +/* + * + * 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.lang.reflect.Array; +import java.net.URI; +import java.util.UUID; + +import javax.management.MBeanAttributeInfo; +import javax.management.MBeanInfo; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import javax.xml.namespace.QName; + +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); + } + + /** + * Test the WS-RP GetResourceProperty interface of the WS-DM adapter. + * + *
precondition : a ws resource exists and is registered. + *
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)); + } + } + } + + /** + * 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/GetMultipleResourcePropertiesTestCase.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetMultipleResourcePropertiesTestCase.java new file mode 100644 index 0000000000..2481d4a406 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/GetMultipleResourcePropertiesTestCase.java @@ -0,0 +1,126 @@ +/* + * + * 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. + * + *
precondition : the GetMultipleResourceProperties request contains an unknwon resource. + *
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.setTrace(true); + + _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. + * + *
precondition : a ws resource exists and is registered. + *
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/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. + * + *
precondition : the GetResourcePropertyDocument contains an unknwon resource. + *
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. + * + *
precondition : a ws resource exists and is registered. + *
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. + * + *
precondition : a ws resource exists, it is registered and has at least one read-only property. + *
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..d22c51f57e --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/MetadataExchangeInterfaceTestCase.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 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.metadata.WsxConstants; +import org.apache.muse.ws.resource.metadata.WsrmdConstants; +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. + * + *
precondition : the GetMetadata request doesn't contain a dialect. + *
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. + * + *
precondition : the GetMetadata request contains WSDL dialect. + *
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. + * + *
precondition : the GetMetadata request contains RMD dialect. + *
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. + * + *
precondition : the GetMetadata request contains an unknown dialect. + *
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); + } + + /** + * 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..76d3775334 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/OperationInvocationInterfaceTestCase.java @@ -0,0 +1,597 @@ +/* + * + * 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 final Long _retCodeOk = new Long(0); + private Map _invocationHandlers = createInvocationHandlers(); + + /** + * Test operation invocation on WS-Resource. + * This method tests the exchange of a byte type array between requestor + * and service provider. + * + *
precondition : a WS-Resource exists and is registered and the requested + * operation is available on that. + *
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 getStatusCode = result.getClass().getMethod("getStatusCode"); + Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); + + assertEquals(_retCodeOk,getStatusCode.invoke(result)); + Map out = (Map) 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. + * + *
precondition : a ws resource exists and is registered and the requested operation + * is available on that. + *
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); + + Method getStatusCode = result.getClass().getMethod("getStatusCode"); + assertEquals( + "Something was wrong...expected return code is "+_retCodeOk, + _retCodeOk, + getStatusCode.invoke(result)); + } + + /** + * Test a the invocation on a WS-Resource with a method that throws an exception.. + * + *
precondition : a ws resource exists and is registered and the requested + * operation is available on that. + *
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. + * + *
precondition : a WS-Resource exists and is registered and the requested operation + * is available on that. + *
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 getStatusCode = result.getClass().getMethod("getStatusCode"); + Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); + + assertEquals(_retCodeOk,getStatusCode.invoke(result)); + Map out = (Map) 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 : + * + *
precondition : a ws resource exists and is registered and the requested + * operation is available on that. + *
postcondition : invocations are executed successfully, no exception is + * thrown and parameters are correctly returned. + */ + @SuppressWarnings("unchecked") + public void testOperationInvocationOK_withMap() throws Exception + { + Map expectedMap = new HashMap(); + 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 getStatusCode = result.getClass().getMethod("getStatusCode"); + Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); + + assertEquals(_retCodeOk,getStatusCode.invoke(result)); + Map out = (Map) ((Map) 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 : + * + *
    + *
  • java.lang.Long / long (xsd:long) + *
  • java.lang.Integer / int (xsd:int / xsd:integer) + *
  • java.lang.Double/ double (xsd:double) + *
  • java.lang.Float / float (xsd:float) + *
  • java.lang.Short / short (xsd:short) + *
  • java.lang.Boolean / boolean (xsd:boolean) + *
  • java.lang.String (xsd:string) + *
  • java.net.URI (xsd:anyURI) + *
  • java.util.Date(xsd:dateTime) + *
+ * + *
precondition : a ws resource exists and is registered and the requested operation is + * available on that. + *
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 getStatusCode = result.getClass().getMethod("getStatusCode"); + Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); + assertEquals(_retCodeOk,getStatusCode.invoke(result)); + Map out = (Map) 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 : + * + *
    + *
  • java.lang.Long (xsd:long) + *
  • java.lang.Integer (xsd:int / xsd:integer) + *
  • java.lang.Double (xsd:double) + *
  • java.lang.Float (xsd:float) + *
  • java.lang.Short (xsd:short) + *
  • java.lang.Boolean (xsd:boolean) + *
  • java.lang.String (xsd:string) + *
  • java.net.URI (xsd:anyURI) + *
  • java.util.Date(xsd:dateTime) + *
+ * + *
precondition : a ws resource exists and is registered and the requested operation is available on that. + *
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 getStatusCode = result.getClass().getMethod("getStatusCode"); + Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); + assertEquals(_retCodeOk,getStatusCode.invoke(result)); + Map out = (Map) 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 : + * + *
    + *
  • java.lang.Long / long (xsd:long) + *
  • java.lang.Integer / int (xsd:int / xsd:integer) + *
  • java.lang.Double/ double (xsd:double) + *
  • java.lang.Float / float (xsd:float) + *
  • java.lang.Short / short (xsd:short) + *
  • java.lang.Boolean / boolean (xsd:boolean) + *
+ * + *
precondition : a ws resource exists and is registered and the requested operation is available on that. + *
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 getStatusCode = result.getClass().getMethod("getStatusCode"); + Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); + assertEquals(_retCodeOk,getStatusCode.invoke(result)); + Map out = (Map) 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 createInvocationHandlers() + { + Map handlers = new HashMap(); + + 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/SetResourcePropertiesTestCase.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/SetResourcePropertiesTestCase.java new file mode 100644 index 0000000000..eed8a00508 --- /dev/null +++ b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/SetResourcePropertiesTestCase.java @@ -0,0 +1,221 @@ +/* + * + * 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. + * + *
precondition : a WS-Resource exists and is registered. + *
postcondition : property values are correctly updated on the target WS-Resource.. + */ + public void testSetResourcePropertiesOK() throws Exception + { + Map sampleMap = new HashMap(); + sampleMap.put("Key1", "BLABALABLABALBAL"); + sampleMap.put("Key2", 182838484l); + sampleMap.put("Key3", -928376362); + sampleMap.put("Key4", 23762736276.33D); + sampleMap.put("Key4", 2327363.2F); + + Map sampleValues = new HashMap(); + 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. + * + *
precondition : a ws resource exists and is registered. The value of the target property is null. + *
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. + * + *
precondition : the SetResourceProperties contains an unknwon resource. + *
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.setTrace(true); + + _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. + * + *
precondition : the SetResourceProperties contains an unknwon resource. + *
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.setTrace(true); + + _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/WsDmAdapterTest.java b/java/management/client/src/test/java/org/apache/qpid/management/wsdm/WsDmAdapterTest.java index 6644b5ae25..631beb7488 100644 --- 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 @@ -21,36 +21,13 @@ package org.apache.qpid.management.wsdm; import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.lang.reflect.Array; -import java.lang.reflect.Method; import java.net.ServerSocket; -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.management.MBeanAttributeInfo; -import javax.management.MBeanInfo; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import javax.xml.namespace.QName; - -import junit.extensions.TestSetup; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.apache.muse.core.proxy.ProxyHandler; -import org.apache.muse.core.proxy.ReflectionProxyHandler; import org.apache.muse.core.serializer.SerializerRegistry; -import org.apache.muse.util.xml.XmlUtils; -import org.apache.muse.ws.addressing.EndpointReference; -import org.apache.muse.ws.addressing.soap.SoapFault; -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.wsdm.capabilities.Result; @@ -61,26 +38,14 @@ 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 org.w3c.dom.Element; -/** - * Test case for WS-Resource lifecycle management. - * - * @author Andrea Gazzarini - */ -public class WsDmAdapterTest extends TestCase { - - private MBeanServer _managementServer; - private ObjectName _resourceObjectName; - - private WsResourceClient _resourceClient; - private MBeanInfo _mbeanInfo; - - private Map _invocationHandlers = createInvocationHandlers(); - final Long retCodeOk = new Long(0); +import junit.extensions.TestSetup; +import junit.framework.Test; +import junit.framework.TestSuite; + +public class WsDmAdapterTest +{ - private static ServerThread _server; - /** * Test case wide set up. * Provides Server startup & shutdown global procedure. @@ -102,6 +67,7 @@ public class WsDmAdapterTest extends TestCase { } }; + private ServerThread _server; /** * Builds a new test setup with for the given test. @@ -153,927 +119,29 @@ public class WsDmAdapterTest extends TestCase { }; /** - * 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); - } - - /** - * Test the WS-RP GetResourceProperty interface of the WS-DM adapter. - * - *
precondition : a ws resource exists and is registered. - *
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)); - } - } - } - - /** - * Test the WS-RP SetResourceProperty interface of the WS-DM adapter. + * Gets the test suite composition. * - *
precondition : a WS-Resource exists and is registered. - *
postcondition : property values are correctly updated on the target WS-Resource.. + * @return the test suite composition. */ - public void testSetResourcePropertiesOK() throws Exception + public static Test suite() { - Map sampleMap = new HashMap(); - sampleMap.put("Key1", "BLABALABLABALBAL"); - sampleMap.put("Key2", 182838484l); - sampleMap.put("Key3", -928376362); - sampleMap.put("Key4", 23762736276.33D); - sampleMap.put("Key4", 2327363.2F); - - Map sampleValues = new HashMap(); - 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. - * - *
precondition : a ws resource exists and is registered. The value of the target property is null. - *
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 WS-RP PutResourcePropertyDocument interface of the WS-DM adapter. - * - *
precondition : a ws resource exists and is registered. - *
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. - * - *
precondition : a ws resource exists, it is registered and has at least one read-only property. - *
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) - { - - } - } - - /** - * Test the WS-RP GetResourceProperties interface of the WS-DM adapter. - * - *
precondition : a ws resource exists and is registered. - *
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())); - } - } - } - - /** - * Test operation invocation on WS-Resource. - * This method tests the exchange of simple types between requestor and service provider. - * With simple types we mean : - * - *
    - *
  • java.lang.Long / long (xsd:long) - *
  • java.lang.Integer / int (xsd:int / xsd:integer) - *
  • java.lang.Double/ double (xsd:double) - *
  • java.lang.Float / float (xsd:float) - *
  • java.lang.Short / short (xsd:short) - *
  • java.lang.Boolean / boolean (xsd:boolean) - *
  • java.lang.String (xsd:string) - *
  • java.net.URI (xsd:anyURI) - *
  • java.util.Date(xsd:dateTime) - *
- * - *
precondition : a ws resource exists and is registered and the requested operation is available on that. - *
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 getStatusCode = result.getClass().getMethod("getStatusCode"); - Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); - assertEquals(retCodeOk,getStatusCode.invoke(result)); - Map out = (Map) 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 : - * - *
    - *
  • java.lang.Long (xsd:long) - *
  • java.lang.Integer (xsd:int / xsd:integer) - *
  • java.lang.Double (xsd:double) - *
  • java.lang.Float (xsd:float) - *
  • java.lang.Short (xsd:short) - *
  • java.lang.Boolean (xsd:boolean) - *
  • java.lang.String (xsd:string) - *
  • java.net.URI (xsd:anyURI) - *
  • java.util.Date(xsd:dateTime) - *
- * - *
precondition : a ws resource exists and is registered and the requested operation is available on that. - *
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 getStatusCode = result.getClass().getMethod("getStatusCode"); - Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); - assertEquals(retCodeOk,getStatusCode.invoke(result)); - Map out = (Map) 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 : - * - *
    - *
  • java.lang.Long / long (xsd:long) - *
  • java.lang.Integer / int (xsd:int / xsd:integer) - *
  • java.lang.Double/ double (xsd:double) - *
  • java.lang.Float / float (xsd:float) - *
  • java.lang.Short / short (xsd:short) - *
  • java.lang.Boolean / boolean (xsd:boolean) - *
- * - *
precondition : a ws resource exists and is registered and the requested operation is available on that. - *
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 getStatusCode = result.getClass().getMethod("getStatusCode"); - Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); - assertEquals(retCodeOk,getStatusCode.invoke(result)); - Map out = (Map) 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())); - } - - /** - * Test operation invocation on WS-Resource. - * This method tests the exchange of a byte type array between requestor and service provider. - * - *
precondition : a WS-Resource exists and is registered and the requested operation is available on that. - *
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 getStatusCode = result.getClass().getMethod("getStatusCode"); - Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); - - assertEquals(retCodeOk,getStatusCode.invoke(result)); - Map out = (Map) 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. - * - *
precondition : a ws resource exists and is registered and the requested operation is available on that. - *
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); - - Method getStatusCode = result.getClass().getMethod("getStatusCode"); - assertEquals( - "Something was wrong...expected return code is "+retCodeOk, - retCodeOk, - getStatusCode.invoke(result)); - } - - /** - * Test a the invocation on a WS-Resource with a method that throws an exception.. - * - *
precondition : a ws resource exists and is registered and the requested operation is available on that. - *
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. - * - *
precondition : a WS-Resource exists and is registered and the requested operation is available on that. - *
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 getStatusCode = result.getClass().getMethod("getStatusCode"); - Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); - - assertEquals(retCodeOk,getStatusCode.invoke(result)); - Map out = (Map) 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 : - * - *
precondition : a ws resource exists and is registered and the requested operation is available on that. - *
postcondition : invocations are executed successfully, no exception is thrown and parameters are correctly returned. - */ - @SuppressWarnings("unchecked") - public void testOperationInvocationOK_withMap() throws Exception - { - Map expectedMap = new HashMap(); - 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 getStatusCode = result.getClass().getMethod("getStatusCode"); - Method getOutputParameters = result.getClass().getMethod("getOutputParameters"); - - assertEquals(retCodeOk,getStatusCode.invoke(result)); - Map out = (Map) ((Map) 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"))); - } - - /** - * Main entry point for running this test case. - * - * @return the decorated test case. - */ - public static Test suite() { - TestSuite suite = new TestSuite("Test Suite for WS-DM Adapter"); - suite.addTestSuite(WsDmAdapterTest.class); + 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); return new WsDmAdapterTestSetup(suite); } /** - * 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()); - } - - private Map createInvocationHandlers() - { - Map handlers = new HashMap(); - - 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; - } - - /** - * Internal method used for array comparison using reflection. + * Finds a free port that will be used to run the embedded + * web server. * - * @param expectedArray the expected array. - * @param resultArray the array that must match the expected one. + * @return a free port that will be used to run the + * embedded web server. */ - 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); - } - } - - public static int getFreePort() throws IOException { + private static int getFreePort() throws IOException { ServerSocket server = null; try { -- cgit v1.2.1