View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.commons.compress.osgi;
20  
21  import static org.junit.Assert.assertNotNull;
22  import static org.junit.Assert.assertTrue;
23  
24  import java.lang.reflect.Method;
25  
26  import javax.inject.Inject;
27  
28  import org.junit.Test;
29  import org.ops4j.pax.exam.Option;
30  import org.osgi.framework.Bundle;
31  import org.osgi.framework.BundleContext;
32  
33  /**
34   * Tests if the library can be loaded with an OSGi environment provided by {@link #config()}.
35   */
36  abstract class AbstractOsgiITest {
37  
38      private static final String EXPECTED_BUNDLE_NAME = "org.apache.commons.commons-compress";
39  
40      @Inject
41      private BundleContext ctx;
42  
43      /**
44       * Gets the OSGi configuration to use for the test.
45       *
46       * @return the OSGi configuration to use for the test.
47       * @implNote Concrete implementation needs the @Configuration annotation.
48       */
49      public abstract Option[] config();
50  
51      private Bundle loadBundle() {
52          for (final Bundle b : ctx.getBundles()) {
53              if (EXPECTED_BUNDLE_NAME.equals(b.getSymbolicName())) {
54                  return b;
55              }
56          }
57          return null;
58      }
59  
60      @Test
61      void testCanLoadBundle() {
62          assertNotNull("Expected to find bundle " + EXPECTED_BUNDLE_NAME, loadBundle());
63      }
64  
65      @Test
66      void testProperlyDetectsRunningInsideOsgiEnv() throws Exception {
67          final String className = "org.apache.commons.compress.utils.OsgiUtils";
68          final Class<?> osgiUtils = loadBundle().loadClass(className);
69          assertNotNull("Can't load " + className + " via bundle", osgiUtils);
70          final Method method = osgiUtils.getMethod("isRunningInOsgiEnvironment");
71          assertNotNull("Can't access isRunningInOsgiEnvironment method", method);
72          assertTrue("Compress can't detect OSGi environment", (Boolean) method.invoke(null));
73      }
74  }