[maven-release-plugin] copy for tag org.apache.aries.jmx.core-0.3.1
git-svn-id: https://svn.apache.org/repos/asf/aries/tags/org.apache.aries.jmx.core-0.3.1@1342414 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/jmx-core/pom.xml b/jmx-core/pom.xml
deleted file mode 100644
index c6c257c..0000000
--- a/jmx-core/pom.xml
+++ /dev/null
@@ -1,97 +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.
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.aries.jmx</groupId>
- <artifactId>jmx</artifactId>
- <version>0.3</version>
- </parent>
-
- <artifactId>org.apache.aries.jmx.core</artifactId>
- <packaging>bundle</packaging>
- <version>0.3.1</version>
- <name>Apache Aries JMX Core</name>
- <description>
- This bundle contains the core implementation
- of the JMX Control specification
- </description>
-
- <properties>
- <aries.osgi.activator>
- org.apache.aries.jmx.Activator
- </aries.osgi.activator>
- <aries.osgi.import>
- !org.apache.aries.jmx*,
- org.osgi.framework;version="1.5.0",
- org.osgi.service.cm;version="1.3.0";resolution:="optional",
- org.osgi.service.permissionadmin;version="1.2.0";resolution:="optional",
- org.osgi.service.provisioning;version="1.2.0";resolution:="optional",
- org.osgi.service.useradmin;version="1.1.0";resolution:="optional",
- org.osgi.util.tracker,
- org.osgi.jmx;version="1.0.0",
- org.osgi.jmx.framework;version="1.5.0",
- org.osgi.jmx.service.cm;version="1.3.0",
- org.osgi.jmx.service.permissionadmin;version="1.2.0",
- org.osgi.jmx.service.provisioning;version="1.2.0",
- org.osgi.jmx.service.useradmin;version="1.1.0",
- *
- </aries.osgi.import>
- <aries.osgi.export.pkg>
- org.apache.aries.jmx.codec
- </aries.osgi.export.pkg>
- <aries.osgi.private.pkg>
- org.apache.aries.jmx*
- </aries.osgi.private.pkg>
- <aries.osgi.import.service>
- javax.management.MBeanServer
- </aries.osgi.import.service>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.apache.aries.jmx</groupId>
- <artifactId>org.apache.aries.jmx.api</artifactId>
- <version>0.3</version>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.compendium</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.aries</groupId>
- <artifactId>org.apache.aries.util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <scm>
- <connection>scm:svn:http://svn.apache.org/repos/asf/aries/tags/org.apache.aries.jmx.core-0.3.1</connection>
- <developerConnection>scm:svn:https://svn.apache.org/repos/asf/aries/tags/org.apache.aries.jmx.core-0.3.1</developerConnection>
- <url>http://svn.apache.org/viewvc/aries/tags/org.apache.aries.jmx.core-0.3.1</url>
- </scm>
-
- </project>
diff --git a/jmx-core/src/main/appended-resources/META-INF/NOTICE.vm b/jmx-core/src/main/appended-resources/META-INF/NOTICE.vm
deleted file mode 100644
index 3e5ad36..0000000
--- a/jmx-core/src/main/appended-resources/META-INF/NOTICE.vm
+++ /dev/null
@@ -1,2 +0,0 @@
-This product includes software developed at
-the OSGi Alliance (http://www.osgi.org/).
\ No newline at end of file
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/AbstractCompendiumHandler.java b/jmx-core/src/main/java/org/apache/aries/jmx/AbstractCompendiumHandler.java
deleted file mode 100644
index 529d518..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/AbstractCompendiumHandler.java
+++ /dev/null
@@ -1,146 +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.aries.jmx;
-
-import java.util.concurrent.ExecutorService;
-
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.agent.JMXAgentContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.Filter;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.log.LogService;
-import org.osgi.util.tracker.ServiceTracker;
-
-/**
- * <p>
- * Abstract implementation of {@link MBeanHandler} that provides a template with basic tracking of an optional
- * compendium service. MBeanHandler implementations that manage a {@link StandardMBean} that is backed by a single OSGi
- * compendium service should extend this class and implement the {@linkplain #constructInjectMBean(Object)} and
- * {@linkplain #getName()} methods
- * </p>
- *
- * @see MBeanHandler
- *
- * @version $Rev$ $Date$
- */
-public abstract class AbstractCompendiumHandler extends ServiceTracker implements MBeanHandler {
-
- protected final JMXAgentContext agentContext;
- protected StandardMBean mbean;
- protected Long trackedId;
-
- /**
- *
- * @param agentContext
- * @param filter
- */
- protected AbstractCompendiumHandler(JMXAgentContext agentContext, Filter filter) {
- super(agentContext.getBundleContext(), filter, null);
- this.agentContext = agentContext;
- }
-
- /**
- *
- * @param agentContext
- * @param clazz
- */
- protected AbstractCompendiumHandler(JMXAgentContext agentContext, String clazz) {
- super(agentContext.getBundleContext(), clazz, null);
- this.agentContext = agentContext;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference)
- */
- public Object addingService(ServiceReference reference) {
- Logger logger = agentContext.getLogger();
- Object trackedService = null;
- Long serviceId = (Long) reference.getProperty(Constants.SERVICE_ID);
- //API stipulates versions for compendium services with static ObjectName
- //This shouldn't happen but added as a consistency check
- if (trackedId != null) {
- String serviceDescription = (String) ((reference.getProperty(Constants.SERVICE_DESCRIPTION) != null) ?
- reference.getProperty(Constants.SERVICE_DESCRIPTION) : reference.getProperty(Constants.OBJECTCLASS));
- logger.log(LogService.LOG_WARNING, "Detected secondary ServiceReference for [" + serviceDescription
- + "] with " + Constants.SERVICE_ID + " [" + serviceId + "] Only 1 instance will be JMX managed");
- } else {
- logger.log(LogService.LOG_INFO, "Registering MBean with ObjectName [" + getName() + "] for service with "
- + Constants.SERVICE_ID + " [" + serviceId + "]");
- trackedService = context.getService(reference);
- mbean = constructInjectMBean(trackedService);
- ExecutorService executor = agentContext.getRegistrationExecutor();
- executor.submit(new Runnable() {
- public void run() {
- agentContext.registerMBean(AbstractCompendiumHandler.this);
- }
- });
- trackedId = serviceId;
- }
- return trackedService;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference, java.lang.Object)
- */
- public void removedService(ServiceReference reference, Object service) {
- Logger logger = agentContext.getLogger();
- Long serviceID = (Long) reference.getProperty(Constants.SERVICE_ID);
- if (trackedId != null && !trackedId.equals(serviceID)) {
- String serviceDescription = (String) ((reference.getProperty(Constants.SERVICE_DESCRIPTION) != null) ?
- reference.getProperty(Constants.SERVICE_DESCRIPTION) : reference.getProperty(Constants.OBJECTCLASS));
- logger.log(LogService.LOG_WARNING, "ServiceReference for [" + serviceDescription + "] with "
- + Constants.SERVICE_ID + " [" + serviceID + "] is not currently JMX managed");
- } else {
- logger.log(LogService.LOG_INFO, "Unregistering MBean with ObjectName [" + getName() + "] for service with "
- + Constants.SERVICE_ID + " [" + serviceID + "]");
- ExecutorService executor = agentContext.getRegistrationExecutor();
- executor.submit(new Runnable() {
- public void run() {
- agentContext.unregisterMBean(AbstractCompendiumHandler.this);
- }
- });
- trackedId = null;
- context.ungetService(reference);
- }
- }
-
- /**
- * Gets the <code>StandardMBean</code> managed by this handler when the backing service is available or null
- *
- * @see org.apache.aries.jmx.MBeanHandler#getMbean()
- */
- public StandardMBean getMbean() {
- return mbean;
- }
-
- /**
- * Implement this method to construct an appropriate {@link StandardMBean} instance which is backed by the supplied
- * service tracked by this handler
- *
- * @param targetService
- * the compendium service tracked by this handler
- * @return The <code>StandardMBean</code> instance whose registration lifecycle will be managed by this handler
- */
- protected abstract StandardMBean constructInjectMBean(Object targetService);
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/Activator.java b/jmx-core/src/main/java/org/apache/aries/jmx/Activator.java
deleted file mode 100644
index 2088b44..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/Activator.java
+++ /dev/null
@@ -1,71 +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.aries.jmx;
-
-import org.apache.aries.jmx.agent.JMXAgent;
-import org.apache.aries.jmx.agent.JMXAgentImpl;
-import org.apache.aries.jmx.agent.JMXAgentContext;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.log.LogService;
-
-/**
- * <p>Activator for JMX OSGi bundle.</p>
- *
- * @version $Rev$ $Date$
- */
-public class Activator implements BundleActivator {
-
- private JMXAgent agent;
- private Logger logger;
-
- /**
- * <p>Called when JMX OSGi bundle starts.
- * This method creates and starts JMX agent.</p>
- *
- * @see org.osgi.framework.BundleActivator#start(BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- logger = new Logger(context);
- //starting logger
- logger.open();
- logger.log(LogService.LOG_DEBUG, "Starting JMX OSGi bundle");
- agent = new JMXAgentImpl(logger);
- JMXAgentContext agentContext = new JMXAgentContext(context, agent, logger);
- agent.setAgentContext(agentContext);
- agent.start();
- }
-
- /**
- * <p>Called when JMX OSGi bundle stops.
- * This method stops agent and logger @see {@link Logger}.</p>
- *
- * @see org.osgi.framework.BundleActivator#stop(BundleContext)
- */
- public void stop(BundleContext bc) throws Exception {
- if (logger != null) {
- logger.log(LogService.LOG_DEBUG, "Stopping JMX OSGi bundle");
- }
- if (agent != null) {
- agent.stop();
- }
- if (logger != null) {
- logger.close();
- }
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/JMXThreadFactory.java b/jmx-core/src/main/java/org/apache/aries/jmx/JMXThreadFactory.java
deleted file mode 100644
index efff03e..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/JMXThreadFactory.java
+++ /dev/null
@@ -1,36 +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.aries.jmx;
-
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-
-public class JMXThreadFactory implements ThreadFactory {
- private final ThreadFactory factory = Executors.defaultThreadFactory();
- private final String name;
-
- public JMXThreadFactory(String name) {
- this.name = name;
- }
-
- public Thread newThread(Runnable r) {
- final Thread t = factory.newThread(r);
- t.setName(name);
- t.setDaemon(true);
- return t;
- }
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/Logger.java b/jmx-core/src/main/java/org/apache/aries/jmx/Logger.java
deleted file mode 100644
index ec15c89..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/Logger.java
+++ /dev/null
@@ -1,88 +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.aries.jmx;
-
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.log.LogService;
-import org.osgi.util.tracker.ServiceTracker;
-
-/**
- * <p>This <tt>Logger</tt> class represents ServiceTracker for LogService.
- * It provides methods for logging messages. If LogService is not available it logs to stdout.</p>
- *
- * @see org.osgi.service.log.LogService
- * @see org.osgi.util.tracker.ServiceTracker
- * @version $Rev$ $Date$
- */
-public class Logger extends ServiceTracker implements LogService {
-
- private String bundleLocation;
-
- /**
- * Constructs new Logger(ServiceTracker for LogService).
- *
- * @param context bundle context.
- */
- public Logger(BundleContext context) {
- super(context, LogService.class.getName(), null);
- this.bundleLocation = context.getBundle().getLocation();
- }
-
- /**
- * @see org.osgi.service.log.LogService#log(int, java.lang.String)
- */
- public void log(int level, String message) {
- LogService logService = (LogService) getService();
- if (logService != null) {
- logService.log(level, message);
- }
-
- }
-
- /**
- * @see org.osgi.service.log.LogService#log(int, java.lang.String, java.lang.Throwable)
- */
- public void log(int level, String message, Throwable exception) {
- LogService logService = (LogService) getService();
- if (logService != null) {
- logService.log(level, message, exception);
- }
- }
-
- /**
- * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String)
- */
- public void log(ServiceReference ref, int level, String message) {
- LogService logService = (LogService) getService();
- if (logService != null) {
- logService.log(ref, level, message);
- }
- }
-
- /**
- * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String,
- * java.lang.Throwable)
- */
- public void log(ServiceReference ref, int level, String message, Throwable exception) {
- LogService logService = (LogService) getService();
- if (logService != null) {
- logService.log(ref, level, message, exception);
- }
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/MBeanHandler.java b/jmx-core/src/main/java/org/apache/aries/jmx/MBeanHandler.java
deleted file mode 100644
index 6bfb42c..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/MBeanHandler.java
+++ /dev/null
@@ -1,51 +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.aries.jmx;
-
-import javax.management.StandardMBean;
-
-/**
- * <p>Represents JMX OSGi MBeans handler.
- * Storing information about holden MBean.</p>
- *
- * @version $Rev$ $Date$
- */
-public interface MBeanHandler {
-
- /**
- * Gets MBean holden by handler.
- * @return MBean @see {@link StandardMBean}.
- */
- StandardMBean getMbean();
-
- /**
- * Starts handler.
- */
- void open();
-
- /**
- * Stops handler.
- */
- void close();
-
- /**
- * Gets name of the MBean.
- * @return MBean name.
- */
- String getName();
-
-}
\ No newline at end of file
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/MBeanServiceTracker.java b/jmx-core/src/main/java/org/apache/aries/jmx/MBeanServiceTracker.java
deleted file mode 100644
index f35e495..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/MBeanServiceTracker.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.aries.jmx;
-
-import java.util.concurrent.ExecutorService;
-
-import javax.management.MBeanServer;
-
-import org.apache.aries.jmx.agent.JMXAgentContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.log.LogService;
-import org.osgi.util.tracker.ServiceTracker;
-
-/**
- * <p>This class <tt>MBeanServiceTracker</tt> represents {@link ServiceTracker} for {@link MBeanServer}'s
- * registered as services.
- * Tracking all registered MBeanServers in ServiceRegistry.</p>
- * @see ServiceTracker
- * @version $Rev$ $Date$
- */
-public class MBeanServiceTracker extends ServiceTracker {
-
- private JMXAgentContext agentContext;
-
- /**
- * Constructs new MBeanServiceTracker.
- * @param agentContext agent context.
- */
- public MBeanServiceTracker(JMXAgentContext agentContext) {
- super(agentContext.getBundleContext(), MBeanServer.class.getName(), null);
- this.agentContext = agentContext;
- }
-
- /**
- * <p>Register MBeans using {@link JMXAgentContext#registerMBeans(MBeanServer)}
- * when MBeanServer service is discovered</p>
- * @see ServiceTracker#addingService(ServiceReference)
- */
- public Object addingService(final ServiceReference reference) {
- final MBeanServer mbeanServer = (MBeanServer) context.getService(reference);
- Logger logger = agentContext.getLogger();
- logger.log(LogService.LOG_DEBUG, "Discovered MBean server " + mbeanServer);
- ExecutorService executor = agentContext.getRegistrationExecutor();
- executor.submit(new Runnable() {
-
- public void run() {
- agentContext.registerMBeans(mbeanServer);
-
- }
- });
-
- return super.addingService(reference);
- }
-
- /**
- * <p>Unregister MBeans using {@link JMXAgentContext#unregisterMBeans(MBeanServer)}
- * when MBeanServer service is removed (unregistered from ServiceRegistry) or
- * tracker is closed</p>
- * @see ServiceTracker#removedService(ServiceReference, Object)
- */
- public void removedService(final ServiceReference reference, Object service) {
- final MBeanServer mbeanServer = (MBeanServer) context.getService(reference);
- Logger logger = agentContext.getLogger();
- logger.log(LogService.LOG_DEBUG, "MBean server " + mbeanServer+ " is unregistered from SeviceRegistry");
- ExecutorService executor = agentContext.getRegistrationExecutor();
- executor.submit(new Runnable() {
-
- public void run() {
- agentContext.unregisterMBeans(mbeanServer);
- }
- });
- super.removedService(reference, service);
- }
-
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgent.java b/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgent.java
deleted file mode 100644
index c7d31f4..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgent.java
+++ /dev/null
@@ -1,95 +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.aries.jmx.agent;
-
-import java.util.concurrent.ExecutorService;
-
-import javax.management.MBeanServer;
-
-import org.apache.aries.jmx.MBeanHandler;
-
-/**
- * <p>This <tt>JMXAgent</tt> class represent agent for MBeanServers registered in ServiceRegistry.
- * It's responsible for registration and unregistration MBeans with available MBeanServers.
- * </p>
- *
- * @version $Rev$ $Date$
- */
-public interface JMXAgent {
-
- /**
- * This method starts JMX agent.
- * Creates and starting all MBean Handlers and MBeanServiceTracker.
- */
- void start();
-
- /**
- * Registers MBeans with provided MBeanServer.
- * @param server MBeanServer with which MBeans are going to be registered
- */
- void registerMBeans(final MBeanServer server);
-
- /**
- * Unregisters MBeans with provided MBeanServer.
- * @param server MBeanServer with which MBeans are going to be unregistered.
- */
- void unregisterMBeans(final MBeanServer server);
-
- /**
- * Registers MBean with all available MBeanServers.
- * @param mBeanHandler handler which contains MBean info.
- */
- void registerMBean(final MBeanHandler mBeanHandler);
-
- /**
- * Unregisters MBean with all available MBeanServers.
- * @param mBeanHandler handler which contains MBean info.
- */
- void unregisterMBean(final MBeanHandler mBeanHandler);
-
- /**
- * Unregisters MBean with all available MBeanServers.
- * @param name of MBean to be unregistered.
- * @deprecated
- */
- void unregisterMBean(final String name);
-
- /**
- * Stops JMXAgent.
- * This method stops MBeanServiceTracker and all MBean handlers.
- */
- void stop();
-
- /**
- * Gets JMXAgentContext @see {@link JMXAgentContext}.
- * @return JMXAgentContext instance.
- */
- JMXAgentContext getAgentContext();
-
- /**
- * Sets JMXAgentContext for this agent.
- * @param agentContext JMXAgentContext instance created for this agent.
- */
- void setAgentContext(JMXAgentContext agentContext);
-
- /**
- * Gets registration {@link ExecutorService}.
- * @return registration executor.
- */
- ExecutorService getRegistrationExecutor();
-
-}
\ No newline at end of file
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgentContext.java b/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgentContext.java
deleted file mode 100644
index 8e43f88..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgentContext.java
+++ /dev/null
@@ -1,117 +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.aries.jmx.agent;
-
-import java.util.concurrent.ExecutorService;
-
-import javax.management.MBeanServer;
-
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.MBeanHandler;
-import org.osgi.framework.BundleContext;
-
-/**
- * <p>This class <tt>JMXAgentContext</tt> represents context of JMXAgent.
- * Delegates registration and unregistration methods to {@link JMXAgent}.</p>
- * @see JMXAgent
- *
- * @version $Rev$ $Date$
- */
-public class JMXAgentContext {
-
- private JMXAgent agent;
- private BundleContext bundleContext;
- private Logger logger;
-
- /**
- * Constructs new JMXAgentContext.
- * @param bundleContext bundle context @see {@link BundleContext}.
- * @param agent {@link JMXAgent}.
- * @param log logger represents by @see {@link Logger}.
- */
- public JMXAgentContext(BundleContext bundleContext, JMXAgent agent, Logger log) {
- this.bundleContext = bundleContext;
- this.agent = agent;
- this.logger = log;
- }
-
- /**
- * Delegates invocation to JMX agent.
- * @see org.apache.aries.jmx.agent.JMXAgent#registerMBeans(MBeanServer)
- *
- */
- public void registerMBeans(final MBeanServer server) {
- agent.registerMBeans(server);
- }
-
- /**
- * Delegates invocation to JMX agent.
- * @see org.apache.aries.jmx.agent.JMXAgent#unregisterMBeans(MBeanServer)
- */
- public void unregisterMBeans(final MBeanServer server) {
- agent.unregisterMBeans(server);
- }
-
- /**
- * Delegates invocation to JMX agent.
- * @see org.apache.aries.jmx.agent.JMXAgent#registerMBean(MBeanHandler)
- */
- public void registerMBean(final MBeanHandler mbeanData) {
- agent.registerMBean(mbeanData);
- }
-
- /**
- * Delegates invocation to JMX agent.
- * @see org.apache.aries.jmx.agent.JMXAgent#unregisterMBean(MBeanHandler)
- */
- public void unregisterMBean(final MBeanHandler mBeanHandler) {
- agent.unregisterMBean(mBeanHandler);
- }
-
- /**
- * Delegates invocation to JMX agent.
- * @see org.apache.aries.jmx.agent.JMXAgent#unregisterMBean(String)
- * @deprecated
- */
- public void unregisterMBean(final String name) {
- agent.unregisterMBean(name);
- }
-
- /**
- * Gets bundle context.
- * @return bundle context.
- */
- public BundleContext getBundleContext() {
- return bundleContext;
- }
-
- /**
- * Gets a logger represents by @see {@link Logger}.
- * @return LogService tracker.
- */
- public Logger getLogger() {
- return logger;
- }
-
- /**
- * Delegates invocation to JMX agent.
- * @see org.apache.aries.jmx.agent.JMXAgent#getRegistrationExecutor()
- */
- public ExecutorService getRegistrationExecutor() {
- return agent.getRegistrationExecutor();
- }
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgentImpl.java b/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgentImpl.java
deleted file mode 100644
index 569fa0e..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgentImpl.java
+++ /dev/null
@@ -1,309 +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.aries.jmx.agent;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
-import javax.management.NotCompliantMBeanException;
-import javax.management.ObjectName;
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.JMXThreadFactory;
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.MBeanHandler;
-import org.apache.aries.jmx.MBeanServiceTracker;
-import org.apache.aries.jmx.cm.ConfigurationAdminMBeanHandler;
-import org.apache.aries.jmx.framework.BundleStateMBeanHandler;
-import org.apache.aries.jmx.framework.FrameworkMBeanHandler;
-import org.apache.aries.jmx.framework.PackageStateMBeanHandler;
-import org.apache.aries.jmx.framework.ServiceStateMBeanHandler;
-import org.apache.aries.jmx.permissionadmin.PermissionAdminMBeanHandler;
-import org.apache.aries.jmx.provisioning.ProvisioningServiceMBeanHandler;
-import org.apache.aries.jmx.useradmin.UserAdminMBeanHandler;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.log.LogService;
-import org.osgi.util.tracker.ServiceTracker;
-
-/**
- * <p>
- * Represent agent for MBeanServers registered in ServiceRegistry. Providing registration and unregistration methods.
- * </p>
- *
- * @see JMXAgent
- *
- * @version $Rev$ $Date$
- */
-public class JMXAgentImpl implements JMXAgent {
-
- private ServiceTracker mbeanServiceTracker;
- /**
- * {@link MBeanHandler} store.
- */
- private Map<MBeanHandler, Boolean> mbeansHandlers;
- private JMXAgentContext agentContext;
- private Logger logger;
-
- /**
- * Registration {@link ExecutorService}.
- */
- private ExecutorService registrationExecutor;
-
- /**
- * Constructs new JMXAgent.
- *
- * @param logger @see org.apache.aries.jmx.Logger
- */
- public JMXAgentImpl(Logger logger) {
- this.logger = logger;
- this.mbeansHandlers = new HashMap<MBeanHandler, Boolean>();
- this.registrationExecutor = Executors.newSingleThreadExecutor(new JMXThreadFactory("JMX OSGi Agent"));
- }
-
- /**
- * @see org.apache.aries.jmx.agent.JMXAgent#start()
- */
- public synchronized void start() {
- logger.log(LogService.LOG_INFO, "Starting JMX OSGi agent");
- BundleContext bc = agentContext.getBundleContext();
- MBeanHandler frameworkHandler = new FrameworkMBeanHandler(bc, logger);
- mbeansHandlers.put(frameworkHandler, Boolean.FALSE);
- frameworkHandler.open();
- MBeanHandler bundleStateHandler = new BundleStateMBeanHandler(bc, logger);
- mbeansHandlers.put(bundleStateHandler, Boolean.FALSE);
- bundleStateHandler.open();
- MBeanHandler serviceStateHandler = new ServiceStateMBeanHandler(bc, logger);
- mbeansHandlers.put(serviceStateHandler, Boolean.FALSE);
- serviceStateHandler.open();
- MBeanHandler packageStateHandler = new PackageStateMBeanHandler(bc, logger);
- mbeansHandlers.put(packageStateHandler, Boolean.FALSE);
- packageStateHandler.open();
- MBeanHandler permissionAdminHandler = new PermissionAdminMBeanHandler(agentContext);
- mbeansHandlers.put(permissionAdminHandler, Boolean.FALSE);
- permissionAdminHandler.open();
- MBeanHandler userAdminHandler = new UserAdminMBeanHandler(agentContext);
- mbeansHandlers.put(userAdminHandler, Boolean.FALSE);
- userAdminHandler.open();
- MBeanHandler configAdminHandler = new ConfigurationAdminMBeanHandler(agentContext);
- mbeansHandlers.put(configAdminHandler, Boolean.FALSE);
- configAdminHandler.open();
- MBeanHandler provServiceHandler = new ProvisioningServiceMBeanHandler(agentContext);
- mbeansHandlers.put(provServiceHandler, Boolean.FALSE);
- provServiceHandler.open();
- mbeanServiceTracker = new MBeanServiceTracker(agentContext);
- mbeanServiceTracker.open();
- }
-
- /**
- * @see org.apache.aries.jmx.agent.JMXAgent#registerMBeans(javax.management.MBeanServer)
- */
- public synchronized void registerMBeans(final MBeanServer server) {
- for (MBeanHandler mbeanHandler : mbeansHandlers.keySet()) {
- if (mbeansHandlers.get(mbeanHandler) == Boolean.FALSE) {
- String name = mbeanHandler.getName();
- StandardMBean mbean = mbeanHandler.getMbean();
- if (mbean != null) {
- try {
- logger.log(LogService.LOG_INFO, "Registering " + mbean.getMBeanInterface().getName()
- + " to MBeanServer " + server + " with name " + name);
- server.registerMBean(mbean, new ObjectName(name));
- mbeansHandlers.put(mbeanHandler, Boolean.TRUE);
- } catch (InstanceAlreadyExistsException e) {
- logger.log(LogService.LOG_ERROR, "MBean is already registered", e);
- } catch (MBeanRegistrationException e) {
- logger.log(LogService.LOG_ERROR, "Can't register MBean", e);
- } catch (NotCompliantMBeanException e) {
- logger.log(LogService.LOG_ERROR, "MBean is not compliant MBean", e);
- } catch (MalformedObjectNameException e) {
- logger.log(LogService.LOG_ERROR, "Try to register with no valid objectname", e);
- } catch (NullPointerException e) {
- logger.log(LogService.LOG_ERROR, "Name of objectname can't be null", e);
- }
- }
- }
- }
-
- }
-
- /**
- * @see org.apache.aries.jmx.agent.JMXAgent#unregisterMBeans(javax.management.MBeanServer)
- */
- public synchronized void unregisterMBeans(final MBeanServer server) {
- for (MBeanHandler mBeanHandler : mbeansHandlers.keySet()) {
- if (mbeansHandlers.get(mBeanHandler) == Boolean.TRUE) {
- try
- {
- String name = mBeanHandler.getName();
- StandardMBean mbean = mBeanHandler.getMbean();
- if (mbean != null) {
- logger.log(LogService.LOG_INFO, "Unregistering " + mbean.getMBeanInterface().getName()
- + " to MBeanServer " + server + " with name " + name);
- server.unregisterMBean(new ObjectName(name));
- mbeansHandlers.put(mBeanHandler, Boolean.FALSE);
- }
- } catch (MBeanRegistrationException e) {
- logger.log(LogService.LOG_ERROR, "Can't unregister MBean", e);
- } catch (InstanceNotFoundException e) {
- logger.log(LogService.LOG_ERROR, "MBean doesn't exist in the repository", e);
- } catch (MalformedObjectNameException e) {
- logger.log(LogService.LOG_ERROR, "Try to unregister with no valid objectname", e);
- } catch (NullPointerException e) {
- logger.log(LogService.LOG_ERROR, "Name of objectname can't be null ", e);
- } catch (Exception e) {
- logger.log(LogService.LOG_ERROR, "Cannot unregister MBean: " + mBeanHandler, e);
- }
- }
- }
- }
-
- /**
- * @see org.apache.aries.jmx.agent.JMXAgent#registerMBean(org.apache.aries.jmx.MBeanHandler)
- */
- public synchronized void registerMBean(final MBeanHandler mBeanHandler) {
- Object[] servers = getMBeanServers();
- if (servers == null) {
- logger.log(LogService.LOG_WARNING, "There are no MBean servers registred, can't register MBeans");
- return;
- }
-
- for (Object server : servers) {
- String name = mBeanHandler.getName();
- StandardMBean mbean = mBeanHandler.getMbean();
- try {
- logger.log(LogService.LOG_INFO, "Registering " + mbean.getMBeanInterface().getName()
- + " to MBeanServer " + server + " with name " + name);
- ((MBeanServer) server).registerMBean(mbean, new ObjectName(name));
- mbeansHandlers.put(mBeanHandler, Boolean.TRUE);
- } catch (InstanceAlreadyExistsException e) {
- logger.log(LogService.LOG_ERROR, "MBean is already registered", e);
- } catch (MBeanRegistrationException e) {
- logger.log(LogService.LOG_ERROR, "Can't register MBean", e);
- } catch (NotCompliantMBeanException e) {
- logger.log(LogService.LOG_ERROR, "MBean is not compliant MBean, Stopping registration", e);
- return;
- } catch (MalformedObjectNameException e) {
- logger.log(LogService.LOG_ERROR, "Try to register with no valid objectname, Stopping registration", e);
- return;
- } catch (NullPointerException e) {
- logger.log(LogService.LOG_ERROR, "Name of objectname can't be null, Stopping registration", e);
- return;
- }
- }
- }
-
- /**
- * @see org.apache.aries.jmx.agent.JMXAgent#unregisterMBean(org.apache.aries.jmx.MBeanHandler)
- */
- public synchronized void unregisterMBean(final MBeanHandler mBeanHandler) {
- Object[] servers = getMBeanServers();
- for (Object server : servers) {
- String name = mBeanHandler.getName();
- try {
- logger.log(LogService.LOG_INFO, "Unregistering mbean " + " to MBeanServer " + server + " with name "
- + name);
- ((MBeanServer) server).unregisterMBean(new ObjectName(name));
- mbeansHandlers.put(mBeanHandler, Boolean.FALSE);
- } catch (MBeanRegistrationException e) {
- logger.log(LogService.LOG_ERROR, "Can't register MBean", e);
- } catch (InstanceNotFoundException e) {
- logger.log(LogService.LOG_ERROR, "MBean doesn't exist in the repository", e);
- } catch (MalformedObjectNameException e) {
- logger.log(LogService.LOG_ERROR, "Try to register with no valid objectname, Stopping registration", e);
- return;
- } catch (NullPointerException e) {
- logger.log(LogService.LOG_ERROR, "Name of objectname can't be null, Stopping registration", e);
- return;
- }
-
- }
- }
-
- /**
- * @see org.apache.aries.jmx.agent.JMXAgent#unregisterMBean(java.lang.String)
- */
- public synchronized void unregisterMBean(final String name) {
- Object[] servers = getMBeanServers();
- for (Object server : servers) {
- try {
- logger.log(LogService.LOG_INFO, "Unregistering mbean " + " to MBeanServer " + server + " with name "
- + name);
- ((MBeanServer) server).unregisterMBean(new ObjectName(name));
- } catch (MBeanRegistrationException e) {
- logger.log(LogService.LOG_ERROR, "Can't register MBean", e);
- } catch (InstanceNotFoundException e) {
- logger.log(LogService.LOG_ERROR, "MBean doesn't exist in the repository", e);
- } catch (MalformedObjectNameException e) {
- logger.log(LogService.LOG_ERROR, "Try to register with no valid objectname, Stopping registration", e);
- return;
- } catch (NullPointerException e) {
- logger.log(LogService.LOG_ERROR, "Name of objectname can't be null, Stopping registration", e);
- return;
- }
- }
- }
-
- /**
- * @see org.apache.aries.jmx.agent.JMXAgent#stop()
- */
- public synchronized void stop() {
- logger.log(LogService.LOG_INFO, "Stopping JMX OSGi agent");
- mbeanServiceTracker.close();
- for (MBeanHandler mBeanHandler : mbeansHandlers.keySet()) {
- mBeanHandler.close();
- }
- if (registrationExecutor != null && !registrationExecutor.isShutdown()) {
- registrationExecutor.shutdown();
- }
- }
-
- /**
- * @see org.apache.aries.jmx.agent.JMXAgent#getAgentContext()
- */
- public JMXAgentContext getAgentContext() {
- return agentContext;
- }
-
- /**
- * @see org.apache.aries.jmx.agent.JMXAgent#setAgentContext(org.apache.aries.jmx.agent.JMXAgentContext)
- */
- public void setAgentContext(JMXAgentContext agentContext) {
- this.agentContext = agentContext;
- }
-
- /**
- * Gets all MBeanServers from MBeanServiceTracker.
- *
- * @return array of MBean servers.
- */
- private Object[] getMBeanServers() {
- return mbeanServiceTracker.getServices();
- }
-
- /**
- * @see org.apache.aries.jmx.agent.JMXAgent#getRegistrationExecutor()
- */
- public ExecutorService getRegistrationExecutor() {
- return registrationExecutor;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/cm/ConfigurationAdmin.java b/jmx-core/src/main/java/org/apache/aries/jmx/cm/ConfigurationAdmin.java
deleted file mode 100644
index 5991144..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/cm/ConfigurationAdmin.java
+++ /dev/null
@@ -1,237 +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.aries.jmx.cm;
-
-import static org.osgi.jmx.JmxConstants.PROPERTIES_TYPE;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.List;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.aries.jmx.codec.PropertyData;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.jmx.service.cm.ConfigurationAdminMBean;
-import org.osgi.service.cm.Configuration;
-
-/**
- * Implementation of <code>ConfigurationAdminMBean</code>
- *
- * @version $Rev$ $Date$
- */
-public class ConfigurationAdmin implements ConfigurationAdminMBean {
-
- private org.osgi.service.cm.ConfigurationAdmin configurationAdmin;
-
- /**
- * Constructs a ConfigurationAdmin implementation
- * @param configurationAdmin instance of org.osgi.service.cm.ConfigurationAdmin service
- */
- public ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin configurationAdmin) {
- this.configurationAdmin = configurationAdmin;
- }
-
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#createFactoryConfiguration(java.lang.String)
- */
- public String createFactoryConfiguration(String factoryPid) throws IOException {
- return createFactoryConfigurationForLocation(factoryPid, null);
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#createFactoryConfigurationForLocation(java.lang.String, java.lang.String)
- */
- public String createFactoryConfigurationForLocation(String factoryPid, String location) throws IOException {
- if (factoryPid == null || factoryPid.length() < 1) {
- throw new IOException("Argument factoryPid cannot be null or empty");
- }
- Configuration config = configurationAdmin.createFactoryConfiguration(factoryPid);
- config.setBundleLocation(location);
- return config.getPid();
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#delete(java.lang.String)
- */
- public void delete(String pid) throws IOException {
- deleteForLocation(pid, null);
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#deleteForLocation(java.lang.String, java.lang.String)
- */
- public void deleteForLocation(String pid, String location) throws IOException {
- if (pid == null || pid.length() < 1) {
- throw new IOException("Argument pid cannot be null or empty");
- }
- Configuration config = configurationAdmin.getConfiguration(pid, location);
- config.delete();
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#deleteConfigurations(java.lang.String)
- */
- public void deleteConfigurations(String filter) throws IOException {
- if (filter == null || filter.length() < 1) {
- throw new IOException("Argument filter cannot be null or empty");
- }
- Configuration[] configuations = null;
- try {
- configuations = configurationAdmin.listConfigurations(filter);
- } catch (InvalidSyntaxException e) {
- throw new IOException("Invalid filter [" + filter + "] : " + e);
- }
- if (configuations != null) {
- for (Configuration config : configuations) {
- config.delete();
- }
- }
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getBundleLocation(java.lang.String)
- */
- public String getBundleLocation(String pid) throws IOException {
- if (pid == null || pid.length() < 1) {
- throw new IOException("Argument pid cannot be null or empty");
- }
- Configuration config = configurationAdmin.getConfiguration(pid, null);
- String bundleLocation = (config.getBundleLocation() == null) ? "Configuration is not yet bound to a bundle location" : config.getBundleLocation();
- return bundleLocation;
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getConfigurations(java.lang.String)
- */
- public String[][] getConfigurations(String filter) throws IOException {
- if (filter == null || filter.length() < 1) {
- throw new IOException("Argument filter cannot be null or empty");
- }
- List<String[]> result = new ArrayList<String[]>();
- Configuration[] configurations = null;
- try {
- configurations = configurationAdmin.listConfigurations(filter);
- } catch (InvalidSyntaxException e) {
- throw new IOException("Invalid filter [" + filter + "] : " + e);
- }
- if (configurations != null) {
- for (Configuration config : configurations) {
- result.add(new String[] { config.getPid(), config.getBundleLocation() });
- }
- }
- return result.toArray(new String[result.size()][]);
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getFactoryPid(java.lang.String)
- */
- public String getFactoryPid(String pid) throws IOException {
- return getFactoryPidForLocation(pid, null);
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getFactoryPidForLocation(java.lang.String, java.lang.String)
- */
- public String getFactoryPidForLocation(String pid, String location) throws IOException {
- if (pid == null || pid.length() < 1) {
- throw new IOException("Argument pid cannot be null or empty");
- }
- Configuration config = configurationAdmin.getConfiguration(pid, location);
- return config.getFactoryPid();
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getProperties(java.lang.String)
- */
- public TabularData getProperties(String pid) throws IOException {
- return getPropertiesForLocation(pid, null);
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getPropertiesForLocation(java.lang.String, java.lang.String)
- */
- @SuppressWarnings("unchecked")
- public TabularData getPropertiesForLocation(String pid, String location) throws IOException {
- if (pid == null || pid.length() < 1) {
- throw new IOException("Argument pid cannot be null or empty");
- }
- TabularData propertiesTable = null;
- Configuration config = configurationAdmin.getConfiguration(pid, location);
- Dictionary<String, Object> properties = config.getProperties();
- if (properties != null) {
- propertiesTable = new TabularDataSupport(PROPERTIES_TYPE);
- Enumeration<String> keys = properties.keys();
- while (keys.hasMoreElements()) {
- String key = keys.nextElement();
- propertiesTable.put(PropertyData.newInstance(key, properties.get(key)).toCompositeData());
- }
- }
- return propertiesTable;
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#setBundleLocation(java.lang.String, java.lang.String)
- */
- public void setBundleLocation(String pid, String location) throws IOException {
- if (pid == null || pid.length() < 1) {
- throw new IOException("Argument factoryPid cannot be null or empty");
- }
- Configuration config = configurationAdmin.getConfiguration(pid, null);
- config.setBundleLocation(location);
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#update(java.lang.String, javax.management.openmbean.TabularData)
- */
- public void update(String pid, TabularData configurationTable) throws IOException {
- updateForLocation(pid, null, configurationTable);
- }
-
- /**
- * @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#updateForLocation(java.lang.String, java.lang.String, javax.management.openmbean.TabularData)
- */
- @SuppressWarnings("unchecked")
- public void updateForLocation(String pid, String location, TabularData configurationTable) throws IOException {
- if (pid == null || pid.length() < 1) {
- throw new IOException("Argument pid cannot be null or empty");
- }
- if (configurationTable == null) {
- throw new IOException("Argument configurationTable cannot be null");
- }
-
- if (!PROPERTIES_TYPE.equals(configurationTable.getTabularType())) {
- throw new IOException("Invalid TabularType [" + configurationTable.getTabularType() + "]");
- }
- Dictionary<String, Object> configurationProperties = new Hashtable<String, Object>();
- Collection<CompositeData> compositeData = (Collection<CompositeData>) configurationTable.values();
- for (CompositeData row: compositeData) {
- PropertyData<? extends Class> propertyData = PropertyData.from(row);
- configurationProperties.put(propertyData.getKey(), propertyData.getValue());
- }
- Configuration config = configurationAdmin.getConfiguration(pid, location);
- config.update(configurationProperties);
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/cm/ConfigurationAdminMBeanHandler.java b/jmx-core/src/main/java/org/apache/aries/jmx/cm/ConfigurationAdminMBeanHandler.java
deleted file mode 100644
index 1389b92..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/cm/ConfigurationAdminMBeanHandler.java
+++ /dev/null
@@ -1,74 +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.aries.jmx.cm;
-
-import javax.management.NotCompliantMBeanException;
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.AbstractCompendiumHandler;
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.MBeanHandler;
-import org.apache.aries.jmx.agent.JMXAgentContext;
-import org.osgi.jmx.service.cm.ConfigurationAdminMBean;
-import org.osgi.service.log.LogService;
-
-/**
- * <p>
- * Implementation of <code>MBeanHandler</code> which manages the <code>ConfigurationAdminMBean</code> implementation
- *
- * @see MBeanHandler </p>
- *
- * @version $Rev$ $Date$
- */
-public class ConfigurationAdminMBeanHandler extends AbstractCompendiumHandler {
-
- /**
- * Constructs new ConfigurationAdminMBeanHandler instance
- *
- * @param agentContext
- * JMXAgentContext instance
- */
- public ConfigurationAdminMBeanHandler(JMXAgentContext agentContext) {
- super(agentContext, "org.osgi.service.cm.ConfigurationAdmin");
- }
-
- /**
- * @see org.apache.aries.jmx.AbstractCompendiumHandler#constructInjectMBean(java.lang.Object)
- */
- @Override
- protected StandardMBean constructInjectMBean(Object targetService) {
- ConfigurationAdminMBean caMBean = new org.apache.aries.jmx.cm.ConfigurationAdmin(
- (org.osgi.service.cm.ConfigurationAdmin) targetService);
- StandardMBean mbean = null;
- try {
- mbean = new StandardMBean(caMBean, ConfigurationAdminMBean.class);
- } catch (NotCompliantMBeanException e) {
- Logger logger = agentContext.getLogger();
- logger.log(LogService.LOG_ERROR, "Failed to instantiate MBean for "
- + ConfigurationAdminMBean.class.getName(), e);
- }
- return mbean;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getName()
- */
- public String getName() {
- return ConfigurationAdminMBean.OBJECTNAME;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/AuthorizationData.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/AuthorizationData.java
deleted file mode 100644
index 017fdcf..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/AuthorizationData.java
+++ /dev/null
@@ -1,114 +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.aries.jmx.codec;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-
-import org.osgi.jmx.service.useradmin.UserAdminMBean;
-import org.osgi.service.useradmin.Authorization;
-
-/**
- * <p>
- * <tt>AuthorizationData</tt> represents Authorization Type @see {@link UserAdminMBean#AUTORIZATION_TYPE}.It is a codec
- * for the <code>CompositeData</code> representing an Authorization .
- * </p>
- *
- *
- * @version $Rev$ $Date$
- */
-public class AuthorizationData {
-
- /**
- * authorization context name.
- */
- private String name;
- /**
- * roles implied by authorization context.
- */
- private String[] roles;
-
- /**
- * Constructs new AuthorizationData from Authorization.
- * @param auth {@link Authorization} instance.
- */
- public AuthorizationData(Authorization auth){
- this.name = auth.getName();
- this.roles = auth.getRoles();
- }
-
- /**
- * Constructs new AuthorizationData.
- *
- * @param name of authorization context.
- * @param roles implied by authorization context.
- */
- public AuthorizationData(String name, String[] roles){
- this.name = name;
- this.roles = roles;
- }
- /**
- * Translates AuthorizationData to CompositeData represented by
- * compositeType {@link UserAdminMBean#AUTORIZATION_TYPE}.
- *
- * @return translated AuthorizationData to compositeData.
- */
- public CompositeData toCompositeData() {
- try {
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(UserAdminMBean.NAME, name);
- items.put(UserAdminMBean.ROLES, roles);
- return new CompositeDataSupport(UserAdminMBean.AUTORIZATION_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Can't create CompositeData" + e);
- }
- }
-
- /**
- * Static factory method to create AuthorizationData from CompositeData object.
- *
- * @param data {@link CompositeData} instance.
- * @return AuthorizationData instance.
- */
- public static AuthorizationData from(CompositeData data) {
- if(data == null){
- return null;
- }
- String name = (String) data.get(UserAdminMBean.NAME);
- String[] roles = (String[]) data.get(UserAdminMBean.ROLES);
- return new AuthorizationData(name, roles);
- }
-
- /**
- * @return the name
- */
- public String getName() {
- return name;
- }
-
- /**
- * @return the roles
- */
- public String[] getRoles() {
- return roles;
- }
-
-}
\ No newline at end of file
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchActionResult.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchActionResult.java
deleted file mode 100644
index f68d240..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchActionResult.java
+++ /dev/null
@@ -1,164 +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.aries.jmx.codec;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-
-import org.osgi.jmx.framework.FrameworkMBean;
-
-/**
- * <p>
- * <tt>BatchInstallResult</tt> represents codec for resulting CompositeData of batch operations
- * made on bundle via FrameworkMBean.
- * It's converting batch install results to CompositeData {@link #toCompositeData()}
- * and from CompositeData to this BatchActionResult {@link #from(CompositeData)}.
- * It provides also constructors to build BatchActionResult.
- * Structure of compositeData is as defined in compositeType @see {@link FrameworkMBean#BATCH_ACTION_RESULT_TYPE}.
- * </p>
- * @see BatchResult
- *
- * @version $Rev$ $Date$
- */
-public class BatchActionResult extends BatchResult{
-
- /**
- * @see FrameworkMBean#REMAINING_ID_ITEM
- * @see FrameworkMBean#REMAINING_LOCATION_ITEM
- */
- private long[] remainingItems;
- /**
- * @see FrameworkMBean#BUNDLE_IN_ERROR_ID_ITEM
- * @see FrameworkMBean#BUNDLE_IN_ERROR
- */
- private long bundleInError;
-
- /**
- * Constructs new BatchActionResult with completedItems array.
- * Newly created object represents successful batch result.
- * @param completedItems containing the list of bundles completing the batch operation.
- */
- public BatchActionResult(long[] completedItems){
- this.completed = completedItems;
- success = true;
- }
-
- /**
- * Constructs new BatchActionResult with error message.
- * Newly created object represents failed batch result.
- * @param error containing the error message of the batch operation.
- */
- public BatchActionResult(String error){
- this.error = error;
- success = false;
- }
-
- /**
- * Constructs new BatchActionResult.
- * Newly created object represents failed batch result.
- *
- * @param completedItems containing the list of bundles completing the batch operation.
- * @param error containing the error message of the batch operation.
- * @param remainingItems remaining bundles unprocessed by the
- * failing batch operation.
- * @param bundleInError containing the bundle which caused the error during the batch
- * operation.
- */
- public BatchActionResult(long[] completedItems, String error, long[] remainingItems, long bundleInError){
- this(completedItems,error,remainingItems,false,bundleInError);
- }
-
- /**
- * Constructs new BatchActionResult.
- *
- * @param completedItems containing the list of bundles completing the batch operation.
- * @param error containing the error message of the batch operation.
- * @param remainingItems remaining bundles unprocessed by the
- * failing batch operation.
- * @param success indicates if this operation was successful.
- * @param bundleInError containing the bundle which caused the error during the batch
- * operation.
- */
- public BatchActionResult(long[] completedItems, String error, long[] remainingItems, boolean success, long bundleInError){
- this.bundleInError = bundleInError;
- this.completed = completedItems;
- this.error = error;
- this.remainingItems = remainingItems;
- this.success = success;
- }
-
- /**
- * Translates BatchActionResult to CompositeData represented by
- * compositeType {@link FrameworkMBean#BATCH_ACTION_RESULT_TYPE}.
- *
- * @return translated BatchActionResult to compositeData.
- */
- public CompositeData toCompositeData(){
- try {
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(FrameworkMBean.BUNDLE_IN_ERROR, bundleInError);
- items.put(FrameworkMBean.COMPLETED, toLongArray(completed));
- items.put(FrameworkMBean.ERROR, error);
- items.put(FrameworkMBean.REMAINING, toLongArray(remainingItems));
- items.put(FrameworkMBean.SUCCESS, success);
- return new CompositeDataSupport(FrameworkMBean.BATCH_ACTION_RESULT_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Can't create CompositeData" + e);
- }
- }
-
- /**
- * Static factory method to create BatchActionResult from CompositeData object.
- *
- * @param data {@link CompositeData} instance.
- * @return BatchActionResult instance.
- */
- public static BatchActionResult from(CompositeData data){
- if(data == null){
- return null;
- }
- long bundleInError = (Long) data.get(FrameworkMBean.BUNDLE_IN_ERROR);
- // need to convert primitive array to wrapper type array
- // compositeData accept only wrapper type array
- long[] completedItems = toLongPrimitiveArray((Long[])data.get(FrameworkMBean.COMPLETED));
- long[] remainingItems = toLongPrimitiveArray((Long[]) data.get(FrameworkMBean.REMAINING));
- String error = (String) data.get(FrameworkMBean.ERROR);
- Boolean success = (Boolean) data.get(FrameworkMBean.SUCCESS);
- return new BatchActionResult(completedItems, error, remainingItems, success, bundleInError);
- }
-
- /**
- * Gets remaining items id's.
- * @return the remainingItems.
- */
- public long[] getRemainingItems() {
- return remainingItems;
- }
-
- /**
- * Gets bundle in error id.
- * @return the bundleInError.
- */
- public long getBundleInError() {
- return bundleInError;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchInstallResult.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchInstallResult.java
deleted file mode 100644
index ea2d712..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchInstallResult.java
+++ /dev/null
@@ -1,163 +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.aries.jmx.codec;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-
-import org.osgi.jmx.framework.FrameworkMBean;
-
-/**
- * <p>
- * <tt>BatchInstallResult</tt> represents codec for resulting CompositeData of
- * FrameworkMBean installBundles methods.
- * It converting batch install results to CompositeData {@link #toCompositeData()}
- * and from CompositeData to this BatchInstallResult {@link #from(CompositeData)}.
- * It provides also constructors to build BatchInstallResult.
- * Structure of compositeData as defined in compositeType @see {@link FrameworkMBean#BATCH_INSTALL_RESULT_TYPE}.
- * </p>
- * @see BatchResult
- *
- * @version $Rev$ $Date$
- */
-public class BatchInstallResult extends BatchResult {
-
- /**
- * @see FrameworkMBean#REMAINING_LOCATION_ITEM
- * @see FrameworkMBean#REMAINING
- */
- private String[] remainingLocationItems;
-
- /**
- * @see FrameworkMBean#BUNDLE_IN_ERROR_LOCATION_ITEM
- * @see FrameworkMBean#BUNDLE_IN_ERROR
- */
- private String bundleInError;
-
- /**
- * Constructs new BatchInstallResult with completedItems array.
- * Newly created object represents successful batch result.
- * @param completedItems containing the list of bundles completing the batch operation.
- */
- public BatchInstallResult(long[] completedItems) {
- this.completed = completedItems;
- success = true;
- }
-
- /**
- * Constructs new BatchInstallResult with error message.
- * Newly created object represents failed batch result.
- * @param error containing the error message of the batch operation.
- */
- public BatchInstallResult(String error){
- this.error = error;
- success = false;
- }
- /**
- * Constructs new BatchInstallResult.
- * Newly created object represents failed batch result.
- *
- * @param completedItems containing the list of bundles completing the batch operation.
- * @param error containing the error message of the batch operation.
- * @param remainingLocationItems remaining bundles unprocessed by the
- * failing batch operation.
- * @param bundleInError containing the bundle which caused the error during the batch
- * operation.
- */
- public BatchInstallResult(long[] completedItems, String error, String[] remainingLocationItems, String bundleInError) {
- this(completedItems, error, remainingLocationItems, false, bundleInError);
- }
-
- /**
- * Constructs new BatchInstallResult.
- *
- * @param completedItems containing the list of bundles completing the batch operation.
- * @param error containing the error message of the batch operation.
- * @param remainingLocationItems remaining bundles unprocessed by the
- * failing batch operation.
- * @param success indicates if this operation was successful.
- * @param bundleInError containing the bundle which caused the error during the batch
- * operation.
- */
- public BatchInstallResult(long[] completedItems, String error, String[] remainingLocationItems, boolean success,
- String bundleInError) {
- this.bundleInError = bundleInError;
- this.completed = completedItems;
- this.error = error;
- this.remainingLocationItems = remainingLocationItems;
- this.success = success;
- }
-
- /**
- * Translates BatchInstallResult to CompositeData represented by
- * compositeType {@link FrameworkMBean#BATCH_INSTALL_RESULT_TYPE}.
- *
- * @return translated BatchInstallResult to compositeData.
- */
- public CompositeData toCompositeData() {
- try {
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(FrameworkMBean.BUNDLE_IN_ERROR, bundleInError);
- items.put(FrameworkMBean.COMPLETED, toLongArray(completed));
- items.put(FrameworkMBean.ERROR, error);
- items.put(FrameworkMBean.REMAINING, remainingLocationItems);
- items.put(FrameworkMBean.SUCCESS, success);
- return new CompositeDataSupport(FrameworkMBean.BATCH_INSTALL_RESULT_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Can't create CompositeData" + e);
- }
- }
-
- /**
- * Static factory method to create BatchInstallResult from CompositeData object.
- *
- * @param data {@link CompositeData} instance.
- * @return BatchInstallResult instance.
- */
- public static BatchInstallResult from(CompositeData data) {
- if(data == null){
- return null;
- }
- String bundleInError = (String) data.get(FrameworkMBean.BUNDLE_IN_ERROR);
- long[] completedItems = toLongPrimitiveArray((Long[]) data.get(FrameworkMBean.COMPLETED));
- String[] remainingLocationItems = (String[]) data.get(FrameworkMBean.REMAINING);
- String error = (String) data.get(FrameworkMBean.ERROR);
- boolean success = (Boolean) data.get(FrameworkMBean.SUCCESS);
- return new BatchInstallResult(completedItems, error, remainingLocationItems, success, bundleInError);
- }
-
- /**
- * Gets remaining location items.
- * @return array of String with locations.
- */
- public String[] getRemainingLocationItems() {
- return remainingLocationItems;
- }
-
- /**
- * Gets bundle in error location.
- * @return the bundleInError.
- */
- public String getBundleInError() {
- return bundleInError;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchResult.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchResult.java
deleted file mode 100644
index 7bdbb43..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchResult.java
+++ /dev/null
@@ -1,113 +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.aries.jmx.codec;
-
-import org.osgi.jmx.framework.FrameworkMBean;
-
-/**
- * <p>
- * <tt>BatchResult</tt> represents abstract class for BatchResults.
- * It contains common data structure of batch result:
- * <ul>
- * <li>completed containing the list of bundles completing the batch operation.</li>
- * <li>error containing the error message of the batch operation.</li>
- * <li>success indicates if this operation was successful.</li>
- * </ul>
- * </p>
- *
- *
- * @version $Rev$ $Date$
- */
-public abstract class BatchResult {
-
- /**
- * @see FrameworkMBean#COMPLETED_ITEM
- * @see FrameworkMBean#COMPLETED
- */
- protected long[] completed;
- /**
- * @see FrameworkMBean#ERROR_ITEM
- * @see FrameworkMBean#ERROR
- */
- protected String error;
- /**
- * @see FrameworkMBean#SUCCESS_ITEM
- * @see FrameworkMBean#SUCCESS
- */
- protected boolean success;
-
- /**
- * Gets completed item id's.
- * @return completed items id's.
- */
- public long[] getCompleted() {
- return completed;
- }
-
- /**
- * Gets error message.
- * @return error message.
- */
- public String getError() {
- return error;
- }
-
- /**
- * Gets success value.
- * @return true if success false if not.
- */
- public boolean isSuccess() {
- return success;
- }
-
- /**
- * Converts primitive array of strings to Long array.
- *
- * @param primitiveArray primitive long array.
- * @return Long array.
- */
- protected Long[] toLongArray(long[] primitiveArray) {
- if (primitiveArray == null) {
- return null;
- }
- Long[] converted = new Long[primitiveArray.length];
- for (int i = 0; i < primitiveArray.length; i++) {
- converted[i] = primitiveArray[i];
- }
-
- return converted;
- }
-
- /**
- * Converts Long array to primitive array of long.
- *
- * @param wrapperArray Long array.
- * @return primitive long array.
- */
- protected static long[] toLongPrimitiveArray(Long[] wrapperArray) {
- if (wrapperArray == null) {
- return null;
- }
- long[] converted = new long[wrapperArray.length];
- for (int i = 0; i < wrapperArray.length; i++) {
- converted[i] = wrapperArray[i];
- }
-
- return converted;
- }
-
-}
\ No newline at end of file
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/BundleData.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/BundleData.java
deleted file mode 100644
index 64b7eb6..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/BundleData.java
+++ /dev/null
@@ -1,445 +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.aries.jmx.codec;
-
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleDependencies;
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleExportedPackages;
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleImportedPackages;
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleState;
-import static org.apache.aries.jmx.util.FrameworkUtils.getDependentBundles;
-import static org.apache.aries.jmx.util.FrameworkUtils.getFragmentIds;
-import static org.apache.aries.jmx.util.FrameworkUtils.getHostIds;
-import static org.apache.aries.jmx.util.FrameworkUtils.getRegisteredServiceIds;
-import static org.apache.aries.jmx.util.FrameworkUtils.getServicesInUseByBundle;
-import static org.apache.aries.jmx.util.FrameworkUtils.isBundlePendingRemoval;
-import static org.apache.aries.jmx.util.FrameworkUtils.isBundleRequiredByOthers;
-import static org.apache.aries.jmx.util.TypeUtils.toLong;
-import static org.apache.aries.jmx.util.TypeUtils.toPrimitive;
-import static org.osgi.jmx.framework.BundleStateMBean.BUNDLE_TYPE;
-import static org.osgi.jmx.framework.BundleStateMBean.EXPORTED_PACKAGES;
-import static org.osgi.jmx.framework.BundleStateMBean.FRAGMENT;
-import static org.osgi.jmx.framework.BundleStateMBean.FRAGMENTS;
-import static org.osgi.jmx.framework.BundleStateMBean.HEADERS;
-import static org.osgi.jmx.framework.BundleStateMBean.HEADERS_TYPE;
-import static org.osgi.jmx.framework.BundleStateMBean.HEADER_TYPE;
-import static org.osgi.jmx.framework.BundleStateMBean.HOSTS;
-import static org.osgi.jmx.framework.BundleStateMBean.IDENTIFIER;
-import static org.osgi.jmx.framework.BundleStateMBean.IMPORTED_PACKAGES;
-import static org.osgi.jmx.framework.BundleStateMBean.KEY;
-import static org.osgi.jmx.framework.BundleStateMBean.LAST_MODIFIED;
-import static org.osgi.jmx.framework.BundleStateMBean.LOCATION;
-import static org.osgi.jmx.framework.BundleStateMBean.PERSISTENTLY_STARTED;
-import static org.osgi.jmx.framework.BundleStateMBean.REGISTERED_SERVICES;
-import static org.osgi.jmx.framework.BundleStateMBean.REMOVAL_PENDING;
-import static org.osgi.jmx.framework.BundleStateMBean.REQUIRED;
-import static org.osgi.jmx.framework.BundleStateMBean.REQUIRED_BUNDLES;
-import static org.osgi.jmx.framework.BundleStateMBean.REQUIRING_BUNDLES;
-import static org.osgi.jmx.framework.BundleStateMBean.SERVICES_IN_USE;
-import static org.osgi.jmx.framework.BundleStateMBean.START_LEVEL;
-import static org.osgi.jmx.framework.BundleStateMBean.STATE;
-import static org.osgi.jmx.framework.BundleStateMBean.SYMBOLIC_NAME;
-import static org.osgi.jmx.framework.BundleStateMBean.VALUE;
-import static org.osgi.jmx.framework.BundleStateMBean.VERSION;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.management.JMRuntimeException;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.jmx.framework.BundleStateMBean;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.startlevel.StartLevel;
-
-/**
- * <p>
- * <tt>BundleData</tt> represents BundleData Type @see {@link BundleStateMBean#BUNDLE_TYPE}. It is a codec for the
- * <code>CompositeData</code> representing an OSGi BundleData.
- * </p>
- *
- * @version $Rev$ $Date$
- */
-public class BundleData {
-
- /**
- * @see BundleStateMBean#EXPORTED_PACKAGES_ITEM
- */
- private String[] exportedPackages;
-
- /**
- * @see BundleStateMBean#FRAGMENT_ITEM
- */
- private boolean fragment;
-
- /**
- * @see BundleStateMBean#FRAGMENTS_ITEM
- */
- private long[] fragments;
-
- /**
- * @see BundleStateMBean#HEADER_TYPE
- */
- private List<Header> headers = new ArrayList<Header>();
-
- /**
- * @see BundleStateMBean#HOSTS_ITEM
- */
- private long[] hosts;
-
- /**
- * @see BundleStateMBean#IDENTIFIER_ITEM
- */
- private long identifier;
-
- /**
- * @see BundleStateMBean#IMPORTED_PACKAGES_ITEM
- */
- private String[] importedPackages;
-
- /**
- * @see BundleStateMBean#LAST_MODIFIED_ITEM
- */
- private long lastModified;
-
- /**
- * @see BundleStateMBean#LOCATION_ITEM
- */
- private String location;
-
- /**
- * @see BundleStateMBean#PERSISTENTLY_STARTED_ITEM
- */
- private boolean persistentlyStarted;
-
- /**
- * @see BundleStateMBean#REGISTERED_SERVICES_ITEM
- */
- private long[] registeredServices;
-
- /**
- * @see BundleStateMBean#REMOVAL_PENDING_ITEM
- */
- private boolean removalPending;
-
- /**
- * @see BundleStateMBean#REQUIRED_ITEM
- */
- private boolean required;
-
- /**
- * @see BundleStateMBean#REQUIRED_BUNDLES_ITEM
- */
- private long[] requiredBundles;
-
- /**
- * @see BundleStateMBean#REQUIRING_BUNDLES_ITEM
- */
- private long[] requiringBundles;
-
- /**
- * @see BundleStateMBean#SERVICES_IN_USE_ITEM
- */
- private long[] servicesInUse;
-
- /**
- * @see BundleStateMBean#START_LEVEL_ITEM
- */
- private int bundleStartLevel;
-
- /**
- * @see BundleStateMBean#STATE_ITEM
- */
- private String state;
-
- /**
- * @see BundleStateMBean#SYMBOLIC_NAME_ITEM
- */
- private String symbolicName;
-
- /**
- * @see BundleStateMBean#VERSION_ITEM
- */
- private String version;
-
- private BundleData() {
- super();
- }
-
- @SuppressWarnings("unchecked")
- public BundleData(BundleContext localBundleContext, Bundle bundle, PackageAdmin packageAdmin, StartLevel startLevel) {
- if (bundle == null) {
- throw new IllegalArgumentException("Argument bundle cannot be null");
- }
- if (packageAdmin == null || startLevel == null) {
- throw new IllegalArgumentException("Arguments PackageAdmin / startLevel cannot be null");
- }
- this.exportedPackages = getBundleExportedPackages(bundle, packageAdmin);
- this.fragment = (PackageAdmin.BUNDLE_TYPE_FRAGMENT == packageAdmin.getBundleType(bundle));
- this.fragments = getFragmentIds(bundle, packageAdmin);
- Dictionary<String, String> bundleHeaders = bundle.getHeaders();
- Enumeration<String> keys = bundleHeaders.keys();
- while (keys.hasMoreElements()) {
- String key = keys.nextElement();
- headers.add(new Header(key, bundleHeaders.get(key)));
- }
- this.hosts = getHostIds(bundle, packageAdmin);
- this.identifier = bundle.getBundleId();
- this.importedPackages = getBundleImportedPackages(localBundleContext, bundle, packageAdmin);
- this.lastModified = bundle.getLastModified();
- this.location = bundle.getLocation();
- this.persistentlyStarted = startLevel.isBundlePersistentlyStarted(bundle);
- this.registeredServices = getRegisteredServiceIds(bundle);
- this.removalPending = isBundlePendingRemoval(bundle, packageAdmin);
- this.required = isBundleRequiredByOthers(bundle, packageAdmin);
- this.requiredBundles = getBundleDependencies(localBundleContext, bundle, packageAdmin);
- this.requiringBundles = getDependentBundles(bundle, packageAdmin);
- this.servicesInUse = getServicesInUseByBundle(bundle);
- this.bundleStartLevel = startLevel.getBundleStartLevel(bundle);
- this.state = getBundleState(bundle);
- this.symbolicName = bundle.getSymbolicName();
- this.version = bundle.getVersion().toString();
- }
-
- /**
- * Returns CompositeData representing a BundleData complete state typed by {@link BundleStateMBean#BUNDLE_TYPE}
- *
- * @return
- */
- public CompositeData toCompositeData() {
- CompositeData result = null;
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(EXPORTED_PACKAGES, this.exportedPackages);
- items.put(FRAGMENT, this.fragment);
- items.put(FRAGMENTS, toLong(this.fragments));
- items.put(HOSTS, toLong(this.hosts));
- items.put(IDENTIFIER, this.identifier);
- items.put(IMPORTED_PACKAGES, this.importedPackages);
- items.put(LAST_MODIFIED, this.lastModified);
- items.put(LOCATION, this.location);
- items.put(PERSISTENTLY_STARTED, this.persistentlyStarted);
- items.put(REGISTERED_SERVICES, toLong(this.registeredServices));
- items.put(REMOVAL_PENDING, this.removalPending);
- items.put(REQUIRED, this.required);
- items.put(REQUIRED_BUNDLES, toLong(this.requiredBundles));
- items.put(REQUIRING_BUNDLES, toLong(this.requiringBundles));
- items.put(SERVICES_IN_USE, toLong(this.servicesInUse));
- items.put(START_LEVEL, this.bundleStartLevel);
- items.put(STATE, this.state);
- items.put(SYMBOLIC_NAME, this.symbolicName);
- items.put(VERSION, this.version);
- TabularData headerTable = new TabularDataSupport(HEADERS_TYPE);
- for (Header header : this.headers) {
- headerTable.put(header.toCompositeData());
- }
- items.put(HEADERS, headerTable);
- try {
- result = new CompositeDataSupport(BUNDLE_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Failed to create CompositeData for BundleData [" + this.identifier
- + "]", e);
- }
- return result;
- }
-
- /**
- * Constructs a <code>BundleData</code> object from the given <code>CompositeData</code>
- *
- * @param compositeData
- * @return
- * @throws IlleglArgumentException
- * if compositeData is null or not of type {@link BundleStateMBean#BUNDLE_TYPE}
- */
- @SuppressWarnings("unchecked")
- public static BundleData from(CompositeData compositeData) throws IllegalArgumentException {
- if (compositeData == null) {
- throw new IllegalArgumentException("Argument compositeData cannot be null");
- }
- if (!compositeData.getCompositeType().equals(BUNDLE_TYPE)) {
- throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
- }
- BundleData bundleData = new BundleData();
- bundleData.exportedPackages = (String[]) compositeData.get(EXPORTED_PACKAGES);
- bundleData.fragment = (Boolean) compositeData.get(FRAGMENT);
- bundleData.fragments = toPrimitive((Long[]) compositeData.get(FRAGMENTS));
- bundleData.hosts = toPrimitive((Long[]) compositeData.get(HOSTS));
- bundleData.identifier = (Long) compositeData.get(IDENTIFIER);
- bundleData.importedPackages = (String[]) compositeData.get(IMPORTED_PACKAGES);
- bundleData.lastModified = (Long) compositeData.get(LAST_MODIFIED);
- bundleData.location = (String) compositeData.get(LOCATION);
- bundleData.persistentlyStarted = (Boolean) compositeData.get(PERSISTENTLY_STARTED);
- bundleData.registeredServices = toPrimitive((Long[]) compositeData.get(REGISTERED_SERVICES));
- bundleData.removalPending = (Boolean) compositeData.get(REMOVAL_PENDING);
- bundleData.required = (Boolean) compositeData.get(REQUIRED);
- bundleData.requiredBundles = toPrimitive((Long[]) compositeData.get(REQUIRED_BUNDLES));
- bundleData.requiringBundles = toPrimitive((Long[]) compositeData.get(REQUIRING_BUNDLES));
- bundleData.servicesInUse = toPrimitive((Long[]) compositeData.get(SERVICES_IN_USE));
- bundleData.bundleStartLevel = (Integer) compositeData.get(START_LEVEL);
- bundleData.state = (String) compositeData.get(STATE);
- bundleData.symbolicName = (String) compositeData.get(SYMBOLIC_NAME);
- bundleData.version = (String) compositeData.get(VERSION);
- TabularData headerTable = (TabularData) compositeData.get(HEADERS);
- Collection<CompositeData> headerData = (Collection<CompositeData>) headerTable.values();
- for (CompositeData headerRow : headerData) {
- bundleData.headers.add(Header.from(headerRow));
- }
- return bundleData;
- }
-
- public String[] getExportedPackages() {
- return exportedPackages;
- }
-
- public boolean isFragment() {
- return fragment;
- }
-
- public long[] getFragments() {
- return fragments;
- }
-
- public List<Header> getHeaders() {
- return headers;
- }
-
- public long[] getHosts() {
- return hosts;
- }
-
- public long getIdentifier() {
- return identifier;
- }
-
- public String[] getImportedPackages() {
- return importedPackages;
- }
-
- public long getLastModified() {
- return lastModified;
- }
-
- public String getLocation() {
- return location;
- }
-
- public boolean isPersistentlyStarted() {
- return persistentlyStarted;
- }
-
- public long[] getRegisteredServices() {
- return registeredServices;
- }
-
- public boolean isRemovalPending() {
- return removalPending;
- }
-
- public boolean isRequired() {
- return required;
- }
-
- public long[] getRequiredBundles() {
- return requiredBundles;
- }
-
- public long[] getRequiringBundles() {
- return requiringBundles;
- }
-
- public long[] getServicesInUse() {
- return servicesInUse;
- }
-
- public int getBundleStartLevel() {
- return bundleStartLevel;
- }
-
- public String getState() {
- return state;
- }
-
- public String getSymbolicName() {
- return symbolicName;
- }
-
- public String getVersion() {
- return version;
- }
-
- /*
- * Represents key/value pair in BundleData headers
- */
- public static class Header {
-
- private String key;
- private String value;
-
- public String getKey() {
- return key;
- }
-
- public String getValue() {
- return value;
- }
-
- private Header() {
- super();
- }
-
- public Header(String key, String value) {
- this.key = key;
- this.value = value;
- }
-
- public CompositeData toCompositeData() throws JMRuntimeException {
- CompositeData result = null;
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(KEY, key);
- items.put(VALUE, value);
- try {
- result = new CompositeDataSupport(HEADER_TYPE, items);
- } catch (OpenDataException e) {
- throw new JMRuntimeException("Failed to create CompositeData for header [" + key + ":" + value + "] - "
- + e.getMessage());
- }
- return result;
- }
-
- public static Header from(CompositeData compositeData) {
- if (compositeData == null) {
- throw new IllegalArgumentException("Argument compositeData cannot be null");
- }
- if (!compositeData.getCompositeType().equals(HEADER_TYPE)) {
- throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
- }
- Header header = new Header();
- header.key = (String) compositeData.get(KEY);
- header.value = (String) compositeData.get(VALUE);
- return header;
- }
- }
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/BundleEventData.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/BundleEventData.java
deleted file mode 100644
index 01c11c6..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/BundleEventData.java
+++ /dev/null
@@ -1,137 +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.aries.jmx.codec;
-
-import static org.osgi.jmx.framework.BundleStateMBean.BUNDLE_EVENT_TYPE;
-import static org.osgi.jmx.framework.BundleStateMBean.EVENT;
-import static org.osgi.jmx.framework.BundleStateMBean.IDENTIFIER;
-import static org.osgi.jmx.framework.BundleStateMBean.LOCATION;
-import static org.osgi.jmx.framework.BundleStateMBean.SYMBOLIC_NAME;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleEvent;
-import org.osgi.jmx.framework.BundleStateMBean;
-
-/**
- * <p>
- * <tt>BundleEventData</tt> represents BundleEvent Type @see {@link BundleStateMBean#BUNDLE_EVENT_TYPE}. It is a codec
- * for the <code>CompositeData</code> representing an OSGi BundleEvent.
- * </p>
- *
- * @version $Rev$ $Date$
- */
-public class BundleEventData {
-
- /**
- * @see BundleStateMBean#IDENTIFIER_ITEM
- */
- private long bundleId;
-
- /**
- * @see BundleStateMBean#LOCATION_ITEM
- */
- private String location;
-
- /**
- * @see BundleStateMBean#SYMBOLIC_NAME_ITEM
- */
- private String bundleSymbolicName;
-
- /**
- * @see BundleStateMBean#EVENT_ITEM
- */
- private int eventType;
-
- private BundleEventData() {
- super();
- }
-
- public BundleEventData(BundleEvent bundleEvent) {
- this.eventType = bundleEvent.getType();
- Bundle bundle = bundleEvent.getBundle();
- this.bundleId = bundle.getBundleId();
- this.location = bundle.getLocation();
- this.bundleSymbolicName = bundle.getSymbolicName();
- }
-
- /**
- * Returns CompositeData representing a BundleEvent typed by {@link BundleStateMBean#BUNDLE_EVENT_TYPE}
- *
- * @return
- */
- public CompositeData toCompositeData() {
- CompositeData result = null;
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(IDENTIFIER, this.bundleId);
- items.put(SYMBOLIC_NAME, this.bundleSymbolicName);
- items.put(LOCATION, this.location);
- items.put(EVENT, this.eventType);
- try {
- result = new CompositeDataSupport(BUNDLE_EVENT_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Failed to create CompositeData for BundleEvent for Bundle ["
- + this.bundleId + "]", e);
- }
- return result;
- }
-
- /**
- * Returns a <code>BundleEventData</code> representation of the given compositeData
- *
- * @param compositeData
- * @return
- * @throws IllegalArgumentException
- * if the compositeData is null or incorrect type
- */
- public static BundleEventData from(CompositeData compositeData) throws IllegalArgumentException {
- BundleEventData eventData = new BundleEventData();
- if (compositeData == null) {
- throw new IllegalArgumentException("Argument compositeData cannot be null");
- }
- if (!compositeData.getCompositeType().equals(BUNDLE_EVENT_TYPE)) {
- throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
- }
- eventData.bundleId = (Long) compositeData.get(IDENTIFIER);
- eventData.bundleSymbolicName = (String) compositeData.get(SYMBOLIC_NAME);
- eventData.eventType = (Integer) compositeData.get(EVENT);
- eventData.location = (String) compositeData.get(LOCATION);
- return eventData;
- }
-
- public long getBundleId() {
- return bundleId;
- }
-
- public String getLocation() {
- return location;
- }
-
- public String getBundleSymbolicName() {
- return bundleSymbolicName;
- }
-
- public int getEventType() {
- return eventType;
- }
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/GroupData.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/GroupData.java
deleted file mode 100644
index 476c4e9..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/GroupData.java
+++ /dev/null
@@ -1,135 +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.aries.jmx.codec;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-
-import org.osgi.jmx.service.useradmin.UserAdminMBean;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.Role;
-
-/**
- * <p>
- * <tt>GroupData</tt> represents Group Type @see {@link UserAdminMBean#GROUP_TYPE}.It is a codec
- * for the <code>CompositeData</code> representing a Group.
- * </p>
- * </p>
- *
- * @version $Rev$ $Date$
- */
-public class GroupData extends UserData {
-
- /**
- * @see UserAdminMBean#MEMBERS_ITEM
- * @see UserAdminMBean#MEMBERS
- */
- private String[] members;
- /**
- * @see UserAdminMBean#REQUIRED_MEMBERS
- * @see UserAdminMBean#REQUIRED_MEMBERS_ITEM
- */
- private String[] requiredMembers;
-
- /**
- * Constructs new GroupData from Group object.
- * @param group {@link Group} instance.
- */
- public GroupData(Group group) {
- super(group.getName(), Role.GROUP);
- this.members = toArray(group.getMembers());
- this.requiredMembers = toArray(group.getRequiredMembers());
- }
-
- /**
- * Constructs new GroupData.
- *
- * @param name group name.
- * @param members basic members.
- * @param requiredMembers required members.
- */
- public GroupData(String name, String[] members, String[] requiredMembers) {
- super(name, Role.GROUP);
- this.members = (members == null) ? new String[0] : members;
- this.requiredMembers = (requiredMembers == null) ? new String[0] : requiredMembers;
- }
-
- /**
- * Translates GroupData to CompositeData represented by compositeType {@link UserAdminMBean#GROUP_TYPE}.
- *
- * @return translated GroupData to compositeData.
- */
- public CompositeData toCompositeData() {
- try {
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(UserAdminMBean.NAME, name);
- items.put(UserAdminMBean.TYPE, type);
- items.put(UserAdminMBean.MEMBERS, members);
- items.put(UserAdminMBean.REQUIRED_MEMBERS, requiredMembers);
- return new CompositeDataSupport(UserAdminMBean.GROUP_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Can't create CompositeData" + e);
- }
- }
-
- /**
- * Static factory method to create GroupData from CompositeData object.
- *
- * @param data
- * {@link CompositeData} instance.
- * @return GroupData instance.
- */
- public static GroupData from(CompositeData data) {
- if (data == null) {
- return null;
- }
- String name = (String) data.get(UserAdminMBean.NAME);
- String[] members = (String[]) data.get(UserAdminMBean.MEMBERS);
- String[] requiredMembers = (String[]) data.get(UserAdminMBean.REQUIRED_MEMBERS);
- return new GroupData(name, members, requiredMembers);
- }
-
- /**
- * @return the members
- */
- public String[] getMembers() {
- return members;
- }
-
- /**
- * @return the requiredMembers
- */
- public String[] getRequiredMembers() {
- return requiredMembers;
- }
-
- private static String[] toArray(Role[] roles) {
- List<String> members = new ArrayList<String>();
- if (roles != null) {
- for (Role role : roles) {
- members.add(role.getName());
- }
- }
- return members.toArray(new String[members.size()]);
- }
-}
\ No newline at end of file
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/PackageData.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/PackageData.java
deleted file mode 100644
index f27941b..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/PackageData.java
+++ /dev/null
@@ -1,258 +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.aries.jmx.codec;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.osgi.framework.Bundle;
-import org.osgi.jmx.framework.PackageStateMBean;
-import org.osgi.service.packageadmin.ExportedPackage;
-
-/**
- * <p>
- * <tt>PackageData</tt>represents PackageType @see {@link PackageStateMBean#PACKAGE_TYPE}.
- * It is a codec for the composite data representing an OSGi ExportedPackage.
- * </p>
- *
- * @version $Rev$ $Date$
- */
-public class PackageData {
-
- /**
- * {@link PackageStateMBean#EXPORTING_BUNDLES}
- */
- long[] exportingBundles;
-
- /**
- * {@link PackageStateMBean#IMPORTING_BUNDLES}
- */
- long[] importingBundles;
-
- /**
- * {@link PackageStateMBean#NAME}
- */
- String name;
-
- /**
- * {@link PackageStateMBean#REMOVAL_PENDING}
- */
- boolean removalPending;
-
- /**
- * {@link PackageStateMBean#VERSION}
- */
- String version;
-
- /**
- * Constructs new PackageData with provided ExportedPackage.
- * @param exportedPackage @see {@link ExportedPackage}.
- */
- public PackageData(ExportedPackage exportedPackage) {
- this(new long[]{exportedPackage.getExportingBundle().getBundleId()}, toBundleIds(exportedPackage.getImportingBundles()),
- exportedPackage.getName(), exportedPackage.isRemovalPending(), exportedPackage.getVersion().toString());
-
- }
-
- /**
- * Constructs new PackageData.
- *
- * @param exportingBundles the bundle the package belongs to.
- * @param importingBundles the importing bundles of the package.
- * @param name the package name.
- * @param removalPending whether the package is pending removal.
- * @param version package version.
- */
- public PackageData(long[] exportingBundles, long[] importingBundles, String name, boolean removalPending, String version) {
- this.exportingBundles = exportingBundles;
- this.importingBundles = importingBundles;
- this.name = name;
- this.removalPending = removalPending;
- this.version = version;
- }
-
- /**
- * Translates PackageData to CompositeData represented by
- * compositeType {@link PackageStateMBean#PACKAGE_TYPE}.
- *
- * @return translated PackageData to compositeData.
- */
- public CompositeData toCompositeData() {
- try {
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(PackageStateMBean.EXPORTING_BUNDLES, toLongArray(exportingBundles));
- items.put(PackageStateMBean.IMPORTING_BUNDLES, toLongArray(importingBundles));
- items.put(PackageStateMBean.NAME, name);
- items.put(PackageStateMBean.REMOVAL_PENDING, removalPending);
- items.put(PackageStateMBean.VERSION, version);
- return new CompositeDataSupport(PackageStateMBean.PACKAGE_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Can't create CompositeData" + e);
- }
- }
-
- /**
- * Static factory method to create PackageData from CompositeData object.
- *
- * @param data {@link CompositeData} instance.
- * @return PackageData instance.
- */
- public static PackageData from(CompositeData data) {
- if(data == null){
- return null;
- }
- long[] exportingBundle = toLongPrimitiveArray((Long[])data.get(PackageStateMBean.EXPORTING_BUNDLES));
- long[] importingBundles = toLongPrimitiveArray((Long[]) data.get(PackageStateMBean.IMPORTING_BUNDLES));
- String name = (String) data.get(PackageStateMBean.NAME);
- boolean removalPending = (Boolean) data.get(PackageStateMBean.REMOVAL_PENDING);
- String version = (String) data.get(PackageStateMBean.VERSION);
- return new PackageData(exportingBundle,importingBundles,name, removalPending,version);
- }
-
- /**
- * Creates {@link TabularData} for set of PackageData's.
- *
- * @param packages set of PackageData's
- * @return {@link TabularData} instance.
- */
- public static TabularData tableFrom(Set<PackageData> packages){
- TabularData table = new TabularDataSupport(PackageStateMBean.PACKAGES_TYPE);
- for(PackageData pkg : packages){
- table.put(pkg.toCompositeData());
- }
- return table;
- }
-
- /**
- * Converts array of bundles to array of bundle id's.
- *
- * @param bundles array of Bundle's.
- * @return array of bundle id's.
- */
- public static long[] toBundleIds(Bundle[] bundles) {
- if (bundles != null) {
- long[] importingBundles = new long[bundles.length];
- for (int i = 0; i < bundles.length; i++) {
- importingBundles[i] = bundles[i].getBundleId();
- }
- return importingBundles;
- }
- return null;
- }
-
- /**
- * Converts primitive array of strings to Long array.
- *
- * @param primitiveArray primitive long array.
- * @return Long array.
- */
- protected Long[] toLongArray(long[] primitiveArray) {
- if (primitiveArray == null) {
- return null;
- }
- Long[] converted = new Long[primitiveArray.length];
- for (int i = 0; i < primitiveArray.length; i++) {
- converted[i] = primitiveArray[i];
- }
-
- return converted;
- }
-
- /**
- * Converts Long array to primitive array of long.
- *
- * @param wrapperArray Long array.
- * @return primitive long array.
- */
- protected static long[] toLongPrimitiveArray(Long[] wrapperArray) {
- if (wrapperArray == null) {
- return null;
- }
- long[] converted = new long[wrapperArray.length];
- for (int i = 0; i < wrapperArray.length; i++) {
- converted[i] = wrapperArray[i];
- }
-
- return converted;
- }
-
- /**
- * @return the exportingBundles
- */
- public long[] getExportingBundles() {
- return exportingBundles;
- }
-
- /**
- * @return the importingBundles
- */
- public long[] getImportingBundles() {
- return importingBundles;
- }
-
- /**
- * @return the name
- */
- public String getName() {
- return name;
- }
-
- /**
- * @return the removalPending
- */
- public boolean isRemovalPending() {
- return removalPending;
- }
-
- /**
- * @return the version
- */
- public String getVersion() {
- return version;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- PackageData that = (PackageData) o;
-
- // exportingBundle must be always there
- if (exportingBundles[0] != that.exportingBundles[0]) return false;
- if (!name.equals(that.name)) return false;
- if (!version.equals(that.version)) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = (int) (exportingBundles[0] ^ (exportingBundles[0] >>> 32));
- result = 31 * result + name.hashCode();
- result = 31 * result + version.hashCode();
- return result;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/PropertyData.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/PropertyData.java
deleted file mode 100644
index d9b6ebc..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/PropertyData.java
+++ /dev/null
@@ -1,332 +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.aries.jmx.codec;
-
-import static org.apache.aries.jmx.util.TypeUtils.fromString;
-import static org.apache.aries.jmx.util.TypeUtils.primitiveTypes;
-import static org.apache.aries.jmx.util.TypeUtils.types;
-import static org.osgi.jmx.JmxConstants.ARRAY_OF;
-import static org.osgi.jmx.JmxConstants.KEY;
-import static org.osgi.jmx.JmxConstants.PROPERTY_TYPE;
-import static org.osgi.jmx.JmxConstants.P_BOOLEAN;
-import static org.osgi.jmx.JmxConstants.P_BYTE;
-import static org.osgi.jmx.JmxConstants.P_CHAR;
-import static org.osgi.jmx.JmxConstants.P_DOUBLE;
-import static org.osgi.jmx.JmxConstants.P_FLOAT;
-import static org.osgi.jmx.JmxConstants.P_INT;
-import static org.osgi.jmx.JmxConstants.P_LONG;
-import static org.osgi.jmx.JmxConstants.TYPE;
-import static org.osgi.jmx.JmxConstants.VALUE;
-import static org.osgi.jmx.JmxConstants.VECTOR_OF;
-
-import java.lang.reflect.Array;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-
-import org.osgi.jmx.JmxConstants;
-
-/**
- * <p>
- * <tt>PropertyData</tt> represents Property Type @see {@link JmxConstants#PROPERTY_TYPE}. It is a codec for the
- * <code>CompositeData</code> representing a Property with an associated Type and Value.
- * </p>
- *
- * @version $Rev$ $Date$
- */
-public class PropertyData<T> {
-
- /**
- * @see JmxConstants#KEY_ITEM
- */
- private String key;
-
- /**
- * @see JmxConstants#SCALAR
- */
- private T value;
-
- /**
- * @see JmxConstants#VALUE_ITEM
- */
- private String encodedValue;
-
- /**
- * @see JmxConstants#TYPE_ITEM
- */
- private String encodedType;
-
- private PropertyData() {
- super();
- }
-
-
- @SuppressWarnings("unchecked")
- private PropertyData(String key, T value, String preservedBaseType) throws IllegalArgumentException {
- if (key == null) {
- throw new IllegalArgumentException("Argument key cannot be null");
- }
- if (value == null) {
- throw new IllegalArgumentException("Argument value cannot be null");
- }
- this.key = key;
- this.value = value;
- Class<T> type = (Class<T>) value.getClass();
- if (type.isArray()) {
- this.encodedType = ARRAY_OF + type.getComponentType().getSimpleName();
- StringBuilder builder = new StringBuilder();
- int length = Array.getLength(value);
- boolean useDelimiter = false;
- for (int i = 0; i < length; i++) {
- if (useDelimiter) {
- builder.append(",");
- } else {
- useDelimiter = true;
- }
- builder.append(Array.get(value, i));
- }
- this.encodedValue = builder.toString();
- } else if (type.equals(Vector.class)) {
- Vector vector = (Vector) value;
- Class<? extends Object> componentType = Object.class;
- if (vector.size() > 0) {
- componentType = vector.firstElement().getClass();
- }
- this.encodedType = VECTOR_OF + componentType.getSimpleName();
- StringBuilder builder = new StringBuilder();
- Vector valueVector = (Vector) value;
- boolean useDelimiter = false;
- for (Object val: valueVector) {
- if (useDelimiter) {
- builder.append(",");
- } else {
- useDelimiter = true;
- }
- builder.append(val);
- }
- this.encodedValue = builder.toString();
- } else {
- this.encodedType = (preservedBaseType == null) ? type.getSimpleName() : preservedBaseType;
- this.encodedValue = value.toString();
- }
- }
-
- /**
- * Static factory method for <code>PropertyData</code> instance parameterized by value's type
- * @param <T>
- * @param key
- * @param value an instance of {@link JmxConstants#SCALAR}
- * @return
- * @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
- */
- public static <T> PropertyData<T> newInstance(String key, T value) throws IllegalArgumentException {
- return new PropertyData<T>(key, value, null);
- }
-
- /**
- * Static factory method for <code>PropertyData</code> instance which preserves encoded type
- * information for primitive int type
- * @param key
- * @param value
- * @return
- * @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
- */
- public static PropertyData<Integer> newInstance(String key, int value) throws IllegalArgumentException {
- return new PropertyData<Integer>(key, value, P_INT);
- }
-
- /**
- * Static factory method for <code>PropertyData</code> instance which preserves encoded type
- * information for primitive long type
- * @param key
- * @param value
- * @return
- * @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
- */
- public static PropertyData<Long> newInstance(String key, long value) throws IllegalArgumentException {
- return new PropertyData<Long>(key, value, P_LONG);
- }
-
- /**
- * Static factory method for <code>PropertyData</code> instance which preserves encoded type
- * information for primitive float type
- * @param key
- * @param value
- * @return
- * @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
- */
- public static PropertyData<Float> newInstance(String key, float value) throws IllegalArgumentException {
- return new PropertyData<Float>(key, value, P_FLOAT);
- }
-
- /**
- * Static factory method for <code>PropertyData</code> instance which preserves encoded type
- * information for primitive double type
- * @param key
- * @param value
- * @return
- * @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
- */
- public static PropertyData<Double> newInstance(String key, double value) throws IllegalArgumentException {
- return new PropertyData<Double>(key, value, P_DOUBLE);
- }
-
- /**
- * Static factory method for <code>PropertyData</code> instance which preserves encoded type
- * information for primitive byte type
- * @param key
- * @param value
- * @return
- * @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
- */
- public static PropertyData<Byte> newInstance(String key, byte value) throws IllegalArgumentException {
- return new PropertyData<Byte>(key, value, P_BYTE);
- }
-
- /**
- * Static factory method for <code>PropertyData</code> instance which preserves encoded type
- * information for primitive char type
- * @param key
- * @param value
- * @return
- * @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
- */
- public static PropertyData<Character> newInstance(String key, char value) throws IllegalArgumentException {
- return new PropertyData<Character>(key, value, P_CHAR);
- }
-
- /**
- * Static factory method for <code>PropertyData</code> instance which preserves encoded type
- * information for primitive boolean type
- * @param key
- * @param value
- * @return
- * @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
- */
- public static PropertyData<Boolean> newInstance(String key, boolean value) throws IllegalArgumentException {
- return new PropertyData<Boolean>(key, value, P_BOOLEAN);
- }
-
-
- /**
- * Returns CompositeData representing a Property typed by {@link JmxConstants#PROPERTY_TYPE}.
- * @return
- */
- public CompositeData toCompositeData() {
- CompositeData result = null;
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(KEY, this.key);
- items.put(VALUE, this.encodedValue);
- items.put(TYPE, this.encodedType);
- try {
- result = new CompositeDataSupport(PROPERTY_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Failed to create CompositeData for Property [" + this.key + ":" + this.value + "]", e);
- }
- return result;
- }
-
- /**
- * Constructs a <code>PropertyData</code> object from the given <code>CompositeData</code>
- * @param compositeData
- * @return
- * @throws IlleglArgumentException if compositeData is null or not of type {@link JmxConstants#PROPERTY_TYPE}
- */
- @SuppressWarnings("unchecked")
- public static <T> PropertyData<T> from(CompositeData compositeData) throws IllegalArgumentException {
- if ( compositeData == null ) {
- throw new IllegalArgumentException("Argument compositeData cannot be null");
- }
- if (!compositeData.getCompositeType().equals(PROPERTY_TYPE)) {
- throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
- }
- PropertyData propertyData = new PropertyData();
- propertyData.key = (String) compositeData.get(KEY);
- propertyData.encodedType = (String) compositeData.get(TYPE);
- propertyData.encodedValue = (String) compositeData.get(VALUE);
- if (propertyData.encodedType == null || propertyData.encodedType.length() < 1) {
- throw new IllegalArgumentException ("Cannot determine type from compositeData : " + compositeData);
- }
- StringTokenizer values = new StringTokenizer(propertyData.encodedValue, ",");
- int valuesLength = values.countTokens();
- if (propertyData.encodedType.startsWith(ARRAY_OF)) {
- String[] arrayTypeParts = propertyData.encodedType.split("\\s");
- if (arrayTypeParts.length < 3) {
- throw new IllegalArgumentException("Cannot parse Array type from type item : " + propertyData.encodedType);
- }
- String arrayTypeName = arrayTypeParts[2].trim();
- if (!types.containsKey(arrayTypeName)) {
- throw new IllegalArgumentException ("Cannot determine type from value : " + arrayTypeName);
- }
- Class<? extends Object> arrayType = types.get(arrayTypeName);
- propertyData.value = Array.newInstance(arrayType, valuesLength);
- int index = 0;
- while (values.hasMoreTokens()) {
- Array.set(propertyData.value, index++, fromString(arrayType, values.nextToken()));
- }
- } else if (propertyData.encodedType.startsWith(VECTOR_OF)) {
- String[] vectorTypeParts = propertyData.encodedType.split("\\s");
- if (vectorTypeParts.length < 3) {
- throw new IllegalArgumentException("Cannot parse Array type from type item : " + propertyData.encodedType);
- }
- String vectorTypeName = vectorTypeParts[2].trim();
- if (!types.containsKey(vectorTypeName)) {
- throw new IllegalArgumentException ("Cannot determine type from value : " + vectorTypeName);
- }
- Class<? extends Object> vectorType = types.get(vectorTypeName);
- Vector vector = new Vector();
- while (values.hasMoreTokens()) {
- vector.add(fromString(vectorType, values.nextToken()));
- }
- propertyData.value = vector;
- } else {
- if (!types.containsKey(propertyData.encodedType)) {
- throw new IllegalArgumentException ("Cannot determine type from value : " + propertyData.encodedType);
- }
- Class<? extends Object> valueType = types.get(propertyData.encodedType);
- propertyData.value = fromString(valueType, propertyData.encodedValue);
- }
- return propertyData;
- }
-
-
- public String getKey() {
- return key;
- }
-
- public T getValue() {
- return value;
- }
-
- public String getEncodedType() {
- return encodedType;
- }
-
- public String getEncodedValue() {
- return encodedValue;
- }
-
- public boolean isEncodingPrimitive() {
- return primitiveTypes.containsKey(encodedType);
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/RoleData.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/RoleData.java
deleted file mode 100644
index 2f17ac1..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/RoleData.java
+++ /dev/null
@@ -1,157 +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.aries.jmx.codec;
-
-import java.util.Collection;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.osgi.jmx.JmxConstants;
-import org.osgi.jmx.service.useradmin.UserAdminMBean;
-import org.osgi.service.useradmin.Role;
-
-
-/**
- * <p>
- * <tt>RoleData</tt> represents Role Type @see {@link UserAdminMBean#ROLE_TYPE}.It is a codec
- * for the <code>CompositeData</code> representing a Role.
- * </p>
- *
- * @version $Rev$ $Date$
- */
-public class RoleData {
-
- /**
- * role name.
- */
- protected String name;
- /**
- * role type.
- */
- protected int type;
-
- /**
- * Constructs new RoleData from Role object.
- * @param role {@link Role} instance.
- */
- public RoleData(Role role){
- this(role.getName(),role.getType());
- }
-
- /**
- * Constructs new RoleData.
- * @param name role name.
- * @param type role type.
- */
- public RoleData(String name, int type){
- this.name = name;
- this.type = type;
- }
-
- /**
- * Translates RoleData to CompositeData represented by
- * compositeType {@link UserAdminMBean#ROLE_TYPE}.
- *
- * @return translated RoleData to compositeData.
- */
- public CompositeData toCompositeData() {
- try {
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(UserAdminMBean.NAME, name);
- items.put(UserAdminMBean.TYPE, type);
- return new CompositeDataSupport(UserAdminMBean.ROLE_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Can't create CompositeData" + e);
- }
- }
-
- /**
- * Static factory method to create RoleData from CompositeData object.
- *
- * @param data {@link CompositeData} instance.
- * @return RoleData instance.
- */
- public static RoleData from(CompositeData data) {
- if(data == null){
- return null;
- }
- String name = (String) data.get(UserAdminMBean.NAME);
- int type = (Integer) data.get(UserAdminMBean.TYPE);
- return new RoleData(name, type);
- }
-
- /**
- * Creates TabularData from Dictionary.
- *
- * @param props Dictionary instance.
- * @return TabularData instance.
- */
- protected static TabularData toTabularData(Dictionary<String, Object> props){
- if(props == null){
- return null;
- }
- TabularData data = new TabularDataSupport(JmxConstants.PROPERTIES_TYPE);
- for (Enumeration<String> keys = props.keys(); keys.hasMoreElements();) {
- String key = keys.nextElement();
- data.put(PropertyData.newInstance(key, props.get(key)).toCompositeData());
- }
- return data;
- }
-
- /**
- * Creates properties from TabularData object.
- *
- * @param data {@link TabularData} instance.
- * @return translated tabular data to properties {@link Dictionary}.
- */
- protected static Dictionary<String, Object> propertiesFrom(TabularData data){
- if(data == null){
- return null;
- }
-
- Dictionary<String, Object> props = new Hashtable<String, Object>();
- for(CompositeData compositeData : (Collection<CompositeData>)data.values()){
- PropertyData property = PropertyData.from(compositeData);
- props.put(property.getKey(), property.getValue());
- }
-
- return props;
- }
- /**
- * @return the name
- */
- public String getName() {
- return name;
- }
-
- /**
- * @return the type
- */
- public int getType() {
- return type;
- }
-
-}
\ No newline at end of file
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/ServiceData.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/ServiceData.java
deleted file mode 100644
index 036f5f3..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/ServiceData.java
+++ /dev/null
@@ -1,165 +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.aries.jmx.codec;
-
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleIds;
-import static org.apache.aries.jmx.util.TypeUtils.toLong;
-import static org.apache.aries.jmx.util.TypeUtils.toPrimitive;
-import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_IDENTIFIER;
-import static org.osgi.jmx.framework.ServiceStateMBean.IDENTIFIER;
-import static org.osgi.jmx.framework.ServiceStateMBean.OBJECT_CLASS;
-import static org.osgi.jmx.framework.ServiceStateMBean.SERVICE_TYPE;
-import static org.osgi.jmx.framework.ServiceStateMBean.USING_BUNDLES;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceReference;
-import org.osgi.jmx.framework.ServiceStateMBean;
-
-/**
- * <p>
- * <tt>ServiceData</tt> represents Service Type @see {@link ServiceStateMBean#SERVICE_TYPE}. It is a codec for the
- * <code>CompositeData</code> representing an OSGi <code>ServiceReference</code>.
- * </p>
- *
- * @version $Rev$ $Date$
- */
-public class ServiceData {
-
- /**
- * @see ServiceStateMBean#IDENTIFIER_ITEM
- */
- private long serviceId;
-
- /**
- * @see ServiceStateMBean#BUNDLE_IDENTIFIER_ITEM
- */
- private long bundleId;
-
- /**
- * @see ServiceStateMBean#OBJECT_CLASS_ITEM
- */
- private String[] serviceInterfaces;
-
- // keep properties for next version of the spec
- ///**
- // * @see ServiceStateMBean#PROPERTIES_ITEM
- // */
- //private List<PropertyData<? extends Object>> properties = new ArrayList<PropertyData<? extends Object>>();
-
- /**
- * @see ServiceStateMBean#USING_BUNDLES_ITEM
- */
- private long[] usingBundles;
-
- private ServiceData() {
- super();
- }
-
- public ServiceData(ServiceReference serviceReference) throws IllegalArgumentException {
- if (serviceReference == null) {
- throw new IllegalArgumentException("Argument serviceReference cannot be null");
- }
- this.serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID);
- this.bundleId = serviceReference.getBundle().getBundleId();
- this.serviceInterfaces = (String[]) serviceReference.getProperty(Constants.OBJECTCLASS);
- this.usingBundles = getBundleIds(serviceReference.getUsingBundles());
- //for (String propertyKey: serviceReference.getPropertyKeys()) {
- // this.properties.add(PropertyData.newInstance(propertyKey, serviceReference.getProperty(propertyKey)));
- //}
- }
-
- /**
- * Returns CompositeData representing a ServiceReference typed by {@link ServiceStateMBean#SERVICE_TYPE}.
- * @return
- */
- public CompositeData toCompositeData() {
- CompositeData result = null;
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(IDENTIFIER, this.serviceId);
- items.put(BUNDLE_IDENTIFIER, this.bundleId);
- items.put(OBJECT_CLASS, this.serviceInterfaces);
- //TabularData propertiesTable = new TabularDataSupport(PROPERTIES_TYPE);
- //for (PropertyData<? extends Object> propertyData : this.properties) {
- // propertiesTable.put(propertyData.toCompositeData());
- //}
- // items.put(PROPERTIES, propertiesTable);
- items.put(USING_BUNDLES, toLong(this.usingBundles));
- try {
- result = new CompositeDataSupport(SERVICE_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Failed to create CompositeData for ServiceReference with "
- + Constants.SERVICE_ID + " [" + this.serviceId + "]", e);
- }
- return result;
- }
-
- /**
- * Constructs a <code>ServiceData</code> object from the given <code>CompositeData</code>
- *
- * @param compositeData
- * @return
- * @throws IlleglArugmentException
- * if compositeData is null or not of type {@link ServiceStateMBean#SERVICE_TYPE}.
- */
- public static ServiceData from(CompositeData compositeData) {
- if (compositeData == null) {
- throw new IllegalArgumentException("Argument compositeData cannot be null");
- }
- if (!compositeData.getCompositeType().equals(SERVICE_TYPE)) {
- throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
- }
- ServiceData serviceData = new ServiceData();
- serviceData.serviceId = (Long) compositeData.get(IDENTIFIER);
- serviceData.bundleId = (Long) compositeData.get(BUNDLE_IDENTIFIER);
- serviceData.serviceInterfaces = (String[]) compositeData.get(OBJECT_CLASS);
- serviceData.usingBundles = toPrimitive((Long[]) compositeData.get(USING_BUNDLES));
- // TabularData propertiesTable = (TabularData) compositeData.get(PROPERTIES);
- // Collection<CompositeData> propertyData = (Collection<CompositeData>) propertiesTable.values();
- // for (CompositeData propertyRow: propertyData) {
- // serviceData.properties.add(PropertyData.from(propertyRow));
- // }
- return serviceData;
- }
-
- public long getServiceId() {
- return serviceId;
- }
-
- public long getBundleId() {
- return bundleId;
- }
-
- public String[] getServiceInterfaces() {
- return serviceInterfaces;
- }
-
- //public List<PropertyData<? extends Object>> getProperties() {
- // return properties;
- //}
-
- public long[] getUsingBundles() {
- return usingBundles;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/ServiceEventData.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/ServiceEventData.java
deleted file mode 100644
index b76e8d4..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/ServiceEventData.java
+++ /dev/null
@@ -1,164 +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.aries.jmx.codec;
-
-import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_IDENTIFIER;
-import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_LOCATION;
-import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_SYMBOLIC_NAME;
-import static org.osgi.jmx.framework.ServiceStateMBean.EVENT;
-import static org.osgi.jmx.framework.ServiceStateMBean.IDENTIFIER;
-import static org.osgi.jmx.framework.ServiceStateMBean.OBJECT_CLASS;
-import static org.osgi.jmx.framework.ServiceStateMBean.SERVICE_EVENT_TYPE;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-
-import org.osgi.framework.Bundle;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceReference;
-import org.osgi.jmx.framework.ServiceStateMBean;
-
-/**
- <p>
- * <tt>ServiceEventData</tt> represents ServiceEvent Type @see {@link ServiceStateMBean#SERVICE_EVENT_TYPE}.
- * It is a codec for the <code>CompositeData</code> representing an OSGi ServiceEvent.
- * </p>
- *
- * @version $Rev$ $Date$
- */
-public class ServiceEventData {
-
- /**
- * @see ServiceStateMBean#IDENTIFIER_ITEM
- */
- private long serviceId;
-
- /**
- * @see ServiceStateMBean#OBJECT_CLASS_ITEM
- */
- private String[] serviceInterfaces;
-
- /**
- * @see ServiceStateMBean#BUNDLE_IDENTIFIER_ITEM
- */
- private long bundleId;
-
- /**
- * @see ServiceStateMBean#BUNDLE_LOCATION_ITEM
- */
- private String bundleLocation;
-
- /**
- * @see ServiceStateMBean#BUNDLE_SYMBOLIC_NAME_ITEM
- */
- private String bundleSymbolicName;
-
- /**
- * @see ServiceStateMBean#EVENT_ITEM
- */
- private int eventType;
-
-
- private ServiceEventData(){
- super();
- }
-
- public ServiceEventData(ServiceEvent serviceEvent) {
- ServiceReference serviceReference = serviceEvent.getServiceReference();
- this.serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID);
- this.serviceInterfaces = (String[]) serviceReference.getProperty(Constants.OBJECTCLASS);
- Bundle bundle = serviceReference.getBundle();
- this.bundleId = bundle.getBundleId();
- this.bundleLocation = bundle.getLocation();
- this.bundleSymbolicName = bundle.getSymbolicName();
- this.eventType = serviceEvent.getType();
- }
-
- /**
- * Returns CompositeData representing a ServiceEvent typed by {@link ServiceStateMBean#SERVICE_EVENT_TYPE}.
- * @return
- */
- public CompositeData toCompositeData() {
- CompositeData result = null;
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(IDENTIFIER, this.serviceId);
- items.put(OBJECT_CLASS, this.serviceInterfaces);
- items.put(BUNDLE_IDENTIFIER, this.bundleId);
- items.put(BUNDLE_LOCATION, this.bundleLocation);
- items.put(BUNDLE_SYMBOLIC_NAME, this.bundleSymbolicName);
- items.put(EVENT, this.eventType);
- try {
- result = new CompositeDataSupport(SERVICE_EVENT_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Failed to create CompositeData for ServiceEvent for Service [" + this.serviceId + "]", e);
- }
- return result;
- }
-
- /**
- * Returns a <code>ServiceEventData</code> representation of the given compositeData
- * @param compositeData
- * @return
- * @throws IllegalArgumentException if the compositeData is null or incorrect type
- */
- public static ServiceEventData from(CompositeData compositeData) throws IllegalArgumentException {
- ServiceEventData serviceEventData = new ServiceEventData();
- if ( compositeData == null ) {
- throw new IllegalArgumentException("Argument compositeData cannot be null");
- }
- if (!compositeData.getCompositeType().equals(SERVICE_EVENT_TYPE)) {
- throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
- }
- serviceEventData.serviceId = (Long) compositeData.get(IDENTIFIER);
- serviceEventData.serviceInterfaces = (String[]) compositeData.get(OBJECT_CLASS);
- serviceEventData.bundleId = (Long) compositeData.get(BUNDLE_IDENTIFIER);
- serviceEventData.bundleLocation = (String) compositeData.get(BUNDLE_LOCATION);
- serviceEventData.bundleSymbolicName = (String) compositeData.get(BUNDLE_SYMBOLIC_NAME);
- serviceEventData.eventType = (Integer) compositeData.get(EVENT);
- return serviceEventData;
- }
-
- public long getServiceId() {
- return serviceId;
- }
-
- public String[] getServiceInterfaces() {
- return serviceInterfaces;
- }
-
- public long getBundleId() {
- return bundleId;
- }
-
- public String getBundleLocation() {
- return bundleLocation;
- }
-
- public String getBundleSymbolicName() {
- return bundleSymbolicName;
- }
-
- public int getEventType() {
- return eventType;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/codec/UserData.java b/jmx-core/src/main/java/org/apache/aries/jmx/codec/UserData.java
deleted file mode 100644
index 782e287..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/codec/UserData.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.aries.jmx.codec;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-
-import org.osgi.jmx.service.useradmin.UserAdminMBean;
-import org.osgi.service.useradmin.User;
-
-/**
- * <p>
- * <tt>UserData</tt> represents User Type @see {@link UserAdminMBean#USER_TYPE}.It is a codec
- * for the <code>CompositeData</code> representing a User.
- * </p>
- * @see RoleData
- *
- * @version $Rev$ $Date$
- */
-public class UserData extends RoleData {
-
- /**
- * Constructs new UserData.
- *
- * @param name user name.
- * @param type role type.
- */
- public UserData(String name, int type){
- super(name, type);
- }
-
- /**
- * Constructs new UserData from {@link User} object.
- *
- * @param user {@link User} instance.
- */
- public UserData(User user){
- this(user.getName(), user.getType());
- }
-
- /**
- * Translates UserData to CompositeData represented by
- * compositeType {@link UserAdminMBean#USER_TYPE}.
- *
- * @return translated UserData to compositeData.
- */
- public CompositeData toCompositeData() {
- try {
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(UserAdminMBean.NAME, name);
- items.put(UserAdminMBean.TYPE, type);
- return new CompositeDataSupport(UserAdminMBean.USER_TYPE, items);
- } catch (OpenDataException e) {
- throw new IllegalStateException("Can't create CompositeData" + e);
- }
- }
-
- /**
- * Static factory method to create UserData from CompositeData object.
- *
- * @param data {@link CompositeData} instance.
- * @return UserData instance.
- */
- public static UserData from(CompositeData data) {
- if(data == null){
- return null;
- }
- String name = (String) data.get(UserAdminMBean.NAME);
- int type = (Integer)data.get(UserAdminMBean.TYPE);
- return new UserData(name, type);
- }
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/framework/BundleState.java b/jmx-core/src/main/java/org/apache/aries/jmx/framework/BundleState.java
deleted file mode 100644
index 5497e20..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/framework/BundleState.java
+++ /dev/null
@@ -1,374 +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.aries.jmx.framework;
-
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleDependencies;
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleExportedPackages;
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleImportedPackages;
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleState;
-import static org.apache.aries.jmx.util.FrameworkUtils.getDependentBundles;
-import static org.apache.aries.jmx.util.FrameworkUtils.getFragmentIds;
-import static org.apache.aries.jmx.util.FrameworkUtils.getHostIds;
-import static org.apache.aries.jmx.util.FrameworkUtils.getRegisteredServiceIds;
-import static org.apache.aries.jmx.util.FrameworkUtils.getServicesInUseByBundle;
-import static org.apache.aries.jmx.util.FrameworkUtils.isBundlePendingRemoval;
-import static org.apache.aries.jmx.util.FrameworkUtils.isBundleRequiredByOthers;
-import static org.apache.aries.jmx.util.FrameworkUtils.resolveBundle;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import javax.management.MBeanNotificationInfo;
-import javax.management.MBeanRegistration;
-import javax.management.MBeanServer;
-import javax.management.Notification;
-import javax.management.NotificationBroadcasterSupport;
-import javax.management.ObjectName;
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.aries.jmx.JMXThreadFactory;
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.codec.BundleData;
-import org.apache.aries.jmx.codec.BundleEventData;
-import org.apache.aries.jmx.codec.BundleData.Header;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.BundleListener;
-import org.osgi.jmx.framework.BundleStateMBean;
-import org.osgi.service.log.LogService;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.startlevel.StartLevel;
-
-/**
- * Implementation of <code>BundleStateMBean</code> which emits JMX <code>Notification</code> on <code>Bundle</code>
- * state changes
- *
- * @version $Rev$ $Date$
- */
-public class BundleState extends NotificationBroadcasterSupport implements BundleStateMBean, MBeanRegistration {
-
- protected Logger logger;
- protected BundleContext bundleContext;
- protected PackageAdmin packageAdmin;
- protected StartLevel startLevel;
-
- protected ExecutorService eventDispatcher;
- protected BundleListener bundleListener;
- private AtomicInteger notificationSequenceNumber = new AtomicInteger(1);
- private Lock lock = new ReentrantLock();
- private AtomicInteger registrations = new AtomicInteger(0);
-
- // notification type description
- public static String BUNDLE_EVENT = "org.osgi.bundle.event";
-
- public BundleState(BundleContext bundleContext, PackageAdmin packageAdmin, StartLevel startLevel, Logger logger) {
- this.bundleContext = bundleContext;
- this.packageAdmin = packageAdmin;
- this.startLevel = startLevel;
- this.logger = logger;
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getExportedPackages(long)
- */
- public String[] getExportedPackages(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return getBundleExportedPackages(bundle, packageAdmin);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getFragments(long)
- */
- public long[] getFragments(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return getFragmentIds(bundle, packageAdmin);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getHeaders(long)
- */
- @SuppressWarnings("unchecked")
- public TabularData getHeaders(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- List<Header> headers = new ArrayList<Header>();
- Dictionary<String, String> bundleHeaders = bundle.getHeaders();
- Enumeration<String> keys = bundleHeaders.keys();
- while (keys.hasMoreElements()) {
- String key = keys.nextElement();
- headers.add(new Header(key, bundleHeaders.get(key)));
- }
- TabularData headerTable = new TabularDataSupport(HEADERS_TYPE);
- for (Header header : headers) {
- headerTable.put(header.toCompositeData());
- }
- return headerTable;
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getHosts(long)
- */
- public long[] getHosts(long fragmentId) throws IOException, IllegalArgumentException {
- Bundle fragment = resolveBundle(bundleContext, fragmentId);
- return getHostIds(fragment, packageAdmin);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getImportedPackages(long)
- */
- public String[] getImportedPackages(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return getBundleImportedPackages(bundleContext, bundle, packageAdmin);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getLastModified(long)
- */
- public long getLastModified(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return bundle.getLastModified();
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getLocation(long)
- */
- public String getLocation(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return bundle.getLocation();
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getRegisteredServices(long)
- */
- public long[] getRegisteredServices(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return getRegisteredServiceIds(bundle);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getRequiredBundles(long)
- */
- public long[] getRequiredBundles(long bundleIdentifier) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleIdentifier);
- return getBundleDependencies(bundleContext, bundle, packageAdmin);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getRequiringBundles(long)
- */
- public long[] getRequiringBundles(long bundleIdentifier) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleIdentifier);
- return getDependentBundles(bundle, packageAdmin);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getServicesInUse(long)
- */
- public long[] getServicesInUse(long bundleIdentifier) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleIdentifier);
- return getServicesInUseByBundle(bundle);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getStartLevel(long)
- */
- public int getStartLevel(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return startLevel.getBundleStartLevel(bundle);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getState(long)
- */
- public String getState(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return getBundleState(bundle);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getSymbolicName(long)
- */
- public String getSymbolicName(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return bundle.getSymbolicName();
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#getVersion(long)
- */
- public String getVersion(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return bundle.getVersion().toString();
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#isFragment(long)
- */
- public boolean isFragment(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return (PackageAdmin.BUNDLE_TYPE_FRAGMENT == packageAdmin.getBundleType(bundle));
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#isPersistentlyStarted(long)
- */
- public boolean isPersistentlyStarted(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return startLevel.isBundlePersistentlyStarted(bundle);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#isRemovalPending(long)
- */
- public boolean isRemovalPending(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return isBundlePendingRemoval(bundle, packageAdmin);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#isRequired(long)
- */
- public boolean isRequired(long bundleId) throws IOException, IllegalArgumentException {
- Bundle bundle = resolveBundle(bundleContext, bundleId);
- return isBundleRequiredByOthers(bundle, packageAdmin);
- }
-
- /**
- * @see org.osgi.jmx.framework.BundleStateMBean#listBundles()
- */
- public TabularData listBundles() throws IOException {
- Bundle[] containerBundles = bundleContext.getBundles();
- List<BundleData> bundleDatas = new ArrayList<BundleData>();
- if (containerBundles != null) {
- for (Bundle containerBundle : containerBundles) {
- bundleDatas.add(new BundleData(bundleContext, containerBundle, packageAdmin, startLevel));
- }
- }
- TabularData bundleTable = new TabularDataSupport(BUNDLES_TYPE);
- for (BundleData bundleData : bundleDatas) {
- bundleTable.put(bundleData.toCompositeData());
- }
- return bundleTable;
- }
-
- /**
- * @see javax.management.NotificationBroadcasterSupport#getNotificationInfo()
- */
- public MBeanNotificationInfo[] getNotificationInfo() {
- String[] types = new String[] { BUNDLE_EVENT };
- String name = Notification.class.getName();
- String description = "A BundleEvent issued from the Framework describing a bundle lifecycle change";
- MBeanNotificationInfo info = new MBeanNotificationInfo(types, name, description);
- return new MBeanNotificationInfo[] { info };
- }
-
- /**
- * @see javax.management.MBeanRegistration#postDeregister()
- */
- public void postDeregister() {
- if (registrations.decrementAndGet() < 1) {
- shutDownDispatcher();
- }
- }
-
- /**
- * @see javax.management.MBeanRegistration#postRegister(java.lang.Boolean)
- */
- public void postRegister(Boolean registrationDone) {
- if (registrationDone && registrations.incrementAndGet() == 1) {
- eventDispatcher = Executors.newSingleThreadExecutor(new JMXThreadFactory("JMX OSGi Bundle State Event Dispatcher"));
- bundleContext.addBundleListener(bundleListener);
- }
- }
-
- /**
- * @see javax.management.MBeanRegistration#preDeregister()
- */
- public void preDeregister() throws Exception {
- // No action
- }
-
- /**
- * @see javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName)
- */
- public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
- lock.lock();
- try {
- if (bundleListener == null) {
- bundleListener = new BundleListener() {
- public void bundleChanged(BundleEvent event) {
- final Notification notification = new Notification(EVENT, OBJECTNAME,
- notificationSequenceNumber.getAndIncrement());
- try {
- notification.setUserData(new BundleEventData(event).toCompositeData());
- eventDispatcher.submit(new Runnable() {
- public void run() {
- sendNotification(notification);
- }
- });
- } catch (RejectedExecutionException re) {
- logger.log(LogService.LOG_WARNING, "Task rejected for JMX Notification dispatch of event ["
- + event + "] - Dispatcher may have been shutdown");
- } catch (Exception e) {
- logger.log(LogService.LOG_WARNING,
- "Exception occured on JMX Notification dispatch for event [" + event + "]", e);
- }
- }
- };
- }
- } finally {
- lock.unlock();
- }
- return name;
- }
-
- /*
- * Shuts down the notification dispatcher
- * [ARIES-259] MBeans not getting unregistered reliably
- */
- protected void shutDownDispatcher() {
- if (bundleListener != null) {
- try {
- bundleContext.removeBundleListener(bundleListener);
- }
- catch (Exception e) {
- // ignore
- }
- }
- if (eventDispatcher != null) {
- eventDispatcher.shutdown();
- }
- }
-
- /*
- * Returns the ExecutorService used to dispatch Notifications
- */
- protected ExecutorService getEventDispatcher() {
- return eventDispatcher;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/framework/BundleStateMBeanHandler.java b/jmx-core/src/main/java/org/apache/aries/jmx/framework/BundleStateMBeanHandler.java
deleted file mode 100644
index 7cf7b26..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/framework/BundleStateMBeanHandler.java
+++ /dev/null
@@ -1,120 +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.aries.jmx.framework;
-
-import static org.osgi.jmx.framework.BundleStateMBean.OBJECTNAME;
-
-import javax.management.NotCompliantMBeanException;
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.MBeanHandler;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.jmx.framework.BundleStateMBean;
-import org.osgi.service.log.LogService;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.startlevel.StartLevel;
-
-/**
- * <p>
- * Implementation of <code>MBeanHandler</code> which manages the <code>BundleState</code>
- * MBean implementation
- * @see MBeanHandler
- * </p>
- *
- * @version $Rev$ $Date$
- */
-public class BundleStateMBeanHandler implements MBeanHandler {
-
- private Logger logger;
- private String name;
- private StandardMBean mbean;
- private BundleState bundleStateMBean;
- private BundleContext bundleContext;
- private ServiceReference packageAdminRef;
- private ServiceReference startLevelRef;
-
-
- public BundleStateMBeanHandler(BundleContext bundleContext, Logger logger) {
- this.bundleContext = bundleContext;
- this.logger = logger;
- this.name = OBJECTNAME;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#open()
- */
- public void open() {
- packageAdminRef = bundleContext.getServiceReference(PackageAdmin.class.getName());
- PackageAdmin packageAdmin = (PackageAdmin) bundleContext.getService(packageAdminRef);
- startLevelRef = bundleContext.getServiceReference(StartLevel.class.getName());
- StartLevel startLevel = (StartLevel) bundleContext.getService(startLevelRef);
- bundleStateMBean = new BundleState(bundleContext, packageAdmin, startLevel, logger);
- try {
- mbean = new RegistrableStandardEmitterMBean(bundleStateMBean, BundleStateMBean.class);
- } catch (NotCompliantMBeanException e) {
- logger.log(LogService.LOG_ERROR, "Failed to instantiate MBean for " + BundleStateMBean.class.getName(), e);
- }
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getMbean()
- */
- public StandardMBean getMbean() {
- return mbean;
- }
-
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getName()
- */
- public String getName() {
- return name;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#close()
- */
- public void close() {
- if (packageAdminRef != null) {
- try {
- bundleContext.ungetService(packageAdminRef);
- } catch (RuntimeException e) {
- logger.log(LogService.LOG_WARNING, "Exception occured during cleanup", e);
- }
- packageAdminRef = null;
- }
- if (startLevelRef != null) {
- try {
- bundleContext.ungetService(startLevelRef);
- } catch (RuntimeException e) {
- logger.log(LogService.LOG_WARNING, "Exception occured during cleanup", e);
- }
- startLevelRef = null;
- }
- // ensure dispatcher is shutdown even if postDeRegister is not honored
- if (bundleStateMBean != null) {
- bundleStateMBean.shutDownDispatcher();
- }
- }
-
-
-
-
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/framework/Framework.java b/jmx-core/src/main/java/org/apache/aries/jmx/framework/Framework.java
deleted file mode 100644
index 52303f5..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/framework/Framework.java
+++ /dev/null
@@ -1,511 +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.aries.jmx.framework;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-
-import javax.management.openmbean.CompositeData;
-
-import org.apache.aries.jmx.codec.BatchActionResult;
-import org.apache.aries.jmx.codec.BatchInstallResult;
-import org.apache.aries.jmx.util.FrameworkUtils;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.jmx.framework.FrameworkMBean;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.startlevel.StartLevel;
-
-/**
- * <p>
- * <tt>Framework</tt> represents {@link FrameworkMBean} implementation.
- * </p>
- * @see FrameworkMBean
- *
- * @version $Rev$ $Date$
- */
-public class Framework implements FrameworkMBean {
-
- private StartLevel startLevel;
- private PackageAdmin packageAdmin;
- private BundleContext context;
-
- /**
- * Constructs new FrameworkMBean.
- *
- * @param context bundle context of jmx bundle.
- * @param startLevel @see {@link StartLevel} service reference.
- * @param packageAdmin @see {@link PackageAdmin} service reference.
- */
- public Framework(BundleContext context, StartLevel startLevel, PackageAdmin packageAdmin) {
- this.context = context;
- this.startLevel = startLevel;
- this.packageAdmin = packageAdmin;
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#getFrameworkStartLevel()
- */
- public int getFrameworkStartLevel() throws IOException {
- return startLevel.getStartLevel();
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#getInitialBundleStartLevel()
- */
- public int getInitialBundleStartLevel() throws IOException {
- return startLevel.getInitialBundleStartLevel();
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#installBundle(java.lang.String)
- */
- public long installBundle(String location) throws IOException {
- try {
- Bundle bundle = context.installBundle(location);
- return bundle.getBundleId();
- } catch (Exception e) {
- IOException ioex = new IOException("Installation of a bundle with location " + location + " failed with the message: " + e.getMessage());
- ioex.initCause(e);
- throw ioex;
- }
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#installBundleFromURL(String, String)
- */
- public long installBundleFromURL(String location, String url) throws IOException {
- InputStream inputStream = null;
- try {
- inputStream = createStream(url);
- Bundle bundle = context.installBundle(location, inputStream);
- return bundle.getBundleId();
- } catch (Exception e) {
- IOException ioex = new IOException("Installation of a bundle with location " + location + " failed with the message: " + e.getMessage());
- ioex.initCause(e);
- throw ioex;
- } finally {
- if (inputStream != null) {
- try {
- inputStream.close();
- } catch (IOException ioe) {
- }
- }
- }
- }
-
- public InputStream createStream(String url) throws IOException {
- return new URL(url).openStream();
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#installBundles(java.lang.String[])
- */
- public CompositeData installBundles(String[] locations) throws IOException {
- if(locations == null){
- return new BatchInstallResult("Failed to install bundles locations can't be null").toCompositeData();
- }
- long[] ids = new long[locations.length];
- for (int i = 0; i < locations.length; i++) {
- try {
- long id = installBundle(locations[i]);
- ids[i] = id;
- } catch (Throwable t) {
- long[] completed = new long[i];
- System.arraycopy(ids, 0, completed, 0, i);
- String[] remaining = new String[locations.length - i - 1];
- System.arraycopy(locations, i + 1, remaining, 0, remaining.length);
- return new BatchInstallResult(completed, t.toString(), remaining, locations[i]).toCompositeData();
- }
- }
-
- return new BatchInstallResult(ids).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#installBundlesFromURL(String[], String[])
- */
- public CompositeData installBundlesFromURL(String[] locations, String[] urls) throws IOException {
- if(locations == null || urls == null){
- return new BatchInstallResult("Failed to install bundles arguments can't be null").toCompositeData();
- }
-
- if(locations.length != urls.length){
- return new BatchInstallResult("Failed to install bundles size of arguments should be same").toCompositeData();
- }
- long[] ids = new long[locations.length];
- for (int i = 0; i < locations.length; i++) {
- try {
- long id = installBundleFromURL(locations[i], urls[i]);
- ids[i] = id;
- } catch (Throwable t) {
- long[] completed = new long[i];
- System.arraycopy(ids, 0, completed, 0, i);
- String[] remaining = new String[locations.length - i - 1];
- System.arraycopy(locations, i + 1, remaining, 0, remaining.length);
- return new BatchInstallResult(completed, t.toString(), remaining, locations[i]).toCompositeData();
- }
- }
- return new BatchInstallResult(ids).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#refreshBundle(long)
- */
- public void refreshBundle(long bundleIdentifier) throws IOException {
- Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
- packageAdmin.refreshPackages(new Bundle[] { bundle });
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#refreshBundles(long[])
- */
- public void refreshBundles(long[] bundleIdentifiers) throws IOException {
- Bundle[] bundles = null;
- if(bundleIdentifiers != null) {
- bundles = new Bundle[bundleIdentifiers.length];
- for (int i = 0; i < bundleIdentifiers.length; i++) {
- try {
- bundles[i] = FrameworkUtils.resolveBundle(context, bundleIdentifiers[i]);
- } catch (Exception e) {
- IOException ex = new IOException("Unable to find bundle with id " + bundleIdentifiers[i]);
- ex.initCause(e);
- throw ex;
- }
- }
- }
- packageAdmin.refreshPackages(bundles);
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#resolveBundle(long)
- */
- public boolean resolveBundle(long bundleIdentifier) throws IOException {
- Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
- return packageAdmin.resolveBundles(new Bundle[] { bundle });
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#resolveBundles(long[])
- */
- public boolean resolveBundles(long[] bundleIdentifiers) throws IOException {
- Bundle[] bundles = null;
- if(bundleIdentifiers != null) {
- bundles = new Bundle[bundleIdentifiers.length];
- for (int i = 0; i < bundleIdentifiers.length; i++) {
- try {
- bundles[i] = FrameworkUtils.resolveBundle(context, bundleIdentifiers[i]);
- } catch (Exception e) {
- IOException ex = new IOException("Unable to find bundle with id " + bundleIdentifiers[i]);
- ex.initCause(e);
- throw ex;
- }
- }
- }
- return packageAdmin.resolveBundles(bundles);
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#restartFramework()
- */
- public void restartFramework() throws IOException {
- Bundle bundle = FrameworkUtils.resolveBundle(context, 0);
- try {
- bundle.update();
- } catch (Exception be) {
- IOException ioex = new IOException("Framework restart failed with message: " + be.getMessage());
- ioex.initCause(be);
- throw ioex;
- }
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#setBundleStartLevel(long, int)
- */
- public void setBundleStartLevel(long bundleIdentifier, int newlevel) throws IOException {
- Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
- try {
- startLevel.setBundleStartLevel(bundle, newlevel);
- } catch (IllegalArgumentException e) {
- IOException ioex = new IOException("Setting the start level for bundle with id " + bundle.getBundleId() + " to level " + newlevel + " failed with message: " + e.getMessage());
- ioex.initCause(e);
- throw ioex;
- }
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#setBundleStartLevels(long[], int[])
- */
- public CompositeData setBundleStartLevels(long[] bundleIdentifiers, int[] newlevels) throws IOException {
- if (bundleIdentifiers == null || newlevels == null) {
- return new BatchActionResult("Failed to setBundleStartLevels arguments can't be null").toCompositeData();
- }
-
- if (bundleIdentifiers != null && newlevels != null && bundleIdentifiers.length != newlevels.length) {
- return new BatchActionResult("Failed to setBundleStartLevels size of arguments should be same").toCompositeData();
- }
- for (int i = 0; i < bundleIdentifiers.length; i++) {
- try {
- setBundleStartLevel(bundleIdentifiers[i], newlevels[i]);
- } catch (Throwable t) {
- return createFailedBatchActionResult(bundleIdentifiers, i, t);
- }
- }
- return new BatchActionResult(bundleIdentifiers).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#setFrameworkStartLevel(int)
- */
- public void setFrameworkStartLevel(int newlevel) throws IOException {
- try {
- startLevel.setStartLevel(newlevel);
- } catch (Exception e) {
- IOException ioex = new IOException("Setting the framework start level to " + newlevel + " failed with message: " + e.getMessage());
- ioex.initCause(e);
- throw ioex;
- }
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#setInitialBundleStartLevel(int)
- */
- public void setInitialBundleStartLevel(int newlevel) throws IOException {
- try {
- startLevel.setInitialBundleStartLevel(newlevel);
- } catch (Exception e) {
- IOException ioex = new IOException("Setting the initial start level to " + newlevel + " failed with message: " + e.getMessage());
- ioex.initCause(e);
- throw ioex;
- }
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#shutdownFramework()
- */
- public void shutdownFramework() throws IOException {
- Bundle bundle = FrameworkUtils.resolveBundle(context, 0);
- try {
- bundle.stop();
- } catch (Exception be) {
- IOException ioex = new IOException("Stopping the framework failed with message: " + be.getMessage());
- ioex.initCause(be);
- throw ioex;
- }
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#startBundle(long)
- */
- public void startBundle(long bundleIdentifier) throws IOException {
- Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
- try {
- bundle.start();
- } catch (Exception be) {
- IOException ioex = new IOException("Start of bundle with id " + bundleIdentifier + " failed with message: " + be.getMessage());
- ioex.initCause(be);
- throw ioex;
- }
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#startBundles(long[])
- */
- public CompositeData startBundles(long[] bundleIdentifiers) throws IOException {
- if (bundleIdentifiers == null) {
- return new BatchActionResult("Failed to start bundles, bundle id's can't be null").toCompositeData();
- }
- for (int i = 0; i < bundleIdentifiers.length; i++) {
- try {
- startBundle(bundleIdentifiers[i]);
- } catch (Throwable t) {
- return createFailedBatchActionResult(bundleIdentifiers, i, t);
- }
- }
- return new BatchActionResult(bundleIdentifiers).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#stopBundle(long)
- */
- public void stopBundle(long bundleIdentifier) throws IOException {
- Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
- try {
- bundle.stop();
- } catch (Exception e) {
- IOException ioex = new IOException("Stop of bundle with id " + bundleIdentifier + " failed with message: " + e.getMessage());
- ioex.initCause(e);
- throw ioex;
- }
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#stopBundles(long[])
- */
- public CompositeData stopBundles(long[] bundleIdentifiers) throws IOException {
- if (bundleIdentifiers == null) {
- return new BatchActionResult("Failed to stop bundles, bundle id's can't be null").toCompositeData();
- }
- for (int i = 0; i < bundleIdentifiers.length; i++) {
- try {
- stopBundle(bundleIdentifiers[i]);
- } catch (Throwable t) {
- return createFailedBatchActionResult(bundleIdentifiers, i, t);
- }
- }
- return new BatchActionResult(bundleIdentifiers).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#uninstallBundle(long)
- */
- public void uninstallBundle(long bundleIdentifier) throws IOException {
- Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
- try {
- bundle.uninstall();
- } catch (Exception be) {
- IOException ioex = new IOException("Uninstall of bundle with id " + bundleIdentifier + " failed with message: " + be.getMessage());
- ioex.initCause(be);
- throw ioex;
- }
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#uninstallBundles(long[])
- */
- public CompositeData uninstallBundles(long[] bundleIdentifiers) throws IOException {
- if (bundleIdentifiers == null) {
- return new BatchActionResult("Failed uninstall bundles, bundle id's can't be null").toCompositeData();
- }
- for (int i = 0; i < bundleIdentifiers.length; i++) {
- try {
- uninstallBundle(bundleIdentifiers[i]);
- } catch (Throwable t) {
- return createFailedBatchActionResult(bundleIdentifiers, i, t);
- }
- }
- return new BatchActionResult(bundleIdentifiers).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#updateBundle(long)
- */
- public void updateBundle(long bundleIdentifier) throws IOException {
- Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
- try {
- bundle.update();
- } catch (Exception be) {
- IOException ioex = new IOException("Update of bundle with id " + bundleIdentifier + " failed with message: " + be.getMessage());
- ioex.initCause(be);
- throw ioex;
- }
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#updateBundleFromURL(long, String)
- */
- public void updateBundleFromURL(long bundleIdentifier, String url) throws IOException {
- Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
- InputStream inputStream = null;
- try {
- inputStream = createStream(url);
- bundle.update(inputStream);
- } catch (Exception be) {
- IOException ioex = new IOException("Update of bundle with id " + bundleIdentifier + " from url " + url + " failed with message: " + be.getMessage());
- ioex.initCause(be);
- throw ioex;
- } finally {
- if (inputStream != null) {
- try {
- inputStream.close();
- } catch (IOException ioe) {
-
- }
- }
- }
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#updateBundles(long[])
- */
- public CompositeData updateBundles(long[] bundleIdentifiers) throws IOException {
- if (bundleIdentifiers == null) {
- return new BatchActionResult("Failed to update bundles, bundle id's can't be null").toCompositeData();
- }
- for (int i = 0; i < bundleIdentifiers.length; i++) {
- try {
- updateBundle(bundleIdentifiers[i]);
- } catch (Throwable t) {
- return createFailedBatchActionResult(bundleIdentifiers, i, t);
- }
- }
- return new BatchActionResult(bundleIdentifiers).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#updateBundlesFromURL(long[], String[])
- */
- public CompositeData updateBundlesFromURL(long[] bundleIdentifiers, String[] urls) throws IOException {
- if(bundleIdentifiers == null || urls == null){
- return new BatchActionResult("Failed to update bundles arguments can't be null").toCompositeData();
- }
-
- if(bundleIdentifiers != null && urls != null && bundleIdentifiers.length != urls.length){
- return new BatchActionResult("Failed to update bundles size of arguments should be same").toCompositeData();
- }
- for (int i = 0; i < bundleIdentifiers.length; i++) {
- try {
- updateBundleFromURL(bundleIdentifiers[i], urls[i]);
- } catch (Throwable t) {
- return createFailedBatchActionResult(bundleIdentifiers, i, t);
- }
- }
- return new BatchActionResult(bundleIdentifiers).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.framework.FrameworkMBean#updateFramework()
- */
- public void updateFramework() throws IOException {
- Bundle bundle = FrameworkUtils.resolveBundle(context, 0);
- try {
- bundle.update();
- } catch (Exception be) {
- IOException ioex = new IOException("Update of framework bundle failed with message: " + be.getMessage());
- ioex.initCause(be);
- throw ioex;
- }
- }
-
- /**
- * Create {@link BatchActionResult}, when the operation fail.
- *
- * @param bundleIdentifiers bundle ids for operation.
- * @param i index of loop pointing on which operation fails.
- * @param t Throwable thrown by failed operation.
- * @return created BatchActionResult instance.
- */
- private CompositeData createFailedBatchActionResult(long[] bundleIdentifiers, int i, Throwable t) {
- long[] completed = new long[i];
- System.arraycopy(bundleIdentifiers, 0, completed, 0, i);
- long[] remaining = new long[bundleIdentifiers.length - i - 1];
- System.arraycopy(bundleIdentifiers, i + 1, remaining, 0, remaining.length);
- return new BatchActionResult(completed, t.toString(), remaining, bundleIdentifiers[i]).toCompositeData();
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/framework/FrameworkMBeanHandler.java b/jmx-core/src/main/java/org/apache/aries/jmx/framework/FrameworkMBeanHandler.java
deleted file mode 100644
index 924794f..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/framework/FrameworkMBeanHandler.java
+++ /dev/null
@@ -1,96 +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.aries.jmx.framework;
-
-import javax.management.NotCompliantMBeanException;
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.MBeanHandler;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.jmx.framework.FrameworkMBean;
-import org.osgi.service.log.LogService;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.startlevel.StartLevel;
-
-/**
- * <p>
- * <tt>FrameworkMBeanHandler</tt> represents MBeanHandler which
- * holding information about {@link FrameworkMBean}.</p>
- *
- * @see MBeanHandler
- *
- * @version $Rev$ $Date$
- */
-public class FrameworkMBeanHandler implements MBeanHandler {
-
- private String name;
- private StandardMBean mbean;
- private BundleContext context;
- private Logger logger;
-
- /**
- * Constructs new FrameworkMBeanHandler.
- *
- * @param context bundle context of JMX bundle.
- * @param logger @see {@link Logger}.
- */
- public FrameworkMBeanHandler(BundleContext context, Logger logger) {
- this.context = context;
- this.name = FrameworkMBean.OBJECTNAME;
- this.logger = logger;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getMbean()
- */
- public StandardMBean getMbean() {
- return mbean;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#open()
- */
- public void open() {
- ServiceReference adminRef = context.getServiceReference(PackageAdmin.class.getCanonicalName());
- PackageAdmin packageAdmin = (PackageAdmin) context.getService(adminRef);
- ServiceReference startLevelRef = context.getServiceReference(StartLevel.class.getCanonicalName());
- StartLevel startLevel = (StartLevel) context.getService(startLevelRef);
- FrameworkMBean framework = new Framework(context, startLevel, packageAdmin);
- try {
- mbean = new StandardMBean(framework, FrameworkMBean.class);
- } catch (NotCompliantMBeanException e) {
- logger.log(LogService.LOG_ERROR, "Not compliant MBean", e);
- }
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#close()
- */
- public void close() {
- //not used
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getName()
- */
- public String getName() {
- return name;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/framework/PackageState.java b/jmx-core/src/main/java/org/apache/aries/jmx/framework/PackageState.java
deleted file mode 100644
index 55965e9..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/framework/PackageState.java
+++ /dev/null
@@ -1,148 +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.aries.jmx.framework;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import javax.management.openmbean.TabularData;
-
-import org.apache.aries.jmx.codec.PackageData;
-import org.apache.aries.jmx.util.FrameworkUtils;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Version;
-import org.osgi.jmx.framework.PackageStateMBean;
-import org.osgi.service.packageadmin.ExportedPackage;
-import org.osgi.service.packageadmin.PackageAdmin;
-
-/**
- * <p>
- * <tt>PackageState</tt> represents implementation of PackageStateMBean.
- * </p>
- *
- * @see PackageStateMBean
- *
- * @version $Rev$ $Date$
- */
-public class PackageState implements PackageStateMBean {
-
- /**
- * {@link PackageAdmin} service reference.
- */
- private PackageAdmin packageAdmin;
- private BundleContext context;
-
- /**
- * Constructs new PackagesState MBean.
- *
- * @param context bundle context.
- * @param packageAdmin {@link PackageAdmin} service reference.
- */
- public PackageState(BundleContext context, PackageAdmin packageAdmin) {
- this.context = context;
- this.packageAdmin = packageAdmin;
- }
-
- /**
- * @see org.osgi.jmx.framework.PackageStateMBean#getExportingBundles(String, String)
- */
- public long[] getExportingBundles(String packageName, String version) throws IOException {
- if (packageName == null || packageName.length() < 1) {
- throw new IOException("Package name cannot be null or empty");
- }
- ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(packageName);
- if (exportedPackages != null) {
- Version ver = Version.parseVersion(version);
- List<Bundle> exportingBundles = new ArrayList<Bundle>();
- for (ExportedPackage exportedPackage : exportedPackages) {
- if (exportedPackage.getVersion().equals(ver)) {
- Bundle bundle = exportedPackage.getExportingBundle();
- exportingBundles.add(bundle);
- }
- }
-
- return FrameworkUtils.getBundleIds(exportingBundles);
- }
- return null;
- }
-
- /**
- * @see org.osgi.jmx.framework.PackageStateMBean#getImportingBundles(String, String, long)
- */
- public long[] getImportingBundles(String packageName, String version, long exportingBundle) throws IOException {
- if (packageName == null || packageName.length() < 1) {
- throw new IOException("Package name cannot be null or empty");
- }
- ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(packageName);
- if (exportedPackages != null) {
- Version ver = Version.parseVersion(version);
- for (ExportedPackage exportedPackage : exportedPackages) {
- if (exportedPackage.getVersion().equals(ver)
- && exportedPackage.getExportingBundle().getBundleId() == exportingBundle) {
- Bundle[] bundles = exportedPackage.getImportingBundles();
- if (bundles != null) {
- return FrameworkUtils.getBundleIds(bundles);
- }
- }
- }
- }
- return null;
- }
-
- /**
- * @see org.osgi.jmx.framework.PackageStateMBean#isRemovalPending(String, String, long)
- */
- public boolean isRemovalPending(String packageName, String version, long exportingBundle) throws IOException {
- if (packageName == null || packageName.length() < 1) {
- throw new IOException("Package name cannot be null or empty");
- }
- ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(packageName);
- if (exportedPackages != null) {
- Version ver = Version.parseVersion(version);
- for (ExportedPackage exportedPackage : exportedPackages) {
- if (exportedPackage.getVersion().equals(ver)
- && exportedPackage.getExportingBundle().getBundleId() == exportingBundle
- && exportedPackage.isRemovalPending()) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * @see org.osgi.jmx.framework.PackageStateMBean#listPackages()
- */
- public TabularData listPackages() throws IOException {
- Set<PackageData> packages = new HashSet<PackageData>();
- for (Bundle bundle : context.getBundles()) {
- ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(bundle);
- if (exportedPackages != null) {
- for (ExportedPackage exportedPackage : exportedPackages) {
- packages.add(new PackageData(exportedPackage));
- }
- }
-
- }
- return PackageData.tableFrom(packages);
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/framework/PackageStateMBeanHandler.java b/jmx-core/src/main/java/org/apache/aries/jmx/framework/PackageStateMBeanHandler.java
deleted file mode 100644
index 1dc0772..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/framework/PackageStateMBeanHandler.java
+++ /dev/null
@@ -1,94 +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.aries.jmx.framework;
-
-import javax.management.NotCompliantMBeanException;
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.MBeanHandler;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.jmx.framework.PackageStateMBean;
-import org.osgi.service.log.LogService;
-import org.osgi.service.packageadmin.PackageAdmin;
-
-/**
- * <p>
- * <tt>PackageStateMBeanHandler</tt> represents MBeanHandler which
- * holding information about {@link PackageStateMBean}.</p>
- *
- * @see MBeanHandler
- *
- * @version $Rev$ $Date$
- */
-public class PackageStateMBeanHandler implements MBeanHandler {
-
- private String name;
- private StandardMBean mbean;
- private BundleContext context;
- private Logger logger;
-
- /**
- * Constructs new PackageStateMBeanHandler.
- *
- * @param context bundle context of JMX bundle.
- * @param logger @see {@link Logger}.
- */
- public PackageStateMBeanHandler(BundleContext context, Logger logger) {
- this.context = context;
- this.name = PackageStateMBean.OBJECTNAME;
- this.logger = logger;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getMbean()
- */
- public StandardMBean getMbean() {
- return mbean;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#open()
- */
- public void open() {
- ServiceReference adminRef = context.getServiceReference(PackageAdmin.class.getCanonicalName());
- PackageAdmin packageAdmin = (PackageAdmin) context.getService(adminRef);
- PackageStateMBean packageState = new PackageState(context, packageAdmin);
- try {
- mbean = new StandardMBean(packageState, PackageStateMBean.class);
- } catch (NotCompliantMBeanException e) {
- logger.log(LogService.LOG_ERROR, "Not compliant MBean", e);
- }
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#close()
- */
- public void close() {
- //not used
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getName()
- */
- public String getName() {
- return name;
- }
-
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/framework/RegistrableStandardEmitterMBean.java b/jmx-core/src/main/java/org/apache/aries/jmx/framework/RegistrableStandardEmitterMBean.java
deleted file mode 100644
index e889776..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/framework/RegistrableStandardEmitterMBean.java
+++ /dev/null
@@ -1,153 +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.aries.jmx.framework;
-
-import javax.management.ListenerNotFoundException;
-import javax.management.MBeanInfo;
-import javax.management.MBeanNotificationInfo;
-import javax.management.MBeanRegistration;
-import javax.management.MBeanServer;
-import javax.management.NotCompliantMBeanException;
-import javax.management.NotificationEmitter;
-import javax.management.NotificationFilter;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import javax.management.StandardMBean;
-
-/**
- * The <code>StandardMBean</code> does not appear to delegate correctly to the underlying MBean implementation. Due to
- * issues surrounding the <code>MBeanRegistration</code> callback methods and <code>NotificationEmmitter</code> methods,
- * this subclass was introduced to force the delegation
- *
- * @version $Rev$ $Date$
- */
-public class RegistrableStandardEmitterMBean extends StandardMBean implements MBeanRegistration, NotificationEmitter {
-
- public <T> RegistrableStandardEmitterMBean(T impl, Class<T> intf) throws NotCompliantMBeanException {
- super(impl, intf);
- }
-
- /**
- * @see javax.management.StandardMBean#getMBeanInfo()
- */
- public MBeanInfo getMBeanInfo() {
- MBeanInfo mbeanInfo = super.getMBeanInfo();
- if (mbeanInfo != null) {
- MBeanNotificationInfo[] notificationInfo;
- Object impl = getImplementation();
- if (impl instanceof NotificationEmitter) {
- notificationInfo = ((NotificationEmitter) (impl)).getNotificationInfo();
- } else {
- notificationInfo = new MBeanNotificationInfo[0];
- }
- mbeanInfo = new MBeanInfo(mbeanInfo.getClassName(), mbeanInfo.getDescription(), mbeanInfo.getAttributes(),
- mbeanInfo.getConstructors(), mbeanInfo.getOperations(), notificationInfo);
- }
- return mbeanInfo;
- }
-
- /**
- * @see javax.management.MBeanRegistration#postDeregister()
- */
- public void postDeregister() {
- Object impl = getImplementation();
- if (impl instanceof MBeanRegistration) {
- ((MBeanRegistration) impl).postDeregister();
- }
- }
-
- /**
- * @see javax.management.MBeanRegistration#postRegister(java.lang.Boolean)
- */
- public void postRegister(Boolean registrationDone) {
- Object impl = getImplementation();
- if (impl instanceof MBeanRegistration) {
- ((MBeanRegistration) impl).postRegister(registrationDone);
- }
- }
-
- /**
- * @see javax.management.MBeanRegistration#preDeregister()
- */
- public void preDeregister() throws Exception {
- Object impl = getImplementation();
- if (impl instanceof MBeanRegistration) {
- ((MBeanRegistration) impl).preDeregister();
- }
- }
-
- /**
- * @see javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName)
- */
- public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
- ObjectName result = name;
- Object impl = getImplementation();
- if (impl instanceof MBeanRegistration) {
- result = ((MBeanRegistration) impl).preRegister(server, name);
- }
- return result;
- }
-
- /**
- * @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener,
- * javax.management.NotificationFilter, java.lang.Object)
- */
- public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
- throws ListenerNotFoundException {
- Object impl = getImplementation();
- if (impl instanceof NotificationEmitter) {
- ((NotificationEmitter) (impl)).removeNotificationListener(listener, filter, handback);
- }
- }
-
- /**
- * @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener,
- * javax.management.NotificationFilter, java.lang.Object)
- */
- public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
- throws IllegalArgumentException {
- Object impl = getImplementation();
- if (impl instanceof NotificationEmitter) {
- ((NotificationEmitter) (impl)).addNotificationListener(listener, filter, handback);
- }
- }
-
- /**
- * @see javax.management.NotificationBroadcaster#getNotificationInfo()
- */
- public MBeanNotificationInfo[] getNotificationInfo() {
- MBeanNotificationInfo[] result;
- Object impl = getImplementation();
- if (impl instanceof NotificationEmitter) {
- result = ((NotificationEmitter) (impl)).getNotificationInfo();
- } else {
- result = new MBeanNotificationInfo[0];
- }
- return result;
- }
-
- /**
- * @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)
- */
- public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
- Object impl = getImplementation();
- if (impl instanceof NotificationEmitter) {
- ((NotificationEmitter) (impl)).removeNotificationListener(listener);
- }
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/framework/ServiceState.java b/jmx-core/src/main/java/org/apache/aries/jmx/framework/ServiceState.java
deleted file mode 100644
index 9eb1539..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/framework/ServiceState.java
+++ /dev/null
@@ -1,233 +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.aries.jmx.framework;
-
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleIds;
-import static org.apache.aries.jmx.util.FrameworkUtils.resolveService;
-import static org.osgi.jmx.JmxConstants.PROPERTIES_TYPE;
-
-import java.io.IOException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import javax.management.MBeanNotificationInfo;
-import javax.management.MBeanRegistration;
-import javax.management.MBeanServer;
-import javax.management.Notification;
-import javax.management.NotificationBroadcasterSupport;
-import javax.management.ObjectName;
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.aries.jmx.JMXThreadFactory;
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.codec.PropertyData;
-import org.apache.aries.jmx.codec.ServiceData;
-import org.apache.aries.jmx.codec.ServiceEventData;
-import org.osgi.framework.AllServiceListener;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceReference;
-import org.osgi.jmx.framework.ServiceStateMBean;
-import org.osgi.service.log.LogService;
-
-/**
- * Implementation of <code>ServiceStateMBean</code> which emits JMX <code>Notification</code> for framework
- * <code>ServiceEvent</code> events
- *
- * @version $Rev$ $Date$
- */
-public class ServiceState extends NotificationBroadcasterSupport implements ServiceStateMBean, MBeanRegistration {
-
- protected Logger logger;
- private BundleContext bundleContext;
-
- protected ExecutorService eventDispatcher;
- protected AllServiceListener serviceListener;
- private AtomicInteger notificationSequenceNumber = new AtomicInteger(1);
- private AtomicInteger registrations = new AtomicInteger(0);
- private Lock lock = new ReentrantLock();
- // notification type description
- public static String SERVICE_EVENT = "org.osgi.service.event";
-
- public ServiceState(BundleContext bundleContext, Logger logger) {
- if (bundleContext == null) {
- throw new IllegalArgumentException("Argument bundleContext cannot be null");
- }
- this.bundleContext = bundleContext;
- this.logger = logger;
- }
-
- /**
- * @see org.osgi.jmx.framework.ServiceStateMBean#getBundleIdentifier(long)
- */
- public long getBundleIdentifier(long serviceId) throws IOException {
- ServiceReference reference = resolveService(bundleContext, serviceId);
- return reference.getBundle().getBundleId();
- }
-
- /**
- * @see org.osgi.jmx.framework.ServiceStateMBean#getObjectClass(long)
- */
- public String[] getObjectClass(long serviceId) throws IOException {
- ServiceReference reference = resolveService(bundleContext, serviceId);
- return (String[]) reference.getProperty(Constants.OBJECTCLASS);
- }
-
- /**
- * @see org.osgi.jmx.framework.ServiceStateMBean#getProperties(long)
- */
- public TabularData getProperties(long serviceId) throws IOException {
- ServiceReference reference = resolveService(bundleContext, serviceId);
- TabularData propertiesTable = new TabularDataSupport(PROPERTIES_TYPE);
- for (String propertyKey : reference.getPropertyKeys()) {
- propertiesTable.put(PropertyData.newInstance(propertyKey, reference.getProperty(propertyKey))
- .toCompositeData());
- }
- return propertiesTable;
- }
-
- /**
- * @see org.osgi.jmx.framework.ServiceStateMBean#getUsingBundles(long)
- */
- public long[] getUsingBundles(long serviceId) throws IOException {
- ServiceReference reference = resolveService(bundleContext, serviceId);
- Bundle[] usingBundles = reference.getUsingBundles();
- return getBundleIds(usingBundles);
- }
-
- /**
- * @see org.osgi.jmx.framework.ServiceStateMBean#listServices()
- */
- public TabularData listServices() throws IOException {
- TabularData servicesTable = new TabularDataSupport(SERVICES_TYPE);
- ServiceReference[] allServiceReferences = null;
- try {
- allServiceReferences = bundleContext.getAllServiceReferences(null, null);
- } catch (InvalidSyntaxException e) {
- throw new IllegalStateException("Failed to retrieve all service references", e);
- }
- if (allServiceReferences != null) {
- for (ServiceReference reference : allServiceReferences) {
- servicesTable.put(new ServiceData(reference).toCompositeData());
- }
- }
- return servicesTable;
- }
-
- /**
- * @see javax.management.NotificationBroadcasterSupport#getNotificationInfo()
- */
- public MBeanNotificationInfo[] getNotificationInfo() {
- String[] types = new String[] { SERVICE_EVENT };
- String name = Notification.class.getName();
- String description = "A ServiceEvent issued from the Framework describing a service lifecycle change";
- MBeanNotificationInfo info = new MBeanNotificationInfo(types, name, description);
- return new MBeanNotificationInfo[] { info };
- }
-
- /**
- * @see javax.management.MBeanRegistration#postDeregister()
- */
- public void postDeregister() {
- if (registrations.decrementAndGet() < 1) {
- shutDownDispatcher();
- }
- }
-
- /**
- * @see javax.management.MBeanRegistration#postRegister(java.lang.Boolean)
- */
- public void postRegister(Boolean registrationDone) {
- if (registrationDone && registrations.incrementAndGet() == 1) {
- eventDispatcher = Executors.newSingleThreadExecutor(new JMXThreadFactory("JMX OSGi Service State Event Dispatcher"));
- bundleContext.addServiceListener(serviceListener);
- }
- }
-
- public void preDeregister() throws Exception {
- // No action
- }
-
- /**
- * @see javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName)
- */
- public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
- lock.lock();
- try {
- if (serviceListener == null) {
- serviceListener = new AllServiceListener() {
- public void serviceChanged(ServiceEvent serviceevent) {
- final Notification notification = new Notification(EVENT, OBJECTNAME,
- notificationSequenceNumber.getAndIncrement());
- try {
- notification.setUserData(new ServiceEventData(serviceevent).toCompositeData());
- eventDispatcher.submit(new Runnable() {
- public void run() {
- sendNotification(notification);
- }
- });
- } catch (RejectedExecutionException re) {
- logger.log(LogService.LOG_WARNING, "Task rejected for JMX Notification dispatch of event ["
- + serviceevent + "] - Dispatcher may have been shutdown");
- } catch (Exception e) {
- logger.log(LogService.LOG_WARNING,
- "Exception occured on JMX Notification dispatch for event [" + serviceevent + "]",
- e);
- }
- }
- };
- }
- } finally {
- lock.unlock();
- }
- return name;
- }
-
- /*
- * Shuts down the notification dispatcher
- * [ARIES-259] MBeans not getting unregistered reliably
- */
- protected void shutDownDispatcher() {
- if (serviceListener != null) {
- try {
- bundleContext.removeServiceListener(serviceListener);
- }
- catch (Exception e) {
- // ignore
- }
- }
- if (eventDispatcher != null) {
- eventDispatcher.shutdown();
- }
- }
-
- /*
- * Returns the ExecutorService used to dispatch Notifications
- */
- protected ExecutorService getEventDispatcher() {
- return eventDispatcher;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/framework/ServiceStateMBeanHandler.java b/jmx-core/src/main/java/org/apache/aries/jmx/framework/ServiceStateMBeanHandler.java
deleted file mode 100644
index 470cd7a..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/framework/ServiceStateMBeanHandler.java
+++ /dev/null
@@ -1,92 +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.aries.jmx.framework;
-
-import static org.osgi.jmx.framework.ServiceStateMBean.OBJECTNAME;
-
-import javax.management.NotCompliantMBeanException;
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.MBeanHandler;
-import org.osgi.framework.BundleContext;
-import org.osgi.jmx.framework.ServiceStateMBean;
-import org.osgi.service.log.LogService;
-
-/**
- * <p>
- * Implementation of <code>MBeanHandler</code> which manages the <code>ServiceState</code>
- * MBean implementation
- * @see MBeanHandler
- * </p>
- *
- * @version $Rev$ $Date$
- */
-public class ServiceStateMBeanHandler implements MBeanHandler {
-
- private String name;
- private StandardMBean mbean;
- private ServiceState serviceStateMBean;
- private BundleContext bundleContext;
- private Logger logger;
-
-
- public ServiceStateMBeanHandler(BundleContext bundleContext, Logger logger) {
- this.bundleContext = bundleContext;
- this.logger = logger;
- this.name = OBJECTNAME;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#open()
- */
- public void open() {
- serviceStateMBean = new ServiceState(bundleContext, logger);
- try {
- mbean = new RegistrableStandardEmitterMBean(serviceStateMBean, ServiceStateMBean.class);
- } catch (NotCompliantMBeanException e) {
- logger.log(LogService.LOG_ERROR, "Failed to instantiate MBean for " + ServiceStateMBean.class.getName(), e);
- }
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getMbean()
- */
- public StandardMBean getMbean() {
- return mbean;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getName()
- */
- public String getName() {
- return name;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#close()
- */
- public void close() {
- // ensure dispatcher is shutdown even if postDeRegister is not honored
- if (serviceStateMBean != null) {
- serviceStateMBean.shutDownDispatcher();
- }
- }
-
-
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/permissionadmin/PermissionAdmin.java b/jmx-core/src/main/java/org/apache/aries/jmx/permissionadmin/PermissionAdmin.java
deleted file mode 100644
index 073356b..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/permissionadmin/PermissionAdmin.java
+++ /dev/null
@@ -1,126 +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.aries.jmx.permissionadmin;
-
-import java.io.IOException;
-
-import org.osgi.jmx.service.permissionadmin.PermissionAdminMBean;
-import org.osgi.service.permissionadmin.PermissionInfo;
-
-/**
- * <p>
- * <tt>PermissionAdmin</tt> represents implementation of PermissionAdminMBean.
- * </p>
- * @see PermissionAdminMBean
- *
- * @version $Rev$ $Date$
- */
-public class PermissionAdmin implements PermissionAdminMBean {
-
- /**
- * {@link org.osgi.service.permissionadmin.PermissionAdmin} service.
- */
- private org.osgi.service.permissionadmin.PermissionAdmin permAdmin;
-
- /**
- * Constructs new PermissionAdmin MBean.
- *
- * @param permAdmin {@link org.osgi.service.permissionadmin.PermissionAdmin} service reference.
- */
- public PermissionAdmin(org.osgi.service.permissionadmin.PermissionAdmin permAdmin) {
- this.permAdmin = permAdmin;
- }
-
- /**
- * @see org.osgi.jmx.service.permissionadmin.PermissionAdminMBean#getPermissions(java.lang.String)
- */
- public String[] getPermissions(String location) throws IOException {
- if (location == null) {
- throw new IOException("Location cannot be null");
- }
- PermissionInfo[] permissions = permAdmin.getPermissions(location);
- if (permissions != null) {
- String[] encoded = new String[permissions.length];
- for (int i = 0; i < permissions.length; i++) {
- PermissionInfo info = permissions[i];
- encoded[i] = info.getEncoded();
- }
- return encoded;
- }
- return null;
- }
-
- /**
- * @see org.osgi.jmx.service.permissionadmin.PermissionAdminMBean#listDefaultPermissions()
- */
- public String[] listDefaultPermissions() throws IOException {
- PermissionInfo[] permissions = permAdmin.getDefaultPermissions();
- if (permissions != null) {
- String[] encoded = new String[permissions.length];
- for (int i = 0; i < permissions.length; i++) {
- PermissionInfo info = permissions[i];
- encoded[i] = info.getEncoded();
- }
- return encoded;
- }
- return null;
- }
-
- /**
- * @see org.osgi.jmx.service.permissionadmin.PermissionAdminMBean#listLocations()
- */
- public String[] listLocations() throws IOException {
- return permAdmin.getLocations();
- }
-
- /**
- * @see org.osgi.jmx.service.permissionadmin.PermissionAdminMBean#setDefaultPermissions(java.lang.String[])
- */
- public void setDefaultPermissions(String[] encodedPermissions) throws IOException {
- PermissionInfo[] permissions = toPermissionInfo(encodedPermissions);
- permAdmin.setDefaultPermissions(permissions);
- }
-
- /**
- * @see org.osgi.jmx.service.permissionadmin.PermissionAdminMBean#setPermissions(java.lang.String,
- * java.lang.String[])
- */
- public void setPermissions(String location, String[] encodedPermissions) throws IOException {
- if (location == null) {
- throw new IOException("Location cannot be null");
- }
- PermissionInfo[] permissions = toPermissionInfo(encodedPermissions);
- permAdmin.setPermissions(location, permissions);
- }
-
- private static PermissionInfo[] toPermissionInfo(String[] encodedPermissions) throws IOException {
- if (encodedPermissions == null) {
- return null;
- }
- PermissionInfo[] permissions = new PermissionInfo[encodedPermissions.length];
- for (int i = 0; i < encodedPermissions.length; i++) {
- try {
- permissions[i] = new PermissionInfo(encodedPermissions[i]);
- } catch (Exception e) {
- IOException ex = new IOException("Invalid encoded permission: " + encodedPermissions[i]);
- ex.initCause(e);
- throw ex;
- }
- }
- return permissions;
- }
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/permissionadmin/PermissionAdminMBeanHandler.java b/jmx-core/src/main/java/org/apache/aries/jmx/permissionadmin/PermissionAdminMBeanHandler.java
deleted file mode 100644
index f83639f..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/permissionadmin/PermissionAdminMBeanHandler.java
+++ /dev/null
@@ -1,71 +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.aries.jmx.permissionadmin;
-
-import javax.management.NotCompliantMBeanException;
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.AbstractCompendiumHandler;
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.MBeanHandler;
-import org.apache.aries.jmx.agent.JMXAgentContext;
-import org.osgi.jmx.service.permissionadmin.PermissionAdminMBean;
-import org.osgi.service.log.LogService;
-
-/**
- * <p>
- * <tt>PermissionAdminMBeanHandler</tt> represents MBeanHandler which
- * holding information about {@link PermissionAdminMBean}.</p>
- * @see MBeanHandler
- *
- * @version $Rev$ $Date$
- */
-public class PermissionAdminMBeanHandler extends AbstractCompendiumHandler {
-
- /**
- * Constructs new PermissionAdminMBeanHandler.
- *
- * @param agentContext JMXAgentContext instance.
- */
- public PermissionAdminMBeanHandler(JMXAgentContext agentContext) {
- super(agentContext, "org.osgi.service.permissionadmin.PermissionAdmin");
- }
-
- /**
- * @see org.apache.aries.jmx.AbstractCompendiumHandler#constructInjectMBean(java.lang.Object)
- */
- @Override
- protected StandardMBean constructInjectMBean(Object targetService) {
- PermissionAdminMBean paMBean = new PermissionAdmin((org.osgi.service.permissionadmin.PermissionAdmin) targetService);
- StandardMBean mbean = null;
- try {
- mbean = new StandardMBean(paMBean, PermissionAdminMBean.class);
- } catch (NotCompliantMBeanException e) {
- Logger logger = agentContext.getLogger();
- logger.log(LogService.LOG_ERROR, "Not compliant MBean", e);
- }
- return mbean;
- }
-
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getName()
- */
- public String getName() {
- return PermissionAdminMBean.OBJECTNAME;
- }
-}
\ No newline at end of file
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/provisioning/ProvisioningService.java b/jmx-core/src/main/java/org/apache/aries/jmx/provisioning/ProvisioningService.java
deleted file mode 100644
index 543cb2e..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/provisioning/ProvisioningService.java
+++ /dev/null
@@ -1,121 +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.aries.jmx.provisioning;
-
-import static org.osgi.jmx.JmxConstants.PROPERTIES_TYPE;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.Collection;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.zip.ZipInputStream;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.aries.jmx.codec.PropertyData;
-import org.osgi.jmx.service.provisioning.ProvisioningServiceMBean;
-
-/**
- * Implementation of <code>ProvisioningServiceMBean</code>
- *
- * @version $Rev$ $Date$
- */
-public class ProvisioningService implements ProvisioningServiceMBean {
-
- private org.osgi.service.provisioning.ProvisioningService provisioningService;
-
- /**
- * Constructs new ProvisioningService instance
- * @param provisioningService instance of org.osgi.service.provisioning.ProvisioningService service
- */
- public ProvisioningService(org.osgi.service.provisioning.ProvisioningService provisioningService){
- this.provisioningService = provisioningService;
- }
-
- /**
- * @see org.osgi.jmx.service.provisioning.ProvisioningServiceMBean#addInformationFromZip(java.lang.String)
- */
- public void addInformationFromZip(String zipURL) throws IOException {
- if (zipURL == null || zipURL.length() < 1) {
- throw new IOException("Argument zipURL cannot be null or empty");
- }
- InputStream is = createStream(zipURL);
- ZipInputStream zis = new ZipInputStream(is);
- try {
- provisioningService.addInformation(zis);
- } finally {
- zis.close();
- }
- }
-
- /**
- * @see org.osgi.jmx.service.provisioning.ProvisioningServiceMBean#addInformation(javax.management.openmbean.TabularData)
- */
- public void addInformation(TabularData info) throws IOException {
- Dictionary<String, Object> provisioningInfo = extractProvisioningDictionary(info);
- provisioningService.addInformation(provisioningInfo);
- }
-
- /**
- * @see org.osgi.jmx.service.provisioning.ProvisioningServiceMBean#listInformation()
- */
- @SuppressWarnings("unchecked")
- public TabularData listInformation() throws IOException {
- TabularData propertiesTable = new TabularDataSupport(PROPERTIES_TYPE);
- Dictionary<String, Object> information = (Dictionary<String, Object>) provisioningService.getInformation();
- if (information != null) {
- Enumeration<String> keys = information.keys();
- while (keys.hasMoreElements()) {
- String key = keys.nextElement();
- propertiesTable.put(PropertyData.newInstance(key, information.get(key)).toCompositeData());
- }
- }
- return propertiesTable;
- }
-
- /**
- * @see org.osgi.jmx.service.provisioning.ProvisioningServiceMBean#setInformation(javax.management.openmbean.TabularData)
- */
- public void setInformation(TabularData info) throws IOException {
- Dictionary<String, Object> provisioningInfo = extractProvisioningDictionary(info);
- provisioningService.setInformation(provisioningInfo);
- }
-
-
- @SuppressWarnings("unchecked")
- protected Dictionary<String, Object> extractProvisioningDictionary(TabularData info) {
- Dictionary<String, Object> provisioningInfo = new Hashtable<String, Object>();
- if (info != null) {
- Collection<CompositeData> compositeData = (Collection<CompositeData>) info.values();
- for (CompositeData row: compositeData) {
- PropertyData<? extends Class> propertyData = PropertyData.from(row);
- provisioningInfo.put(propertyData.getKey(), propertyData.getValue());
- }
- }
- return provisioningInfo;
- }
-
- protected InputStream createStream(String url) throws IOException {
- return new URL(url).openStream();
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/provisioning/ProvisioningServiceMBeanHandler.java b/jmx-core/src/main/java/org/apache/aries/jmx/provisioning/ProvisioningServiceMBeanHandler.java
deleted file mode 100644
index 0dee354..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/provisioning/ProvisioningServiceMBeanHandler.java
+++ /dev/null
@@ -1,74 +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.aries.jmx.provisioning;
-
-import javax.management.NotCompliantMBeanException;
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.AbstractCompendiumHandler;
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.MBeanHandler;
-import org.apache.aries.jmx.agent.JMXAgentContext;
-import org.osgi.jmx.service.provisioning.ProvisioningServiceMBean;
-import org.osgi.service.log.LogService;
-
-/**
- * <p>
- * Implementation of <code>MBeanHandler</code> which manages the <code>ProvisioningServiceMBean</code> implementation
- *
- * @see MBeanHandler
- *
- * @version $Rev$ $Date$
- */
-public class ProvisioningServiceMBeanHandler extends AbstractCompendiumHandler {
-
- /**
- * Constructs new ProvisioningServiceMBeanHandler instance
- *
- * @param agentContext
- * JMXAgentContext instance
- */
- public ProvisioningServiceMBeanHandler(JMXAgentContext agentContext) {
- super(agentContext, "org.osgi.service.provisioning.ProvisioningService");
- }
-
- /**
- * @see org.apache.aries.jmx.AbstractCompendiumHandler#constructInjectMBean(java.lang.Object)
- */
- @Override
- protected StandardMBean constructInjectMBean(Object targetService) {
- ProvisioningService psMBean = new ProvisioningService(
- (org.osgi.service.provisioning.ProvisioningService) targetService);
- StandardMBean mbean = null;
- try {
- mbean = new StandardMBean(psMBean, ProvisioningServiceMBean.class);
- } catch (NotCompliantMBeanException e) {
- Logger logger = agentContext.getLogger();
- logger.log(LogService.LOG_ERROR, "Failed to instantiate MBean for "
- + ProvisioningServiceMBean.class.getName(), e);
- }
- return mbean;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getName()
- */
- public String getName() {
- return ProvisioningServiceMBean.OBJECTNAME;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/useradmin/UserAdmin.java b/jmx-core/src/main/java/org/apache/aries/jmx/useradmin/UserAdmin.java
deleted file mode 100644
index 48aa54e..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/useradmin/UserAdmin.java
+++ /dev/null
@@ -1,617 +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.aries.jmx.useradmin;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.List;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.aries.jmx.codec.AuthorizationData;
-import org.apache.aries.jmx.codec.GroupData;
-import org.apache.aries.jmx.codec.PropertyData;
-import org.apache.aries.jmx.codec.RoleData;
-import org.apache.aries.jmx.codec.UserData;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.jmx.JmxConstants;
-import org.osgi.jmx.service.useradmin.UserAdminMBean;
-import org.osgi.service.useradmin.Authorization;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-
-/**
- * <p>
- * <tt>UserAdmin</tt> represents {@link UserAdminMBean} implementation.
- * </p>
- *
- * @see UserAdminMBean
- *
- * @version $Rev$ $Date$
- */
-public class UserAdmin implements UserAdminMBean {
-
- /**
- * @see org.osgi.service.useradmin.UserAdmin service reference;
- */
- private org.osgi.service.useradmin.UserAdmin userAdmin;
-
- /**
- * Constructs new UserAdmin MBean.
- *
- * @param userAdmin
- * {@link UserAdmin} service reference.
- */
- public UserAdmin(org.osgi.service.useradmin.UserAdmin userAdmin) {
- this.userAdmin = userAdmin;
- }
-
- /**
- * Validate Role against roleType.
- *
- * @see Role#USER
- * @see Role#GROUP
- * @see Role#USER_ANYONE
- *
- * @param role
- * Role instance.
- * @param roleType
- * role type.
- */
- private void validateRoleType(Role role, int roleType) throws IOException {
- if (role.getType() != roleType) {
- throw new IOException("Unexpected role type. Expected " + roleType + " but got " + role.getType());
- }
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#addCredential(java.lang.String, byte[], java.lang.String)
- */
- public void addCredential(String key, byte[] value, String username) throws IOException {
- addCredential(key, (Object)value, username);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#addCredentialString(String, String, String)
- */
- public void addCredentialString(String key, String value, String username) throws IOException {
- addCredential(key, (Object)value, username);
- }
-
- private void addCredential(String key, Object value, String username) throws IOException {
- if (username == null) {
- throw new IOException("User name cannot be null");
- }
- if (key == null) {
- throw new IOException("Credential key cannot be null");
- }
- Role role = userAdmin.getRole(username);
- if (role == null) {
- throw new IOException("Operation fails user with provided username = [" + username + "] doesn't exist");
- }
- validateRoleType(role, Role.USER);
- Dictionary<String, Object> credentials = ((User) role).getCredentials();
- if (credentials != null) {
- credentials.put(key, value);
- }
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#addMember(java.lang.String, java.lang.String)
- */
- public boolean addMember(String groupname, String rolename) throws IOException {
- if (groupname == null) {
- throw new IOException("Group name cannot be null");
- }
- if (rolename == null) {
- throw new IOException("Role name cannot be null");
- }
- Role group = userAdmin.getRole(groupname);
- Role member = userAdmin.getRole(rolename);
- if (group == null) {
- throw new IOException("Operation fails role with provided groupname = [" + groupname + "] doesn't exist");
- }
- validateRoleType(group, Role.GROUP);
- return ((Group) group).addMember(member);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#addPropertyString(String, String, String)
- */
- public void addPropertyString(String key, String value, String rolename) throws IOException {
- addRoleProperty(key, value, rolename);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#addProperty(java.lang.String, byte[], java.lang.String)
- */
- public void addProperty(String key, byte[] value, String rolename) throws IOException {
- addRoleProperty(key, value, rolename);
- }
-
- /**
- * @see UserAdminMBean#addProperty(String, byte[], String)
- * @see UserAdminMBean#addProperty(String, String, String)
- */
- private void addRoleProperty(String key, Object value, String rolename) throws IOException {
- if (rolename == null) {
- throw new IOException("Role name cannot be null");
- }
- if (key == null) {
- throw new IOException("Property key cannot be null");
- }
- Role role = userAdmin.getRole(rolename);
- if (role == null) {
- throw new IOException("Operation fails role with provided rolename = [" + rolename + "] doesn't exist");
- }
- Dictionary<String, Object> properties = role.getProperties();
- if (properties != null) {
- properties.put(key, value);
- }
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#addRequiredMember(java.lang.String, java.lang.String)
- */
- public boolean addRequiredMember(String groupname, String rolename) throws IOException {
- if (groupname == null) {
- throw new IOException("Group name cannot be null");
- }
- if (rolename == null) {
- throw new IOException("Role name cannot be null");
- }
- Role group = userAdmin.getRole(groupname);
- Role member = userAdmin.getRole(rolename);
- if (group == null) {
- throw new IOException("Operation fails role with provided groupname = [" + groupname + "] doesn't exist");
- }
- validateRoleType(group, Role.GROUP);
- return ((Group) group).addRequiredMember(member);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#createGroup(java.lang.String)
- */
- public void createGroup(String name) throws IOException {
- if (name == null) {
- throw new IOException("Group name cannot be null");
- }
- userAdmin.createRole(name, Role.GROUP);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#createRole(java.lang.String)
- */
- public void createRole(String name) throws IOException {
- throw new IOException("Deprecated: use createGroup or createUser");
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#createUser(java.lang.String)
- */
- public void createUser(String name) throws IOException {
- if (name == null) {
- throw new IOException("User name cannot be null");
- }
- userAdmin.createRole(name, Role.USER);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getAuthorization(java.lang.String)
- */
- public CompositeData getAuthorization(String username) throws IOException {
- if (username== null) {
- throw new IOException("User name cannot be null");
- }
- Role role = userAdmin.getRole(username);
- if (role == null) {
- return null;
- }
- validateRoleType(role, Role.USER);
- Authorization auth = userAdmin.getAuthorization((User) role);
- if (auth == null) {
- return null;
- }
-
- return new AuthorizationData(auth).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getCredentials(java.lang.String)
- */
- public TabularData getCredentials(String username) throws IOException {
- if (username == null) {
- throw new IOException("User name cannot be null");
- }
- Role role = userAdmin.getRole(username);
- if (role == null) {
- return null;
- }
- validateRoleType(role, Role.USER);
- Dictionary<String, Object> credentials = ((User) role).getCredentials();
- if (credentials == null) {
- return null;
- }
- TabularData data = new TabularDataSupport(JmxConstants.PROPERTIES_TYPE);
- for (Enumeration<String> keys = credentials.keys(); keys.hasMoreElements();) {
- String key = keys.nextElement();
- data.put(PropertyData.newInstance(key, credentials.get(key)).toCompositeData());
- }
- return data;
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getGroup(java.lang.String)
- */
- public CompositeData getGroup(String groupname) throws IOException {
- if (groupname == null) {
- throw new IOException("Group name cannot be null");
- }
- Role role = userAdmin.getRole(groupname);
- if (role == null) {
- return null;
- }
- validateRoleType(role, Role.GROUP);
- return new GroupData((Group) role).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getGroups(java.lang.String)
- */
- public String[] getGroups(String filter) throws IOException {
- Role[] roles = null;
- try {
- roles = userAdmin.getRoles(filter);
- } catch (InvalidSyntaxException ise) {
- IOException ioex = new IOException("Operation fails illegal filter provided: " + filter);
- ioex.initCause(ise);
- throw ioex;
- }
-
- if (roles == null) {
- return null;
- }
-
- return getRoleByType(roles, Role.GROUP);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getImpliedRoles(java.lang.String)
- */
- public String[] getImpliedRoles(String username) throws IOException {
- if (username == null) {
- throw new IOException("User name cannot be null");
- }
- Role role = userAdmin.getRole(username);
- if (role != null) {
- validateRoleType(role, Role.USER);
- Authorization auth = userAdmin.getAuthorization((User) role);
- if (auth != null) {
- return auth.getRoles();
- }
- }
- return null;
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getMembers(java.lang.String)
- */
- public String[] getMembers(String groupname) throws IOException {
- if (groupname == null) {
- throw new IOException("Group name cannot be null");
- }
- Role role = userAdmin.getRole(groupname);
- if (role != null) {
- validateRoleType(role, Role.GROUP);
- Role[] roles = ((Group) role).getMembers();
- if (roles != null) {
- String[] members = new String[roles.length];
- for (int i = 0; i < roles.length; i++) {
- members[i] = roles[i].getName();
- }
- return members;
- }
- }
- return null;
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getProperties(java.lang.String)
- */
- public TabularData getProperties(String rolename) throws IOException {
- if (rolename == null) {
- throw new IOException("Role name cannot be null");
- }
- Role role = userAdmin.getRole(rolename);
- if (role == null) {
- return null;
- }
- Dictionary<String, Object> properties = role.getProperties();
- if (properties == null) {
- return null;
- }
- TabularData data = new TabularDataSupport(JmxConstants.PROPERTIES_TYPE);
- for (Enumeration<String> keys = properties.keys(); keys.hasMoreElements();) {
- String key = keys.nextElement();
- data.put(PropertyData.newInstance(key, properties.get(key)).toCompositeData());
- }
- return data;
-
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getRequiredMembers(java.lang.String)
- */
- public String[] getRequiredMembers(String groupname) throws IOException {
- if (groupname == null) {
- throw new IOException("Group name cannot be null");
- }
- Role role = userAdmin.getRole(groupname);
- if (role != null) {
- validateRoleType(role, Role.GROUP);
- Role[] roles = ((Group) role).getRequiredMembers();
- if (roles != null) {
- String[] reqMembers = new String[roles.length];
- for (int i = 0; i < roles.length; i++) {
- reqMembers[i] = roles[i].getName();
- }
- return reqMembers;
- }
- }
- return null;
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getRole(java.lang.String)
- */
- public CompositeData getRole(String name) throws IOException {
- if (name == null) {
- throw new IOException("Role name cannot be null");
- }
- Role role = userAdmin.getRole(name);
- if (role == null) {
- return null;
- }
- return new RoleData(role).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getRoles(java.lang.String)
- */
- public String[] getRoles(String filter) throws IOException {
- Role[] roles = null;
- try {
- roles = userAdmin.getRoles(filter);
- } catch (InvalidSyntaxException ise) {
- IOException ioex = new IOException("Operation fails illegal filter provided: " + filter);
- ioex.initCause(ise);
- throw ioex;
- }
- if (roles == null) {
- return null;
- }
- return getRoleByType(roles, Role.ROLE);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getUser(java.lang.String)
- */
- public CompositeData getUser(String username) throws IOException {
- if (username == null) {
- throw new IOException("User name cannot be null");
- }
- Role role = userAdmin.getRole(username);
- if (role == null) {
- return null;
- }
- validateRoleType(role, Role.USER);
- return new UserData((User) role).toCompositeData();
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getUserWithProperty(String, String)
- */
- public String getUserWithProperty(String key, String value) throws IOException {
- if (key == null) {
- throw new IOException("Property key cannot be null");
- }
- User user = userAdmin.getUser(key, value);
- if (user == null) {
- return null;
- }
- return user.getName();
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#getUsers(java.lang.String)
- */
- public String[] getUsers(String filter) throws IOException {
- Role[] roles = null;
- try {
- roles = userAdmin.getRoles(filter);
- } catch (InvalidSyntaxException ise) {
- IOException ioex = new IOException("Operation fails illegal filter provided: " + filter);
- ioex.initCause(ise);
- throw ioex;
- }
- if (roles == null) {
- return null;
- }
- return getRoleByType(roles, Role.USER);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#listGroups()
- */
- public String[] listGroups() throws IOException {
- Role[] roles = null;
- try {
- roles = userAdmin.getRoles(null);
- } catch (InvalidSyntaxException e) {
- // shouldn't happened we are not using filter
- }
- if (roles == null) {
- return null;
- }
- return getRoleByType(roles, Role.GROUP);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#listRoles()
- */
- public String[] listRoles() throws IOException {
- Role[] roles = null;
- try {
- roles = userAdmin.getRoles(null);
- } catch (InvalidSyntaxException e) {
- // shouldn't happened we are not using filter
- }
-
- if (roles == null) {
- return null;
- }
-
- return getRoleByType(roles, Role.ROLE);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#listUsers()
- */
- public String[] listUsers() throws IOException {
- Role[] roles = null;
- try {
- roles = userAdmin.getRoles(null);
- } catch (InvalidSyntaxException e) {
- // shouldn't happened we are not using filter
- }
- if (roles == null) {
- return null;
- }
- return getRoleByType(roles, Role.USER);
- }
-
- /**
- * Gets role names by type from provided roles array.
- *
- * @param roles
- * array of Role's.
- * @param roleType
- * role Type.
- * @return array of role names.
- */
- private String[] getRoleByType(Role[] roles, int roleType) {
- List<String> rs = new ArrayList<String>();
- for (Role role : roles) {
- if (roleType == Role.ROLE) {
- rs.add(role.getName());
- continue;
- }
-
- if (role.getType() == roleType) {
- rs.add(role.getName());
- }
- }
- return rs.toArray(new String[rs.size()]);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeCredential(java.lang.String, java.lang.String)
- */
- public void removeCredential(String key, String username) throws IOException {
- if (username == null) {
- throw new IOException("User name cannot be null");
- }
- if (key == null) {
- throw new IOException("Credential key cannot be null");
- }
- Role role = userAdmin.getRole(username);
- if (role == null) {
- throw new IOException("Operation fails can't find user with username = [" + username + "] doesn't exist");
- }
- validateRoleType(role, Role.USER);
- ((User) role).getCredentials().remove(key);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeGroup(java.lang.String)
- */
- public boolean removeGroup(String name) throws IOException {
- if (name == null) {
- throw new IOException("Group name cannot be null");
- }
- return userAdmin.removeRole(name);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeMember(java.lang.String, java.lang.String)
- */
- public boolean removeMember(String groupname, String rolename) throws IOException {
- if (groupname == null) {
- throw new IOException("Group name cannot be null");
- }
- if (rolename == null) {
- throw new IOException("Role name cannot be null");
- }
- Role group = userAdmin.getRole(groupname);
- Role member = userAdmin.getRole(rolename);
- if (group == null) {
- throw new IOException("Operation fails role with provided groupname = [" + groupname + "] doesn't exist");
- }
- validateRoleType(group, Role.GROUP);
- return ((Group) group).removeMember(member);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeProperty(java.lang.String, java.lang.String)
- */
- public void removeProperty(String key, String rolename) throws IOException {
- if (rolename == null) {
- throw new IOException("Role name cannot be null");
- }
- Role role = userAdmin.getRole(rolename);
- if (role == null) {
- throw new IOException("Operation fails role with provided rolename = [" + rolename + "] doesn't exist");
- }
- role.getProperties().remove(key);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeRole(java.lang.String)
- */
- public boolean removeRole(String name) throws IOException {
- if (name == null) {
- throw new IOException("Role name cannot be null");
- }
- return userAdmin.removeRole(name);
- }
-
- /**
- * @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeUser(java.lang.String)
- */
- public boolean removeUser(String name) throws IOException {
- if (name == null) {
- throw new IOException("User name cannot be null");
- }
- return userAdmin.removeRole(name);
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/useradmin/UserAdminMBeanHandler.java b/jmx-core/src/main/java/org/apache/aries/jmx/useradmin/UserAdminMBeanHandler.java
deleted file mode 100644
index 33f87aa..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/useradmin/UserAdminMBeanHandler.java
+++ /dev/null
@@ -1,73 +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.aries.jmx.useradmin;
-
-import javax.management.NotCompliantMBeanException;
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.AbstractCompendiumHandler;
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.MBeanHandler;
-import org.apache.aries.jmx.agent.JMXAgentContext;
-import org.osgi.jmx.service.permissionadmin.PermissionAdminMBean;
-import org.osgi.jmx.service.useradmin.UserAdminMBean;
-import org.osgi.service.log.LogService;
-
-/**
- * <p>
- * <tt>UserAdminMBeanHandler</tt> represents MBeanHandler which
- * holding information about {@link PermissionAdminMBean}.</p>
- * @see AbstractCompendiumHandler
- * @see MBeanHandler
- *
- * @version $Rev$ $Date$
- */
-public class UserAdminMBeanHandler extends AbstractCompendiumHandler {
-
- /**
- * Constructs new UserAdminMBeanHandler.
- *
- * @param agentContext JMXAgentContext instance.
- */
- public UserAdminMBeanHandler(JMXAgentContext agentContext) {
- super(agentContext, "org.osgi.service.useradmin.UserAdmin");
- }
-
- /**
- * @see org.apache.aries.jmx.AbstractCompendiumHandler#constructInjectMBean(java.lang.Object)
- */
- @Override
- protected StandardMBean constructInjectMBean(Object targetService) {
- UserAdminMBean uaMBean = new UserAdmin((org.osgi.service.useradmin.UserAdmin) targetService);
- StandardMBean mbean = null;
- try {
- mbean = new StandardMBean(uaMBean, UserAdminMBean.class);
- } catch (NotCompliantMBeanException e) {
- Logger logger = agentContext.getLogger();
- logger.log(LogService.LOG_ERROR, "Not compliant MBean", e);
- }
- return mbean;
- }
-
- /**
- * @see org.apache.aries.jmx.MBeanHandler#getName()
- */
- public String getName() {
- return UserAdminMBean.OBJECTNAME;
- }
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/util/FrameworkUtils.java b/jmx-core/src/main/java/org/apache/aries/jmx/util/FrameworkUtils.java
deleted file mode 100644
index eb53a00..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/util/FrameworkUtils.java
+++ /dev/null
@@ -1,638 +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.aries.jmx.util;
-
-import static org.osgi.jmx.framework.BundleStateMBean.ACTIVE;
-import static org.osgi.jmx.framework.BundleStateMBean.INSTALLED;
-import static org.osgi.jmx.framework.BundleStateMBean.RESOLVED;
-import static org.osgi.jmx.framework.BundleStateMBean.STARTING;
-import static org.osgi.jmx.framework.BundleStateMBean.STOPPING;
-import static org.osgi.jmx.framework.BundleStateMBean.UNINSTALLED;
-import static org.osgi.jmx.framework.BundleStateMBean.UNKNOWN;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Dictionary;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.aries.util.ManifestHeaderUtils;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.packageadmin.ExportedPackage;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.packageadmin.RequiredBundle;
-
-/**
- * This class contains common utilities related to Framework operations for the MBean implementations
- *
- * @version $Rev$ $Date$
- */
-public class FrameworkUtils {
-
- private FrameworkUtils() {
- super();
- }
-
- /**
- *
- * Returns the Bundle object for a given id
- *
- * @param bundleContext
- * @param bundleId
- * @return
- * @throws IllegalArgumentException
- * if no Bundle is found with matching bundleId
- */
- public static Bundle resolveBundle(BundleContext bundleContext, long bundleId) throws IOException {
- if (bundleContext == null) {
- throw new IllegalArgumentException("Argument bundleContext cannot be null");
- }
- Bundle bundle = bundleContext.getBundle(bundleId);
- if (bundle == null) {
- throw new IOException("Bundle with id [" + bundleId + "] not found");
- }
- return bundle;
- }
-
- /**
- * Returns an array of bundleIds
- *
- * @param bundles
- * array of <code>Bundle</code> objects
- * @return bundleIds in sequence
- */
- public static long[] getBundleIds(Bundle[] bundles) {
- long[] result;
- if (bundles == null) {
- result = new long[0];
- } else {
- result = new long[bundles.length];
- for (int i = 0; i < bundles.length; i++) {
- result[i] = bundles[i].getBundleId();
- }
- }
- return result;
- }
-
- public static long[] getBundleIds(List<Bundle> bundles) {
- long[] result;
- if (bundles == null) {
- result = new long[0];
- } else {
- result = new long[bundles.size()];
- for (int i = 0; i < bundles.size(); i++) {
- result[i] = bundles.get(i).getBundleId();
- }
- }
- return result;
- }
-
- /**
- *
- * Returns the ServiceReference object with matching service.id
- *
- * @param bundleContext
- * @param serviceId
- * @return ServiceReference with matching service.id property
- * @throws IllegalArgumentException if bundleContext is null
- * @throws IOException if no service is found with the given id
- */
- public static ServiceReference resolveService(BundleContext bundleContext, long serviceId) throws IOException {
- if (bundleContext == null) {
- throw new IllegalArgumentException("Argument bundleContext cannot be null");
- }
- ServiceReference result = null;
- try {
- ServiceReference[] references = bundleContext.getAllServiceReferences(null, "(" + Constants.SERVICE_ID
- + "=" + serviceId + ")");
- if (references == null || references.length < 1) {
- throw new IOException("Service with id [" + serviceId + "] not found");
- } else {
- result = references[0];
- }
- } catch (InvalidSyntaxException e) {
- IOException ioe = new IOException("Failure when resolving service ");
- ioe.initCause(e);
- throw ioe;
- }
- return result;
- }
-
- /**
- * Returns an array of service.id values
- *
- * @param serviceReferences
- * array of <code>ServiceReference</code> objects
- * @return service.id values in sequence
- */
- public static long[] getServiceIds(ServiceReference[] serviceReferences) {
- long result[] = (serviceReferences == null) ? new long[0] : new long[serviceReferences.length];
- for (int i = 0; i < result.length; i++) {
- result[i] = (Long) serviceReferences[i].getProperty(Constants.SERVICE_ID);
- }
- return result;
- }
-
- /**
- * Returns the packages exported by the specified bundle
- *
- * @param bundle
- * @param packageAdmin
- * @return
- * @throws IllegalArgumentException
- * if bundle or packageAdmin are null
- */
- public static String[] getBundleExportedPackages(Bundle bundle, PackageAdmin packageAdmin)
- throws IllegalArgumentException {
- if (bundle == null) {
- throw new IllegalArgumentException("Argument bundle cannot be null");
- }
- if (packageAdmin == null) {
- throw new IllegalArgumentException("Argument packageAdmin cannot be null");
- }
- String[] exportedPackages;
- ExportedPackage[] exported = packageAdmin.getExportedPackages(bundle);
- if (exported != null) {
- exportedPackages = new String[exported.length];
- for (int i = 0; i < exported.length; i++) {
- exportedPackages[i] = exported[i].getName() + ";" + exported[i].getVersion().toString();
- }
- } else {
- exportedPackages = new String[0];
- }
- return exportedPackages;
- }
-
- /**
- * Returns the bundle ids of any resolved fragments
- *
- * @param bundle
- * @param packageAdmin
- * @return
- * @throws IllegalArgumentException
- * if bundle or packageAdmin are null
- */
- public static long[] getFragmentIds(Bundle bundle, PackageAdmin packageAdmin) throws IllegalArgumentException {
- if (bundle == null) {
- throw new IllegalArgumentException("Argument bundle cannot be null");
- }
- if (packageAdmin == null) {
- throw new IllegalArgumentException("Argument packageAdmin cannot be null");
- }
- long[] fragmentIds;
- Bundle[] fragments = packageAdmin.getFragments(bundle);
- if (fragments != null) {
- fragmentIds = getBundleIds(fragments);
- } else {
- fragmentIds = new long[0];
- }
- return fragmentIds;
- }
-
- /**
- * Returns the bundle ids of any resolved hosts
- *
- * @param fragment
- * @param packageAdmin
- * @return
- * @throws IllegalArgumentException
- * if fragment or packageAdmin are null
- */
- public static long[] getHostIds(Bundle fragment, PackageAdmin packageAdmin) throws IllegalArgumentException {
- if (fragment == null) {
- throw new IllegalArgumentException("Argument bundle cannot be null");
- }
- if (packageAdmin == null) {
- throw new IllegalArgumentException("Argument packageAdmin cannot be null");
- }
- long[] hostIds;
- Bundle[] hosts = packageAdmin.getHosts(fragment);
- if (hosts != null) {
- hostIds = getBundleIds(hosts);
- } else {
- hostIds = new long[0];
- }
- return hostIds;
- }
-
- /**
- * Returns the resolved package imports for the given bundle
- *
- * @param localBundleContext
- * BundleContext object of this bundle/caller
- * @param bundle
- * target Bundle object to query imported packages for
- * @param packageAdmin
- *
- * @return
- * @throws IllegalArgumentException
- * if fragment or packageAdmin are null
- */
- public static String[] getBundleImportedPackages(BundleContext localBundleContext, Bundle bundle,
- PackageAdmin packageAdmin) throws IllegalArgumentException {
- if (bundle == null) {
- throw new IllegalArgumentException("Argument bundle cannot be null");
- }
- if (packageAdmin == null) {
- throw new IllegalArgumentException("Argument packageAdmin cannot be null");
- }
-
- List<String> result = new ArrayList<String>();
- for (ExportedPackage ep : getBundleImportedPackagesRaw(localBundleContext, bundle, packageAdmin)) {
- result.add(ep.getName()+";"+ep.getVersion());
- }
-
- return result.toArray(new String[0]);
- }
-
- @SuppressWarnings("unchecked")
- private static Collection<ExportedPackage> getBundleImportedPackagesRaw(BundleContext localBundleContext, Bundle bundle, PackageAdmin packageAdmin) throws IllegalArgumentException
- {
- List<ExportedPackage> result = new ArrayList<ExportedPackage>();
- Dictionary<String, String> bundleHeaders = bundle.getHeaders();
- String dynamicImportHeader = bundleHeaders.get(Constants.DYNAMICIMPORT_PACKAGE);
- // if DynamicImport-Package used, then do full iteration
- // else means no dynamic import or has dynamic import but no wildcard "*" in it.
- if (dynamicImportHeader != null && dynamicImportHeader.contains("*")) {
- Bundle[] bundles = localBundleContext.getBundles();
- for (Bundle candidate : bundles) {
- if (candidate.equals(bundle)) {
- continue;
- }
- ExportedPackage[] candidateExports = packageAdmin.getExportedPackages(candidate);
- if (candidateExports != null) {
- for (ExportedPackage exportedPackage : candidateExports) {
- Bundle[] userBundles = exportedPackage.getImportingBundles();
- if (userBundles != null && arrayContains(userBundles, bundle)) {
- result.add(exportedPackage);
- }
- }// end for candidateExports
- }
- }// end for bundles
- } else { // only query ExportPackage for package names declared as imported
- List<String> importPackages = new ArrayList<String>();
- String importPackageHeader = bundleHeaders.get(Constants.IMPORT_PACKAGE);
- if (importPackageHeader != null && importPackageHeader.length() > 0) {
- importPackages.addAll(extractHeaderDeclaration(importPackageHeader));
- }
- if (dynamicImportHeader != null) {
- importPackages.addAll(extractHeaderDeclaration(dynamicImportHeader));
- }
- for (String packageName : importPackages) {
- ExportedPackage[] candidateExports = packageAdmin.getExportedPackages(packageName);
- if (candidateExports != null) {
- for (ExportedPackage exportedPackage : candidateExports) {
- Bundle[] userBundles = exportedPackage.getImportingBundles();
- if (userBundles != null && arrayContains(userBundles, bundle)) {
- result.add(exportedPackage);
- }
- }// end for candidateExports
- }
- }
- }
- return result;
- }
-
- /**
- * Returns the service.id values for services registered by the given bundle
- *
- * @param bundle
- * @return
- * @throws IllegalArgumentException
- * if bundle is null
- * @throws IlleglStateException
- * if bundle has been uninstalled
- */
- public static long[] getRegisteredServiceIds(Bundle bundle) throws IllegalArgumentException, IllegalStateException {
- if (bundle == null) {
- throw new IllegalArgumentException("Argument bundle cannot be null");
- }
- long[] serviceIds;
- ServiceReference[] serviceReferences = bundle.getRegisteredServices();
- if (serviceReferences != null) {
- serviceIds = new long[serviceReferences.length];
- for (int i = 0; i < serviceReferences.length; i++) {
- serviceIds[i] = (Long) serviceReferences[i].getProperty(Constants.SERVICE_ID);
- }
- } else {
- serviceIds = new long[0];
- }
- return serviceIds;
- }
-
- /**
- * Returns the service.id values of services being used by the given bundle
- *
- * @param bundle
- * @return
- * @throws IllegalArgumentException
- * if bundle is null
- * @throws IlleglStateException
- * if bundle has been uninstalled
- */
- public static long[] getServicesInUseByBundle(Bundle bundle) throws IllegalArgumentException, IllegalStateException {
- if (bundle == null) {
- throw new IllegalArgumentException("Argument bundle cannot be null");
- }
- long[] serviceIds;
- ServiceReference[] serviceReferences = bundle.getServicesInUse();
- if (serviceReferences != null) {
- serviceIds = new long[serviceReferences.length];
- for (int i = 0; i < serviceReferences.length; i++) {
- serviceIds[i] = (Long) serviceReferences[i].getProperty(Constants.SERVICE_ID);
- }
- } else {
- serviceIds = new long[0];
- }
- return serviceIds;
- }
-
- /**
- * Returns the status of pending removal
- *
- * @param bundle
- * @return true if the bundle is pending removal
- * @throws IllegalArgumentException
- * if bundle or packageAdmin are null
- */
- public static boolean isBundlePendingRemoval(Bundle bundle, PackageAdmin packageAdmin)
- throws IllegalArgumentException {
- if (bundle == null) {
- throw new IllegalArgumentException("Argument bundle cannot be null");
- }
- if (packageAdmin == null) {
- throw new IllegalArgumentException("Argument packageAdmin cannot be null");
- }
- boolean result = false;
- ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(bundle);
- if (exportedPackages != null) {
- for (ExportedPackage exportedPackage : exportedPackages) {
- if (exportedPackage.isRemovalPending()) {
- result = true;
- break;
- }
- }
- }
- if (!result) {
- RequiredBundle[] requiredBundles = packageAdmin.getRequiredBundles(bundle.getSymbolicName());
- if (requiredBundles != null) {
- for (RequiredBundle requiredBundle : requiredBundles) {
- Bundle required = requiredBundle.getBundle();
- if (required == bundle) {
- result = requiredBundle.isRemovalPending();
- break;
- }
- }
- }
- }
- return result;
- }
-
- /**
- * Checks if the given bundle is currently required by other bundles
- *
- * @param bundle
- * @param packageAdmin
- * @return
- * @throws IllegalArgumentException
- * if bundle or packageAdmin are null
- */
- public static boolean isBundleRequiredByOthers(Bundle bundle, PackageAdmin packageAdmin)
- throws IllegalArgumentException {
- if (bundle == null) {
- throw new IllegalArgumentException("Argument bundle cannot be null");
- }
- if (packageAdmin == null) {
- throw new IllegalArgumentException("Argument packageAdmin cannot be null");
- }
- boolean result = false;
- // Check imported packages (statically or dynamically)
- ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(bundle);
- if (exportedPackages != null) {
- for (ExportedPackage exportedPackage : exportedPackages) {
- Bundle[] importingBundles = exportedPackage.getImportingBundles();
- if (importingBundles != null && importingBundles.length > 0) {
- result = true;
- break;
- }
- }
- }
- if (!result) {
- // Check required bundles
- RequiredBundle[] requiredBundles = packageAdmin.getRequiredBundles(bundle.getSymbolicName());
- if (requiredBundles != null) {
- for (RequiredBundle requiredBundle : requiredBundles) {
- Bundle required = requiredBundle.getBundle();
- if (required == bundle) {
- Bundle[] requiring = requiredBundle.getRequiringBundles();
- if (requiring != null && requiring.length > 0) {
- result = true;
- break;
- }
- }
- }
- }
- }
- if (!result) {
- // Check fragment bundles
- Bundle[] fragments = packageAdmin.getFragments(bundle);
- if (fragments != null && fragments.length > 0) {
- result = true;
- }
- }
- return result;
- }
-
- /**
- * Returns an array of ids of bundles the given bundle depends on
- *
- * @param localBundleContext
- * BundleContext object of this bundle/caller
- * @param bundle
- * target Bundle object to query dependencies for
- * @param packageAdmin
- *
- * @return
- * @throws IllegalArgumentException
- * if bundle or packageAdmin are null
- */
- @SuppressWarnings("unchecked")
- public static long[] getBundleDependencies(BundleContext localBundleContext,
- Bundle bundle,
- PackageAdmin packageAdmin) throws IllegalArgumentException {
- if (bundle == null) {
- throw new IllegalArgumentException("Argument bundle cannot be null");
- }
- if (packageAdmin == null) {
- throw new IllegalArgumentException("Argument packageAdmin cannot be null");
- }
- Set<Bundle> dependencies = new HashSet<Bundle>();
-
- for (ExportedPackage ep : getBundleImportedPackagesRaw(localBundleContext, bundle, packageAdmin)) {
- dependencies.add(ep.getExportingBundle());
- }
-
- // Handle required bundles
- Dictionary<String, String> bundleHeaders = bundle.getHeaders();
- String requireBundleHeader = bundleHeaders.get(Constants.REQUIRE_BUNDLE);
- if (requireBundleHeader != null) { // only check if Require-Bundle is used
- List<String> bundleSymbolicNames = extractHeaderDeclaration(requireBundleHeader);
- for (String bundleSymbolicName: bundleSymbolicNames) {
- RequiredBundle[] candidateRequiredBundles = packageAdmin.getRequiredBundles(bundleSymbolicName);
- if (candidateRequiredBundles != null) {
- for (RequiredBundle candidateRequiredBundle : candidateRequiredBundles) {
- Bundle[] bundlesRequiring = candidateRequiredBundle.getRequiringBundles();
- if (bundlesRequiring != null && arrayContains(bundlesRequiring, bundle)) {
- dependencies.add(candidateRequiredBundle.getBundle());
- }
- }
- }
- }
- }
- // Handle fragment bundles
- Bundle[] hosts = packageAdmin.getHosts(bundle);
- if (hosts != null) {
- for (Bundle host : hosts) {
- dependencies.add(host);
- }
- }
- return getBundleIds(dependencies.toArray(new Bundle[dependencies.size()]));
- }
-
- /**
- * Returns an array of ids of bundles that depend on the given bundle
- *
- * @param bundle
- * @param packageAdmin
- * @return
- * @throws IllegalArgumentException
- * if bundle or packageAdmin are null
- */
- public static long[] getDependentBundles(Bundle bundle, PackageAdmin packageAdmin) throws IllegalArgumentException {
- if (bundle == null) {
- throw new IllegalArgumentException("Argument bundle cannot be null");
- }
- if (packageAdmin == null) {
- throw new IllegalArgumentException("Argument packageAdmin cannot be null");
- }
- Set<Bundle> dependencies = new HashSet<Bundle>();
- // Handle imported packages (statically or dynamically)
- ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(bundle);
- if (exportedPackages != null) {
- for (ExportedPackage exportedPackage : exportedPackages) {
- Bundle[] importingBundles = exportedPackage.getImportingBundles();
- if (importingBundles != null) {
- for (Bundle importingBundle : importingBundles) {
- dependencies.add(importingBundle);
- }
- }
- }
- }
- // Handle required bundles
- RequiredBundle[] requiredBundles = packageAdmin.getRequiredBundles(bundle.getSymbolicName());
- if (requiredBundles != null) {
- for (RequiredBundle requiredBundle : requiredBundles) {
- Bundle required = requiredBundle.getBundle();
- if (required == bundle) {
- Bundle[] requiringBundles = requiredBundle.getRequiringBundles();
- if (requiringBundles != null) {
- for (Bundle requiringBundle : requiringBundles) {
- dependencies.add(requiringBundle);
- }
- }
- }
- }
- }
- // Handle fragment bundles
- Bundle[] fragments = packageAdmin.getFragments(bundle);
- if (fragments != null) {
- for (Bundle fragment : fragments) {
- dependencies.add(fragment);
- }
- }
- return getBundleIds(dependencies.toArray(new Bundle[dependencies.size()]));
- }
-
- /**
- * Returns a String representation of the bundles state
- *
- * @param bundle
- * @return
- */
- public static String getBundleState(Bundle bundle) {
- String state = UNKNOWN;
- switch (bundle.getState()) {
- case Bundle.INSTALLED:
- state = INSTALLED;
- break;
- case Bundle.RESOLVED:
- state = RESOLVED;
- break;
- case Bundle.STARTING:
- state = STARTING;
- break;
- case Bundle.ACTIVE:
- state = ACTIVE;
- break;
- case Bundle.STOPPING:
- state = STOPPING;
- break;
- case Bundle.UNINSTALLED:
- state = UNINSTALLED;
- }
- return state;
- }
-
- /*
- * Checks if an object exists in the given array (based on object equality)
- */
- public static boolean arrayContains(Object[] array, Object value) {
- boolean result = false;
- if (array != null && value != null) {
- for (Object element : array) {
- if (value.equals(element)) {
- result = true;
- break;
- }
- }
- }
- return result;
- }
-
- /*
- * Will parse a header value, strip out trailing attributes and return a list of declarations
- */
- public static List<String> extractHeaderDeclaration(String headerStatement) {
- List<String> result = new ArrayList<String>();
-
- for (String headerDeclaration : ManifestHeaderUtils.split(headerStatement, ",")) {
- String name = headerDeclaration.contains(";") ? headerDeclaration.substring(0, headerDeclaration
- .indexOf(";")) : headerDeclaration;
- result.add(name);
- }
-
- return result;
- }
-
-
-}
diff --git a/jmx-core/src/main/java/org/apache/aries/jmx/util/TypeUtils.java b/jmx-core/src/main/java/org/apache/aries/jmx/util/TypeUtils.java
deleted file mode 100644
index ce5003a..0000000
--- a/jmx-core/src/main/java/org/apache/aries/jmx/util/TypeUtils.java
+++ /dev/null
@@ -1,194 +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.aries.jmx.util;
-
-import static org.osgi.jmx.JmxConstants.BIGDECIMAL;
-import static org.osgi.jmx.JmxConstants.BIGINTEGER;
-import static org.osgi.jmx.JmxConstants.BOOLEAN;
-import static org.osgi.jmx.JmxConstants.BYTE;
-import static org.osgi.jmx.JmxConstants.CHARACTER;
-import static org.osgi.jmx.JmxConstants.DOUBLE;
-import static org.osgi.jmx.JmxConstants.FLOAT;
-import static org.osgi.jmx.JmxConstants.INTEGER;
-import static org.osgi.jmx.JmxConstants.LONG;
-import static org.osgi.jmx.JmxConstants.P_BOOLEAN;
-import static org.osgi.jmx.JmxConstants.P_BYTE;
-import static org.osgi.jmx.JmxConstants.P_CHAR;
-import static org.osgi.jmx.JmxConstants.P_DOUBLE;
-import static org.osgi.jmx.JmxConstants.P_FLOAT;
-import static org.osgi.jmx.JmxConstants.P_INT;
-import static org.osgi.jmx.JmxConstants.P_LONG;
-import static org.osgi.jmx.JmxConstants.P_SHORT;
-import static org.osgi.jmx.JmxConstants.SHORT;
-import static org.osgi.jmx.JmxConstants.STRING;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * This class provides common utilities related to type conversions for the MBean implementations
- *
- * @version $Rev$ $Date$
- */
-public class TypeUtils {
-
- private TypeUtils() {
- super();
- }
-
- public static Map<String, Class<? extends Object>> primitiveTypes = new HashMap<String, Class<? extends Object>>();
- public static Map<String, Class<? extends Object>> wrapperTypes = new HashMap<String, Class<? extends Object>>();
- public static Map<String, Class<? extends Object>> mathTypes = new HashMap<String, Class<? extends Object>>();
- public static Map<Class<? extends Object>, Class<? extends Object>> primitiveToWrapper = new HashMap<Class<? extends Object>, Class<? extends Object>>();
- public static Map<String, Class<? extends Object>> types = new HashMap<String, Class<? extends Object>>();
-
- static {
- primitiveTypes.put(P_FLOAT, Float.TYPE);
- primitiveTypes.put(P_INT, Integer.TYPE);
- primitiveTypes.put(P_LONG, Long.TYPE);
- primitiveTypes.put(P_DOUBLE, Double.TYPE);
- primitiveTypes.put(P_BYTE, Byte.TYPE);
- primitiveTypes.put(P_SHORT, Short.TYPE);
- primitiveTypes.put(P_CHAR, Character.TYPE);
- primitiveTypes.put(P_BOOLEAN, Boolean.TYPE);
- primitiveToWrapper.put(Float.TYPE, Float.class);
- primitiveToWrapper.put(Integer.TYPE, Integer.class);
- primitiveToWrapper.put(Long.TYPE, Long.class);
- primitiveToWrapper.put(Double.TYPE, Double.class);
- primitiveToWrapper.put(Byte.TYPE, Byte.class);
- primitiveToWrapper.put(Short.TYPE, Short.class);
- primitiveToWrapper.put(Boolean.TYPE, Boolean.class);
- wrapperTypes.put(INTEGER, Integer.class);
- wrapperTypes.put(FLOAT, Float.class);
- wrapperTypes.put(LONG, Long.class);
- wrapperTypes.put(DOUBLE, Double.class);
- wrapperTypes.put(BYTE, Byte.class);
- wrapperTypes.put(SHORT, Short.class);
- wrapperTypes.put(BOOLEAN, Boolean.class);
- wrapperTypes.put(CHARACTER, Character.class);
- mathTypes.put(BIGDECIMAL, BigDecimal.class);
- mathTypes.put(BIGINTEGER, BigInteger.class);
- types.put(STRING, String.class);
- types.putAll(primitiveTypes);
- types.putAll(wrapperTypes);
- types.putAll(mathTypes);
- }
-
- /**
- * Converts a <code>Dictionary</code> object to a <code>Map</code>
- *
- * @param dictionary
- * @return
- */
- public static Map<String, String> fromDictionary(Dictionary<String, String> dictionary) {
- Map<String, String> result = new HashMap<String, String>();
- Enumeration<String> keys = dictionary.keys();
- while (keys.hasMoreElements()) {
- String key = keys.nextElement();
- result.put(key, dictionary.get(key));
- }
- return result;
- }
-
- /**
- * Converts primitive long[] array to Long[]
- *
- * @param array
- * @return
- */
- public static Long[] toLong(long[] array) {
- Long[] toArray = (array == null) ? new Long[0] : new Long[array.length];
- for (int i = 0; i < toArray.length; i++) {
- toArray[i] = array[i];
- }
- return toArray;
- }
-
- /**
- * Converts Long[] array to primitive
- *
- * @param array
- * @return
- */
- public static long[] toPrimitive(Long[] array) {
- long[] toArray = (array == null) ? new long[0] : new long[array.length];
- for (int i = 0; i < toArray.length; i++) {
- toArray[i] = array[i];
- }
- return toArray;
- }
-
- /**
- * Converts a String value to an Object of the specified type
- *
- * @param type
- * one of types listed in {@link #types}
- * @param value
- * @return instance of class <code>type</code>
- * @throws IllegalArgumentException
- * if type or value are null or if the Class type does not support a valueOf() or cannot be converted to
- * a wrapper type
- */
- @SuppressWarnings("unchecked")
- public static <T> T fromString(Class<T> type, String value) {
- if (type == null || !types.containsValue(type)) {
- throw new IllegalArgumentException("Cannot convert to type argument : " + type);
- }
- if (value == null || value.length() < 1) {
- throw new IllegalArgumentException("Argument value cannot be null or empty");
- }
- T result = null;
- try {
- if (type.equals(String.class)) {
- result = (T) value;
- } else if (type.equals(Character.class) || type.equals(Character.TYPE)) {
- result = (T) Character.valueOf(value.charAt(0));
- } else if (wrapperTypes.containsValue(type) || mathTypes.containsValue(type)) {
- Constructor<? extends Object> constructor = type.getConstructor(String.class);
- result = (T) constructor.newInstance(value);
- } else if (primitiveToWrapper.containsKey(type)) { // attempt to promote to wrapper and resolve to the base
- // type
- Class<? extends Object> promotedType = primitiveToWrapper.get(type);
- char[] simpleTypeName = type.getName().toCharArray();
- simpleTypeName[0] = Character.toUpperCase(simpleTypeName[0]);
- String parseMethodName = "parse" + new String(simpleTypeName);
- Method parseMethod = promotedType.getDeclaredMethod(parseMethodName, String.class);
- result = (T) parseMethod.invoke(null, value);
- }
- } catch (SecurityException e) {
- throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
- } catch (NoSuchMethodException e) {
- throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
- } catch (IllegalArgumentException e) {
- throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
- } catch (IllegalAccessException e) {
- throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
- } catch (InvocationTargetException e) {
- throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
- } catch (InstantiationException e) {
- throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
- }
- return result;
- }
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/CompendiumHandlerTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/CompendiumHandlerTest.java
deleted file mode 100644
index 4cdb072..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/CompendiumHandlerTest.java
+++ /dev/null
@@ -1,132 +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.aries.jmx;
-
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.agent.JMXAgentContext;
-import org.junit.After;
-import org.junit.Test;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.ServiceReference;
-
-import static org.mockito.Mockito.*;
-
-public class CompendiumHandlerTest {
-
- protected AbstractCompendiumHandler target;
-
- @After
- public void tearDown(){
- target = null;
- }
-
-
- @Test
- public void testAddingServiceWillInitiateMBeanRegistration() throws Exception {
-
- Object service = new Object();
-
- ServiceReference reference = mock(ServiceReference.class);
- BundleContext bundleContext = mock(BundleContext.class);
- when(bundleContext.getService(reference)).thenReturn(service);
-
- Logger agentLogger = mock(Logger.class);
- JMXAgentContext agentContext = mock(JMXAgentContext.class);
- when(agentContext.getBundleContext()).thenReturn(bundleContext);
- when(agentContext.getLogger()).thenReturn(agentLogger);
- ExecutorService executor = Executors.newSingleThreadExecutor();
- when(agentContext.getRegistrationExecutor()).thenReturn(executor);
-
- AbstractCompendiumHandler concreteHandler = new CompendiumHandler(agentContext, "org.osgi.service.Xxx");
- target = spy(concreteHandler);
-
- target.addingService(reference);
-
- executor.shutdown();
- executor.awaitTermination(2, TimeUnit.SECONDS);
-
- //service only got once
- verify(bundleContext).getService(reference);
- //template method is invoked
- verify(target).constructInjectMBean(service);
- //registration is invoked on context
- verify(agentContext).registerMBean(target);
-
- }
-
- @Test
- public void testRemovedServiceWillUnregisterMBean() throws Exception{
-
- Object service = new Object();
- ServiceReference reference = mock(ServiceReference.class);
-
- BundleContext bundleContext = mock(BundleContext.class);
- Logger agentLogger = mock(Logger.class);
- JMXAgentContext agentContext = mock(JMXAgentContext.class);
- when(agentContext.getBundleContext()).thenReturn(bundleContext);
- when(agentContext.getLogger()).thenReturn(agentLogger);
- ExecutorService executor = Executors.newSingleThreadExecutor();
- when(agentContext.getRegistrationExecutor()).thenReturn(executor);
-
- AbstractCompendiumHandler concreteHandler = new CompendiumHandler(agentContext, "org.osgi.service.Xxx");
- target = spy(concreteHandler);
-
- String name = "osgi.compendium:service=xxx,version=1.0";
- doReturn(name).when(target).getName();
-
- target.removedService(reference, service);
-
- executor.shutdown();
- executor.awaitTermination(2, TimeUnit.SECONDS);
-
- //service unget
- verify(bundleContext).ungetService(reference);
- //unregister is invoked on context
- verify(agentContext).unregisterMBean(target);
-
- }
-
-
-
- /*
- * Concrete implementation used for test
- */
- class CompendiumHandler extends AbstractCompendiumHandler {
-
- protected CompendiumHandler(JMXAgentContext agentContext, Filter filter) {
- super(agentContext, filter);
- }
-
- protected CompendiumHandler(JMXAgentContext agentContext, String clazz) {
- super(agentContext, clazz);
- }
-
- protected StandardMBean constructInjectMBean(Object targetService) {
- return null;
- }
-
- public String getName() {
- return null;
- }
-
- }
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/cm/ConfigurationAdminMBeanHandlerTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/cm/ConfigurationAdminMBeanHandlerTest.java
deleted file mode 100644
index 101eda2..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/cm/ConfigurationAdminMBeanHandlerTest.java
+++ /dev/null
@@ -1,52 +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.aries.jmx.cm;
-
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.mock;
-
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.agent.JMXAgentContext;
-import org.junit.Test;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.cm.ConfigurationAdmin;
-
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class ConfigurationAdminMBeanHandlerTest {
-
-
- @Test
- public void testConstructInjectMBean() {
-
- BundleContext bundleContext = mock(BundleContext.class);
- Logger agentLogger = mock(Logger.class);
- JMXAgentContext agentContext = new JMXAgentContext(bundleContext, null, agentLogger);
- ConfigurationAdmin cAdmin = mock(ConfigurationAdmin.class);
-
- ConfigurationAdminMBeanHandler handler = new ConfigurationAdminMBeanHandler(agentContext);
- StandardMBean mbean = handler.constructInjectMBean(cAdmin);
- assertNotNull(mbean);
-
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/cm/ConfigurationAdminTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/cm/ConfigurationAdminTest.java
deleted file mode 100644
index 91cae37..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/cm/ConfigurationAdminTest.java
+++ /dev/null
@@ -1,248 +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.aries.jmx.cm;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.osgi.jmx.JmxConstants.PROPERTIES_TYPE;
-
-import java.util.Dictionary;
-import java.util.Hashtable;
-
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.aries.jmx.codec.PropertyData;
-import org.junit.Test;
-import org.mockito.ArgumentCaptor;
-import org.osgi.framework.Constants;
-import org.osgi.service.cm.Configuration;
-
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class ConfigurationAdminTest {
-
-
- @Test
- public void testCreateFactoryConfiguration() throws Exception {
-
- org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
- String fpid = "org.apache.aries.jmx.mock.factory";
- Configuration config = mock(Configuration.class);
-
- when(admin.createFactoryConfiguration(eq(fpid))).thenReturn(config);
- when(admin.createFactoryConfiguration(eq(fpid), anyString())).thenReturn(config);
- when(config.getPid()).thenReturn(fpid + "-1260133982371-0");
-
- ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
- assertEquals(fpid + "-1260133982371-0", mbean.createFactoryConfiguration(fpid));
- assertEquals(fpid + "-1260133982371-0", mbean.createFactoryConfigurationForLocation(fpid, "/bundlex"));
-
- }
-
-
- @Test
- public void testDelete() throws Exception {
-
- org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
- String pid = "org.apache.aries.jmx.mock";
- Configuration config = mock(Configuration.class);
-
- when(admin.getConfiguration(pid, null)).thenReturn(config);
-
- ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
- mbean.delete(pid);
- verify(config).delete();
-
- reset(config);
-
- when(admin.getConfiguration(pid, "location")).thenReturn(config);
- mbean.deleteForLocation(pid, "location");
- verify(config).delete();
-
- }
-
-
- @Test
- public void testDeleteConfigurations() throws Exception {
-
- org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
- String filter = "(" + Constants.SERVICE_PID + "=org.apache.aries.jmx.mock)";
-
- Configuration a = mock(Configuration.class);
- Configuration b = mock(Configuration.class);
-
- when(admin.listConfigurations(filter)).thenReturn(new Configuration[] { a, b });
-
- ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
- mbean.deleteConfigurations(filter);
-
- verify(a).delete();
- verify(b).delete();
-
- }
-
-
- @Test
- public void testGetBundleLocation() throws Exception {
-
- org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
- String pid = "org.apache.aries.jmx.mock";
- Configuration config = mock(Configuration.class);
-
- when(admin.getConfiguration(pid, null)).thenReturn(config);
- when(config.getBundleLocation()).thenReturn("/location");
- ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
-
- assertEquals("/location", mbean.getBundleLocation(pid));
-
- }
-
-
- @Test
- public void testGetConfigurations() throws Exception {
-
- org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
- String factoryPid = "org.apache.aries.jmx.factory.mock";
- String filter = "(" + org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID + "=org.apache.aries.jmx.factory.mock)";
- String location = "../location";
-
- Configuration a = mock(Configuration.class);
- when(a.getPid()).thenReturn(factoryPid + "-2160133952674-0");
- when(a.getBundleLocation()).thenReturn(location);
- Configuration b = mock(Configuration.class);
- when(b.getPid()).thenReturn(factoryPid + "-1260133982371-1");
- when(b.getBundleLocation()).thenReturn(location);
-
- when(admin.listConfigurations(filter)).thenReturn(new Configuration[] { a, b});
-
- ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
- String[][] result = mbean.getConfigurations(filter);
- assertEquals(2, result.length);
- assertArrayEquals(new String[]{ factoryPid + "-2160133952674-0", location }, result[0] );
- assertArrayEquals(new String[]{ factoryPid + "-1260133982371-1", location }, result[1] );
-
- }
-
-
- @Test
- public void testGetFactoryPid() throws Exception {
-
- org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
- String factoryPid = "org.apache.aries.jmx.factory.mock";
-
- Configuration config = mock(Configuration.class);
- when(admin.getConfiguration(eq(factoryPid + "-1260133982371-0"), anyString())).thenReturn(config);
- when(config.getFactoryPid()).thenReturn(factoryPid);
-
- ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
- assertEquals(factoryPid, mbean.getFactoryPid(factoryPid + "-1260133982371-0"));
- assertEquals(factoryPid, mbean.getFactoryPidForLocation(factoryPid + "-1260133982371-0", "location"));
-
- }
-
-
- @Test
- public void testGetProperties() throws Exception {
-
- org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
- String pid = "org.apache.aries.jmx.mock";
- Configuration config = mock(Configuration.class);
-
- Dictionary<String, Object> props = new Hashtable<String, Object>();
- props.put("one", "value");
- props.put("two", 2);
- when(admin.getConfiguration(eq(pid), anyString())).thenReturn(config);
- when(config.getProperties()).thenReturn(props);
-
- ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
-
- TabularData properties = mbean.getPropertiesForLocation(pid, null);
- assertNotNull(properties);
- assertEquals(PROPERTIES_TYPE, properties.getTabularType());
- assertEquals(2, properties.values().size());
- PropertyData<? extends Object> oneData = PropertyData.from(properties.get(new Object[]{ "one"}));
- assertEquals("value", oneData.getValue());
- PropertyData<? extends Object> twoData = PropertyData.from(properties.get(new Object[]{ "two"}));
- assertEquals(2, twoData.getValue());
- assertEquals("2", twoData.getEncodedValue());
-
- }
-
-
-
- @Test
- public void testSetBundleLocation() throws Exception {
-
- org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
- String pid = "org.apache.aries.jmx.mock";
-
- Configuration config = mock(Configuration.class);
- when(admin.getConfiguration(pid, null)).thenReturn(config);
-
- ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
- mbean.setBundleLocation(pid, "file:/newlocation");
-
- ArgumentCaptor<String> locationArgument = ArgumentCaptor.forClass(String.class);
- verify(config).setBundleLocation(locationArgument.capture());
-
- assertEquals("file:/newlocation", locationArgument.getValue());
-
- }
-
-
- @SuppressWarnings("unchecked")
- @Test
- public void testUpdateTabularData() throws Exception {
-
- TabularData data = new TabularDataSupport(PROPERTIES_TYPE);
- PropertyData<String> p1 = PropertyData.newInstance("one", "first");
- data.put(p1.toCompositeData());
- PropertyData<Integer> p2 = PropertyData.newInstance("two", 3);
- data.put(p2.toCompositeData());
-
- org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
- String pid = "org.apache.aries.jmx.mock";
-
- Configuration config = mock(Configuration.class);
- when(admin.getConfiguration(pid, null)).thenReturn(config);
-
- ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
- mbean.updateForLocation(pid, null, data);
-
- ArgumentCaptor<Dictionary> props = ArgumentCaptor.forClass(Dictionary.class);
- verify(config).update(props.capture());
-
- Dictionary configProperties = props.getValue();
- assertEquals("first", configProperties.get("one"));
- assertEquals(3, configProperties.get("two"));
-
- }
-
-
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/codec/BundleDataTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/codec/BundleDataTest.java
deleted file mode 100644
index eb47d48..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/codec/BundleDataTest.java
+++ /dev/null
@@ -1,276 +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.aries.jmx.codec;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.osgi.jmx.framework.BundleStateMBean.BUNDLES_TYPE;
-import static org.osgi.jmx.framework.BundleStateMBean.BUNDLE_TYPE;
-import static org.osgi.jmx.framework.BundleStateMBean.EXPORTED_PACKAGES;
-import static org.osgi.jmx.framework.BundleStateMBean.FRAGMENT;
-import static org.osgi.jmx.framework.BundleStateMBean.FRAGMENTS;
-import static org.osgi.jmx.framework.BundleStateMBean.HEADERS;
-import static org.osgi.jmx.framework.BundleStateMBean.HEADERS_TYPE;
-import static org.osgi.jmx.framework.BundleStateMBean.HEADER_TYPE;
-import static org.osgi.jmx.framework.BundleStateMBean.HOSTS;
-import static org.osgi.jmx.framework.BundleStateMBean.IDENTIFIER;
-import static org.osgi.jmx.framework.BundleStateMBean.IMPORTED_PACKAGES;
-import static org.osgi.jmx.framework.BundleStateMBean.KEY;
-import static org.osgi.jmx.framework.BundleStateMBean.LAST_MODIFIED;
-import static org.osgi.jmx.framework.BundleStateMBean.LOCATION;
-import static org.osgi.jmx.framework.BundleStateMBean.PERSISTENTLY_STARTED;
-import static org.osgi.jmx.framework.BundleStateMBean.REGISTERED_SERVICES;
-import static org.osgi.jmx.framework.BundleStateMBean.REMOVAL_PENDING;
-import static org.osgi.jmx.framework.BundleStateMBean.REQUIRED;
-import static org.osgi.jmx.framework.BundleStateMBean.REQUIRED_BUNDLES;
-import static org.osgi.jmx.framework.BundleStateMBean.REQUIRING_BUNDLES;
-import static org.osgi.jmx.framework.BundleStateMBean.SERVICES_IN_USE;
-import static org.osgi.jmx.framework.BundleStateMBean.START_LEVEL;
-import static org.osgi.jmx.framework.BundleStateMBean.STATE;
-import static org.osgi.jmx.framework.BundleStateMBean.SYMBOLIC_NAME;
-import static org.osgi.jmx.framework.BundleStateMBean.VALUE;
-import static org.osgi.jmx.framework.BundleStateMBean.VERSION;
-
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Set;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.aries.jmx.codec.BundleData.Header;
-import org.junit.Test;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.Version;
-import org.osgi.service.packageadmin.ExportedPackage;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.packageadmin.RequiredBundle;
-import org.osgi.service.startlevel.StartLevel;
-
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class BundleDataTest {
-
-
- @Test
- public void testToCompositeData() throws Exception {
-
- Bundle bundle = mock(Bundle.class);
- BundleContext context = mock(BundleContext.class);
- PackageAdmin packageAdmin = mock(PackageAdmin.class);
- StartLevel startLevel = mock(StartLevel.class);
-
- Bundle b1 = mock(Bundle.class);
- when(b1.getSymbolicName()).thenReturn("b1");
- when(b1.getBundleId()).thenReturn(new Long(44));
- Bundle b2 = mock(Bundle.class);
- when(b2.getSymbolicName()).thenReturn("b2");
- when(b2.getBundleId()).thenReturn(new Long(55));
- Bundle b3 = mock(Bundle.class);
- when(b3.getSymbolicName()).thenReturn("b3");
- when(b3.getBundleId()).thenReturn(new Long(66));
- when(context.getBundles()).thenReturn(new Bundle[] { bundle, b1, b2, b3 });
-
- when(bundle.getSymbolicName()).thenReturn("test");
- when(bundle.getVersion()).thenReturn(Version.emptyVersion);
- when(bundle.getBundleId()).thenReturn(new Long(1));
- when(bundle.getLastModified()).thenReturn(new Long(12345));
- when(bundle.getLocation()).thenReturn("location");
-
- //headers
- Dictionary<String, String> headers = new Hashtable<String, String>();
- headers.put(Constants.BUNDLE_SYMBOLICNAME, "test");
- headers.put(Constants.BUNDLE_VERSION, "0.0.0");
- when(bundle.getHeaders()).thenReturn(headers);
-
- //exported packages
- ExportedPackage exported = mock(ExportedPackage.class);
- when(exported.getName()).thenReturn("org.apache.aries.jmx");
- when(exported.getVersion()).thenReturn(new Version("1.0.0"));
- when(exported.getExportingBundle()).thenReturn(bundle);
- when(packageAdmin.getExportedPackages(bundle)).thenReturn(new ExportedPackage[] { exported });
-
- //imported packages
- ExportedPackage ep1 = mock(ExportedPackage.class);
- when(ep1.getImportingBundles()).thenReturn(new Bundle[] { bundle, b2, b3 });
- when(ep1.getName()).thenReturn("org.apache.aries.jmx.b1");
- when(ep1.getVersion()).thenReturn(Version.emptyVersion);
- when(ep1.getExportingBundle()).thenReturn(b1);
- ExportedPackage ep2 = mock(ExportedPackage.class);
- when(ep2.getImportingBundles()).thenReturn(new Bundle[] { bundle, b3 });
- when(ep2.getName()).thenReturn("org.apache.aries.jmx.b2");
- when(ep2.getVersion()).thenReturn(Version.parseVersion("2.0.1"));
- when(ep2.getExportingBundle()).thenReturn(b2);
- headers.put(Constants.DYNAMICIMPORT_PACKAGE, "*");
-
- when(packageAdmin.getExportedPackages(b1)).thenReturn(new ExportedPackage[] { ep1 });
- when(packageAdmin.getExportedPackages(b2)).thenReturn(new ExportedPackage[] { ep2 });
- when(packageAdmin.getExportedPackages(b3)).thenReturn(null);
-
- //required bundles
- RequiredBundle rb1 = mock(RequiredBundle.class);
- when(rb1.getBundle()).thenReturn(b1);
- when(rb1.getRequiringBundles()).thenReturn(new Bundle[] { bundle, b2 });
- RequiredBundle rb2 = mock(RequiredBundle.class);
- when(rb2.getBundle()).thenReturn(b2);
- when(rb2.getRequiringBundles()).thenReturn(new Bundle[] { b1 });
- RequiredBundle rb3 = mock(RequiredBundle.class);
- when(rb3.getBundle()).thenReturn(b3);
- when(rb3.getRequiringBundles()).thenReturn(new Bundle[] { bundle, b1, b2 });
- headers.put(Constants.REQUIRE_BUNDLE, "b1;bundle-version=\"1.0.0\",b3;bundle-version=\"2.0.0\"");
- when(packageAdmin.getRequiredBundles("b1")).thenReturn(new RequiredBundle[] { rb1 });
- when(packageAdmin.getRequiredBundles("b2")).thenReturn(new RequiredBundle[] { rb2 });
- when(packageAdmin.getRequiredBundles("b3")).thenReturn(new RequiredBundle[] { rb3 });
-
- //services in use
- ServiceReference s1 = mock(ServiceReference.class);
- when(s1.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(15));
- ServiceReference s2 = mock(ServiceReference.class);
- when(s2.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(16));
- ServiceReference s3 = mock(ServiceReference.class);
- when(s3.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(17));
-
- when(bundle.getServicesInUse()).thenReturn(new ServiceReference[] { s1, s2, s3 });
-
- BundleData b = new BundleData(context, bundle, packageAdmin, startLevel);
- CompositeData compositeData = b.toCompositeData();
-
- assertEquals("test", compositeData.get(SYMBOLIC_NAME));
- assertEquals("0.0.0", compositeData.get(VERSION));
- TabularData headerTable = (TabularData) compositeData.get(HEADERS);
- assertEquals(4, headerTable.values().size());
- CompositeData header = headerTable.get(new Object[]{Constants.BUNDLE_SYMBOLICNAME});
- assertNotNull(header);
- String value = (String) header.get(VALUE);
- assertEquals("test", value);
- String key = (String)header.get(KEY);
- assertEquals(Constants.BUNDLE_SYMBOLICNAME, key);
-
-
- TabularData bundleTable = new TabularDataSupport(BUNDLES_TYPE);
- bundleTable.put(b.toCompositeData());
-
- CompositeData bundleData = bundleTable.get(new Object[]{Long.valueOf(1)});
- assertNotNull(bundleData);
- String location = (String) bundleData.get(LOCATION);
- assertEquals("location", location);
-
- assertArrayEquals(new String[] { "org.apache.aries.jmx;1.0.0"} , (String[]) compositeData.get(EXPORTED_PACKAGES));
- assertArrayEquals(new String[] { "org.apache.aries.jmx.b1;0.0.0" , "org.apache.aries.jmx.b2;2.0.1"}, (String[]) compositeData.get(IMPORTED_PACKAGES));
- assertEquals(toSet(new long[] { 44, 55, 66 }), toSet((Long[]) compositeData.get(REQUIRED_BUNDLES)));
- assertArrayEquals(new Long[] { new Long(15), new Long(16), new Long(17) },(Long[]) compositeData.get(SERVICES_IN_USE));
- assertEquals("UNKNOWN", compositeData.get(STATE)); //default no return stub
- assertEquals(0,((Long[]) compositeData.get(HOSTS)).length);
- assertEquals(0, ((Long[]) compositeData.get(FRAGMENTS)).length);
-
- }
-
-
- @Test
- public void testFromCompositeData() throws Exception {
-
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(EXPORTED_PACKAGES, new String[] { "org.apache.aries.jmx;1.0.0"});
- items.put(FRAGMENT, false);
- items.put(FRAGMENTS, new Long[0]);
- items.put(HOSTS, new Long[0]);
- items.put(IDENTIFIER, new Long(3));
- items.put(IMPORTED_PACKAGES, new String[] { "org.apache.aries.jmx.b1;0.0.0" , "org.apache.aries.jmx.b2;2.0.1"});
- items.put(LAST_MODIFIED, new Long(8797));
- items.put(LOCATION, "");
- items.put(PERSISTENTLY_STARTED, false);
- items.put(REGISTERED_SERVICES, new Long[0]);
- items.put(REMOVAL_PENDING, false);
- items.put(REQUIRED, true);
- items.put(REQUIRED_BUNDLES, new Long[] { new Long(44), new Long(66) });
- items.put(REQUIRING_BUNDLES, new Long[0]);
- items.put(SERVICES_IN_USE, new Long[] { new Long(15), new Long(16), new Long(17) });
- items.put(START_LEVEL, 1);
- items.put(STATE, "ACTIVE");
- items.put(SYMBOLIC_NAME, "test");
- items.put(VERSION, "0.0.0");
- TabularData headerTable = new TabularDataSupport(HEADERS_TYPE);
- headerTable.put(new Header("a", "a").toCompositeData());
- headerTable.put(new Header("b", "b").toCompositeData());
- items.put(HEADERS, headerTable);
- CompositeData compositeData = new CompositeDataSupport(BUNDLE_TYPE, items);
-
- BundleData b = BundleData.from(compositeData);
-
- assertEquals("test", b.getSymbolicName());
- assertEquals("0.0.0", b.getVersion());
- assertEquals(2, b.getHeaders().size());
- assertArrayEquals(new String[] { "org.apache.aries.jmx;1.0.0"} , b.getExportedPackages());
- assertArrayEquals(new String[] { "org.apache.aries.jmx.b1;0.0.0" , "org.apache.aries.jmx.b2;2.0.1"}, b.getImportedPackages());
- assertArrayEquals(new long[] { 44, 66 }, b.getRequiredBundles());
- assertArrayEquals(new long[] { 15, 16, 17 }, b.getServicesInUse());
- assertEquals("ACTIVE", b.getState()); //default no return stub
- assertEquals(0, b.getHosts().length);
- assertEquals(0, b.getFragments().length);
- }
-
- @Test
- public void testHeaderToCompositeData() throws Exception{
-
- Header h1 = new Header("a", "b");
- CompositeData compositeData = h1.toCompositeData();
-
- assertEquals("a", compositeData.get(KEY));
- assertEquals("b", compositeData.get(VALUE));
-
- }
-
- @Test
- public void testHeaderFromCompositeData() throws Exception {
-
- CompositeData compositeData = new CompositeDataSupport(HEADER_TYPE, new String[] { KEY, VALUE } , new String [] { "c", "d" });
- Header header = Header.from(compositeData);
- assertEquals("c", header.getKey());
- assertEquals("d", header.getValue());
-
- }
-
- private static Set<Long> toSet(long[] array) {
- Set<Long> set = new HashSet<Long>();
- for (long value : array) {
- set.add(value);
- }
- return set;
- }
-
- private static Set<Long> toSet(Long[] array) {
- Set<Long> set = new HashSet<Long>();
- for (Long value : array) {
- set.add(value);
- }
- return set;
- }
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/codec/BundleEventDataTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/codec/BundleEventDataTest.java
deleted file mode 100644
index a598ae1..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/codec/BundleEventDataTest.java
+++ /dev/null
@@ -1,86 +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.aries.jmx.codec;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.*;
-import static org.osgi.jmx.framework.BundleStateMBean.BUNDLE_EVENT_TYPE;
-import static org.osgi.jmx.framework.BundleStateMBean.EVENT;
-import static org.osgi.jmx.framework.BundleStateMBean.IDENTIFIER;
-import static org.osgi.jmx.framework.BundleStateMBean.LOCATION;
-import static org.osgi.jmx.framework.BundleStateMBean.SYMBOLIC_NAME;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-
-import org.junit.Test;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleEvent;
-
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class BundleEventDataTest {
-
-
- @Test
- public void testToCompositeData() throws Exception {
-
- BundleEvent event = mock(BundleEvent.class);
- Bundle bundle = mock(Bundle.class);
- when(event.getBundle()).thenReturn(bundle);
- when(bundle.getSymbolicName()).thenReturn("test");
- when(bundle.getBundleId()).thenReturn(new Long(4));
- when(bundle.getLocation()).thenReturn("location");
- when(event.getType()).thenReturn(BundleEvent.INSTALLED);
-
- BundleEventData eventData = new BundleEventData(event);
- CompositeData eventCompositeData = eventData.toCompositeData();
-
- assertEquals(new Long(4), (Long) eventCompositeData.get(IDENTIFIER));
- assertEquals("test", (String) eventCompositeData.get(SYMBOLIC_NAME));
- assertEquals(new Integer(BundleEvent.INSTALLED), (Integer) eventCompositeData.get(EVENT));
- assertEquals("location", (String) eventCompositeData.get(LOCATION));
-
- }
-
-
- @Test
- public void testFrom() throws Exception {
-
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(IDENTIFIER, new Long(7));
- items.put(SYMBOLIC_NAME, "t");
- items.put(LOCATION, "l");
- items.put(EVENT, BundleEvent.RESOLVED);
-
- CompositeData compositeData = new CompositeDataSupport(BUNDLE_EVENT_TYPE, items);
- BundleEventData event = BundleEventData.from(compositeData);
-
- assertEquals(7, event.getBundleId());
- assertEquals("t", event.getBundleSymbolicName());
- assertEquals("l", event.getLocation());
- assertEquals(BundleEvent.RESOLVED, event.getEventType());
-
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/codec/PropertyDataTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/codec/PropertyDataTest.java
deleted file mode 100644
index ba93cc0..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/codec/PropertyDataTest.java
+++ /dev/null
@@ -1,324 +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.aries.jmx.codec;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.osgi.jmx.JmxConstants.BIGINTEGER;
-import static org.osgi.jmx.JmxConstants.BOOLEAN;
-import static org.osgi.jmx.JmxConstants.CHARACTER;
-import static org.osgi.jmx.JmxConstants.DOUBLE;
-import static org.osgi.jmx.JmxConstants.INTEGER;
-import static org.osgi.jmx.JmxConstants.KEY;
-import static org.osgi.jmx.JmxConstants.PROPERTY_TYPE;
-import static org.osgi.jmx.JmxConstants.P_BOOLEAN;
-import static org.osgi.jmx.JmxConstants.P_CHAR;
-import static org.osgi.jmx.JmxConstants.P_DOUBLE;
-import static org.osgi.jmx.JmxConstants.P_INT;
-import static org.osgi.jmx.JmxConstants.STRING;
-import static org.osgi.jmx.JmxConstants.TYPE;
-import static org.osgi.jmx.JmxConstants.VALUE;
-
-import java.math.BigInteger;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Vector;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-
-import org.junit.Test;
-
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class PropertyDataTest {
-
-
- @Test
- public void testToCompositeDataForPrimitiveTypes() throws Exception {
-
- PropertyData<Integer> intData = PropertyData.newInstance("test", 1);
- CompositeData intCData = intData.toCompositeData();
- assertEquals("test", intCData.get(KEY));
- assertEquals("1", intCData.get(VALUE));
- assertEquals(P_INT, intCData.get(TYPE));
-
- PropertyData<Double> doubleData = PropertyData.newInstance("test", 1.0);
- CompositeData doubleCData = doubleData.toCompositeData();
- assertEquals("test", doubleCData.get(KEY));
- assertEquals("1.0", doubleCData.get(VALUE));
- assertEquals(P_DOUBLE, doubleCData.get(TYPE));
-
- PropertyData<Character> charData = PropertyData.newInstance("test", 'c');
- CompositeData charCData = charData.toCompositeData();
- assertEquals("test", charCData.get(KEY));
- assertEquals("c", charCData.get(VALUE));
- assertEquals(P_CHAR, charCData.get(TYPE));
-
- PropertyData<Boolean> booleanData = PropertyData.newInstance("test", true);
- CompositeData booleanCData = booleanData.toCompositeData();
- assertEquals("test", booleanCData.get(KEY));
- assertEquals("true", booleanCData.get(VALUE));
- assertEquals(P_BOOLEAN, booleanCData.get(TYPE));
- }
-
- @Test
- public void testFromCompositeDataForPrimitiveTypes() throws Exception {
-
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(KEY, "key");
- items.put(VALUE, "1");
- items.put(TYPE, P_INT);
- CompositeData compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
-
- PropertyData<Integer> intData = PropertyData.from(compositeData);
- assertEquals("key", intData.getKey());
- assertEquals(new Integer(1), intData.getValue());
- assertEquals(P_INT, intData.getEncodedType());
- assertTrue(intData.isEncodingPrimitive());
-
- items.clear();
- items.put(KEY, "key");
- items.put(VALUE, "1.0");
- items.put(TYPE, P_DOUBLE);
- compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
-
- PropertyData<Double> doubleData = PropertyData.from(compositeData);
- assertEquals("key", doubleData.getKey());
- assertEquals(Double.valueOf(1.0), doubleData.getValue());
- assertEquals(P_DOUBLE, doubleData.getEncodedType());
- assertTrue(doubleData.isEncodingPrimitive());
-
- items.clear();
- items.put(KEY, "key");
- items.put(VALUE, "a");
- items.put(TYPE, P_CHAR);
- compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
-
- PropertyData<Character> charData = PropertyData.from(compositeData);
- assertEquals("key", charData.getKey());
- assertEquals(Character.valueOf('a'), charData.getValue());
- assertEquals(P_CHAR, charData.getEncodedType());
- assertTrue(charData.isEncodingPrimitive());
-
- items.clear();
- items.put(KEY, "key");
- items.put(VALUE, "true");
- items.put(TYPE, P_BOOLEAN);
- compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
-
- PropertyData<Boolean> booleanData = PropertyData.from(compositeData);
- assertEquals("key", booleanData.getKey());
- assertTrue(booleanData.getValue());
- assertEquals(P_BOOLEAN, booleanData.getEncodedType());
- assertTrue(booleanData.isEncodingPrimitive());
-
- }
-
- @Test
- public void testToCompositeDataForWrapperTypes() {
-
- PropertyData<Integer> intData = PropertyData.newInstance("test", new Integer(1));
- CompositeData intCData = intData.toCompositeData();
- assertEquals("test", intCData.get(KEY));
- assertEquals("1", intCData.get(VALUE));
- assertEquals(INTEGER, intCData.get(TYPE));
-
- PropertyData<Double> doubleData = PropertyData.newInstance("test", new Double(1.0));
- CompositeData doubleCData = doubleData.toCompositeData();
- assertEquals("test", doubleCData.get(KEY));
- assertEquals("1.0", doubleCData.get(VALUE));
- assertEquals(DOUBLE, doubleCData.get(TYPE));
-
- PropertyData<Character> charData = PropertyData.newInstance("test", Character.valueOf('c'));
- CompositeData charCData = charData.toCompositeData();
- assertEquals("test", charCData.get(KEY));
- assertEquals("c", charCData.get(VALUE));
- assertEquals(CHARACTER, charCData.get(TYPE));
-
- PropertyData<Boolean> booleanData = PropertyData.newInstance("test", Boolean.TRUE);
- CompositeData booleanCData = booleanData.toCompositeData();
- assertEquals("test", booleanCData.get(KEY));
- assertEquals("true", booleanCData.get(VALUE));
- assertEquals(BOOLEAN, booleanCData.get(TYPE));
-
- }
-
- @Test
- public void testFromCompositeDataForWrapperTypes() throws Exception {
-
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(KEY, "key");
- items.put(VALUE, "1");
- items.put(TYPE, INTEGER);
- CompositeData compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
-
- PropertyData<Integer> intData = PropertyData.from(compositeData);
- assertEquals("key", intData.getKey());
- assertEquals(new Integer(1), intData.getValue());
- assertEquals(INTEGER, intData.getEncodedType());
- assertFalse(intData.isEncodingPrimitive());
-
- items.clear();
- items.put(KEY, "key");
- items.put(VALUE, "1.0");
- items.put(TYPE, DOUBLE);
- compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
-
- PropertyData<Double> doubleData = PropertyData.from(compositeData);
- assertEquals("key", doubleData.getKey());
- assertEquals(Double.valueOf(1.0), doubleData.getValue());
- assertEquals(DOUBLE, doubleData.getEncodedType());
- assertFalse(doubleData.isEncodingPrimitive());
-
- items.clear();
- items.put(KEY, "key");
- items.put(VALUE, "a");
- items.put(TYPE, CHARACTER);
- compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
-
- PropertyData<Character> charData = PropertyData.from(compositeData);
- assertEquals("key", charData.getKey());
- assertEquals(Character.valueOf('a'), charData.getValue());
- assertEquals(CHARACTER, charData.getEncodedType());
- assertFalse(charData.isEncodingPrimitive());
-
- items.clear();
- items.put(KEY, "key");
- items.put(VALUE, "true");
- items.put(TYPE, BOOLEAN);
- compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
-
- PropertyData<Boolean> booleanData = PropertyData.from(compositeData);
- assertEquals("key", booleanData.getKey());
- assertTrue(booleanData.getValue());
- assertEquals(BOOLEAN, booleanData.getEncodedType());
- assertFalse(booleanData.isEncodingPrimitive());
-
- }
-
- @Test
- public void testToFromCompositeDataForAdditionalTypes() {
-
- PropertyData<String> stringData = PropertyData.newInstance("test", "value");
-
- CompositeData stringCData = stringData.toCompositeData();
- assertEquals("test", stringCData.get(KEY));
- assertEquals("value", stringCData.get(VALUE));
- assertEquals(STRING, stringCData.get(TYPE));
-
- stringData = PropertyData.from(stringCData);
- assertEquals("test", stringData.getKey());
- assertEquals("value", stringData.getValue());
- assertEquals(STRING, stringData.getEncodedType());
-
- PropertyData<BigInteger> bigIntData = PropertyData.newInstance("test", new BigInteger("1"));
-
- CompositeData bigIntCData = bigIntData.toCompositeData();
- assertEquals("test", bigIntCData.get(KEY));
- assertEquals("1", bigIntCData.get(VALUE));
- assertEquals(BIGINTEGER, bigIntCData.get(TYPE));
-
- bigIntData = PropertyData.from(bigIntCData);
- assertEquals("test", bigIntData.getKey());
- assertEquals(new BigInteger("1"), bigIntData.getValue());
- assertEquals(BIGINTEGER, bigIntData.getEncodedType());
-
- }
-
- @Test
- public void testToFromCompositeDataForArrayTypes() {
-
- //long[]
- long[] primitiveLongValues = new long[] { 1, 2, 3 };
- PropertyData<long[]> primitiveLongArrayData = PropertyData.newInstance("test", primitiveLongValues);
- CompositeData primitiveLongArrayCData = primitiveLongArrayData.toCompositeData();
- assertEquals("test", primitiveLongArrayCData.get(KEY));
- assertEquals("1,2,3", primitiveLongArrayCData.get(VALUE));
- assertEquals("Array of long", primitiveLongArrayCData.get(TYPE));
- primitiveLongArrayData = PropertyData.from(primitiveLongArrayCData);
- assertEquals("test", primitiveLongArrayData.getKey());
- assertEquals("Array of long", primitiveLongArrayData.getEncodedType());
- assertArrayEquals(primitiveLongValues, primitiveLongArrayData.getValue());
-
- //Long[]
- Long[] longValues = new Long[] { new Long(4), new Long(5), new Long(6) };
- PropertyData<Long[]> longArrayData = PropertyData.newInstance("test", longValues);
- CompositeData longArrayCData = longArrayData.toCompositeData();
- assertEquals("test", longArrayCData.get(KEY));
- assertEquals("4,5,6", longArrayCData.get(VALUE));
- assertEquals("Array of Long", longArrayCData.get(TYPE));
- longArrayData = PropertyData.from(longArrayCData);
- assertEquals("test", longArrayData.getKey());
- assertEquals("Array of Long", longArrayData.getEncodedType());
- assertArrayEquals(longValues, longArrayData.getValue());
-
- //char[]
- char[] primitiveCharValues = new char[] { 'a', 'b', 'c' };
- PropertyData<char[]> primitiveCharArrayData = PropertyData.newInstance("test", primitiveCharValues);
- CompositeData primitiveCharArrayCData = primitiveCharArrayData.toCompositeData();
- assertEquals("test", primitiveCharArrayCData.get(KEY));
- assertEquals("a,b,c", primitiveCharArrayCData.get(VALUE));
- assertEquals("Array of char", primitiveCharArrayCData.get(TYPE));
- primitiveCharArrayData = PropertyData.from(primitiveCharArrayCData);
- assertEquals("test", primitiveCharArrayData.getKey());
- assertEquals("Array of char", primitiveCharArrayData.getEncodedType());
- assertArrayEquals(primitiveCharValues, primitiveCharArrayData.getValue());
-
- //Character[]
- Character[] charValues = new Character[] { 'a', 'b', 'c' };
- PropertyData<Character[]> charArrayData = PropertyData.newInstance("test", charValues);
- CompositeData charArrayCData = charArrayData.toCompositeData();
- assertEquals("test", charArrayCData.get(KEY));
- assertEquals("a,b,c", charArrayCData.get(VALUE));
- assertEquals("Array of Character", charArrayCData.get(TYPE));
- charArrayData = PropertyData.from(charArrayCData);
- assertEquals("test", charArrayData.getKey());
- assertEquals("Array of Character", charArrayData.getEncodedType());
- assertArrayEquals(charValues, charArrayData.getValue());
-
- }
-
- @Test
- public void testToFromCompositeDataForVector() {
-
- Vector<Long> vector = new Vector<Long>();
- vector.add(new Long(40));
- vector.add(new Long(50));
- vector.add(new Long(60));
-
- PropertyData<Vector<Long>> vectorPropertyData = PropertyData.newInstance("test", vector);
- CompositeData vectorCompositeData = vectorPropertyData.toCompositeData();
-
- assertEquals("test", vectorCompositeData.get(KEY));
- assertEquals("40,50,60", vectorCompositeData.get(VALUE));
- assertEquals("Vector of Long", vectorCompositeData.get(TYPE));
-
- vectorPropertyData = PropertyData.from(vectorCompositeData);
- assertEquals("test", vectorPropertyData.getKey());
- assertEquals("Vector of Long", vectorPropertyData.getEncodedType());
- assertArrayEquals(vector.toArray(new Long[vector.size()]), vectorPropertyData.getValue().toArray(new Long[vector.size()]));
-
- }
-
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/codec/ServiceDataTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/codec/ServiceDataTest.java
deleted file mode 100644
index 4c04b54..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/codec/ServiceDataTest.java
+++ /dev/null
@@ -1,151 +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.aries.jmx.codec;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.osgi.jmx.framework.BundleStateMBean.IDENTIFIER;
-import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_IDENTIFIER;
-import static org.osgi.jmx.framework.ServiceStateMBean.OBJECT_CLASS;
-import static org.osgi.jmx.framework.ServiceStateMBean.SERVICE_TYPE;
-import static org.osgi.jmx.framework.ServiceStateMBean.USING_BUNDLES;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-
-import org.junit.Test;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceReference;
-
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class ServiceDataTest {
-
-
- @Test
- public void testToCompositeData() throws Exception {
-
- ServiceReference reference = mock(ServiceReference.class);
- Bundle bundle = mock(Bundle.class);
- String[] interfaces = new String[] { "org.apache.aries.jmx.Test", "org.apache.aries.jmx.Mock" };
-
- Bundle b1 = mock(Bundle.class);
- when(b1.getBundleId()).thenReturn(new Long(6));
- Bundle b2 = mock(Bundle.class);
- when(b2.getBundleId()).thenReturn(new Long(9));
-
-
- when(reference.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(98));
- when(reference.getBundle()).thenReturn(bundle);
- when(bundle.getBundleId()).thenReturn(new Long(34));
- when(reference.getProperty(Constants.OBJECTCLASS)).thenReturn(interfaces);
- when(reference.getUsingBundles()).thenReturn(new Bundle[] { b1, b2 });
- when(reference.getPropertyKeys()).thenReturn( new String[] {"x.vendor", "x.domain", "x.index", "x.optimized" } );
- when(reference.getProperty("x.vendor")).thenReturn("aries");
- when(reference.getProperty("x.domain")).thenReturn("test");
- when(reference.getProperty("x.index")).thenReturn(new Long(67));
- when(reference.getProperty("x.optimized")).thenReturn(true);
-
-
- ServiceData serviceData = new ServiceData(reference);
-
- CompositeData compositeData = serviceData.toCompositeData();
- assertEquals(new Long(98), compositeData.get(IDENTIFIER));
- assertEquals(new Long(34), compositeData.get(BUNDLE_IDENTIFIER));
- assertArrayEquals( new Long[] {new Long(6), new Long(9)}, (Long[]) compositeData.get(USING_BUNDLES));
- assertArrayEquals(interfaces, (String[]) compositeData.get(OBJECT_CLASS));
- // keep Properties for next version
- //TabularData propertiesTable = (TabularData) compositeData.get(PROPERTIES);
- //Collection<CompositeData> propertyData = (Collection<CompositeData>) propertiesTable.values();
- //assertEquals(4, propertyData.size());
- //for (CompositeData propertyRow: propertyData) {
- // String key = (String) propertyRow.get(KEY);
- // if (key.equals("x.vendor")) {
- // assertEquals("aries", propertyRow.get(VALUE));
- // assertEquals(STRING, propertyRow.get(TYPE));
- // } else if (key.equals("x.domain")) {
- // assertEquals("test", propertyRow.get(VALUE));
- // assertEquals(STRING, propertyRow.get(TYPE));
- // } else if (key.equals("x.index")) {
- // assertEquals("67", propertyRow.get(VALUE));
- // assertEquals(LONG, propertyRow.get(TYPE));
- // } else if (key.equals("x.optimized")) {
- // assertEquals("true", propertyRow.get(VALUE));
- // assertEquals(BOOLEAN, propertyRow.get(TYPE));
- // } else {
- // fail("unknown key parsed from properties");
- // }
- //}
- }
-
-
- @Test
- public void testFromCompositeData() throws Exception {
-
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(IDENTIFIER, new Long(99));
- items.put(BUNDLE_IDENTIFIER, new Long(5));
- items.put(USING_BUNDLES, new Long[] { new Long(10), new Long(11) });
- items.put(OBJECT_CLASS, new String[] { "org.apache.aries.jmx.Test", "org.apache.aries.jmx.Mock" });
- //TabularData propertyTable = new TabularDataSupport(PROPERTIES_TYPE);
- //propertyTable.put(PropertyData.newInstance("a", true).toCompositeData());
- //propertyTable.put(PropertyData.newInstance("b", "value").toCompositeData());
- //propertyTable.put(PropertyData.newInstance("c", new int[] {1, 2}).toCompositeData());
- //propertyTable.put(PropertyData.newInstance("d", new Long[] {new Long(3), new Long(4)}).toCompositeData());
- //items.put(PROPERTIES, propertyTable);
- CompositeData compositeData = new CompositeDataSupport(SERVICE_TYPE, items);
-
- ServiceData data = ServiceData.from(compositeData);
- assertEquals(99, data.getServiceId());
- assertEquals(5, data.getBundleId());
- assertArrayEquals(new long[] {10, 11}, data.getUsingBundles());
- assertArrayEquals(new String[] { "org.apache.aries.jmx.Test", "org.apache.aries.jmx.Mock" }, data.getServiceInterfaces());
-
- //List<PropertyData<? extends Object>> properties = data.getProperties();
- //assertEquals(4, properties.size());
-
- //for (PropertyData<? extends Object> property: properties) {
- // if (property.getKey().equals("a")) {
- // assertTrue((Boolean) property.getValue());
- // assertEquals(P_BOOLEAN, property.getEncodedType());
- // } else if (property.getKey().equals("b")) {
- // assertEquals("value", property.getValue());
- // assertEquals(STRING, property.getEncodedType());
- // } else if (property.getKey().equals("c")) {
- // assertArrayEquals(new int[] { 1, 2 }, (int[]) property.getValue());
- // assertEquals("Array of int", property.getEncodedType());
- // assertEquals("1,2", property.getEncodedValue());
- // } else if (property.getKey().equals("d")) {
- // assertArrayEquals(new Long[] {new Long(3), new Long(4) }, (Long[]) property.getValue());
- // assertEquals("Array of Long", property.getEncodedType());
- // assertEquals("3,4", property.getEncodedValue());
- // } else {
- // fail("unknown key parsed from properties");
- // }
- //}
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/codec/ServiceEventDataTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/codec/ServiceEventDataTest.java
deleted file mode 100644
index 96b23da..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/codec/ServiceEventDataTest.java
+++ /dev/null
@@ -1,102 +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.aries.jmx.codec;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_IDENTIFIER;
-import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_LOCATION;
-import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_SYMBOLIC_NAME;
-import static org.osgi.jmx.framework.ServiceStateMBean.EVENT;
-import static org.osgi.jmx.framework.ServiceStateMBean.IDENTIFIER;
-import static org.osgi.jmx.framework.ServiceStateMBean.OBJECT_CLASS;
-import static org.osgi.jmx.framework.ServiceStateMBean.SERVICE_EVENT_TYPE;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-
-import org.junit.Test;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceReference;
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class ServiceEventDataTest {
-
-
- @Test
- public void testToCompositeData() throws Exception {
-
- ServiceEvent event = mock(ServiceEvent.class);
- ServiceReference reference = mock(ServiceReference.class);
- Bundle bundle = mock(Bundle.class);
-
- when(event.getType()).thenReturn(ServiceEvent.REGISTERED);
- when(event.getServiceReference()).thenReturn(reference);
- when(reference.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(44));
- when(reference.getProperty(Constants.OBJECTCLASS)).thenReturn(new String[] {"org.apache.aries.jmx.Mock"});
- when(reference.getBundle()).thenReturn(bundle);
- when(bundle.getBundleId()).thenReturn(new Long(1));
- when(bundle.getLocation()).thenReturn("string");
- when(bundle.getSymbolicName()).thenReturn("org.apache.aries.jmx.core");
-
- ServiceEventData eventData = new ServiceEventData(event);
- CompositeData data = eventData.toCompositeData();
-
- assertEquals(new Long(44), data.get(IDENTIFIER));
- assertEquals(new Long(1), data.get(BUNDLE_IDENTIFIER));
- assertEquals("string", data.get(BUNDLE_LOCATION));
- assertEquals("org.apache.aries.jmx.core", data.get(BUNDLE_SYMBOLIC_NAME));
- assertArrayEquals(new String[] {"org.apache.aries.jmx.Mock" }, (String[]) data.get(OBJECT_CLASS));
- assertEquals(ServiceEvent.REGISTERED, data.get(EVENT));
-
- }
-
-
- @Test
- public void testFrom() throws Exception {
-
- Map<String, Object> items = new HashMap<String, Object>();
- items.put(IDENTIFIER, new Long(7));
- items.put(BUNDLE_IDENTIFIER, new Long(67));
- items.put(BUNDLE_LOCATION, "string");
- items.put(BUNDLE_SYMBOLIC_NAME, "test");
- items.put(OBJECT_CLASS, new String[] {"org.apache.aries.jmx.Mock" });
- items.put(EVENT, ServiceEvent.MODIFIED);
-
- CompositeData compositeData = new CompositeDataSupport(SERVICE_EVENT_TYPE, items);
- ServiceEventData event = ServiceEventData.from(compositeData);
-
- assertEquals(7, event.getServiceId());
- assertEquals(67, event.getBundleId());
- assertArrayEquals(new String[] {"org.apache.aries.jmx.Mock" }, event.getServiceInterfaces());
- assertEquals("test", event.getBundleSymbolicName());
- assertEquals("string", event.getBundleLocation());
- assertEquals(ServiceEvent.MODIFIED, event.getEventType());
-
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/framework/BundleStateMBeanHandlerTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/framework/BundleStateMBeanHandlerTest.java
deleted file mode 100644
index 2d48540..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/framework/BundleStateMBeanHandlerTest.java
+++ /dev/null
@@ -1,64 +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.aries.jmx.framework;
-
-import static org.junit.Assert.*;
-
-import org.apache.aries.jmx.Logger;
-import org.junit.Test;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.startlevel.StartLevel;
-
-import static org.mockito.Mockito.*;
-
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class BundleStateMBeanHandlerTest {
-
-
- @Test
- public void testOpenAndClose() throws Exception {
-
- BundleContext context = mock(BundleContext.class);
- Logger logger = mock(Logger.class);
-
- ServiceReference packageAdminRef = mock(ServiceReference.class);
- PackageAdmin packageAdmin = mock(PackageAdmin.class);
- when(context.getServiceReference(PackageAdmin.class.getName())).thenReturn(packageAdminRef);
- when(context.getService(packageAdminRef)).thenReturn(packageAdmin);
- ServiceReference startLevelRef = mock(ServiceReference.class);
- StartLevel startLevel = mock(StartLevel.class);
- when(context.getServiceReference(StartLevel.class.getName())).thenReturn(startLevelRef);
- when(context.getService(startLevelRef)).thenReturn(startLevel);
-
- BundleStateMBeanHandler handler = new BundleStateMBeanHandler(context, logger);
- handler.open();
-
- assertNotNull(handler.getMbean());
-
- handler.close();
- verify(context).ungetService(packageAdminRef);
- verify(context).ungetService(startLevelRef);
-
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/framework/BundleStateTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/framework/BundleStateTest.java
deleted file mode 100644
index 38f4eee..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/framework/BundleStateTest.java
+++ /dev/null
@@ -1,188 +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.aries.jmx.framework;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.atMost;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.osgi.jmx.framework.BundleStateMBean.OBJECTNAME;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.TimeUnit;
-
-import javax.management.MBeanServer;
-import javax.management.Notification;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import javax.management.openmbean.CompositeData;
-
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.codec.BundleEventData;
-import org.junit.Test;
-import org.mockito.ArgumentCaptor;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.BundleListener;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.startlevel.StartLevel;
-
-
-public class BundleStateTest {
-
- @Test
- public void testNotificationsForBundleEvents() throws Exception {
-
- BundleContext context = mock(BundleContext.class);
- PackageAdmin admin = mock(PackageAdmin.class);
- StartLevel startLevel = mock(StartLevel.class);
- Logger logger = mock(Logger.class);
-
- //holder for Notifications captured
- final List<Notification> received = new LinkedList<Notification>();
-
- BundleState bundleState = new BundleState(context, admin, startLevel, logger);
-
- Bundle b1 = mock(Bundle.class);
- when(b1.getBundleId()).thenReturn(new Long(9));
- when(b1.getSymbolicName()).thenReturn("bundle");
- when(b1.getLocation()).thenReturn("file:/location");
-
- BundleEvent installedEvent = mock(BundleEvent.class);
- when(installedEvent.getBundle()).thenReturn(b1);
- when(installedEvent.getType()).thenReturn(BundleEvent.INSTALLED);
-
- BundleEvent resolvedEvent = mock(BundleEvent.class);
- when(resolvedEvent.getBundle()).thenReturn(b1);
- when(resolvedEvent.getType()).thenReturn(BundleEvent.RESOLVED);
-
- MBeanServer server = mock(MBeanServer.class);
-
- //setup for notification
- ObjectName objectName = new ObjectName(OBJECTNAME);
- bundleState.preRegister(server, objectName);
- bundleState.postRegister(true);
-
- //add NotificationListener to receive the events
- bundleState.addNotificationListener(new NotificationListener() {
- public void handleNotification(Notification notification, Object handback) {
- received.add(notification);
- }
- }, null, null);
-
- // capture the BundleListener registered with BundleContext to issue BundleEvents
- ArgumentCaptor<BundleListener> argument = ArgumentCaptor.forClass(BundleListener.class);
- verify(context).addBundleListener(argument.capture());
-
- //send events
- BundleListener listener = argument.getValue();
- listener.bundleChanged(installedEvent);
- listener.bundleChanged(resolvedEvent);
-
- //shutdown dispatcher via unregister callback
- bundleState.postDeregister();
- //check the BundleListener is cleaned up
- verify(context).removeBundleListener(listener);
-
- ExecutorService dispatcher = bundleState.getEventDispatcher();
- assertTrue(dispatcher.isShutdown());
- dispatcher.awaitTermination(2, TimeUnit.SECONDS);
- assertTrue(dispatcher.isTerminated());
-
- assertEquals(2, received.size());
- Notification installed = received.get(0);
- assertEquals(1, installed.getSequenceNumber());
- CompositeData installedCompositeData = (CompositeData) installed.getUserData();
- BundleEventData installedData = BundleEventData.from(installedCompositeData);
- assertEquals("bundle", installedData.getBundleSymbolicName());
- assertEquals(9, installedData.getBundleId());
- assertEquals("file:/location", installedData.getLocation());
- assertEquals(BundleEvent.INSTALLED, installedData.getEventType());
-
- Notification resolved = received.get(1);
- assertEquals(2, resolved.getSequenceNumber());
- CompositeData resolvedCompositeData = (CompositeData) resolved.getUserData();
- BundleEventData resolvedData = BundleEventData.from(resolvedCompositeData);
- assertEquals("bundle", resolvedData.getBundleSymbolicName());
- assertEquals(9, resolvedData.getBundleId());
- assertEquals("file:/location", resolvedData.getLocation());
- assertEquals(BundleEvent.RESOLVED, resolvedData.getEventType());
-
- }
-
- @Test
- public void testLifeCycleOfNotificationSupport() throws Exception {
-
- BundleContext context = mock(BundleContext.class);
- PackageAdmin admin = mock(PackageAdmin.class);
- StartLevel startLevel = mock(StartLevel.class);
- Logger logger = mock(Logger.class);
-
- BundleState bundleState = new BundleState(context, admin, startLevel, logger);
-
- MBeanServer server1 = mock(MBeanServer.class);
- MBeanServer server2 = mock(MBeanServer.class);
-
- ObjectName objectName = new ObjectName(OBJECTNAME);
- bundleState.preRegister(server1, objectName);
- bundleState.postRegister(true);
-
- // capture the BundleListener registered with BundleContext
- ArgumentCaptor<BundleListener> argument = ArgumentCaptor.forClass(BundleListener.class);
- verify(context).addBundleListener(argument.capture());
- assertEquals(1, argument.getAllValues().size());
-
- BundleListener listener = argument.getValue();
- assertNotNull(listener);
-
- ExecutorService dispatcher = bundleState.getEventDispatcher();
-
- //do registration with another server
- bundleState.preRegister(server2, objectName);
- bundleState.postRegister(true);
-
- // check no more actions on BundleContext
- argument = ArgumentCaptor.forClass(BundleListener.class);
- verify(context, atMost(1)).addBundleListener(argument.capture());
- assertEquals(1, argument.getAllValues().size());
-
- //do one unregister
- bundleState.postDeregister();
-
- //verify bundleListener not invoked
- verify(context, never()).removeBundleListener(listener);
- assertFalse(dispatcher.isShutdown());
-
- //do second unregister and check cleanup
- bundleState.postDeregister();
- verify(context).removeBundleListener(listener);
- assertTrue(dispatcher.isShutdown());
- dispatcher.awaitTermination(2, TimeUnit.SECONDS);
- assertTrue(dispatcher.isTerminated());
-
-
-
- }
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/framework/FrameworkTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/framework/FrameworkTest.java
deleted file mode 100644
index 538f4d9..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/framework/FrameworkTest.java
+++ /dev/null
@@ -1,504 +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.aries.jmx.framework;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import javax.management.openmbean.CompositeData;
-
-import org.junit.Assert;
-
-import org.apache.aries.jmx.codec.BatchActionResult;
-import org.apache.aries.jmx.codec.BatchInstallResult;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleException;
-import org.osgi.jmx.framework.FrameworkMBean;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.startlevel.StartLevel;
-
-/**
- * {@link FrameworkMBean} test case.
- *
- *
- * @version $Rev$ $Date$
- */
-public class FrameworkTest {
-
- @Mock
- private StartLevel startLevel;
- @Mock
- private PackageAdmin admin;
- @Mock
- private BundleContext context;
- private Framework mbean;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- mbean = new Framework(context, startLevel, admin);
- }
-
- @Test
- public void testGetFrameworkStartLevel() throws IOException {
- Mockito.when(startLevel.getStartLevel()).thenReturn(1);
- int level = mbean.getFrameworkStartLevel();
- Assert.assertEquals(1, level);
- }
-
- @Test
- public void testGetInitialBundleStartLevel() throws IOException {
- Mockito.when(startLevel.getInitialBundleStartLevel()).thenReturn(2);
- int level = mbean.getInitialBundleStartLevel();
- Mockito.verify(startLevel).getInitialBundleStartLevel();
- Assert.assertEquals(2, level);
- }
-
- @Test
- public void testInstallBundle() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.installBundle("file:test.jar")).thenReturn(bundle);
- Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(2));
- long bundleId = mbean.installBundle("file:test.jar");
- Assert.assertEquals(2, bundleId);
- Mockito.reset(context);
- Mockito.when(context.installBundle("file:test2.jar")).thenThrow(new BundleException("location doesn't exist"));
-
- try {
- mbean.installBundle("file:test2.jar");
- Assert.fail("Shouldn't go to this stage, location doesn't exist");
- } catch (IOException e) {
- // ok
- }
-
- }
-
- @Test
- public void testInstallBundleFromURL() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.installBundle(Mockito.anyString(), Mockito.any(InputStream.class))).thenReturn(bundle);
- Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(2));
- Framework spiedMBean = Mockito.spy(mbean);
- InputStream stream = Mockito.mock(InputStream.class);
- Mockito.doReturn(stream).when(spiedMBean).createStream("test.jar");
- long bundleId = spiedMBean.installBundleFromURL("file:test.jar", "test.jar");
- Assert.assertEquals(2, bundleId);
- Mockito.reset(context);
- Mockito.doReturn(stream).when(spiedMBean).createStream(Mockito.anyString());
- Mockito.when(context.installBundle(Mockito.anyString(), Mockito.any(InputStream.class))).thenThrow(
- new BundleException("location doesn't exist"));
-
- try {
- spiedMBean.installBundleFromURL("file:test2.jar", "test.jar");
- Assert.fail("Shouldn't go to this stage, location doesn't exist");
- } catch (IOException e) {
- // ok
- }
- }
-
- @Test
- public void testInstallBundles() throws Exception {
- String[] locations = new String[] { "file:test.jar" };
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.installBundle("file:test.jar")).thenReturn(bundle);
- Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(2));
- CompositeData data = mbean.installBundles(locations);
- BatchInstallResult batch = BatchInstallResult.from(data);
- Assert.assertNotNull(batch);
- Assert.assertEquals(2, batch.getCompleted()[0]);
- Assert.assertTrue(batch.isSuccess());
- Assert.assertNull(batch.getError());
- Assert.assertNull(batch.getRemainingLocationItems());
- Mockito.reset(context);
- Mockito.when(context.installBundle("file:test.jar")).thenThrow(new BundleException("location doesn't exist"));
- CompositeData data2 = mbean.installBundles(locations);
- BatchInstallResult batch2 = BatchInstallResult.from(data2);
- Assert.assertNotNull(batch2);
- Assert.assertNotNull(batch2.getCompleted());
- Assert.assertEquals(0, batch2.getCompleted().length);
- Assert.assertFalse(batch2.isSuccess());
- Assert.assertNotNull(batch2.getError());
- Assert.assertEquals("file:test.jar", batch2.getBundleInError());
- Assert.assertNotNull(batch2.getRemainingLocationItems());
- Assert.assertEquals(0, batch2.getRemainingLocationItems().length);
- }
-
- @Test
- public void testInstallBundlesFromURL() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.installBundle(Mockito.anyString(), Mockito.any(InputStream.class))).thenReturn(bundle);
- Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(2));
- Framework spiedMBean = Mockito.spy(mbean);
- InputStream stream = Mockito.mock(InputStream.class);
- Mockito.doReturn(stream).when(spiedMBean).createStream(Mockito.anyString());
- CompositeData data = spiedMBean.installBundlesFromURL(new String[] { "file:test.jar" }, new String[] { "test.jar" });
- Assert.assertNotNull(data);
- BatchInstallResult batch = BatchInstallResult.from(data);
- Assert.assertEquals(2, batch.getCompleted()[0]);
- Assert.assertTrue(batch.isSuccess());
- Assert.assertNull(batch.getError());
- Assert.assertNull(batch.getRemainingLocationItems());
- Mockito.reset(context);
- Mockito.when(spiedMBean.createStream(Mockito.anyString())).thenReturn(stream);
- Mockito.when(context.installBundle(Mockito.anyString(), Mockito.any(InputStream.class))).thenThrow(
- new BundleException("location doesn't exist"));
- CompositeData data2 = spiedMBean.installBundlesFromURL(new String[] { "file:test.jar" }, new String[] { "test.jar" });
- BatchInstallResult batch2 = BatchInstallResult.from(data2);
- Assert.assertNotNull(batch2);
- Assert.assertNotNull(batch2.getCompleted());
- Assert.assertEquals(0, batch2.getCompleted().length);
- Assert.assertFalse(batch2.isSuccess());
- Assert.assertNotNull(batch2.getError());
- Assert.assertEquals("file:test.jar", batch2.getBundleInError());
- Assert.assertNotNull(batch2.getRemainingLocationItems());
- Assert.assertEquals(0, batch2.getRemainingLocationItems().length);
- }
-
- @Test
- public void testRefreshBundle() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(1)).thenReturn(bundle);
-
- mbean.refreshBundle(1);
- Mockito.verify(admin).refreshPackages((Bundle[]) Mockito.any());
-
- try {
- mbean.refreshBundle(2);
- Assert.fail("IOException should be thrown");
- } catch (IOException e) {
- // expected
- }
- }
-
- @Test
- public void testRefreshBundles() throws IOException {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(1)).thenReturn(bundle);
-
- mbean.refreshBundles(new long[] { 1 });
- Mockito.verify(admin).refreshPackages((Bundle[]) Mockito.any());
-
- mbean.refreshBundles(null);
- Mockito.verify(admin).refreshPackages(null);
- }
-
- @Test
- public void testResolveBundle() throws IOException {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(1)).thenReturn(bundle);
-
- mbean.resolveBundle(1);
- Mockito.verify(admin).resolveBundles(new Bundle[] { bundle });
- }
-
- @Test
- public void testResolveBundles() throws IOException {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(1)).thenReturn(bundle);
-
- mbean.resolveBundles(new long[] { 1 });
- Mockito.verify(admin).resolveBundles(new Bundle[] { bundle });
-
- mbean.resolveBundles(null);
- Mockito.verify(admin).resolveBundles(null);
- }
-
- @Test
- public void testRestartFramework() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(0)).thenReturn(bundle);
- mbean.restartFramework();
- Mockito.verify(bundle).update();
- }
-
- @Test
- public void testSetBundleStartLevel() throws IOException {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(2)).thenReturn(bundle);
- mbean.setBundleStartLevel(2, 1);
- Mockito.verify(startLevel).setBundleStartLevel(bundle, 1);
- }
-
- @Test
- public void testSetBundleStartLevels() throws IOException {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(2)).thenReturn(bundle);
- CompositeData data = mbean.setBundleStartLevels(new long[] { 2 }, new int[] { 2 });
- Mockito.verify(startLevel).setBundleStartLevel(bundle, 2);
- BatchActionResult batch = BatchActionResult.from(data);
- Assert.assertEquals(2, batch.getCompleted()[0]);
- Assert.assertTrue(batch.isSuccess());
- Assert.assertNull(batch.getError());
- Assert.assertNull(batch.getRemainingItems());
-
- CompositeData data2 = mbean.setBundleStartLevels(new long[] { 2 }, new int[] { 2, 4 });
- BatchActionResult batch2 = BatchActionResult.from(data2);
- Assert.assertNull(batch2.getCompleted());
- Assert.assertFalse(batch2.isSuccess());
- Assert.assertNotNull(batch2.getError());
- Assert.assertNull(batch2.getRemainingItems());
-
- }
-
- @Test
- public void testSetFrameworkStartLevel() throws IOException {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(0)).thenReturn(bundle);
- mbean.setFrameworkStartLevel(1);
- Mockito.verify(startLevel).setStartLevel(1);
-
- }
-
- @Test
- public void testSetInitialBundleStartLevel() throws IOException {
- mbean.setInitialBundleStartLevel(5);
- Mockito.verify(startLevel).setInitialBundleStartLevel(5);
- }
-
- @Test
- public void testShutdownFramework() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(0)).thenReturn(bundle);
- mbean.shutdownFramework();
- Mockito.verify(bundle).stop();
- }
-
- @Test
- public void testStartBundle() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(5)).thenReturn(bundle);
- mbean.startBundle(5);
- Mockito.verify(bundle).start();
-
- Mockito.reset(context);
- Mockito.when(context.getBundle(6)).thenReturn(bundle);
- Mockito.doThrow(new BundleException("")).when(bundle).start();
-
- try {
- mbean.startBundle(6);
- Assert.fail("Shouldn't go to this stage, BundleException was thrown");
- } catch (IOException ioe) {
- // expected
- }
-
- Mockito.when(context.getBundle(6)).thenReturn(null);
- try {
- mbean.startBundle(6);
- Assert.fail("IOException should be thrown");
- } catch (IOException e) {
- //expected
- }
- }
-
- @Test
- public void testStartBundles() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(5)).thenReturn(bundle);
- CompositeData data = mbean.startBundles(new long[] { 5 });
- Mockito.verify(bundle).start();
-
- BatchActionResult batch = BatchActionResult.from(data);
- Assert.assertEquals(5, batch.getCompleted()[0]);
- Assert.assertTrue(batch.isSuccess());
- Assert.assertNull(batch.getError());
- Assert.assertNull(batch.getRemainingItems());
-
- CompositeData data2 = mbean.startBundles(null);
-
- BatchActionResult batch2 = BatchActionResult.from(data2);
- Assert.assertNull(batch2.getCompleted());
- Assert.assertFalse(batch2.isSuccess());
- Assert.assertNotNull(batch2.getError());
- Assert.assertNull(batch2.getRemainingItems());
- }
-
- @Test
- public void testStopBundle() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(5)).thenReturn(bundle);
- mbean.stopBundle(5);
- Mockito.verify(bundle).stop();
-
- Mockito.when(context.getBundle(5)).thenReturn(null);
- try {
- mbean.stopBundle(5);
- Assert.fail("IOException should be thrown");
- } catch (IOException e) {
- //expected
- }
-
- }
-
- @Test
- public void testStopBundles() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(5)).thenReturn(bundle);
- CompositeData data = mbean.stopBundles(new long[] { 5 });
- Mockito.verify(bundle).stop();
-
- BatchActionResult batch = BatchActionResult.from(data);
- Assert.assertEquals(5, batch.getCompleted()[0]);
- Assert.assertTrue(batch.isSuccess());
- Assert.assertNull(batch.getError());
- Assert.assertNull(batch.getRemainingItems());
-
- CompositeData data2 = mbean.stopBundles(null);
-
- BatchActionResult batch2 = BatchActionResult.from(data2);
- Assert.assertNull(batch2.getCompleted());
- Assert.assertFalse(batch2.isSuccess());
- Assert.assertNotNull(batch2.getError());
- Assert.assertNull(batch2.getRemainingItems());
- }
-
- @Test
- public void testUninstallBundle() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(5)).thenReturn(bundle);
- mbean.uninstallBundle(5);
- Mockito.verify(bundle).uninstall();
- }
-
- @Test
- public void testUninstallBundles() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(5)).thenReturn(bundle);
- CompositeData data = mbean.uninstallBundles(new long[] { 5 });
- Mockito.verify(bundle).uninstall();
- BatchActionResult batch = BatchActionResult.from(data);
- Assert.assertEquals(5, batch.getCompleted()[0]);
- Assert.assertTrue(batch.isSuccess());
- Assert.assertNull(batch.getError());
- Assert.assertNull(batch.getRemainingItems());
-
- CompositeData data2 = mbean.uninstallBundles(null);
-
- BatchActionResult batch2 = BatchActionResult.from(data2);
- Assert.assertNull(batch2.getCompleted());
- Assert.assertFalse(batch2.isSuccess());
- Assert.assertNotNull(batch2.getError());
- Assert.assertNull(batch2.getRemainingItems());
- }
-
- @Test
- public void testUpdateBundle() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(5)).thenReturn(bundle);
- mbean.updateBundle(5);
- Mockito.verify(bundle).update();
- }
-
- @Test
- public void testUpdateBundleFromUrl() throws Exception {
- Framework spiedMBean = Mockito.spy(mbean);
- InputStream stream = Mockito.mock(InputStream.class);
- Mockito.doReturn(stream).when(spiedMBean).createStream(Mockito.anyString());
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(5)).thenReturn(bundle);
- spiedMBean.updateBundleFromURL(5, "file:test.jar");
- Mockito.verify(bundle).update(stream);
- }
-
- @Test
- public void testUpdateBundles() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(5)).thenReturn(bundle);
- CompositeData data = mbean.updateBundles(new long[] { 5 });
- Mockito.verify(bundle).update();
- BatchActionResult batch = BatchActionResult.from(data);
- Assert.assertEquals(5, batch.getCompleted()[0]);
- Assert.assertTrue(batch.isSuccess());
- Assert.assertNull(batch.getError());
- Assert.assertNull(batch.getRemainingItems());
-
- CompositeData data2 = mbean.updateBundles(null);
-
- BatchActionResult batch2 = BatchActionResult.from(data2);
- Assert.assertNull(batch2.getCompleted());
- Assert.assertFalse(batch2.isSuccess());
- Assert.assertNotNull(batch2.getError());
- Assert.assertNull(batch2.getRemainingItems());
-
- Mockito.reset(bundle);
- CompositeData data3 = mbean.updateBundles(new long[] { 6 });
- Mockito.when(context.getBundle(6)).thenReturn(bundle);
- Mockito.doThrow(new BundleException("")).when(bundle).update();
- BatchActionResult batch3 = BatchActionResult.from(data3);
- Assert.assertEquals(0, batch3.getCompleted().length);
- Assert.assertFalse(batch3.isSuccess());
- Assert.assertNotNull(batch3.getError());
- Assert.assertEquals(6, batch3.getBundleInError());
-
- Bundle bundle6 = Mockito.mock(Bundle.class);
- Bundle bundle8 = Mockito.mock(Bundle.class);
- Bundle bundle7 = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(6)).thenReturn(bundle6);
- Mockito.when(context.getBundle(8)).thenReturn(bundle8);
- Mockito.when(context.getBundle(7)).thenReturn(bundle7);
- Mockito.doThrow(new BundleException("")).when(bundle8).update();
- CompositeData data4 = mbean.updateBundles(new long[] { 6, 8, 7 });
- BatchActionResult batch4 = BatchActionResult.from(data4);
- Mockito.verify(bundle6).update();
- Assert.assertEquals(1, batch4.getCompleted().length);
- // should contain only bundleid 6
- Assert.assertEquals(6, batch4.getCompleted()[0]);
- Assert.assertFalse(batch4.isSuccess());
- Assert.assertNotNull(batch4.getError());
- Assert.assertEquals(8, batch4.getBundleInError());
- Assert.assertEquals(1, batch4.getRemainingItems().length);
- // should contain only bundleid 7
- Assert.assertEquals(7, batch4.getRemainingItems()[0]);
- }
-
- @Test
- public void testUpdateBundlesFromURL() throws Exception {
- Framework spiedMBean = Mockito.spy(mbean);
- InputStream stream = Mockito.mock(InputStream.class);
- Mockito.doReturn(stream).when(spiedMBean).createStream(Mockito.anyString());
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(5)).thenReturn(bundle);
- CompositeData data = spiedMBean.updateBundlesFromURL(new long[] { 5 }, new String[] { "file:test.jar" });
- Mockito.verify(bundle).update(stream);
- BatchActionResult batch = BatchActionResult.from(data);
- Assert.assertEquals(5, batch.getCompleted()[0]);
- Assert.assertTrue(batch.isSuccess());
- Assert.assertNull(batch.getError());
- Assert.assertNull(batch.getRemainingItems());
-
- CompositeData data2 = spiedMBean.updateBundlesFromURL(new long[] { 2, 4 }, new String[] { "file:test.jar" });
- BatchActionResult batch2 = BatchActionResult.from(data2);
- Assert.assertFalse(batch2.isSuccess());
- Assert.assertNotNull(batch2.getError());
- Assert.assertNotNull(batch2.getError());
- Assert.assertNull(batch2.getRemainingItems());
- }
-
- @Test
- public void testUpdateFramework() throws Exception {
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundle(0)).thenReturn(bundle);
- mbean.restartFramework();
- Mockito.verify(bundle).update();
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/framework/PackageStateTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/framework/PackageStateTest.java
deleted file mode 100644
index afe5e03..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/framework/PackageStateTest.java
+++ /dev/null
@@ -1,131 +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.aries.jmx.framework;
-
-import java.io.IOException;
-import java.util.Collection;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.TabularData;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Version;
-import org.osgi.jmx.framework.PackageStateMBean;
-import org.osgi.service.packageadmin.ExportedPackage;
-import org.osgi.service.packageadmin.PackageAdmin;
-
-/**
- * {@link PackageStateMBean} test case.
- *
- *
- * @version $Rev$ $Date$
- */
-public class PackageStateTest {
-
- @Mock
- private BundleContext context;
- @Mock
- private PackageAdmin admin;
- private PackageState mbean;
-
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- mbean = new PackageState(context, admin);
- }
-
- @Test
- public void testGetExportingBundles() throws IOException {
- ExportedPackage exported = Mockito.mock(ExportedPackage.class);
- Bundle bundle = Mockito.mock(Bundle.class);
- Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
- Mockito.when(exported.getExportingBundle()).thenReturn(bundle);
- Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(5));
- ExportedPackage exported2 = Mockito.mock(ExportedPackage.class);
- Bundle bundle2 = Mockito.mock(Bundle.class);
- Mockito.when(exported2.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
- Mockito.when(exported2.getExportingBundle()).thenReturn(bundle2);
- Mockito.when(bundle2.getBundleId()).thenReturn(Long.valueOf(6));
- Mockito.when(admin.getExportedPackages(Mockito.anyString())).thenReturn(new ExportedPackage[]{exported, exported2});
- long[] ids = mbean.getExportingBundles("test", "1.0.0");
- Assert.assertNotNull(ids);
- Assert.assertArrayEquals(new long[]{5,6}, ids);
- }
-
- @Test
- public void testGetImportingBundles() throws IOException {
- ExportedPackage exported = Mockito.mock(ExportedPackage.class);
- Bundle bundle = Mockito.mock(Bundle.class);
- Bundle exportingBundle = Mockito.mock(Bundle.class);
- Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
- Mockito.when(exported.getExportingBundle()).thenReturn(exportingBundle);
- Mockito.when(exportingBundle.getBundleId()).thenReturn(Long.valueOf(2));
- Mockito.when(exported.getImportingBundles()).thenReturn(new Bundle[]{bundle});
- Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(4));
- Mockito.when(admin.getExportedPackages(Mockito.anyString())).thenReturn(new ExportedPackage[]{exported});
- long[] ids = mbean.getImportingBundles("test", "1.0.0", 2);
- Assert.assertArrayEquals(new long[]{4}, ids);
- }
-
- @Test
- public void testIsRemovalPending() throws IOException {
- ExportedPackage exported = Mockito.mock(ExportedPackage.class);
- Bundle expBundle = Mockito.mock(Bundle.class);
- Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
- Mockito.when(exported.isRemovalPending()).thenReturn(true);
- Mockito.when(exported.getExportingBundle()).thenReturn(expBundle);
- Mockito.when(expBundle.getBundleId()).thenReturn(Long.valueOf(2));
- Mockito.when(admin.getExportedPackages(Mockito.anyString())).thenReturn(new ExportedPackage[]{exported});
- boolean isRemoval = mbean.isRemovalPending("test", "1.0.0", Long.valueOf(2));
- Assert.assertTrue(isRemoval);
- }
-
- @Test
- public void testListPackages() throws IOException {
- Bundle bundle = Mockito.mock(Bundle.class);
- Bundle impBundle = Mockito.mock(Bundle.class);
- Mockito.when(context.getBundles()).thenReturn(new Bundle[]{bundle});
- ExportedPackage exported = Mockito.mock(ExportedPackage.class);
- Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
- Mockito.when(exported.getImportingBundles()).thenReturn(new Bundle[]{impBundle});
- Mockito.when(exported.getName()).thenReturn("test");
- Mockito.when(exported.getExportingBundle()).thenReturn(bundle);
- Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(4));
- Mockito.when(impBundle.getBundleId()).thenReturn(Long.valueOf(5));
- Mockito.when(admin.getExportedPackages(bundle)).thenReturn(new ExportedPackage[]{exported});
- TabularData table = mbean.listPackages();
- Assert.assertEquals(PackageStateMBean.PACKAGES_TYPE,table.getTabularType());
- Collection values = table.values();
- Assert.assertEquals(1, values.size());
- CompositeData data = (CompositeData) values.iterator().next();
- Long[] exportingBundles = (Long[])data.get(PackageStateMBean.EXPORTING_BUNDLES);
- Assert.assertArrayEquals(new Long[]{Long.valueOf(4)}, exportingBundles);
- String name = (String) data.get(PackageStateMBean.NAME);
- Assert.assertEquals("test", name);
- String version = (String) data.get(PackageStateMBean.VERSION);
- Assert.assertEquals("1.0.0", version);
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/framework/ServiceStateMBeanHandlerTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/framework/ServiceStateMBeanHandlerTest.java
deleted file mode 100644
index 5849da4..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/framework/ServiceStateMBeanHandlerTest.java
+++ /dev/null
@@ -1,47 +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.aries.jmx.framework;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.*;
-
-import org.apache.aries.jmx.Logger;
-import org.junit.Test;
-import org.osgi.framework.BundleContext;
-
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class ServiceStateMBeanHandlerTest {
-
-
- @Test
- public void testOpen() throws Exception {
-
- BundleContext context = mock(BundleContext.class);
- Logger logger = mock(Logger.class);
-
- ServiceStateMBeanHandler handler = new ServiceStateMBeanHandler(context, logger);
- handler.open();
-
- assertNotNull(handler.getMbean());
-
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/framework/ServiceStateTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/framework/ServiceStateTest.java
deleted file mode 100644
index c38b1b1..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/framework/ServiceStateTest.java
+++ /dev/null
@@ -1,202 +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.aries.jmx.framework;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.atMost;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_IDENTIFIER;
-import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_LOCATION;
-import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_SYMBOLIC_NAME;
-import static org.osgi.jmx.framework.ServiceStateMBean.EVENT;
-import static org.osgi.jmx.framework.ServiceStateMBean.IDENTIFIER;
-import static org.osgi.jmx.framework.ServiceStateMBean.OBJECTNAME;
-import static org.osgi.jmx.framework.ServiceStateMBean.OBJECT_CLASS;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.TimeUnit;
-
-import javax.management.MBeanServer;
-import javax.management.Notification;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import javax.management.openmbean.CompositeData;
-
-import org.apache.aries.jmx.Logger;
-import org.junit.Test;
-import org.mockito.ArgumentCaptor;
-import org.osgi.framework.AllServiceListener;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceReference;
-
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class ServiceStateTest {
-
-
- @Test
- public void testNotificationsForServiceEvents() throws Exception {
-
- BundleContext context = mock(BundleContext.class);
- Logger logger = mock(Logger.class);
-
- ServiceState serviceState = new ServiceState(context, logger);
-
- ServiceReference reference = mock(ServiceReference.class);
- Bundle b1 = mock(Bundle.class);
-
- when(b1.getBundleId()).thenReturn(new Long(9));
- when(b1.getSymbolicName()).thenReturn("bundle");
- when(b1.getLocation()).thenReturn("file:/location");
- when(reference.getBundle()).thenReturn(b1);
- when(reference.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(44));
- when(reference.getProperty(Constants.OBJECTCLASS)).thenReturn(new String[] {"org.apache.aries.jmx.Mock"});
-
- ServiceEvent registeredEvent = mock(ServiceEvent.class);
- when(registeredEvent.getServiceReference()).thenReturn(reference);
- when(registeredEvent.getType()).thenReturn(ServiceEvent.REGISTERED);
-
- ServiceEvent modifiedEvent = mock(ServiceEvent.class);
- when(modifiedEvent.getServiceReference()).thenReturn(reference);
- when(modifiedEvent.getType()).thenReturn(ServiceEvent.MODIFIED);
-
- MBeanServer server = mock(MBeanServer.class);
-
- //setup for notification
- ObjectName objectName = new ObjectName(OBJECTNAME);
- serviceState.preRegister(server, objectName);
- serviceState.postRegister(true);
-
- //holder for Notifications captured
- final List<Notification> received = new LinkedList<Notification>();
-
- //add NotificationListener to receive the events
- serviceState.addNotificationListener(new NotificationListener() {
- public void handleNotification(Notification notification, Object handback) {
- received.add(notification);
- }
- }, null, null);
-
- // capture the ServiceListener registered with BundleContext to issue ServiceEvents
- ArgumentCaptor<AllServiceListener> argument = ArgumentCaptor.forClass(AllServiceListener.class);
- verify(context).addServiceListener(argument.capture());
-
- //send events
- AllServiceListener serviceListener = argument.getValue();
- serviceListener.serviceChanged(registeredEvent);
- serviceListener.serviceChanged(modifiedEvent);
-
- //shutdown dispatcher via unregister callback
- serviceState.postDeregister();
- //check the ServiceListener is cleaned up
- verify(context).removeServiceListener(serviceListener);
-
- ExecutorService dispatcher = serviceState.getEventDispatcher();
- assertTrue(dispatcher.isShutdown());
- dispatcher.awaitTermination(2, TimeUnit.SECONDS);
- assertTrue(dispatcher.isTerminated());
-
- assertEquals(2, received.size());
- Notification registered = received.get(0);
- assertEquals(1, registered.getSequenceNumber());
- CompositeData data = (CompositeData) registered.getUserData();
- assertEquals(new Long(44), data.get(IDENTIFIER));
- assertEquals(new Long(9), data.get(BUNDLE_IDENTIFIER));
- assertEquals("file:/location", data.get(BUNDLE_LOCATION));
- assertEquals("bundle", data.get(BUNDLE_SYMBOLIC_NAME));
- assertArrayEquals(new String[] {"org.apache.aries.jmx.Mock" }, (String[]) data.get(OBJECT_CLASS));
- assertEquals(ServiceEvent.REGISTERED, data.get(EVENT));
-
- Notification modified = received.get(1);
- assertEquals(2, modified.getSequenceNumber());
- data = (CompositeData) modified.getUserData();
- assertEquals(new Long(44), data.get(IDENTIFIER));
- assertEquals(new Long(9), data.get(BUNDLE_IDENTIFIER));
- assertEquals("file:/location", data.get(BUNDLE_LOCATION));
- assertEquals("bundle", data.get(BUNDLE_SYMBOLIC_NAME));
- assertArrayEquals(new String[] {"org.apache.aries.jmx.Mock" }, (String[]) data.get(OBJECT_CLASS));
- assertEquals(ServiceEvent.MODIFIED, data.get(EVENT));
-
- }
-
- @Test
- public void testLifeCycleOfNotificationSupport() throws Exception {
-
- BundleContext context = mock(BundleContext.class);
- Logger logger = mock(Logger.class);
-
- ServiceState serviceState = new ServiceState(context, logger);
-
- MBeanServer server1 = mock(MBeanServer.class);
- MBeanServer server2 = mock(MBeanServer.class);
-
- ObjectName objectName = new ObjectName(OBJECTNAME);
- serviceState.preRegister(server1, objectName);
- serviceState.postRegister(true);
-
- // capture the ServiceListener registered with BundleContext to issue ServiceEvents
- ArgumentCaptor<AllServiceListener> argument = ArgumentCaptor.forClass(AllServiceListener.class);
- verify(context).addServiceListener(argument.capture());
-
- AllServiceListener serviceListener = argument.getValue();
- assertNotNull(serviceListener);
-
- ExecutorService dispatcher = serviceState.getEventDispatcher();
-
- //do registration with another server
- serviceState.preRegister(server2, objectName);
- serviceState.postRegister(true);
-
- // check no more actions on BundleContext
- argument = ArgumentCaptor.forClass(AllServiceListener.class);
- verify(context, atMost(1)).addServiceListener(argument.capture());
- assertEquals(1, argument.getAllValues().size());
-
- //do one unregister
- serviceState.postDeregister();
-
- //verify bundleListener not invoked
- verify(context, never()).removeServiceListener(serviceListener);
- assertFalse(dispatcher.isShutdown());
-
- //do second unregister and check cleanup
- serviceState.postDeregister();
- verify(context).removeServiceListener(serviceListener);
- assertTrue(dispatcher.isShutdown());
- dispatcher.awaitTermination(2, TimeUnit.SECONDS);
- assertTrue(dispatcher.isTerminated());
-
-
-
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/permissionadmin/PermissionAdminTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/permissionadmin/PermissionAdminTest.java
deleted file mode 100644
index 6d04741..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/permissionadmin/PermissionAdminTest.java
+++ /dev/null
@@ -1,126 +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.aries.jmx.permissionadmin;
-
-import java.io.IOException;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.osgi.jmx.service.permissionadmin.PermissionAdminMBean;
-import org.osgi.service.permissionadmin.PermissionInfo;
-
-/**
- * {@link PermissionAdminMBean} test case.
- *
- *
- * @version $Rev$ $Date$
- */
-public class PermissionAdminTest {
-
- @Mock
- private org.osgi.service.permissionadmin.PermissionAdmin permAdmin;
- private PermissionAdminMBean mbean;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- mbean = new PermissionAdmin(permAdmin);
- }
-
- @Test
- public void testGetPermissions() throws IOException {
- PermissionInfo info = new PermissionInfo("Admin", "test", "get");
- PermissionInfo[] permInfos = new PermissionInfo[] { info, info };
-
- Mockito.when(permAdmin.getPermissions(Mockito.anyString())).thenReturn(permInfos);
- String[] permissions = mbean.getPermissions("test");
-
- Assert.assertNotNull(permissions);
- Assert.assertEquals(2, permissions.length);
- Assert.assertArrayEquals("Checks encoded permissions", new String[] { info.getEncoded(), info.getEncoded() },
- permissions);
-
- Mockito.reset(permAdmin);
- Mockito.when(permAdmin.getPermissions(Mockito.anyString())).thenReturn(null);
- String[] permissions2 = mbean.getPermissions("test");
-
- Assert.assertNull(permissions2);
- }
-
- @Test
- public void testListDefaultPermissions() throws IOException {
- PermissionInfo info = new PermissionInfo("Admin", "test", "get");
- PermissionInfo[] permInfos = new PermissionInfo[] { info, info };
-
- Mockito.when(permAdmin.getDefaultPermissions()).thenReturn(permInfos);
- String[] permissions = mbean.listDefaultPermissions();
-
- Assert.assertNotNull(permissions);
- Assert.assertEquals(2, permissions.length);
- Assert.assertArrayEquals("Checks encoded default permissions", new String[] { info.getEncoded(), info.getEncoded() },
- permissions);
-
- Mockito.reset(permAdmin);
- Mockito.when(permAdmin.getDefaultPermissions()).thenReturn(null);
- String[] permissions2 = mbean.listDefaultPermissions();
-
- Assert.assertNull(permissions2);
- }
-
- @Test
- public void testListLocations() throws IOException {
- String[] locations1 = new String[] { "test1", "test2" };
- Mockito.when(permAdmin.getLocations()).thenReturn(locations1);
- String[] locations2 = mbean.listLocations();
- Assert.assertNotNull(locations2);
- Assert.assertEquals(2, locations2.length);
- Assert.assertSame(locations1, locations2);
- }
-
- @Test
- public void testSetDefaultPermissions() throws IOException {
- PermissionInfo info1 = new PermissionInfo("Admin", "test", "get");
- PermissionInfo info2 = new PermissionInfo("Admin", "test2", "get");
- PermissionInfo[] permInfos = new PermissionInfo[] { info1, info2 };
- String[] encodedPermissions = new String[2];
- int i = 0;
- for (PermissionInfo info : permInfos) {
- encodedPermissions[i++] = info.getEncoded();
- }
- mbean.setDefaultPermissions(encodedPermissions);
- Mockito.verify(permAdmin).setDefaultPermissions(permInfos);
- }
-
- @Test
- public void testSetPermissions() throws IOException {
- PermissionInfo info1 = new PermissionInfo("Admin", "test", "set");
- PermissionInfo info2 = new PermissionInfo("Admin", "test2", "set");
- PermissionInfo[] permInfos = new PermissionInfo[] { info1, info2 };
- String[] encodedPermissions = new String[2];
- int i = 0;
- for (PermissionInfo info : permInfos) {
- encodedPermissions[i++] = info.getEncoded();
- }
- mbean.setPermissions("test", encodedPermissions);
- Mockito.verify(permAdmin).setPermissions("test", permInfos);
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/provisioning/ProvisioningServiceMBeanHandlerTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/provisioning/ProvisioningServiceMBeanHandlerTest.java
deleted file mode 100644
index f65994f..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/provisioning/ProvisioningServiceMBeanHandlerTest.java
+++ /dev/null
@@ -1,53 +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.aries.jmx.provisioning;
-
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.mock;
-
-import javax.management.StandardMBean;
-
-import org.apache.aries.jmx.Logger;
-import org.apache.aries.jmx.agent.JMXAgentContext;
-import org.junit.Test;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.provisioning.ProvisioningService;
-
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class ProvisioningServiceMBeanHandlerTest {
-
-
- @Test
- public void testConstructInjectMBean() {
-
- BundleContext bundleContext = mock(BundleContext.class);
- Logger agentLogger = mock(Logger.class);
- JMXAgentContext agentContext = new JMXAgentContext(bundleContext, null, agentLogger);
- ProvisioningService provService = mock(ProvisioningService.class);
-
- ProvisioningServiceMBeanHandler handler = new ProvisioningServiceMBeanHandler(agentContext);
- StandardMBean mbean = handler.constructInjectMBean(provService);
- assertNotNull(mbean);
-
- }
-
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/provisioning/ProvisioningServiceTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/provisioning/ProvisioningServiceTest.java
deleted file mode 100644
index a882a94..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/provisioning/ProvisioningServiceTest.java
+++ /dev/null
@@ -1,155 +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.aries.jmx.provisioning;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.osgi.jmx.JmxConstants.PROPERTIES_TYPE;
-import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_AGENT_CONFIG;
-import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_REFERENCE;
-import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_RSH_SECRET;
-import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_SPID;
-import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_UPDATE_COUNT;
-
-import java.io.InputStream;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.zip.ZipInputStream;
-
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-
-import org.apache.aries.jmx.codec.PropertyData;
-import org.junit.Test;
-import org.mockito.ArgumentCaptor;
-
-/**
- *
- *
- * @version $Rev$ $Date$
- */
-public class ProvisioningServiceTest {
-
-
- @Test
- public void testAddInformationFromZip() throws Exception {
-
- org.osgi.service.provisioning.ProvisioningService provService = mock(org.osgi.service.provisioning.ProvisioningService.class);
- ProvisioningService mbean = new ProvisioningService(provService);
- ProvisioningService spiedMBean = spy(mbean);
-
- InputStream is = mock(InputStream.class);
- doReturn(is).when(spiedMBean).createStream("file://prov.zip");
-
- spiedMBean.addInformationFromZip("file://prov.zip");
- verify(provService).addInformation(any(ZipInputStream.class));
- verify(is).close();
-
- }
-
-
- @Test
- @SuppressWarnings("unchecked")
- public void testAddInformationWithTabularData() throws Exception {
-
- org.osgi.service.provisioning.ProvisioningService provService = mock(org.osgi.service.provisioning.ProvisioningService.class);
- ProvisioningService mbean = new ProvisioningService(provService);
-
- TabularData data = new TabularDataSupport(PROPERTIES_TYPE);
- PropertyData<byte[]> p1 = PropertyData.newInstance(PROVISIONING_AGENT_CONFIG, new byte[] { 20, 30, 40 });
- data.put(p1.toCompositeData());
- PropertyData<String> p2 = PropertyData.newInstance(PROVISIONING_SPID, "x.test");
- data.put(p2.toCompositeData());
-
- mbean.addInformation(data);
- ArgumentCaptor<Dictionary> dictionaryArgument = ArgumentCaptor.forClass(Dictionary.class);
- verify(provService).addInformation(dictionaryArgument.capture());
-
- Dictionary<String, Object> info = dictionaryArgument.getValue();
- assertEquals(2, info.size() );
- assertArrayEquals(new byte[] { 20, 30, 40 }, (byte[]) info.get(PROVISIONING_AGENT_CONFIG));
- assertEquals("x.test", info.get(PROVISIONING_SPID));
-
- }
-
-
- @Test
- public void testListInformation() throws Exception {
-
- org.osgi.service.provisioning.ProvisioningService provService = mock(org.osgi.service.provisioning.ProvisioningService.class);
- ProvisioningService mbean = new ProvisioningService(provService);
-
- Dictionary<String, Object> info = new Hashtable<String, Object>();
- info.put(PROVISIONING_AGENT_CONFIG, new byte[] { 20, 30, 40 });
- info.put(PROVISIONING_SPID, "x.test");
- info.put(PROVISIONING_REFERENCE, "rsh://0.0.0.0/provX");
- info.put(PROVISIONING_RSH_SECRET, new byte[] { 15, 25, 35 });
- info.put(PROVISIONING_UPDATE_COUNT, 1);
-
- when(provService.getInformation()).thenReturn(info);
-
- TabularData provData = mbean.listInformation();
- assertNotNull(provData);
- assertEquals(PROPERTIES_TYPE, provData.getTabularType());
- assertEquals(5, provData.values().size());
- PropertyData<byte[]> agentConfig = PropertyData.from(provData.get(new Object[]{ PROVISIONING_AGENT_CONFIG }));
- assertArrayEquals(new byte[] { 20, 30, 40 }, agentConfig.getValue());
- PropertyData<String> spid = PropertyData.from(provData.get(new Object[] { PROVISIONING_SPID }));
- assertEquals("x.test", spid.getValue());
- PropertyData<String> ref = PropertyData.from(provData.get(new Object[] { PROVISIONING_REFERENCE }));
- assertEquals("rsh://0.0.0.0/provX", ref.getValue());
- PropertyData<byte[]> sec = PropertyData.from(provData.get(new Object[] { PROVISIONING_RSH_SECRET }));
- assertArrayEquals(new byte[] { 15, 25, 35 }, sec.getValue());
- PropertyData<Integer> count = PropertyData.from(provData.get(new Object[] { PROVISIONING_UPDATE_COUNT }));
- assertEquals(new Integer(1), count.getValue());
-
- }
-
-
- @Test
- @SuppressWarnings("unchecked")
- public void testSetInformation() throws Exception {
-
- org.osgi.service.provisioning.ProvisioningService provService = mock(org.osgi.service.provisioning.ProvisioningService.class);
- ProvisioningService mbean = new ProvisioningService(provService);
-
- TabularData data = new TabularDataSupport(PROPERTIES_TYPE);
- PropertyData<String> p1 = PropertyData.newInstance(PROVISIONING_REFERENCE, "rsh://0.0.0.0/provX");
- data.put(p1.toCompositeData());
- PropertyData<String> p2 = PropertyData.newInstance(PROVISIONING_SPID, "x.test");
- data.put(p2.toCompositeData());
-
- mbean.setInformation(data);
-
- ArgumentCaptor<Dictionary> dictionaryArgument = ArgumentCaptor.forClass(Dictionary.class);
- verify(provService).setInformation(dictionaryArgument.capture());
-
- Dictionary<String, Object> info = dictionaryArgument.getValue();
- assertEquals(2, info.size() );
- assertEquals("rsh://0.0.0.0/provX", info.get(PROVISIONING_REFERENCE));
- assertEquals("x.test", info.get(PROVISIONING_SPID));
-
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/useradmin/UserAdminTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/useradmin/UserAdminTest.java
deleted file mode 100644
index 47488ca..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/useradmin/UserAdminTest.java
+++ /dev/null
@@ -1,596 +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.aries.jmx.useradmin;
-
-import java.io.IOException;
-import java.util.Dictionary;
-import java.util.Hashtable;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.TabularData;
-
-import org.apache.aries.jmx.codec.AuthorizationData;
-import org.apache.aries.jmx.codec.GroupData;
-import org.apache.aries.jmx.codec.RoleData;
-import org.apache.aries.jmx.codec.UserData;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.osgi.jmx.JmxConstants;
-import org.osgi.service.useradmin.Authorization;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-
-/**
- * UserAdminMBean test case.
- *
- * @version $Rev$ $Date$
- */
-public class UserAdminTest {
-
- @Mock
- private org.osgi.service.useradmin.UserAdmin userAdmin;
- private UserAdmin mbean;
-
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- mbean = new UserAdmin(userAdmin);
- }
-
- /**
- * Test method for
- * {@link org.apache.aries.jmx.useradmin.UserAdmin#addCredential(java.lang.String, byte[], java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testAddCredential() throws IOException {
- User user1 = Mockito.mock(User.class);
- Dictionary<String, Object> credentials = new Hashtable<String, Object>();
- Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getCredentials()).thenReturn(credentials);
- mbean.addCredential("password", new byte[] { 1, 2 }, "user1");
- Assert.assertArrayEquals(new byte[] { 1, 2 }, (byte[]) credentials.get("password"));
-
- }
-
- /**
- * Test method for
- * {@link org.apache.aries.jmx.useradmin.UserAdmin#addCredentialString(String, String, String)}
- * .
- *
- * @throws IOException
- */
- @Test
- public void testAddCredentialString() throws IOException {
- User user1 = Mockito.mock(User.class);
- Dictionary<String, Object> credentials = new Hashtable<String, Object>();
- Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getCredentials()).thenReturn(credentials);
- mbean.addCredentialString("password", "1234", "user1");
- Assert.assertEquals("1234", (String) credentials.get("password"));
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#addMember(java.lang.String, java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testAddMember() throws IOException {
- Group group1 = Mockito.mock(Group.class);
- User user1 = Mockito.mock(User.class);
- Mockito.when(userAdmin.getRole("group1")).thenReturn(group1);
- Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
- Mockito.when(group1.getType()).thenReturn(Role.GROUP);
- Mockito.when(group1.addMember(user1)).thenReturn(true);
- boolean isAdded = mbean.addMember("group1", "user1");
- Assert.assertTrue(isAdded);
- Mockito.verify(group1).addMember(user1);
- }
-
- /**
- * Test method for
- * {@link org.apache.aries.jmx.useradmin.UserAdmin#addPropertyString(String, String, String)}
- * .
- *
- * @throws IOException
- */
- @Test
- public void testAddPropertyString() throws IOException {
- User user1 = Mockito.mock(User.class);
- Dictionary<String, Object> props = new Hashtable<String, Object>();
- Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getProperties()).thenReturn(props);
- mbean.addPropertyString("key", "1234", "user1");
- Assert.assertEquals("1234", (String) props.get("key"));
- }
-
- /**
- * Test method for
- * {@link org.apache.aries.jmx.useradmin.UserAdmin#addProperty(java.lang.String, byte[], java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testAddProperty() throws IOException {
- User user1 = Mockito.mock(User.class);
- Dictionary<String, Object> props = new Hashtable<String, Object>();
- Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getProperties()).thenReturn(props);
- mbean.addProperty("key", new byte[] { 1, 2 }, "user1");
- Assert.assertArrayEquals(new byte[] { 1, 2 }, (byte[]) props.get("key"));
- }
-
- /**
- * Test method for
- * {@link org.apache.aries.jmx.useradmin.UserAdmin#addRequiredMember(java.lang.String, java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testAddRequiredMember() throws IOException {
- Group group1 = Mockito.mock(Group.class);
- User user1 = Mockito.mock(User.class);
- Mockito.when(userAdmin.getRole("group1")).thenReturn(group1);
- Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
- Mockito.when(group1.getType()).thenReturn(Role.GROUP);
- Mockito.when(group1.addRequiredMember(user1)).thenReturn(true);
- boolean isAdded = mbean.addRequiredMember("group1", "user1");
- Assert.assertTrue(isAdded);
- Mockito.verify(group1).addRequiredMember(user1);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#createGroup(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testCreateGroup() throws IOException {
- mbean.createGroup("group1");
- Mockito.verify(userAdmin).createRole("group1", Role.GROUP);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#createRole(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testCreateRole() throws IOException {
- try {
- mbean.createRole("role1");
- Assert.fail("Function did not throw exception as expected");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#createUser(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testCreateUser() throws IOException {
- mbean.createUser("user1");
- Mockito.verify(userAdmin).createRole("user1", Role.USER);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getAuthorization(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testGetAuthorization() throws IOException {
- Authorization auth = Mockito.mock(Authorization.class);
- User user = Mockito.mock(User.class);
- Mockito.when(user.getType()).thenReturn(Role.USER);
- Mockito.when(userAdmin.getAuthorization(user)).thenReturn(auth);
- Mockito.when(userAdmin.getRole("role1")).thenReturn(user);
- Mockito.when(auth.getName()).thenReturn("auth1");
- Mockito.when(auth.getRoles()).thenReturn(new String[]{"role1"});
- CompositeData data = mbean.getAuthorization("role1");
- Assert.assertNotNull(data);
- AuthorizationData authData = AuthorizationData.from(data);
- Assert.assertNotNull(authData);
- Assert.assertEquals("auth1", authData.getName());
- Assert.assertArrayEquals(new String[] { "role1" }, authData.getRoles());
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getCredentials(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testGetCredentials() throws IOException {
- User user1 = Mockito.mock(User.class);
- Dictionary<String, Object> properties = new Hashtable<String, Object>();
- properties.put("key", "value");
- Mockito.when(user1.getCredentials()).thenReturn(properties);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(userAdmin.getRole(Mockito.anyString())).thenReturn(user1);
- TabularData data = mbean.getCredentials("user1");
- Assert.assertNotNull(data);
- Assert.assertEquals(JmxConstants.PROPERTIES_TYPE, data.getTabularType());
- CompositeData composite = data.get(new Object[] { "key" });
- Assert.assertNotNull(composite);
- Assert.assertEquals("key", (String) composite.get(JmxConstants.KEY));
- Assert.assertEquals("value", (String) composite.get(JmxConstants.VALUE));
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getGroup(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testGetGroup() throws IOException {
- Group group1 = Mockito.mock(Group.class);
- Mockito.when(group1.getType()).thenReturn(Role.GROUP);
- Mockito.when(group1.getName()).thenReturn("group1");
- Role role1 = Mockito.mock(Role.class);
- Mockito.when(role1.getName()).thenReturn("role1");
- Role role2 = Mockito.mock(Role.class);
- Mockito.when(role2.getName()).thenReturn("role2");
- Mockito.when(group1.getRequiredMembers()).thenReturn(new Role[] { role1 });
- Mockito.when(group1.getMembers()).thenReturn(new Role[] { role2 });
- Mockito.when(userAdmin.getRole(Mockito.anyString())).thenReturn(group1);
- CompositeData data = mbean.getGroup("group1");
- Assert.assertNotNull(data);
- GroupData group = GroupData.from(data);
- Assert.assertNotNull(group);
- Assert.assertEquals("group1", group.getName());
- Assert.assertEquals(Role.GROUP, group.getType());
- Assert.assertArrayEquals(new String[] { "role2" }, group.getMembers());
- Assert.assertArrayEquals(new String[] { "role1" }, group.getRequiredMembers());
- Mockito.verify(userAdmin).getRole(Mockito.anyString());
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getGroups(java.lang.String)}.
- *
- * @throws Exception
- */
- @Test
- public void testGetGroups() throws Exception {
- Group group1 = Mockito.mock(Group.class);
- Mockito.when(group1.getType()).thenReturn(Role.GROUP);
- Mockito.when(group1.getName()).thenReturn("group1");
- Mockito.when(userAdmin.getRoles("name=group1")).thenReturn(new Role[] { group1 });
- String[] groups = mbean.getGroups("name=group1");
- Assert.assertArrayEquals(new String[] { "group1" }, groups);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getImpliedRoles(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testGetImpliedRoles() throws IOException {
- User user1 = Mockito.mock(User.class);
- Authorization auth = Mockito.mock(Authorization.class);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(auth.getRoles()).thenReturn(new String[] { "role1" });
- Mockito.when(userAdmin.getRole("role1")).thenReturn(user1);
- Mockito.when(userAdmin.getAuthorization(user1)).thenReturn(auth);
- String[] roles = mbean.getImpliedRoles("role1");
- Assert.assertArrayEquals(new String[] { "role1" }, roles);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getMembers(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testGetMembers() throws IOException {
- Group group1 = Mockito.mock(Group.class);
- Mockito.when(group1.getType()).thenReturn(Role.GROUP);
- Mockito.when(group1.getName()).thenReturn("group1");
- User user1 = Mockito.mock(Group.class);
- Mockito.when(user1.getName()).thenReturn("user1");
- Mockito.when(group1.getMembers()).thenReturn(new Role[] { user1 });
- Mockito.when(userAdmin.getRole("group1")).thenReturn(group1);
- String[] members = mbean.getMembers("group1");
- Assert.assertArrayEquals(new String[] { "user1" }, members);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getProperties(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testGetProperties() throws IOException {
- User user1 = Mockito.mock(User.class);
- Dictionary<String, Object> properties = new Hashtable<String, Object>();
- properties.put("key", "value");
- Mockito.when(user1.getProperties()).thenReturn(properties);
- Mockito.when(userAdmin.getRole(Mockito.anyString())).thenReturn(user1);
- TabularData data = mbean.getProperties("user1");
- Assert.assertNotNull(data);
- Assert.assertEquals(JmxConstants.PROPERTIES_TYPE, data.getTabularType());
- CompositeData composite = data.get(new Object[] { "key" });
- Assert.assertNotNull(composite);
- Assert.assertEquals("key", (String) composite.get(JmxConstants.KEY));
- Assert.assertEquals("value", (String) composite.get(JmxConstants.VALUE));
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getRequiredMembers(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testGetRequiredMembers() throws IOException {
- Group group1 = Mockito.mock(Group.class);
- Mockito.when(group1.getType()).thenReturn(Role.GROUP);
- Mockito.when(group1.getName()).thenReturn("group1");
- User user1 = Mockito.mock(Group.class);
- Mockito.when(user1.getName()).thenReturn("user1");
- Mockito.when(group1.getRequiredMembers()).thenReturn(new Role[] { user1 });
- Mockito.when(userAdmin.getRole("group1")).thenReturn(group1);
- String[] members = mbean.getRequiredMembers("group1");
- Assert.assertArrayEquals(new String[] { "user1" }, members);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getRole(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testGetRole() throws IOException {
- User user1 = Mockito.mock(User.class);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getName()).thenReturn("user1");
- Mockito.when(userAdmin.getRole(Mockito.anyString())).thenReturn(user1);
- CompositeData data = mbean.getRole("user1");
- Assert.assertNotNull(data);
- RoleData role = RoleData.from(data);
- Assert.assertNotNull(role);
- Assert.assertEquals("user1", role.getName());
- Assert.assertEquals(Role.USER, role.getType());
- Mockito.verify(userAdmin).getRole(Mockito.anyString());
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getRoles(java.lang.String)}.
- *
- * @throws Exception
- */
- @Test
- public void testGetRoles() throws Exception {
- User user1 = Mockito.mock(User.class);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getName()).thenReturn("user1");
- Mockito.when(userAdmin.getRoles("name=user1")).thenReturn(new Role[] { user1 });
- String[] roles = mbean.getRoles("name=user1");
- Assert.assertArrayEquals(new String[] { "user1" }, roles);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getUser(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testGetUser() throws IOException {
- User user1 = Mockito.mock(User.class);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getName()).thenReturn("user1");
- Mockito.when(userAdmin.getRole(Mockito.anyString())).thenReturn(user1);
- CompositeData data = mbean.getUser("user1");
- Assert.assertNotNull(data);
- UserData user = UserData.from(data);
- Assert.assertNotNull(user);
- Assert.assertEquals("user1", user.getName());
- Assert.assertEquals(Role.USER, user.getType());
- Mockito.verify(userAdmin).getRole(Mockito.anyString());
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getUserWithProperty(String, String)}.
- *
- * @throws IOException
- */
- @Test
- public void testGetUserString() throws IOException {
- User user1 = Mockito.mock(User.class);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getName()).thenReturn("user1");
- Mockito.when(userAdmin.getUser("key", "valuetest")).thenReturn(user1);
- String username = mbean.getUserWithProperty("key", "valuetest");
- Assert.assertEquals(username, "user1");
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getUsers(java.lang.String)}.
- *
- * @throws Exception
- */
- @Test
- public void testGetUsers() throws Exception {
- User user1 = Mockito.mock(User.class);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getName()).thenReturn("user1");
- Mockito.when(userAdmin.getRoles("name=user1")).thenReturn(new Role[] { user1 });
- String[] roles = mbean.getUsers("name=user1");
- Assert.assertArrayEquals(new String[] { "user1" }, roles);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#listGroups()}.
- *
- * @throws Exception
- */
- @Test
- public void testListGroups() throws Exception {
- Group group1 = Mockito.mock(Group.class);
- Mockito.when(group1.getType()).thenReturn(Role.GROUP);
- Mockito.when(group1.getName()).thenReturn("group1");
- Group group2 = Mockito.mock(Group.class);
- Mockito.when(group2.getType()).thenReturn(Role.GROUP);
- Mockito.when(group2.getName()).thenReturn("group2");
- Mockito.when(userAdmin.getRoles(null)).thenReturn(new Role[] { group1, group2 });
- String[] groups = mbean.listGroups();
- Assert.assertArrayEquals(new String[] { "group1", "group2" }, groups);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#listRoles()}.
- *
- * @throws Exception
- */
- @Test
- public void testListRoles() throws Exception {
- User user1 = Mockito.mock(User.class);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getName()).thenReturn("user1");
- User user2 = Mockito.mock(User.class);
- Mockito.when(user2.getType()).thenReturn(Role.USER);
- Mockito.when(user2.getName()).thenReturn("user2");
- Mockito.when(userAdmin.getRoles(null)).thenReturn(new Role[] { user1, user2 });
- String[] roles = mbean.listRoles();
- Assert.assertArrayEquals(new String[] { "user1", "user2" }, roles);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#listUsers()}.
- *
- * @throws Exception
- */
- @Test
- public void testListUsers() throws Exception {
- User user1 = Mockito.mock(User.class);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getName()).thenReturn("user1");
- User user2 = Mockito.mock(User.class);
- Mockito.when(user2.getType()).thenReturn(Role.USER);
- Mockito.when(user2.getName()).thenReturn("user2");
- Mockito.when(userAdmin.getRoles(null)).thenReturn(new Role[] { user1, user2 });
- String[] roles = mbean.listUsers();
- Assert.assertArrayEquals(new String[] { "user1", "user2" }, roles);
- }
-
- /**
- * Test method for
- * {@link org.apache.aries.jmx.useradmin.UserAdmin#removeCredential(java.lang.String, java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testRemoveCredential() throws IOException {
- User user1 = Mockito.mock(User.class);
- Dictionary<String, Object> cred = new Hashtable<String, Object>();
- Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getCredentials()).thenReturn(cred);
- mbean.removeCredential("key", "user1");
- Assert.assertEquals(0, cred.size());
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#removeGroup(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testRemoveGroup() throws IOException {
- Mockito.when(userAdmin.removeRole("group1")).thenReturn(true);
- boolean isRemoved = mbean.removeGroup("group1");
- Assert.assertTrue(isRemoved);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#removeMember(java.lang.String, java.lang.String)}
- * .
- *
- * @throws IOException
- */
- @Test
- public void testRemoveMember() throws IOException {
- Group group1 = Mockito.mock(Group.class);
- User user1 = Mockito.mock(User.class);
- Mockito.when(userAdmin.getRole("group1")).thenReturn(group1);
- Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
- Mockito.when(group1.getType()).thenReturn(Role.GROUP);
- Mockito.when(group1.removeMember(user1)).thenReturn(true);
- boolean isAdded = mbean.removeMember("group1", "user1");
- Assert.assertTrue(isAdded);
- Mockito.verify(group1).removeMember(user1);
- }
-
- /**
- * Test method for
- * {@link org.apache.aries.jmx.useradmin.UserAdmin#removeProperty(java.lang.String, java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testRemoveProperty() throws IOException {
- User user1 = Mockito.mock(User.class);
- Dictionary<String, Object> props = new Hashtable<String, Object>();
- Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
- Mockito.when(user1.getType()).thenReturn(Role.USER);
- Mockito.when(user1.getProperties()).thenReturn(props);
- mbean.removeProperty("key", "user1");
- Assert.assertEquals(0, props.size());
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#removeRole(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testRemoveRole() throws IOException {
- Mockito.when(userAdmin.removeRole("role1")).thenReturn(true);
- boolean isRemoved = mbean.removeRole("role1");
- Assert.assertTrue(isRemoved);
- }
-
- /**
- * Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#removeUser(java.lang.String)}.
- *
- * @throws IOException
- */
- @Test
- public void testRemoveUser() throws IOException {
- Mockito.when(userAdmin.removeRole("user1")).thenReturn(true);
- boolean isRemoved = mbean.removeUser("user1");
- Assert.assertTrue(isRemoved);
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/util/FrameworkUtilsTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/util/FrameworkUtilsTest.java
deleted file mode 100644
index 7823bc3..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/util/FrameworkUtilsTest.java
+++ /dev/null
@@ -1,294 +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.aries.jmx.util;
-
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleDependencies;
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleExportedPackages;
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleIds;
-import static org.apache.aries.jmx.util.FrameworkUtils.getBundleImportedPackages;
-import static org.apache.aries.jmx.util.FrameworkUtils.getRegisteredServiceIds;
-import static org.apache.aries.jmx.util.FrameworkUtils.getServiceIds;
-import static org.apache.aries.jmx.util.FrameworkUtils.getServicesInUseByBundle;
-import static org.apache.aries.jmx.util.FrameworkUtils.isBundlePendingRemoval;
-import static org.apache.aries.jmx.util.FrameworkUtils.isBundleRequiredByOthers;
-import static org.apache.aries.jmx.util.FrameworkUtils.resolveService;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.util.Dictionary;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Set;
-
-import org.junit.Test;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.Version;
-import org.osgi.service.packageadmin.ExportedPackage;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.packageadmin.RequiredBundle;
-
-/**
- *
- *
- *
- * @version $Rev$ $Date$
- */
-public class FrameworkUtilsTest {
-
-
- @Test
- public void testGetBundleIds() throws Exception {
-
- assertEquals(0, getBundleIds((Bundle[])null).length);
- assertEquals(0, getBundleIds(new Bundle[0]).length);
-
- Bundle b1 = mock(Bundle.class);
- when(b1.getBundleId()).thenReturn(new Long(47));
- Bundle b2 = mock(Bundle.class);
- when(b2.getBundleId()).thenReturn(new Long(23));
-
- assertArrayEquals(new long[] { 47 , 23 }, getBundleIds(new Bundle[] { b1, b2 }));
-
- }
-
- @Test
- public void testResolveService() throws Exception {
-
- BundleContext context = mock(BundleContext.class);
- ServiceReference reference = mock(ServiceReference.class);
- when(context.getAllServiceReferences(anyString(), anyString())).thenReturn(new ServiceReference[] { reference });
- ServiceReference result = resolveService(context, 998);
- assertNotNull(result);
-
- }
-
- @Test
- public void testGetServiceIds() throws Exception {
-
- assertEquals(0, getServiceIds(null).length);
- assertEquals(0, getServiceIds(new ServiceReference[0]).length);
-
- ServiceReference s1 = mock(ServiceReference.class);
- when(s1.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(15));
- ServiceReference s2 = mock(ServiceReference.class);
- when(s2.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(5));
- ServiceReference s3 = mock(ServiceReference.class);
- when(s3.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(25));
-
- assertArrayEquals(new long[] { 15, 5, 25 },
- getServiceIds(new ServiceReference[] {s1, s2, s3} ) );
- }
-
- @Test
- public void testGetBundleExportedPackages() throws Exception {
-
- Bundle bundle = mock(Bundle.class);
- PackageAdmin admin = mock(PackageAdmin.class);
-
- assertEquals(0, getBundleExportedPackages(bundle, admin).length);
-
- ExportedPackage exported = mock(ExportedPackage.class);
- when(exported.getName()).thenReturn("org.apache.aries.jmx");
- when(exported.getVersion()).thenReturn(new Version("1.0.0"));
- when(admin.getExportedPackages(bundle)).thenReturn(new ExportedPackage[] { exported });
-
- assertArrayEquals(new String[] { "org.apache.aries.jmx;1.0.0"} , getBundleExportedPackages(bundle, admin));
-
- }
-
-
- @Test
- public void testGetBundleImportedPackages() throws Exception {
-
- Bundle bundle = mock(Bundle.class);
- BundleContext context = mock(BundleContext.class);
-
- Bundle b1 = mock(Bundle.class);
- Bundle b2 = mock(Bundle.class);
- Bundle b3 = mock(Bundle.class);
- when(context.getBundles()).thenReturn(new Bundle[] { bundle, b1, b2, b3 });
-
- ExportedPackage ep1 = mock(ExportedPackage.class);
- when(ep1.getImportingBundles()).thenReturn(new Bundle[] { bundle, b2, b3 });
- when(ep1.getName()).thenReturn("org.apache.aries.jmx.b1");
- when(ep1.getVersion()).thenReturn(Version.emptyVersion);
- ExportedPackage ep2 = mock(ExportedPackage.class);
- when(ep2.getImportingBundles()).thenReturn(new Bundle[] { bundle, b3 });
- when(ep2.getName()).thenReturn("org.apache.aries.jmx.b2");
- when(ep2.getVersion()).thenReturn(Version.parseVersion("2.0.1"));
-
- PackageAdmin admin = mock(PackageAdmin.class);
- when(admin.getExportedPackages(b1)).thenReturn(new ExportedPackage[] { ep1 });
- when(admin.getExportedPackages(b2)).thenReturn(new ExportedPackage[] { ep2 });
- when(admin.getExportedPackages(b3)).thenReturn(null);
-
- //check first with DynamicImport
- Dictionary<String, String> headers = new Hashtable<String, String>();
- headers.put(Constants.DYNAMICIMPORT_PACKAGE, "*");
- when(bundle.getHeaders()).thenReturn(headers);
- assertArrayEquals(new String[] { "org.apache.aries.jmx.b1;0.0.0" , "org.apache.aries.jmx.b2;2.0.1"}
- , getBundleImportedPackages(context, bundle, admin));
-
- //check with ImportPackage statement
- headers.remove(Constants.DYNAMICIMPORT_PACKAGE);
- String importPackageStatement = "org.apache.aries.jmx.b1;version=0.0.0;resolution:=optional,org.apache.aries.jmx.b2;attribute:=value;version=\"[2.0, 3.0)\"";
- headers.put(Constants.IMPORT_PACKAGE, importPackageStatement);
- when(admin.getExportedPackages("org.apache.aries.jmx.b1")).thenReturn(new ExportedPackage[] { ep1 });
- when(admin.getExportedPackages("org.apache.aries.jmx.b2")).thenReturn(new ExportedPackage[] { ep2 });
-
- assertArrayEquals(new String[] { "org.apache.aries.jmx.b1;0.0.0" , "org.apache.aries.jmx.b2;2.0.1"}
- , getBundleImportedPackages(context, bundle, admin));
-
-
- }
-
- @Test
- public void testGetRegisteredServiceIds() throws Exception {
-
- Bundle bundle = mock(Bundle.class);
-
- ServiceReference s1 = mock(ServiceReference.class);
- when(s1.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(56));
- ServiceReference s2 = mock(ServiceReference.class);
- when(s2.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(5));
- ServiceReference s3 = mock(ServiceReference.class);
- when(s3.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(34));
-
- when(bundle.getRegisteredServices()).thenReturn(new ServiceReference[] { s1, s2, s3 });
-
- assertArrayEquals(new long[] { 56, 5, 34}, getRegisteredServiceIds(bundle));
-
- }
-
- @Test
- public void testGetServicesInUseByBundle() throws Exception {
-
- Bundle bundle = mock(Bundle.class);
-
- ServiceReference s1 = mock(ServiceReference.class);
- when(s1.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(15));
- ServiceReference s2 = mock(ServiceReference.class);
- when(s2.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(16));
- ServiceReference s3 = mock(ServiceReference.class);
- when(s3.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(17));
-
- when(bundle.getServicesInUse()).thenReturn(new ServiceReference[] { s1, s2, s3 });
-
- assertArrayEquals(new long[] { 15, 16, 17 }, getServicesInUseByBundle(bundle));
-
- }
-
- @Test
- public void testIsBundlePendingRemoval() throws Exception {
-
- Bundle bundle = mock(Bundle.class);
- when(bundle.getSymbolicName()).thenReturn("org.apache.testb");
-
- RequiredBundle reqBundle = mock(RequiredBundle.class);
- when(reqBundle.getBundle()).thenReturn(bundle);
- when(reqBundle.isRemovalPending()).thenReturn(true);
-
- PackageAdmin admin = mock(PackageAdmin.class);
- when(admin.getRequiredBundles("org.apache.testb")).thenReturn(new RequiredBundle[] { reqBundle });
-
- assertTrue(isBundlePendingRemoval(bundle, admin));
-
- }
-
- @Test
- public void testIsBundleRequiredByOthers() throws Exception {
-
- Bundle bundle = mock(Bundle.class);
- when(bundle.getSymbolicName()).thenReturn("org.apache.testb");
-
- RequiredBundle reqBundle = mock(RequiredBundle.class);
- when(reqBundle.getBundle()).thenReturn(bundle);
- when(reqBundle.getRequiringBundles()).thenReturn(new Bundle[0]);
-
- PackageAdmin admin = mock(PackageAdmin.class);
- when(admin.getRequiredBundles("org.apache.testb")).thenReturn(new RequiredBundle[] { reqBundle });
-
- assertFalse(isBundleRequiredByOthers(bundle, admin));
-
- Bundle user = mock(Bundle.class);
- when(reqBundle.getRequiringBundles()).thenReturn(new Bundle[] { user });
-
- assertTrue(isBundleRequiredByOthers(bundle, admin));
- }
-
-
- @Test
- public void testGetBundleDependencies() throws Exception {
-
- Bundle bundle = mock(Bundle.class);
- BundleContext context = mock(BundleContext.class);
-
- Bundle b1 = mock(Bundle.class);
- when(b1.getSymbolicName()).thenReturn("b1");
- when(b1.getBundleId()).thenReturn(new Long(44));
- Bundle b2 = mock(Bundle.class);
- when(b2.getSymbolicName()).thenReturn("b2");
- when(b2.getBundleId()).thenReturn(new Long(55));
- Bundle b3 = mock(Bundle.class);
- when(b3.getSymbolicName()).thenReturn("b3");
- when(b3.getBundleId()).thenReturn(new Long(66));
-
- when(context.getBundles()).thenReturn(new Bundle[] { bundle, b1, b2, b3 });
-
- Dictionary<String, String> headers = new Hashtable<String, String>();
- when(bundle.getHeaders()).thenReturn(headers);
-
- PackageAdmin admin = mock(PackageAdmin.class);
- assertEquals(0, getBundleDependencies(context, bundle, admin).length);
-
- RequiredBundle rb1 = mock(RequiredBundle.class);
- when(rb1.getBundle()).thenReturn(b1);
- when(rb1.getRequiringBundles()).thenReturn(new Bundle[] { bundle, b2 });
- RequiredBundle rb2 = mock(RequiredBundle.class);
- when(rb2.getBundle()).thenReturn(b2);
- when(rb2.getRequiringBundles()).thenReturn(new Bundle[] { b1 });
- RequiredBundle rb3 = mock(RequiredBundle.class);
- when(rb3.getBundle()).thenReturn(b3);
- when(rb3.getRequiringBundles()).thenReturn(new Bundle[] { bundle, b1, b2 });
-
- headers.put(Constants.REQUIRE_BUNDLE, "b1;bundle-version=\"1.0.0\",b3;bundle-version=\"2.0.0\"");
-
- when(admin.getRequiredBundles("b1")).thenReturn(new RequiredBundle[] { rb1 });
- when(admin.getRequiredBundles("b2")).thenReturn(new RequiredBundle[] { rb2 });
- when(admin.getRequiredBundles("b3")).thenReturn(new RequiredBundle[] { rb3 });
-
- assertEquals(toSet(new long[] { 44, 66 }), toSet(getBundleDependencies(context, bundle, admin)));
- }
-
- private static Set<Long> toSet(long[] array) {
- Set<Long> set = new HashSet<Long>();
- for (long value : array) {
- set.add(value);
- }
- return set;
- }
-
-}
diff --git a/jmx-core/src/test/java/org/apache/aries/jmx/util/TypeUtilsTest.java b/jmx-core/src/test/java/org/apache/aries/jmx/util/TypeUtilsTest.java
deleted file mode 100644
index 2e3a111..0000000
--- a/jmx-core/src/test/java/org/apache/aries/jmx/util/TypeUtilsTest.java
+++ /dev/null
@@ -1,104 +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.aries.jmx.util;
-
-import static org.apache.aries.jmx.util.TypeUtils.fromDictionary;
-import static org.apache.aries.jmx.util.TypeUtils.fromString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.Map;
-
-import org.junit.Test;
-
-public class TypeUtilsTest {
-
-
- @Test
- public void testMapFromDictionary() throws Exception{
-
- Dictionary<String, String> dictionary = new Hashtable<String, String>();
- dictionary.put("one", "1");
- dictionary.put("two", "2");
-
- Map<String,String> map = fromDictionary(dictionary);
- assertEquals(2, map.size());
- assertEquals("1", map.get("one"));
- assertEquals("2", map.get("two"));
-
- }
-
- @Test
- public void testFromString() throws Exception {
-
- String value;
-
- value = "1";
- Integer integerValue = fromString(Integer.class, value);
- assertEquals(new Integer(1), integerValue);
-
- int intValue = fromString(Integer.TYPE, value);
- assertEquals(1, intValue);
-
- Long wrappedLongValue = fromString(Long.class, value);
- assertEquals(Long.valueOf(1), wrappedLongValue);
-
- long longValue = fromString(Long.TYPE, value);
- assertEquals(1, longValue);
-
- Double wrappedDoubleValue = fromString(Double.class, value);
- assertEquals(Double.valueOf(1), wrappedDoubleValue);
-
- double doubleValue = fromString(Double.TYPE, value);
- assertEquals(1, doubleValue, 0);
-
- Float wrappedFloatValue = fromString(Float.class, value);
- assertEquals(Float.valueOf(1), wrappedFloatValue);
-
- float floatValue = fromString(Float.TYPE, value);
- assertEquals(1, floatValue, 0);
-
- Short shortValue = fromString(Short.class, value);
- assertEquals(Short.valueOf(value), shortValue);
-
- Byte byteValue = fromString(Byte.class, value);
- assertEquals(Byte.valueOf(value), byteValue);
-
- value = "true";
- assertTrue(fromString(Boolean.class, value));
- assertTrue(fromString(Boolean.TYPE, value));
-
- char charValue = fromString(Character.TYPE, "a");
- assertEquals('a', charValue);
- Character characterValue = fromString(Character.class, "a");
- assertEquals(Character.valueOf('a'), characterValue);
-
- BigDecimal bigDecimal = fromString(BigDecimal.class, "2");
- assertEquals(new BigDecimal("2"), bigDecimal);
-
- BigInteger bigInteger = fromString(BigInteger.class, "2");
- assertEquals(new BigInteger("2"), bigInteger);
-
- String stringValue = fromString(String.class, value);
- assertEquals(stringValue, value);
-
- }
-}
diff --git a/src/main/java/org/apache/aries/jmx/framework/Framework.java b/src/main/java/org/apache/aries/jmx/framework/Framework.java
index a59c8ba..52303f5 100644
--- a/src/main/java/org/apache/aries/jmx/framework/Framework.java
+++ b/src/main/java/org/apache/aries/jmx/framework/Framework.java
@@ -242,7 +242,9 @@
try {
startLevel.setBundleStartLevel(bundle, newlevel);
} catch (IllegalArgumentException e) {
- throw new IOException("Setting the start level for bundle with id " + bundle.getBundleId() + " to level " + newlevel + " failed with message: " + e.getMessage(), e);
+ IOException ioex = new IOException("Setting the start level for bundle with id " + bundle.getBundleId() + " to level " + newlevel + " failed with message: " + e.getMessage());
+ ioex.initCause(e);
+ throw ioex;
}
}
diff --git a/src/main/java/org/apache/aries/jmx/util/FrameworkUtils.java b/src/main/java/org/apache/aries/jmx/util/FrameworkUtils.java
index e81dbc7..eb53a00 100644
--- a/src/main/java/org/apache/aries/jmx/util/FrameworkUtils.java
+++ b/src/main/java/org/apache/aries/jmx/util/FrameworkUtils.java
@@ -131,7 +131,9 @@
result = references[0];
}
} catch (InvalidSyntaxException e) {
- throw new IOException("Failure when resolving service ", e);
+ IOException ioe = new IOException("Failure when resolving service ");
+ ioe.initCause(e);
+ throw ioe;
}
return result;
}