-
Language:
English
-
Language:
English
Red Hat Training
A Red Hat training course is available for Red Hat Fuse
Deploying into the Container
Getting application packages into the container
Red Hat
Copyright © 2011-2014 Red Hat, Inc. and/or its affiliates.
Abstract
Part I. The Red Hat JBoss Fuse Container
Abstract
Chapter 1. Red Hat JBoss Fuse Overview
Abstract
1.1. Red Hat JBoss Fuse Container Architecture
Overview
Figure 1.1. Red Hat JBoss Fuse Container Architecture
Deployment models
- OSGi bundle
- An OSGi bundle is a JAR file augmented with metadata in the JAR's
META-INF/MANIFEST.MF
file. Because the Red Hat JBoss Fuse container is fundamentally an OSGi container, the OSGi bundle is also the native format for the container. Ultimately, after deployment, all of the other deployment unit types are converted into OSGi bundles. - Fuse Application Bundle, FAB
- A Fuse Application Bundle (FAB) is a Fuse-specific deployment unit optimised for the JBoss Fuse container. FABs are a plain JAR built using the Apache Maven. FABs address some of the issues when using OSGi such as dependency resolution and class-loader conflicts. The FAB deployer in JBoss Fuse scans the metadata in the POM and automatically downloads any dependencies needed by the bundle.
- WAR
- A Web application ARchive (WAR) is the standard archive format for applications that run inside a Web server. As originally conceived by the Java servlet specification, a WAR packages Web pages, JSP pages, Java classes, servlet code, and so on, as required for a typical Web application. More generally, however, a WAR can be any deployment unit that obeys the basic WAR packaging rules (which, in particular, require the presence of a Web application deployment descriptor,
web.xml
). - JBI service assembly
- A Java Business Integration (JBI) service assembly is the basic unit of deployment for JBI applications. A discussion of the JBI container lies outside the scope of this document. For details, see "JBI Development Guide".
Spring framework
Blueprint framework
OSGi core framework
Red Hat JBoss Fuse kernel
1.2. Deployment Models
Revision History | |
---|---|
09/27/12 | |
Reordered to make OSGi more prominent |
Overview
Table 1.1. Alternative Deployment Packages
Package | Metadata | Maven Plug-in | URI Scheme | File Suffix |
---|---|---|---|---|
Bundle | MANIFEST.MF | maven-bundle-plugin | None | .jar |
FAB | pom.xml | maven-jar-plugin | fab: | .jar or .fab |
WAR | web.xml | maven-war-plugin | war: | .war |
OSGi bundle deployment model
Figure 1.2. Installing an OSGi Bundle
FAB deployment model
Figure 1.3. Installing a FAB
WAR deployment model
Figure 1.4. Installing a WAR
1.3. Dependency Injection Frameworks
Revision History | |
---|---|
09/27/12 | |
Reordered to make blueprint more prominent |
Dependency injection
OSGi framework extensions
- Blueprint—the blueprint extensor is based on the blueprint implementation from Apache Karaf.
- Spring—the Spring extensor is based on Spring Dynamic Modules (Spring-DM), which is the OSGi integration component from SpringSource.
Activating a framework
osgi:start
) or de-activated (using the command, osgi:stop
). This gives the extenders a chance to scan the bundle, look for configuration files of the appropriate type and, if necessary, activate the dependency injection framework for that bundle.
Blueprint XML file location
OSGI-INF/blueprint/*.xml
Spring XML file location
META-INF/spring/*.xml
1.4. Synchronous Communication
Overview
OSGi services
OSGi registry
service
element to register a Java object in the OSGi registry. For example, to create a SavingsAccountImpl
object and export it as an OSGi service (exposing it through the org.fusesource.example.Account
Java interface)
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<bean id="savings" class="org.fusesource.example.SavingsAccountImpl"/>
<service ref="savings" interface="org.fusesource.example.Account"/>
</blueprint>
reference
element that searches the OSGi registry for a service that supports the org.fusesource.example.Account
interface.
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"> <reference id="savingsRef" interface="org.fusesource.example.Account"/> <bean id="client" class="org.fusesource.example.client.Client"> <property name="savingsAccount" ref="savingsRef"/> </bean> </blueprint>
Dynamic interaction between bundles
osgi:start
), its OSGi services are published to the OSGi registry. And when a bundle is de-activated (for example, using the console command, osgi:stop
), its OSGi services are removed from the OSGi registry. Clients of a service can elect to receive notifications whenever a service is published to or removed from the OSGi registry.
1.5. Asynchronous Communication
Overview
JMS broker
- VM protocol—the Virtual Machine (VM) transport protocol is ideal for communicating within the container. VM is optimized for sending messages within the same JVM instance.
- Persistent or non-persistent messaging—you can choose whether the broker should persist messages or not, depending on the requirements of your application.
- Ease of use—there is no need to create and configure destinations (that is, queues or topics) before you can use them. After connecting to a broker, you can immediately start sending and receiving messages. If you start sending messages to a queue that does not exist yet, Apache ActiveMQ creates it dynamically.
- External communication—you can also configure a TCP port on the broker, opening it up to external JMS clients or other brokers.
NMR bus
- A message body is not required to be in XML format. You can use any data format in the NMR message body.
- A destination address can be an arbitrary string.
- Messages can be sent within the OSGi container; within the JBI container; and between the OSGi container and the JBI container. Therefore, the NMR bus integrates the two containers.
1.6. Fuse Fabric
Overview
Bundle deployment
Things to consider
- Bundles must be accessible through the fabric's Maven proxyWhen a Fabric Agent installs a bundle, it must first copy the bundle to the container's host computer. To do so, the agent uses the fabric's Maven Proxy to locate the bundle in one of the accessible Maven repositories and downloads it. This mechanism ensures that all of the containers in the fabric have access to the same set of bundles.If the installed bundle is a FAB, the dependencies are also resolved using the fabric's Maven proxy. This means that all of the dependencies must be in one of the repositories the proxy is configured to access. If any dependency is not accessible through the proxy, it will not be resolved.To address this issue, you need to ensure that the fabric's Maven proxy is configured to have access to all of the repositories from which your applications will need to download bundles. For more information see chapter "Configuring a Fabric's Maven Proxy" in "Configuring and Running Red Hat JBoss Fuse".
- Fabric Agents only load the bundles specified in a profileA fabric container's contents is completely controlled by the profiles associated with it. The fabric agent managing the container inspects each of the profiles associated with the container, downloads the listed bundles, and features, and installs them. If one of the bundles in a profile depends on a bundle that is not specified in the profile, or one of the other profiles associated with the container, the bundle will not be able to resolve that dependency.To address this issue you can do one of the following:
- construct your profiles to ensure that it contains all of the required bundles and their dependencies
- deploy the application as a feature that contains all of the required bundles and their dependencies
- package the application as a FAB and allow the container to resolve the dependencies and download the required bundles
Chapter 2. Dependency Injection Frameworks
Abstract
2.1. Spring and Blueprint Frameworks
Overview
META-INF/spring/
directory in a JAR, and Spring XML files can also be hot-deployed to the ESBInstallDir/deploy
directory. In the case of the blueprint framework, OSGi automatically activates any blueprint XML files under the OSGI-INF/blueprint/
directory in a JAR, and blueprint XML files can also be hot-deployed to the ESBInstallDir/deploy
directory.
Prefer Blueprint over Spring-DM
Configuration files
- Spring configuration—in the standard Maven directory layout, Spring XML configuration files are located under
ProjectDir/src/main/resources/META-INF/spring
. - Blueprint configuration—in the standard Maven directory layout, blueprint XML configuration files are located under
ProjectDir/src/main/resources/OSGI-INF/blueprint
.
camelContext
elements in the blueprint file, as described in the section called “Blueprint configuration file”.
Prerequisites for blueprint configuration
camel-blueprint
feature is installed. If necessary, install it by entering the following console command:
JBossFuse:karaf@root> features:install camel-blueprint
Spring configuration file
camelContext
using a Spring configuration file, where the root element is a Spring beans
element and the camelContext
element is a child of the beans
element. In this case, the camelContext
namespace must be http://camel.apache.org/schema/spring
.
ExampleRouter
log (which get incorporated into the console log file, InstallDir/data/log/servicemix.log
):
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="timer://myTimer?fixedRate=true&period=2000"/> <to uri="log:ExampleRouter"/> </route> </camelContext> </beans>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> ...
Blueprint configuration file
camelContext
using a blueprint configuration file, where the root element is blueprint
and the camelContext
element is a child of the blueprint
element. In this case, the camelContext
namespace must be http://camel.apache.org/schema/blueprint
.
ExampleRouter
log (which get incorporated into the console log file, InstallDir/data/log/servicemix.log
):
<?xml version="1.0" encoding="UTF-8"?> <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <camelContext xmlns="http://camel.apache.org/schema/blueprint"> <route> <from uri="timer://myTimer?fixedRate=true&period=2000"/> <to uri="log:ExampleRouter"/> </route> </camelContext> </blueprint>
2.2. Hot Deployment
Types of configuration file
- Spring XML file, deployable with the suffix,
.xml
. - Blueprint XML file, deployable with the suffix,
.xml
.
Hot deploy directory
InstallDir/deploy
Prerequisites
camel-blueprint
feature must be installed (which it is by default). If the camel-blueprint
feature has been disabled, however, you can re-install it by entering the following console command:
JBossFuse:karaf@root> features:install camel-blueprint
Default bundle version
0.0.0
.
Customizing the bundle version
manifest
element in the XML file. The manifest
element enables you to override any of the headers in the generated bundle's META-INF/MANIFEST.MF
file. In particular, you can use it to specify the bundle version.
Specifying the bundle version in a Spring XML file
manifest
element as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
>
<manifest xmlns="http://karaf.apache.org/xmlns/deployer/spring/v1.0.0">
Bundle-Version = 1.2.3.4
</manifest>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="timer://myTimer?fixedRate=true&period=2000"/>
<to uri="log:ExampleRouter"/>
</route>
</camelContext>
</beans>
manifest
element for Spring XML files belongs to the following schema namespace:
http://karaf.apache.org/xmlns/deployer/spring/v1.0.0
manifest
element are specified using the syntax of a Java properties file.
Specifying the bundle version in a Blueprint XML file
manifest
element as follows:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
>
<manifest xmlns="http://karaf.apache.org/xmlns/deployer/blueprint/v1.0.0">
Bundle-Version = 1.2.3.4
</manifest>
<camelContext xmlns="http://camel.apache.org/schema/blueprint">
<route>
<from uri="timer://myTimer?fixedRate=true&period=2000"/>
<to uri="log:ExampleRouter"/>
</route>
</camelContext>
</blueprint>
manifest
element for Blueprint XML files belongs to the following schema namespace:
http://karaf.apache.org/xmlns/deployer/blueprint/v1.0.0
manifest
element are specified using the syntax of a Java properties file.
2.3. Using OSGi Configuration Properties
Overview
Persistent ID
PersistentID.cfg
in the ESBInstallDir/etc/
directory. If the corresponding file exists, it can be used to initialize the values of properties belonging to the PersistentID property group.
etc/org.ops4j.pax.url.mvn.cfg
file is used to set the properties associated with the org.ops4j.pax.url.mvn
persistent ID (for the PAX Mvn URL handler).
Blueprint example
prefix
variable to the constructor of the myTransform
bean in blueprint XML, where the value of prefix
is set by the OSGi Configuration Admin service.
Example 2.1. Using OSGi Configuration Properties in Blueprint
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ... > ... <cm:property-placeholder persistent-id="org.fusesource.example"> <cm:default-properties> <cm:property name="prefix" value="Blueprint-Example"/> </cm:default-properties> </cm:property-placeholder> <bean id="myTransform" class="org.apache.servicemix.examples.camel.MyTransform"> <property name="prefix" value="${prefix}" /> </bean> </blueprint>
{{prefix}}
, substitutes the value of the prefix
variable into the blueprint XML file. The OSGi properties are set up using the following XML elements:
cm:property-placeholder
- This element gives you access to the properties associated with the specified persistent ID. After defining this element, you can use the syntax,
{{PropName}}
, to substitute variables belonging to the specified persistent ID. cm:property-placeholder/cm:default-properties
- You can optionally specify default values for properties by defining
cm:property
elements inside thecm:default-properties
element. If the correspondingetc/PersistentID.cfg
file defines property values, however, these will be used instead.
Chapter 3. Building with Maven
Abstract
3.1. Maven Directory Structure
Overview
src/main/java
and put the results into target/classes
.
Standard directory layout
Example 3.1. Standard Maven Directory Layout
ProjectDir/ pom.xml src/ main/ java/ ... resources/ META-INF/ spring/ *.xml OSGI-INF/ blueprint/ *.xml test/ java/ resources/ target/ ...
pom.xml file
pom.xml
file is the Project Object Model (POM) for the current project, which contains a complete description of how to build the current project. A pom.xml
file can be completely self-contained, but frequently (particular for more complex Maven projects) it can import settings from a parent POM file.
pom.xml
file is automatically embedded at the following location in the generated JAR file:
META-INF/maven/groupId/artifactId/pom.xml
src and target directories
src/
directory contains all of the code and resource files that you will work on while developing the project.
target/
directory contains the result of the build (typically a JAR file), as well as all all of the intermediate files generated during the build. For example, after performing a build, the target/classes/
directory will contain a copy of the resource files and the compiled Java classes.
main and test directories
src/main/
directory contains all of the code and resources needed for building the artifact.
src/test/
directory contains all of the code and resources for running unit tests against the compiled artifact.
java directory
java/
sub-directory contains Java source code (*.java
files) with the standard Java directory layout (that is, where the directory pathnames mirror the Java package names, with /
in place of the .
character). The src/main/java/
directory contains the bundle source code and the src/test/java/
directory contains the unit test source code.
resources directory
src/main/resources/
directory. The files and directories under src/main/resources/
will be copied into the root of the JAR file that is generated by the Maven build process.
src/test/resources/
are used only during the testing phase and will not be copied into the generated JAR file.
Spring integration
META-INF/spring/*.xml
, in your bundle. One of the key consequences of having Spring DM enabled in the OSGi container is that the lifecycle of the Spring application context is automatically synchronized with the OSGi bundle lifecycle:
- Activation—when a bundle is activated, Spring DM automatically scans the bundle to look for Spring configuration files in the standard location (any
.xml
files found under theMETA-INF/spring/
directory). If any Spring files are found, Spring DM creates an application context for the bundle and creates the beans defined in the Spring configuration files. - Stopping—when a bundle is stopped, Spring DM automatically shuts down the bundle's Spring application context, causing any Spring beans to be deleted.
Blueprint container
OSGI-INF/blueprint/*.xml
, in your project. For more details about the blueprint container, see Chapter 16, OSGi Services.
3.2. Preparing to use Maven
Overview
Prerequisites
- Maven installation—Maven is a free, open source build tool from Apache. You can download the latest version from the Maven download page. The minimum supported version is 2.2.1.
- Network connection—whilst performing a build, Maven dynamically searches external repositories and downloads the required artifacts on the fly. By default, Maven looks for repositories that are accessed over the Internet. You can change this behavior so that Maven will prefer searching repositories that are on a local network.NoteMaven can run in an offline mode. In offline mode Maven will only look for artifacts in its local repository.
Adding the Red Hat JBoss Fuse repository
settings.xml
file. Maven looks for your settings.xml
file in the .m2
directory of the user's home directory. If there is not a user specified settings.xml
file, Maven will use the system-level settings.xml
file at M2_HOME/conf/settings.xml
.
.m2/settings.xml
file or modify the system-level settings. In the settings.xml
file, add the repository
element for the JBoss Fuse repository as shown in bold text in Example 3.2, “Adding the Red Hat JBoss Fuse Repositories to Maven”.
Example 3.2. Adding the Red Hat JBoss Fuse Repositories to Maven
<settings> <profiles> <profile> <id>my-profile</id> <activation> <activeByDefault>true</activeByDefault> </activation> <repositories> <repository> <id>fusesource</id> <url>http://repo.fusesource.com/nexus/content/groups/public/</url> <snapshots> <enabled>false</enabled> </snapshots> <releases> <enabled>true</enabled> </releases> </repository> <repository> <id>fusesource.snapshot</id> <url>http://repo.fusesource.com/nexus/content/groups/public-snapshots/</url> <snapshots> <enabled>true</enabled> </snapshots> <releases> <enabled>false</enabled> </releases> </repository> <repository> <id>apache-public</id> <url>https://repository.apache.org/content/groups/public/</url> <snapshots> <enabled>true</enabled> </snapshots> <releases> <enabled>true</enabled> </releases> </repository> ... </repositories> </profile> </profiles> ... </settings>
fusesource-snapshot
repository—if you want to experiment with building your application using an Red Hat JBoss Fuse snapshot kit, you can include this repository.apache-public
repository—you might not always need this repository, but it is often useful to include it, because JBoss Fuse depends on many of the artifacts from Apache.
Artifacts
Maven coordinates
{groupId, artifactId, version}
. Sometimes Maven augments the basic set of coordinates with the additional coordinates, packaging and classifier. A tuple can be written with the basic coordinates, or with the additional packaging coordinate, or with the addition of both the packaging and classifier coordinates, as follows:
groupdId:artifactId:version groupdId:artifactId:packaging:version groupdId:artifactId:packaging:classifier:version
- groupdId
- Defines a scope for the name of the artifact. You would typically use all or part of a package name as a group ID—for example,
org.fusesource.example
. - artifactId
- Defines the artifact name (relative to the group ID).
- version
- Specifies the artifact's version. A version number can have up to four parts:
n.n.n.n
, where the last part of the version number can contain non-numeric characters (for example, the last part of1.0-SNAPSHOT
is the alphanumeric substring,0-SNAPSHOT
). - packaging
- Defines the packaged entity that is produced when you build the project. For OSGi projects, the packaging is
bundle
. The default value isjar
. - classifier
- Enables you to distinguish between artifacts that were built from the same POM, but have different content.
<project ... > ... <groupId>org.fusesource.example</groupId> <artifactId>bundle-demo</artifactId> <packaging>bundle</packaging> <version>1.0-SNAPSHOT</version> ... </project>
dependency
element to a POM:
<project ... > ... <dependencies> <dependency> <groupId>org.fusesource.example</groupId> <artifactId>bundle-demo</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> ... </project>
bundle
package type in the preceding dependency, because a bundle is just a particular kind of JAR file and jar
is the default Maven package type. If you do need to specify the packaging type explicitly in a dependency, however, you can use the type
element.
Chapter 4. Locating Dependencies
Abstract
4.1. Understanding Where Red Hat JBoss Fuse Bundles are Stored
Overview
Core Red Hat JBoss Fuse features
EsbInstallDir/system
directory.
Optional Red Hat JBoss Fuse features
features:list
immediately after installing JBoss Fuse, the features listed as uninstalled are the optional JBoss Fuse features. The optional features are not provided in the system repository and must be downloaded over a network connection.
Custom offline repository
4.2. Locating Maven Artifacts at Build Time
Overview
Figure 4.1. How Maven Locates Artifacts at Build Time
Procedure for locating artifacts
- The first place that Maven looks for artifacts is in the local repository, which is the local cache where Maven stores all of the artifacts it has downloaded or found elsewhere. The default location of the local repository is the
.m2/repository/
directory under the user's home directory. - If an artifact is not available in the local repository, Maven has an ordered list repositories, from which it can try to download the artifact. This list of repositories can include both internal and remote repositories. Normally, any internal repositories (that is, repositories maintained in the local network) should appear at the head of the repository list, so that they are consulted first.
- If the artifact is not available from local or internal repositories, the next repositories to try are the remote repositories (which are accessible, for example, through the HTTP or the HTTPS protocols).
- When a Maven project is built using the
mvn install
command, the project itself is installed into the local repository.
Configuration
Local repository
- The location specified by the
localRepository
element in the~/.m2/settings.xml
file (UNIX and Linux) orC:\Documents and Settings\UserName\.m2\settings.xml
(Windows). - Otherwise, the location specified by the
localRepository
element in theM2_HOME/conf/settings.xml
file. - Otherwise, the default location is in the user's home directory,
~/.m2/repository/
(UNIX and Linux) orC:\Documents and Settings\UserName\.m2\repository
(Windows).
Internal repositories
settings.xml
file (which applies to all projects) or in a pom.xml
(which applies to that project only). Typically, the location of an internal repository is specified using either a file://
URL or a http://
URL (assuming you have set up a local Web server to serve up the artifacts) and you should generally ensure that internal repositories are listed before remote repositories. Otherwise, there is nothing special about an internal repository: it is just a repository that happens to be located in your internal network.
settings.xml
file, see the section called “Adding the Red Hat JBoss Fuse repository”.
Remote repositories
4.3. Locating Maven Artifacts at Run Time
Overview
Procedure for locating artifacts
Figure 4.2. How the Container Locates Artifacts at Run Time
- The container searches for artifacts in the system repository.This repository contains all of the artifacts provided with the JBoss Fuse installation. The system repository is located at
EsbInstallDir/system
. - If an artifact is not available in the system repository, the container searches any other configured default repositories.JBoss Fuse allows you to specify one or more repositories into which you can place artifacts. For example, you could use a shared folder as a default repository that provides an easy way to distribute bundles to remote machines. See the section called “Default repositories” for details on configuring the default repositories.
- If the artifact is not available in the default repositories, the container searches the Maven local repository.The default location of the local repository is the
.m2/repository/
directory under the user's home directory. See the section called “Local repository” for details on configuring the local repository. - If the artifact is not available in any of the local repositories, the container searches the remote repositories specified in the JBoss Fuse configuration.The remote repositories are specified by the
org.ops4j.pax.url.mvn.repositories
property in theorg.ops4j.pax.url.mvn.
PID. See the section called “Remote repositories” for details on configuring the remote repositories that the container will check.NoteIf an artifact is found in a remote repository, it is automatically downloaded and installed into the local repository.
Default repositories
org.ops4j.pax.url.mvn.defaultRepositories
in the org.ops4j.pax.url.mvn
PID. The property's initial setting is a single entry for the container's system repository as shown in Example 4.1, “Initial Setting for a Container's Default Repositories”.
Example 4.1. Initial Setting for a Container's Default Repositories
org.ops4j.pax.url.mvn.defaultRepositories=file:${karaf.home}/${karaf.default.repository}@snapshots
org.ops4j.pax.url.mvn.defaultRepositories
property is a comma-separated list, so you can specify multiple default repositories. You can specify the repository location using a URL with a file:
, http:
, or https:
scheme. You can optionally add the following suffixes to the URL:
@snapshots
—allow snapshot versions to be read from the repository@noreleases
—do not allow release versions to be read from the repository
Local repository
- Use the location specified by the
org.ops4j.pax.url.mvn.localRepository.localRepository
property in theorg.ops4j.pax.url.mvn
PID. - Otherwise, use the location specified by the
localRepository
element in thesettings.xml
file specified by theorg.ops4j.pax.url.mvn.localRepository.settings
property in theorg.ops4j.pax.url.mvn
PID. - Otherwise, use the location specified by the
localRepository
element in the.m2/settings.xml
file located under the user's home directory. - Otherwise, use the location specified by the
localRepository
element in theM2_HOME/conf/settings.xml
file. - Otherwise, the default location is
.m2/repository/
under the user's home directory.
Remote repositories
org.ops4j.pax.url.mvn.repositories
property in the org.ops4j.pax.url.mvn
PID. The repositories are specified as a comma-separated list as shown in Example 4.2, “Setting a Container's Remote Repositories”.
Example 4.2. Setting a Container's Remote Repositories
org.ops4j.pax.url.mvn.repositories= \ http://repo1.maven.org/maven2, \ http://repo.fusesource.com/maven2, \ http://repo.fusesource.com/maven2-snapshot@snapshots@noreleases, \ http://repo.fusesource.com/nexus/content/repositories/releases, \ http://repo.fusesource.com/nexus/content/repositories/snapshots@snapshots@noreleases, \ http://repository.apache.org/content/groups/snapshots-group@snapshots@noreleases, \ http://repository.ops4j.org/maven2, \ http://svn.apache.org/repos/asf/servicemix/m2-repo, \ http://repository.springsource.com/maven/bundles/release, \ http://repository.springsource.com/maven/bundles/external
@snapshots
—allow snapshot versions to be read from the repository@noreleases
—do not allow release versions to be read from the repository
4.4. Locating Artifacts in a Fabric
Overview
Procedure for locating artifacts
Figure 4.3. How Containers Locate Artifacts in a Fabric
- The container contacts the fabric Maven proxy to search for the artifacts.
- The proxy searches for the artifacts in the fabric's system repository.This repository contains all of the artifacts provided with the Red Hat JBoss Fuse installation.
- If the artifacts are not available in system repository, the proxy searches the remote repositories specified in its configuration.See chapter "Configuring a Fabric's Maven Proxy" in "Configuring and Running Red Hat JBoss Fuse" for details on how to configure a fabric's Maven proxy.
- The Maven proxy downloads the artifacts to the container.
Loading artifacts into the fabric's repository
- load the application's artifacts into the fabric's system repositoryMaven can upload artifacts directly to the fabric's system repository by adding a
repository
element defining the Maven proxy's repository to the POM'sdistributionManagement
element. Example 4.3, “Adding a Fabric Maven Proxy to a POM” shows a POM entry for connecting to a fabric's repository when one of the Fabric Servers is running on the local machine.Example 4.3. Adding a Fabric Maven Proxy to a POM
<distributionManagement> <repository> <id>fabric-maven-proxy</id> <name>FMC Maven Proxy</name> <url>http://username:password@localhost:8107/maven/upload/</url> </repository> </distributionManagement>
You will need to modify theurl
element to include the connection details for your environment:- The username and password are the credentials used access the Fabric Server to which you are trying to connect.
- The hostname,
localhost
in Example 4.3, “Adding a Fabric Maven Proxy to a POM”, is the address of the machine hosting the Fabric Server. - The port number,
8107
in Example 4.3, “Adding a Fabric Maven Proxy to a POM”, is the port number exposed by the Fabric Server.8107
is the default setting. - The path,
/maven/upload/
in Example 4.3, “Adding a Fabric Maven Proxy to a POM”, is the same for all Fabric Servers.
NoteThe Red Hat JBoss Fuse Plugins for Eclipse can also be used to upload artifacts to a fabric's system repository. Red Hat JBoss Fuse Plugins for Eclipse will also generate a profile for deploying the application to a container. - load the application's artifacts to a custom repository and configure the fabric's Maven proxy to include the custom repositoryThis is a good option if an application is going to be used in multiple fabrics because you will not need to install the application into a separate repository for each fabric used. All of the fabrics will use a single, centrally located version of the application.To configure the fabric's Maven proxy see chapter "Configuring a Fabric's Maven Proxy" in "Configuring and Running Red Hat JBoss Fuse".
4.5. Generating a Custom Offline Repository
Use case for a custom offline repository
features-maven-plugin
plug-in.
features-maven-plugin Maven plug-in
features-maven-plugin
plug-in from Apache Karaf is a utility that is used internally by the Apache Karaf developer community and the Red Hat JBoss Fuse development team to create distributions of the Apache Karaf OSGi container. Some of the goals of this plug-in are also useful for application developers, however, and this section explains how you can use the add-features-to-repo
goal to generate your own custom offline repository.
add-features-to-repo
goal of the features-maven-plugin
plug-in is supported.
Steps to generate a custom repository
Create a POM file
ProjectDir
—create a new directory, ProjectDir/custom-repo
to hold the Maven project. Using a text editor, create the project's POM file, pom.xml
, in the custom-repo
directory and add the following contents to the file:
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.acme.offline-repo</groupId> <artifactId>custom-repo</artifactId> <version>1.0.0</version> <name>Generate offline features repository</name> </project>
jar
), because no package will be generated for this project.
Add the features-maven-plugin
pom.xml
and add the features-maven-plugin
as shown (where the build
element is inserted as a child of the project
element):
<project ...> ... <build> <plugins> <plugin> <groupId>org.apache.karaf.tooling</groupId> <artifactId>features-maven-plugin</artifactId> <version>2.2.1</version> <executions> <execution> <id>add-features-to-repo</id> <phase>generate-resources</phase> <goals> <goal>add-features-to-repo</goal> </goals> <configuration> <descriptors> <!-- List the URLs of required feature repositories here --> </descriptors> <features> <!-- List features you want in the offline repo here --> </features> <repository>target/features-repo</repository> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
Specify the features to download
camel-jms
feature and the camel-quartz
feature available in offline mode. List all of the features you want to download and store in the offline repository in the features
element, which is a child of the configuration
element of the features-maven-plugin
.
camel-jms
and camel-quartz
features available offline, add the following features
element as a child of the feature-maven-plugin
's configuration
element:
<features> <feature>camel-jms</feature> <feature>camel-quartz</feature> </features>
Specify the feature repositories
etc/org.apache.karaf.features.cfg
configuration file and look at the featuresRepository
setting, which is a comma-separated list of feature repositories, like the following:
... # # Comma separated list of feature repositories to register by default # featuresRepositories=mvn:org.apache.karaf/apache-karaf/2.1.3-fuse-00-00/xml/features, mvn:org.apache.servicemix.nmr/apache-servicemix-nmr/1.4.0-fuse-00-00/xml/features,mvn :org.apache.servicemix/apache-servicemix/4.3.1-fuse-00-00/xml/features,mvn:org.apache .camel.karaf/apache-camel/2.6.0-fuse-00-00/xml/features,mvn:org.apache.servicemix/ode -jbi-karaf/1.3.4/xml/features,mvn:org.apache.activemq/activemq-karaf/5.4.2-fuse-01-00 /xml/features ...
features-maven-plugin
in your POM file. Open the project's pom.xml
file and add a descriptor
element (as a child of the descriptors
element) for each of the standard feature repositories. For example, given the preceding value of the featuresRepositories
list, you would define the features-maven-plugin
descriptors list in pom.xml
as follows:
<descriptors> <!-- List taken from featuresRepositories in etc/org.apache.karaf.features.cfg --> <descriptor>mvn:org.apache.karaf/apache-karaf/2.1.3-fuse-00-00/xml/features</descriptor> <descriptor>mvn:org.apache.servicemix.nmr/apache-servicemix-nmr/1.4.0-fuse-00-00/xml/features</descriptor> <descriptor>mvn:org.apache.servicemix/apache-servicemix/4.3.1-fuse-00-00/xml/features</descriptor> <descriptor>mvn:org.apache.camel.karaf/apache-camel/2.6.0-fuse-00-00/xml/features</descriptor> <descriptor>mvn:org.apache.servicemix/ode-jbi-karaf/1.3.4/xml/features</descriptor> <descriptor>mvn:org.apache.activemq/activemq-karaf/5.4.2-fuse-01-00/xml/features</descriptor> </descriptors>
Specify the Red Hat JBoss Fuse system repository
EsbInstallDir/system
, to the list of repositories in the pom.xml
file. This is necessary for two reasons: first of all, it saves you from downloading Maven artificats that are already locally available from your JBoss Fuse installation; and secondly, some of the artifacts in the system repository might not be available from any of the other repositories.
pom.xml
and add the following repositories
element as a child of the project
element, customizing the file URL to point at your local system repository:
<project ...>
...
<repositories>
<repository>
<id>esb.system.repo</id>
<name>Red Hat JBoss Fuse internal system repo</name>
<url>file:///E:/Programs/FUSE/apache-servicemix-6.1.0.redhat-379/system</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
...
</project>
Specify the remote repositories
etc/org.ops4j.pax.url.mvn.cfg
configuration file and look at the org.ops4j.pax.url.mvn.repositories
setting, which is a comma-separated list of URLs like the following:
org.ops4j.pax.url.mvn.repositories= \ http://repo1.maven.org/maven2, \ http://repo.fusesource.com/maven2, \ http://repo.fusesource.com/maven2-snapshot@snapshots@noreleases, \ http://repo.fusesource.com/nexus/content/repositories/releases, \ http://repo.fusesource.com/nexus/content/repositories/snapshots@snapshots@noreleases, \ http://repository.apache.org/content/groups/snapshots-group@snapshots@noreleases, \ http://repository.ops4j.org/maven2, \ http://svn.apache.org/repos/asf/servicemix/m2-repo, \ http://repository.springsource.com/maven/bundles/release, \ http://repository.springsource.com/maven/bundles/external
repository
element, which is then inserted as a child element of the respositories
element in the project's pom.xml
file. The preceding repository URLs have slightly different formats and must be converted as follows:
RepoURL
- The value of the repository URL,
RepoURL
, is inserted directly into theurl
child element of therepository
element. For example, thehttp://repo1.maven.org/maven2
repository URL translates to the followingrepository
element:<repository> <!-- 'id' can be whatever you like --> <id>repo1.maven.org</id> <!-- 'name' can be whatever you like --> <name>Maven central</name> <url>http://repo1.maven.org/maven2</url> <snapshots> <enabled>false</enabled> </snapshots> <releases> <enabled>true</enabled> </releases> </repository>
RepoURL@snapshots
- The
@snapshots
suffix indicates that downloading snapshots should be enabled for this repository. When specifying the value of theurl
element, remove the@snapshots
suffix from the URL. Change thesnapshots/enabled
flag totrue
, as shown in the following example:<repository> <id>IdOfRepo</id> <name>LongNameOfRepo</name> <url>RepoURL</url> <snapshots> <enabled>true</enabled> </snapshots> <releases> <enabled>true</enabled> </releases> </repository>
RepoURL@snapshots@noreleases
- The combination of the
@snapshots
suffix and the@noreleases
suffix indicates that downloading snapshots should be enabled and downloading releases should be disabled for this repository. When specifying the value of theurl
element, remove both suffixes from the URL. Change thesnapshots/enabled
flag totrue
and change thereleases/enabled
flag tofalse
, as shown in the following example:<repository> <id>IdOfRepo</id> <name>LongNameOfRepo</name> <url>RepoURL</url> <snapshots> <enabled>true</enabled> </snapshots> <releases> <enabled>false</enabled> </releases> </repository>
Generate the offline repository
ProjectDir/custom-repo
, and enter the following Maven command:
mvn generate-resources
ProjectDir/custom-repo/target/features-repo
Install the offline repository
etc/org.ops4j.pax.url.mvn.cfg
file and append the offline repository directory to the list of default repositories, as follows:
org.ops4j.pax.url.mvn.defaultRepositories=file:${karaf.home}/${karaf.default.repository}@snapshots,file:ProjectDir/custom-repo/target/features-repo@snapshots
@snapshots
suffix can be added to the offline repository URL, if there is a possibility that some of the artifacts in it are snapshot versions.
Part II. OSGi Bundle Deployment Model
Abstract
Chapter 5. Introduction to OSGi
Abstract
5.1. Red Hat JBoss Fuse
Overview
- Technology layer—includes technologies such as JBI, JAX-WS, JAX-RS, JMS, Spring, and JEE
- the section called “Red Hat JBoss Fuse” —a wrapper layer around the OSGi container implementation, which provides support for deploying the OSGi container as a runtime server. Runtime features provided by the Red Hat JBoss Fuse include hot deployment, management, and administration features.
- OSGi framework —implements OSGi functionality, including managing dependencies and bundle lifecycles
Red Hat JBoss Fuse
Figure 5.1. Red Hat JBoss Fuse Architecture
- Console— an extensible Gogo console manages services, installs and manages applications and libraries, and interacts with the Red Hat JBoss Fuse runtime. It provides console commands to administer instances of Red Hat JBoss Fuse. See the "Console Reference".
- Logging—a powerful, unified logging subsystem provides console commands to display, view and change log levels. See "Configuring and Running Red Hat JBoss Fuse".
- Deployment—supports both manual deployment of OSGi bundles using the
osgi:install
andosgi:start
commands and hot deployment of applications. When a JAR file, WAR file, FAB file, or OSGi bundle is copied into the hot deployment folder InstallDir/deploy
, it's automatically installed on-the-fly inside the Red Hat JBoss Fuse runtime. When you update or delete these files or bundles, the changes are made automatically. See Section 7.1, “Hot Deployment”. - Fuse Application Bundle (FAB)—FABs automate the creation and maintenance of OSGi bundles, freeing application developers to focus on building their applications. See Part III, “The Fuse Application Bundle Deployment Model”.
- Provisioning—provides multiple mechanisms for installing applications and libraries. See Chapter 8, Deploying Features.
- Configuration—the properties files stored in the InstallDir
/etc
folder are continuously monitored, and changes to them are automatically propagated to the relevant services at configurable intervals. - Spring DM—simplifies building Spring applications that run in an OSGi framework. When a Spring configuration file is copied to the hot deployment folder, Red Hat JBoss Fuse generates and OSGi bundle on-the-fly and instantiates the Spring application context.
- Blueprint—is essentially a standardized version of Spring DM. It is a dependency injection framework that simplifies interaction with the OSGi container—for example, providing standard XML elements to import and export OSGi services.
5.2. OSGi Framework
Overview
OSGi architecture
- Bundles — Logical modules that make up an application. See Section 5.4, “OSGi Bundles”.
- Service layer — Provides communication among modules and their contained components. This layer is tightly integrated with the lifecycle layer. See Section 5.3, “OSGi Services”.
- Lifecycle layer — Provides access to the underlying OSGi framework. This layer handles the lifecycle of individual bundles so you can manage your application dynamically, including starting and stopping bundles.
- Module layer — Provides an API to manage bundle packaging, dependency resolution, and class loading.
- Execution environment — A configuration of a JVM. This environment uses profiles that define the environment in which bundles can work.
- Security layer — Optional layer based on Java 2 security, with additional constraints and enhancements.
5.3. OSGi Services
Overview
OSGi service registry
- Service providers register services with the framework to be used by other bundles
- Service requesters find services and bind to service providers
Event notification
- Register services
- Search for services
- Receive notifications when their registration state changes
Service invocation model
OSGi framework services
- Package Admin service—allows a management agent to define the policy for managing Java package sharing by examining the status of the shared packages. It also allows the management agent to refresh packages and to stop and restart bundles as required. This service enables the management agent to make decisions regarding any shared packages when an exporting bundle is uninstalled or updated.The service also provides methods to refresh exported packages that were removed or updated since the last refresh, and to explicitly resolve specific bundles. This service can also trace dependencies between bundles at runtime, allowing you to see what bundles might be affected by upgrading.
- Start Level service—enables a management agent to control the starting and stopping order of bundles. The service assigns each bundle a start level. The management agent can modify the start level of bundles and set the active start level of the framework, which starts and stops the appropriate bundles. Only bundles that have a start level less than, or equal to, this active start level can be active.
- URL Handlers service—dynamically extends the Java runtime with URL schemes and content handlers enabling any component to provide additional URL handlers.
- Permission Admin service—enables the OSGi framework management agent to administer the permissions of a specific bundle and to provide defaults for all bundles. A bundle can have a single set of permissions that are used to verify that it is authorized to execute privileged code. You can dynamically manipulate permissions by changing policies on the fly and by adding new policies for newly installed components. Policy files are used to control what bundles can do.
- Conditional Permission Admin service—extends the Permission Admin service with permissions that can apply when certain conditions are either true or false at the time the permission is checked. These conditions determine the selection of the bundles to which the permissions apply. Permissions are activated immediately after they are set.
OSGi Compendium services
5.4. OSGi Bundles
Overview
Class Loading in OSGi
- Sharing classes directly between bundles. There is no requirement to promote JARs to a parent class-loader.
- You can deploy different versions of the same class at the same time, with no conflict.
Chapter 6. Building an OSGi Bundle
Abstract
6.1. Generating a Bundle Project
Generating bundle projects with Maven archetypes
Apache CXF code-first archetype
:
ArtifactId:
Version, enter the following command:
mvn archetype:generate -DarchetypeGroupId=org.apache.servicemix.tooling -DarchetypeArtifactId=servicemix-cxf-code-first-osgi-bundle -DarchetypeVersion=2013.01.0.redhat-610379 -DgroupId=GroupId -DartifactId=ArtifactId -Dversion=Version
mvn
command are shown on separate lines purely for the sake of readability. When you are entering the command at a command prompt, you must ensure that all of the parameters are on the same line.
Apache CXF WSDL-first archetype
:
ArtifactId:
Version, enter the following command:
mvn archetype:generate -DarchetypeGroupId=org.apache.servicemix.tooling -DarchetypeArtifactId=servicemix-cxf-wsdl-first-osgi-bundle -DarchetypeVersion=2013.01.0.redhat-610379 -DgroupId=GroupId -DartifactId=ArtifactId -Dversion=Version
Apache Camel archetype
:
ArtifactId:
Version, enter the following command:
mvn archetype:generate -DarchetypeGroupId=org.apache.servicemix.tooling -DarchetypeArtifactId=servicemix-camel-osgi-bundle -DarchetypeVersion=2013.01.0.redhat-610379 -DgroupId=GroupId -DartifactId=ArtifactId -Dversion=Version
Building the bundle
pom.xml
file), and enter the following Maven command:
mvn install
/target
directory, and then to install the generated JAR in the local Maven repository.
6.2. Modifying an Existing Maven Project
Overview
Change the package type to bundle
bundle
in your project's pom.xml
file. Change the contents of the packaging
element to bundle
, as shown in the following example:
<project ... >
...
<packaging>bundle</packaging>
...
</project>
maven-bundle-plugin
, to perform packaging for this project. This setting on its own, however, has no effect until you explicitly add the bundle plug-in to your POM.
Add the bundle plug-in to your POM
plugin
element into the project/build/plugins
section of your project's pom.xml
file:
<project ... > ... <build> <defaultGoal>install</defaultGoal> <plugins> ... <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>2.3.7</version> <extensions>true</extensions> <configuration> <instructions> <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName> <Import-Package>*</Import-Package> </instructions> </configuration> </plugin> </plugins> </build> ... </project>
instructions
element.
Customize the bundle plug-in
Customize the JDK compiler version
JAVA_HOME
and the PATH
environment variables to the correct values for your JDK, you must also modify the POM file.
maven-compiler-plugin
plug-in settings to your POM (if they are not already present):
<project ... > ... <build> <defaultGoal>install</defaultGoal> <plugins> ... <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> ... </project>
6.3. Packaging a Web Service in a Bundle
Overview
META-INF/spring
).
Modifying the POM file to generate a bundle
bundle
; and add the Maven bundle plug-in to your POM. For details, see Section 6.1, “Generating a Bundle Project”.
Required bundle
org.apache.cxf.bundle
. The dependency on this bundle can conveniently be expressed by adding the Require-Bundle
element to the Maven bundle plug-in's instructions, as highlighted in the following sample POM:
<project ... >
...
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
...
<Require-Bundle>org.apache.cxf.bundle</Require-Bundle>
...
</instructions>
</configuration>
</plugin>
</plugins>
</build>
...
</project>
Mandatory import packages
javax.jws javax.wsdl javax.xml.bind javax.xml.bind.annotation javax.xml.namespace javax.xml.ws META-INF.cxf META-INF.cxf.osgi org.apache.cxf.bus org.apache.cxf.bus.spring org.apache.cxf.bus.resource org.apache.cxf.configuration.spring org.apache.cxf.resource org.apache.cxf.jaxws org.springframework.beans.factory.config
Sample Maven bundle plug-in instructions
Import-Package
element. Note the appearance of the wildcard, *
, as the last element of the list. The wildcard ensures that the Java source files from the current bundle are scanned to discover what additional packages need to be imported.
Example 6.1. Configuration of Mandatory Import Packages
<project ... > ... <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> ... <Import-Package> javax.jws, javax.wsdl, javax.xml.bind, javax.xml.bind.annotation, javax.xml.namespace, javax.xml.ws, META-INF.cxf, META-INF.cxf.osgi, org.apache.cxf.bus, org.apache.cxf.bus.spring, org.apache.cxf.bus.resource, org.apache.cxf.configuration.spring, org.apache.cxf.resource, org.apache.cxf.jaxws, org.springframework.beans.factory.config, * </Import-Package> ... </instructions> </configuration> </plugin> </plugins> </build> ... </project>
Add a code generation plug-in
- Java-first approach—use the
cxf-java2ws-plugin
plug-in. - WSDL-first approach—use the
cxf-codegen-plugin
plug-in.
OSGi configuration properties
6.4. Configuring the Bundle Plug-In
Overview
instructions
element.
Configuration properties
Setting a bundle's symbolic name
+ "." +
artifactId, with the following exceptions:
- If groupId has only one section (no dots), the first package name with classes is returned.For example, if the group Id is
commons-logging:commons-logging
, the bundle's symbolic name isorg.apache.commons.logging
. - If artifactId is equal to the last section of groupId, then groupId is used.For example, if the POM specifies the group ID and artifact ID as
org.apache.maven:maven
, the bundle's symbolic name isorg.apache.maven
. - If artifactId starts with the last section of groupId, that portion is removed.For example, if the POM specifies the group ID and artifact ID as
org.apache.maven:maven-core
, the bundle's symbolic name isorg.apache.maven.core
.
Bundle-SymbolicName
child in the plug-in's instructions
element, as shown in Example 6.2.
Example 6.2. Setting a bundle's symbolic name
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
...
</instructions>
</configuration>
</plugin>
Setting a bundle's name
${project.name}
.
Bundle-Name
child to the plug-in's instructions
element, as shown in Example 6.3.
Example 6.3. Setting a bundle's name
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Bundle-Name>JoeFred</Bundle-Name>
...
</instructions>
</configuration>
</plugin>
Setting a bundle's version
${project.version}
. Any dashes (-
) are replaced with dots (.
) and the number is padded up to four digits. For example, 4.2-SNAPSHOT
becomes 4.2.0.SNAPSHOT
.
Bundle-Version
child to the plug-in's instructions
element, as shown in Example 6.4.
Example 6.4. Setting a bundle's version
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Bundle-Version>1.0.3.1</Bundle-Version>
...
</instructions>
</configuration>
</plugin>
Specifying exported packages
Export-Package
list is populated by all of the packages in your local Java source code (under src/main/java
), except for the deault package, .
, and any packages containing .impl
or .internal
.
Private-Package
element in your plug-in configuration and you do not specify a list of packages to export, the default behavior includes only the packages listed in the Private-Package
element in the bundle. No packages are exported.
Export-Package
child to the plug-in's instructions
element.
Export-Package
element specifies a list of packages that are to be included in the bundle and that are to be exported. The package names can be specified using the *
wildcard symbol. For example, the entry com.fuse.demo.*
includes all packages on the project's classpath that start with com.fuse.demo.
!
. For example, the entry !com.fuse.demo.private
excludes the package com.fuse.demo.private.
!com.fuse.demo.private,com.fuse.demo.*
Specifying private packages
Private-Package
instruction to the bundle plug-in configuration. By default, if you do not specify a Private-Package
instruction, all packages in your local Java source are included in the bundle.
Private-Package
element and the Export-Package
element, the Export-Package
element takes precedence. The package is added to the bundle and exported.
Private-Package
element works similarly to the Export-Package
element in that you specify a list of packages to be included in the bundle. The bundle plug-in uses the list to find all classes on the project's classpath that are to be included in the bundle. These packages are packaged in the bundle, but not exported (unless they are also selected by the Export-Package
instruction).
Example 6.5. Including a private package in a bundle
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Private-Package>org.apache.cxf.wsdlFirst.impl</Private-Package>
...
</instructions>
</configuration>
</plugin>
Specifying imported packages
Import-Package
property with a list of all the packages referred to by the contents of the bundle.
Import-Package
child to the plug-in's instructions
element. The syntax for the package list is the same as for the Export-Package
element and the Private-Package
element.
Import-Package
element, the plug-in does not automatically scan the bundle's contents to determine if there are any required imports. To ensure that the contents of the bundle are scanned, you must place an *
as the last entry in the package list.
Example 6.6. Specifying the packages imported by a bundle
<plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <configuration> <instructions> <Import-Package>javax.jws, javax.wsdl, org.apache.cxf.bus, org.apache.cxf.bus.spring, org.apache.cxf.bus.resource, org.apache.cxf.configuration.spring, org.apache.cxf.resource, org.springframework.beans.factory.config, * </Import-Package> ... </instructions> </configuration> </plugin>
More information
Chapter 7. Deploying an OSGi Bundle
Abstract
7.1. Hot Deployment
Hot deploy directory
InstallDir/deploy
directory and hot deploys everything in this directory. Each time a JAR file is copied to this directory, it is installed in the runtime and also started. You can subsequently update or delete the JARs, and the changes are handled automatically.
/target/foo-1.0-SNAPSHOT.jar
, you can deploy this bundle by copying it to the InstallDir/deploy
directory as follows (assuming you are working on a UNIX platform):
% cp ProjectDir/target/foo-1.0-SNAPSHOT.jar InstallDir/deploy
7.2. Manual Deployment
Overview
Installing a bundle
osgi:install
command to install one or more bundles in the OSGi container. This command has the following syntax:
osgi:install [-s] [--start] [--help] UrlList
-s
- Start the bundle after installing.
--start
- Same as
-s
. --help
- Show and explain the command syntax.
/target/foo-1.0-SNAPSHOT.jar
, enter the following command at the Karaf console prompt:
osgi:install -s file:ProjectDir/target/foo-1.0-SNAPSHOT.jar
file
URL in this command. See Section A.1, “File URL Handler” for details.
Uninstalling a bundle
osgi:list
command. You can then uninstall the bundle using the osgi:uninstall
command (which takes the bundle ID as its argument).
A Camel OSGi Service Unit
, entering osgi:list
at the console prompt might produce output like the following:
... [ 175] [Active ] [ ] [Started] [ 60] ServiceMix :: FTP (2009.02.0.psc-01-00RC1) [ 181] [Resolved ] [ ] [ ] [ 60] A Camel OSGi Service Unit (1.0.0.SNAPSHOT)
181
, by entering the following console command:
osgi:uninstall 181
URL schemes for locating bundles
osgi:install
command, you can use any of the URL schemes supported by Red Hat JBoss Fuse, which includes the following scheme types:
7.3. Lifecycle Management
Bundle lifecycle states
- Installed — All bundles start in the installed state. Bundles in the installed state are waiting for all of their dependencies to be resolved, and once they are resolved, bundles move to the resolved state.
- Resolved — Bundles are moved to the resolved state when the following conditions are met:
- The runtime environment meets or exceeds the environment specified by the bundle.
- All of the packages imported by the bundle are exposed by bundles that are either in the resolved state or that can be moved into the resolved state at the same time as the current bundle.
- All of the required bundles are either in the resolved state or they can be resolved at the same time as the current bundle.
ImportantAll of an application's bundles must be in the resolved state before the application can be started.If any of the above conditions ceases to be satisfied, the bundle is moved back into the installed state. For example, this can happen when a bundle that contains an imported package is removed from the container. - Starting — The starting state is a transitory state between the resolved state and the active state. When a bundle is started, the container must create the resources for the bundle. The container also calls the
start()
method of the bundle's bundle activator when one is provided. - Active — Bundles in the active state are available to do work. What a bundle does in the active state depends on the contents of the bundle. For example, a bundle containing a JAX-WS service provider indicates that the service is available to accept requests.
- Stopping — The stopping state is a transitory state between the active state and the resolved state. When a bundle is stopped, the container must clean up the resources for the bundle. The container also calls the
stop()
method of the bundle's bundle activator when one is provided. - Uninstalled — When a bundle is uninstalled it is moved from the resolved state to the uninstalled state. A bundle in this state cannot be transitioned back into the resolved state or any other state. It must be explicitly re-installed.
Installing and resolving bundles
osgi:install
command (without the -s
flag), the kernel installs the specified bundle and attempts to put it into the resolved state. If the resolution of the bundle fails for some reason (for example, if one of its dependencies is unsatisfied), the kernel leaves the bundle in the installed state.
osgi:resolve
command, as follows:
osgi:resolve 181
181
, in this example) is the ID of the bundle you want to resolve.
Starting and stopping bundles
osgi:start
command. For example, to start the bundles with IDs, 181, 185, and 186, enter the following console command:
osgi:start 181 185 186
osgi:stop
command. For example, to stop the bundles with IDs, 181, 185, and 186, enter the following console command:
osgi:stop 181 185 186
osgi:restart
command. For example, to restart the bundles with IDs, 181, 185, and 186, enter the following console command:
osgi:restart 181 185 186
Bundle start level
1
, are started first and bundles belonging to the kernel tend to have lower start levels, because they provide the prerequisites for running most other bundles.
Specifying a bundle's start level
osgi:bundle-level
command to set the start level of a particular bundle. For example, to configure the bundle with ID, 181
, to have a start level of 70
, enter the following console command:
osgi:bundle-level 181 70
System start level
osgi:start-level
in the console, as follows:
JBossFuse:karaf@root> osgi:start-level Level 100
osgi:start-level
command, as follows:
osgi:start-level 200
7.4. Troubleshooting Dependencies
Missing dependencies
ClassNotFound
error is logged (to view the log, use the log:display
console command or look at the log file in the InstallDir/data/log
directory).
Import-Package
header is incomplete.
Required features or bundles are not installed
Import-Package header is incomplete
ClassNotFound
error, this means that the Import-Package
header in your bundle's MANIFEST.MF
file is incomplete. The maven-bundle-plugin
(see Section 6.2, “Modifying an Existing Maven Project”) is a great help when it comes to generating your bundle's Import-Package
header, but you should note the following points:
- Make sure that you include the wildcard,
*
, in theImport-Package
element of the Maven bundle plug-in configuration. The wildcard directs the plug-in to scan your Java source code and automatically generates a list of package dependencies. - The Maven bundle plug-in is not able to figure out dynamic dependencies. For example, if your Java code explicitly calls a class loader to load a class dynamically, the bundle plug-in does not take this into account and the required Java package will not be listed in the generated
Import-Package
header. - If you define a Spring XML file (for example, in the
META-INF/spring
directory), the Maven bundle plug-in is not able to figure out dependencies arising from the Spring XML configuration. Any dependencies arising from Spring XML must be added manually to the bundle plug-in'sImport-Package
element. - If you define a blueprint XML file (for example, in the
OSGI-INF/blueprint
directory), any dependencies arising from the blueprint XML file are automatically resolved at run time. This is an important advantage of blueprint over Spring.
How to track down missing dependencies
- Perform a quick check to ensure that all of the required bundles and features are actually installed in the OSGi container. You can use
osgi:list
to check which bundles are installed andfeatures:list
to check which features are installed. - Install (but do not start) your bundle, using the
osgi:install
console command. For example:JBossFuse:karaf@root> osgi:install MyBundleURL
- Use the
dev:dynamic-import
console command to enable dynamic imports on the bundle you just installed. For example, if the bundle ID of your bundle is 218, you would enable dynamic imports on this bundle by entering the following command:JBossFuse:karaf@root> dev:dynamic-import 218
This setting allows OSGi to resolve dependencies using any of the bundles already installed in the container, effectively bypassing the usual dependency resolution mechanism (based on theImport-Package
header). This is not recommemded for normal deployment, because it bypasses version checks: you could easily pick up the wrong version of a package, causing your application to malfunction. - You should now be able to resolve your bundle. For example, if your bundle ID is 218, enter the followng console command:
JBossFuse:karaf@root> osgi:resolve 218
- Assuming your bundle is now resolved (check the bundle status using
osgi:list
), you can get a complete list of all the packages wired to your bundle using thepackage:imports
command. For example, if your bundle ID is 218, enter the following console command:JBossFuse:karaf@root> package:imports 218
You should see a list of dependent packages in the console window (where the package names are highlighted in this example):Spring Beans (67): org.springframework.beans.factory.xml; version=3.0.5.RELEASE Apache ServiceMix :: Specs :: JAXB API 2.2 (87): javax.xml.bind.annotation; version=2.2.1 Apache ServiceMix :: Specs :: JAXB API 2.2 (87): javax.xml.bind; version=2.2.1 Web Services Metadata 2.0 (104): javax.jws; version=2.0.0 Apache ServiceMix :: Specs :: JAXWS API 2.2 (105): javax.xml.ws.handler; version=2.2.0 Apache ServiceMix :: Specs :: JAXWS API 2.2 (105): javax.xml.ws; version=2.2.0 Apache CXF Bundle Jar (125): org.apache.cxf.helpers; version=2.4.2.fuse-00-08 Apache CXF Bundle Jar (125): org.apache.cxf.transport.jms.wsdl11; version=2.4.2.fuse-00-08 ...
- Unpack your bundle JAR file and look at the packages listed under the
Import-Package
header in theMETA-INF/MANIFEST.MF
file. Compare this list with the list of packages found in the previous step. Now, compile a list of the packages that are missing from the manifest'sImport-Package
header and add these package names to theImport-Package
element of the Maven bundle plug-in configuration in your project's POM file. - To cancel the dynamic import option, you must uninstall the old bundle from the OSGi container. For example, if your bundle ID is 218, enter the following command:
JBossFuse:karaf@root> osgi:uninstall 218
- You can now rebuild your bundle with the updated list of imported packages and test it in the OSGi container.
Chapter 8. Deploying Features
Abstract
8.1. Creating a Feature
Overview
feature
element to a special kind of XML file, known as a feature repository. To create a feature, perform the following steps:
Create a custom feature repository
C:\Projects\features.xml
—and use your favorite text editor to add the following lines to it:
<?xml version="1.0" encoding="UTF-8"?> <features name="CustomRepository"> </features>
name
attribute.
Add a feature to the custom feature repository
feature
element as a child of the root features
element. You must give the feature a name and you can list any number of bundles belonging to the feature, by inserting bundle
child elements. For example, to add a feature named example-camel-bundle
containing the single bundle, C:\Projects\camel-bundle\target\camel-bundle-1.0-SNAPSHOT.jar
, add a feature
element as follows:
<?xml version="1.0" encoding="UTF-8"?>
<features name="MyFeaturesRepo">
<feature name="example-camel-bundle">
<bundle>file:C:/Projects/camel-bundle/target/camel-bundle-1.0-SNAPSHOT.jar</bundle>
</feature>
</features>
bundle
element can be any valid URL, giving the location of a bundle (see Appendix A, URL Handlers). You can optionally specify a version
attribute on the feature element, to assign a non-zero version to the feature (you can then specify the version as an optional argument to the features:install
command).
JBossFuse:karaf@root> features:refreshUrl JBossFuse:karaf@root> features:list ... [uninstalled] [0.0.0 ] example-camel-bundle MyFeaturesRepo ...
features:list
command typically produces a rather long listing of features, but you should be able to find the entry for your new feature (in this case, example-camel-bundle
) by scrolling back through the listing. The features:refreshUrl
command forces the kernel to reread all the feature repositories: if you did not issue this command, the kernel would not be aware of any recent changes that you made to any of the repositories (in particular, the new feature would not appear in the listing).
grep
for the example-camel-bundle
feature as follows:
JBossFuse:karaf@root> features:list | grep example-camel-bundle [uninstalled] [0.0.0 ] example-camel-bundle MyFeaturesRepo
grep
command (a standard UNIX pattern matching utility) is built into the shell, so this command also works on Windows platforms.
Add the local repository URL to the features service
features:addUrl
console command. For example, to make the contents of the repository, C:\Projects\features.xml
, available to the kernel, you would enter the following console command:
features:addUrl file:C:/Projects/features.xml
features:addUrl
can be specified using any of the supported URL formats (see Appendix A, URL Handlers).
features:listUrl
console command, to get a complete listing of all registered feature repository URLs, as follows:
JBossFuse:karaf@root> features:listUrl mvn:org.apache.servicemix.nmr/apache-servicemix-nmr/1.1.0-fuse-01-00/xml/features mvn:org.apache.servicemix.camel/features/6.1.0.redhat-379/xml/features file:C:/Projects/features.xml mvn:org.apache.ode/ode-jbi-karaf/1.3.3-fuse-01-00/xml/features mvn:org.apache.felix.karaf/apache-felix-karaf/1.2.0-fuse-01-00/xml/features mvn:org.apache.servicemix/apache-servicemix/6.1.0.redhat-379/xml/features
Add dependent features to the feature
feature
elements as children of the original feature
element. Each child feature
element contains the name of a feature on which the current feature depends. When you deploy a feature with dependent features, the dependency mechanism checks whether or not the dependent features are installed in the container. If not, the dependency mechanism automatically installs the missing dependencies (and any recursive dependencies).
example-camel-bundle
, you can specify explicitly which standard Apache Camel features it depends on. This has the advantage that the application could now be successfully deployed and run, even if the OSGi container does not have the required features pre-deployed. For example, you can define the example-camel-bundle
feature with Apache Camel dependencies as follows:
<?xml version="1.0" encoding="UTF-8"?>
<features name="MyFeaturesRepo">
<feature name="example-camel-bundle">
<bundle>file:C:/Projects/camel-bundle/target/camel-bundle-1.0-SNAPSHOT.jar</bundle>
<feature version="6.1.0.redhat-379">camel-core</feature>
<feature version="6.1.0.redhat-379">camel-spring-osgi</feature>
<feature version="6.1.0.redhat-379">servicemix-camel</feature>
</feature>
</features>
version
attribute is optional. When present, it enables you to select the specified version of the feature.
Add OSGi configurations to the feature
config
child element of your feature definition. For example, to specify that the prefix
property has the value, MyTransform
, add the following config
child element to your feature's configuration:
<?xml version="1.0" encoding="UTF-8"?>
<features name="MyFeaturesRepo">
<feature name="example-camel-bundle">
<config name="org.fusesource.fuseesb.example">
prefix=MyTransform
</config>
</feature>
</features>
name
attribute of the config
element specifies the persistent ID of the property settings (where the persistent ID acts effectively as a name scope for the property names). The content of the config
element is parsed in the same way as a Java properties file.
config
element can optionally be overriden by the settings in the Java properties file located in the InstallDir/etc
directory, which is named after the persistent ID, as follows:
InstallDir/etc/org.fusesource.fuseesb.example.cfg
<?xml version="1.0" encoding="UTF-8"?> <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"> <!-- osgi blueprint property placeholder --> <cm:property-placeholder id="placeholder" persistent-id="org.fusesource.fuseesb.example"> <cm:default-properties> <cm:property name="prefix" value="DefaultValue"/> </cm:default-properties> </cm:property-placeholder> <bean id="myTransform" class="org.fusesource.fuseesb.example.MyTransform"> <property name="prefix" value="${prefix}"/> </bean> </blueprint>
example-camel-bundle
bundle, the property reference, ${prefix}
, is replaced by the value, MyTransform
, which is specified by the config
element in the feature repository.
Automatically deploy an OSGi configuration
configfile
element to a feature, you can ensure that an OSGi configuration file gets added to the InstallDir/etc
directory at the same time that the feature is installed. This means that you can conveniently install a feature and its associated configuration at the same time.
org.fusesource.fuseesb.example.cfg
configuration file is archived in a Maven repository at mvn:org.fusesource.fuseesb.example/configadmin/1.0/cfg
, you could deploy the configuration file by adding the following element to the feature:
<configfile finalname="etc/org.fusesource.fuseesb.example.cfg"> mvn:org.fusesource.fuseesb.example/configadmin/1.0/cfg </configfile>
8.2. Deploying a Feature
Overview
- Install at the console, using
features:install
. - Use hot deployment.
- Modify the boot configuration (first boot only!).
Installing at the console
features:install
console command. For example, to deploy the example-camel-bundle
feature, enter the following pair of console commands:
JBossFuse:karaf@root> features:refreshUrl JBossFuse:karaf@root> features:install example-camel-bundle
features:refreshUrl
command before calling features:install
, in case any recent changes were made to the features in the feature repository which the kernel has not picked up yet. The features:install
command takes the feature name as its argument (and, optionally, the feature version as its second argument).
Uninstalling at the console
features:uninstall
command as follows:
JBossFuse:karaf@root> features:uninstall example-camel-bundle
features:list
, but its status will now be flagged as [uninstalled]
.
Hot deployment
InstallDir/deploy
directory.
example-camel-bundle
feature as follows:
<?xml version="1.0" encoding="UTF-8"?> <features name="CustomDescriptor"> <repository>RepositoryURL</repository> <feature name="hot-example-camel-bundle"> <feature>example-camel-bundle</feature> </feature> </features>
hot-example-camel-bundle
, is just a reference to the existing feature, example-camel-bundle
.
Adding a feature to the boot configuration
/etc/org.apache.felix.karaf.features.cfg
, in your install directory contains the following settings:
... # # Comma separated list of features repositories to register by default # featuresRepositories=mvn:org.apache.felix.karaf/apache-felix-karaf/1.1.0.3-fuse-SNAPSHOT/xml/features, mvn:org.apache.servicemix.nmr/apache-servicemix-nmr/1.1.0-fuse-SNAPSHOT/xml/features, mvn:org.apache.servicemix/apache-servicemix/4.2.0-fuse-SNAPSHOT/xml/features, mvn:org.apache.camel.karaf/apache-camel/2.x-fuse-SNAPSHOT/xml/features, mvn:org.apache.ode/ode-jbi-karaf/1.3.3-fuse-SNAPSHOT/xml/features # # Comma separated list of features to install at startup # # Will put these back in when we decide to include these components # servicemix-smpp,servicemix-snmp,servicemix-vfs, featuresBoot=activemq,activemq-broker,camel,jbi-cluster,web,servicemix-cxf-bc,servicemix-file, servicemix-ftp,servicemix-http,servicemix-jms,servicemix-mail,servicemix-bean,servicemix-camel, servicemix-cxf-se,servicemix-drools,servicemix-eip,servicemix-osworkflow,servicemix-quartz, servicemix-scripting,servicemix-validation,servicemix-saxon,servicemix-wsn2005,camel-cxf,camel-jms
featuresRepositories
—Comma separated list of feature repositories to load at startup.featuresBoot
—Comma separated list of features to install at startup.
featuresRepositories
setting and the featuresBoot
setting are ignored, even if you restart the container.
InstallDir/data/cache
(thereby losing all of the container's custom settings).
Chapter 9. Deploying a Plain JAR
Abstract
9.1. Bundle Tool (Bnd)
About the bnd tool
- Print the manifiest and show the package dependencies of a JAR file or bundle file.
- Wrap a vanilla JAR file, converting it into a bundle.
- Build a bundle from the class path, based on specifications in a
.bnd
file. - Validate manifest entries.
maven-bundle-plugin
. In fact, the approach to building bundles described in Chapter 3, Building with Maven is based on the Maven bundle plug-in and therefore, implicitly, is also based on the Bnd tool.
Downloading and installing bnd
http://www.aqute.biz/Code/Download#bnd
bnd-Version.jar
, to a convenient location. There is no installation involved: the JAR file is all that you need to use the Bnd tool. For convenience, however, it is advisable to rename the JAR file to bnd.jar
, so you won't have to do so much typing when you invoke it from the command line (for example, as in java -jar bnd.jar Cmd Options
)
References
9.2. Converting a JAR Using Bnd
Overview
wrap
command. You can choose either to perform the conversion with default settings (which works in most cases) or to perform a custom conversion with the help of a Bnd properties file.
Sample JAR file
http://commons.apache.org/downloads/download_logging.cgi
Bnd print command
print
command is a useful diagnostic tool that displays most of the information about a JAR that is relevant to bundle creation. For example, to print the Manifest headers and package dependencies of the commons logging JAR, you can invoke the Bnd print
command as follows:
java -jar bnd.jar print commons-logging-1.1.1.jar
[MANIFEST commons-logging-1.1.1.jar] Archiver-Version Plexus Archiver Build-Jdk 1.4.2_16 Built-By dlg01 Created-By Apache Maven Extension-Name org.apache.commons.logging Implementation-Title Commons Logging Implementation-Vendor Apache Software Foundation Implementation-Vendor-Id org.apache Implementation-Version 1.1.1 Manifest-Version 1.0 Specification-Title Commons Logging Specification-Vendor Apache Software Foundation Specification-Version 1.0 X-Compile-Source-JDK 1.2 X-Compile-Target-JDK 1.1 [IMPEXP] [USES] org.apache.commons.logging org.apache.commons.logging.impl org.apache.commons.logging.impl javax.servlet org.apache.avalon.framework.logger org.apache.commons.logging org.apache.log org.apache.log4j One error 1 : Unresolved references to [javax.servlet, org.apache.avalon.framework.logger, org.apache.log, org.apache.log4j] by class(es) on the Bundle-Classpath[Jar:comm ons-logging-1.1.1.jar]: [org/apache/commons/logging/impl/AvalonLogger.class, org /apache/commons/logging/impl/ServletContextCleaner.class, org/apache/commons/log ging/impl/LogKitLogger.class, org/apache/commons/logging/impl/Log4JLogger.class]
[MANIFEST JarFileName]
- Lists all of the header settings from the JAR file's
META-INF/Manifest.mf
file. [IMPEXP]
- Lists any Java packages that are imported or exported through the
Import-Package
orExport-Package
Manifest headers. [USES]
- Shows the JAR's package dependencies. The left column lists all of the packages defined in the JAR, while the right column lists the dependent packages for each of the packages in the left column.
- Errors
- Lists any errors—for example, any unresolved dependencies.
Bnd wrap command
wrap
command as follows:
java -jar bnd.jar wrap commons-logging-1.1.1.jar
commons-logging-1.1.1.bar
, which consists of the original JAR augmented by the Manifest headers required by a bundle.
Checking the new bundle headers
print
command:
java -jar bnd.jar print commons-logging-1.1.1.bar
[MANIFEST commons-logging-1.1.1-bnd.jar] Archiver-Version Plexus Archiver Bnd-LastModified 1263987809524 Build-Jdk 1.4.2_16 Built-By dlg01 Bundle-ManifestVersion 2 Bundle-Name commons-logging-1.1.1 Bundle-SymbolicName commons-logging-1.1.1 Bundle-Version 0 Created-By 1.5.0_08 (Sun Microsystems Inc.) Export-Package org.apache.commons.logging;uses:="org.ap ache.commons.logging.impl",org.apache.commons.logging.impl;uses:="org.apache.ava lon.framework.logger,org.apache.commons.logging,org.apache.log4j,org.apache.log, javax.servlet" Extension-Name org.apache.commons.logging Implementation-Title Commons Logging Implementation-Vendor Apache Software Foundation Implementation-Vendor-Id org.apache Implementation-Version 1.1.1 Import-Package javax.servlet;resolution:=optional,org.a pache.avalon.framework.logger;resolution:=optional,org.apache.commons.logging;re solution:=optional,org.apache.commons.logging.impl;resolution:=optional,org.apac he.log;resolution:=optional,org.apache.log4j;resolution:=optional Manifest-Version 1.0 Originally-Created-By Apache Maven Specification-Title Commons Logging Specification-Vendor Apache Software Foundation Specification-Version 1.0 Tool Bnd-0.0.384 X-Compile-Source-JDK 1.2 X-Compile-Target-JDK 1.1 [IMPEXP] Import-Package javax.servlet {resolution:=optional} org.apache.avalon.framework.logger {resolution:=optional} org.apache.log {resolution:=optional} org.apache.log4j {resolution:=optional} Export-Package org.apache.commons.logging org.apache.commons.logging.impl [USES] org.apache.commons.logging org.apache.commons.logging.impl org.apache.commons.logging.impl javax.servlet org.apache.avalon.framework.logger org.apache.commons.logging org.apache.log org.apache.log4j
Default property file
wrap
command behaves as if it was configured to use the following Bnd property file:
Export-Package: * Import-Package: AllReferencedPackages
Defining a custom property file
wrap
command generates a bundle, you can define a Bnd properties file to control the conversion process. For a detailed description of the syntax and capabilities of the Bnd properties file, see the Bnd tool documentation.
org.apache.commons.logging.impl
package, while exporting the org.apache.commons.logging
package. You could do this by creating a Bnd properties file called commons-logging-1.1.1.bnd
and inserting the following lines using a text editor:
version=1.1.1 Export-Package: org.apache.commons.logging;version=${version} Private-Package: org.apache.commons.logging.impl Bundle-Version: ${version}
version
variable (any properties starting with a lowercase letter are interpreted as variables).
Wrapping with the custom property file
-properties
option of the wrap
command. For example, to wrap the vanilla commons logging JAR using the instructions contained in the commons-logging-1.1.1.bnd
properties file, enter the following command:
java -jar bnd.jar wrap -properties commons-logging-1.1.1.bnd commons-logging-1.1.1.jar
9.3. Converting a JAR Using the wrap Scheme
Overview
wrap
scheme, which can be prefixed to any existing URL format. The wrap
scheme is also based on the Bnd utility.
Syntax
wrap
scheme has the following basic syntax:
wrap:LocationURL
wrap
scheme can prefix any URL that locates a JAR. The locating part of the URL, LocationURL, is used to obtain the (non-bundlized) JAR and the URL handler for the wrap
scheme then converts the JAR automatically into a bundle.
wrap
scheme also supports a more elaborate syntax, which enables you to customize the conversion by specifying a Bnd properties file or by specifying individual Bnd properties in the URL. Typically, however, the wrap
scheme is used just with its default settings.
Default properties
wrap
scheme is based on the Bnd utility, it uses exactly the same default properties to generate the bundle as Bnd does—see the section called “Default property file”.
Wrap and install
commons-logging
JAR from a remote Maven repository, convert it into an OSGi bundle on the fly, and then install it and start it in the OSGi container:
JBossFuse:karaf@root> osgi:install -s wrap:mvn:commons-logging/commons-logging/1.1.1
Feature example
example-jpa-osgi
feature combines the mvn
scheme and the wrap
scheme in order to download the plain HyperSQL JAR file and convert it to an OSGi bundle on the fly.
Example 9.1. The example-jpa-osgi Feature
<feature name="examples-jpa-osgi" version="6.1.0.redhat-379">
<feature version="6.1.0.redhat-379">jpa-hibernate</feature>
<bundle>wrap:mvn:hsqldb/hsqldb/1.8.0.7</bundle>
<bundle>mvn:org.apache.servicemix.examples.jpa-osgi/wsdl-first-cxfbc-bundle/6.1.0.redhat-379</bundle>
<bundle>mvn:org.apache.servicemix.examples.jpa-osgi/wsdl-first-cxfse-bundle/6.1.0.redhat-379</bundle>
</feature>
Reference
wrap
scheme is provided by the Pax project, which is the umbrella project for a variety of open source OSGi utilities. For full documentation on the wrap
scheme, see the Wrap Protocol reference page.
Chapter 10. OSGi Bundle Tutorials
Abstract
10.1. Generating and Running an EIP Bundle
Overview
Prerequisites
- Maven installation—Maven is a free, open source build tool from Apache. You can download the latest version from http://maven.apache.org/download.html (minimum is 2.0.9).
- Internet connection—whilst performing a build, Maven dynamically searches external repositories and downloads the required artifacts on the fly. In order for this to work, your build machine must be connected to the Internet.
- fusesource Maven repository is configured—in order to locate the archetypes, Maven's
settings.xml
file must be configured with the location of thefusesource
Maven repository. For details of how to set this up, see the section called “Adding the Red Hat JBoss Fuse repository”.
Generating an EIP bundle
servicemix-camel-osgi-bundle
archetype creates a router project, which is configured to deploy as a bundle. To generate a Maven project with the coordinates, org.fusesource.example:camel-bundle
, enter the following command:
mvn archetype:generate -DarchetypeGroupId=org.apache.servicemix.tooling -DarchetypeArtifactId=servicemix-camel-osgi-bundle -DarchetypeVersion=2013.01.0.redhat-610379 -DgroupId=org.fusesource.example -DartifactId=camel-bundle
ProjectDir/camel-bundle
, containing the files for the generated bundle project.
Running the EIP bundle
camel-bundle
project, perform the following steps:
- Build the project—open a command prompt and change directory to
ProjectDir/camel-bundle
. Use Maven to build the demonstration by entering the following command:mvn install
If this command runs successfully, theProjectDir/camel-bundle/target
directory should contain the bundle file,camel-bundle-1.0-SNAPSHOT.jar
and the bundle will also be installed in the local Maven repository. - Install prerequisite features (optional)—by default, the
camel-core
feature and some related features are pre-installed in the OSGi container. But many of the Apache Camel components are not installed by default. To check which features are available and whether or not they are installed, enter the following console command:JBossFuse:karaf@root> features:list
Apache Camel features are identifiable by thecamel-
prefix. For example, if one of your routes requires the HTTP component, you can make sure that it is installed in the OSGi container by issuing the following console command:JBossFuse:karaf@root> features:install camel-http
- Install and start the camel-bundle bundle—at the Red Hat JBoss Fuse console, enter the following command to install the bundle from the local Maven repository (see Section A.3, “Mvn URL Handler”):
JBossFuse:karaf@root> osgi:install -s mvn:org.fusesource.example/camel-bundle
After entering this command, you should soon see output like the following being logged to the console screen:>>>> MyTransform set body: Mon Sep 22 11:43:42 BST 2008 >>>> MyTransform set body: Mon Sep 22 11:43:44 BST 2008 >>>> MyTransform set body: Mon Sep 22 11:43:46 BST 2008
NoteOn Windows machines, be careful how you format thefile
URL—for details of the syntax understood by thefile
URL handler, see Section A.1, “File URL Handler”. - Stop the camel-bundle bundle—to stop the
camel-bundle
bundle, you first need to discover the relevant bundle number. To find the bundle number, enter the following console command (this might look a bit confusing, because the text you are typing will intermingle with the output that is being logged to the screen):JBossFuse:karaf@root> osgi:list
At the end of the listing, you should see an entry like the following:[ 189] [Active ] [ ] [ ] [ 60] A Camel OSGi Service Unit (1.0.0.SNAPSHOT)
Where, in this example, the bundle number is 189. To stop this bundle, enter the following console command:JBossFuse:karaf@root> osgi:stop 189
10.2. Generating and Running a Web Services Bundle
Overview
Prerequisites
- Maven installation—Maven is an open source build tool from Apache. You can download the latest version from http://maven.apache.org/download.html (minimum is 2.0.9).
- Internet connection—whilst performing a build, Maven dynamically searches external repositories and downloads the required artifacts on the fly. In order for this to work, your build machine must be connected to the Internet.
- fusesource Maven repository is configured—in order to locate the archetypes, Maven's
settings.xml
file must be configured with the location of thefusesource
Maven repository. For details of how to set this up, see the section called “Adding the Red Hat JBoss Fuse repository”.
Generating a Web services bundle
servicemix-cxf-code-first-osgi-bundle
archetype creates a project for building a Java-first JAX-WS application that can be deployed into the OSGi container. To generate a Maven project with the coordinates, org.fusesource.example:cxf-code-first-bundle
, enter the following command:
mvn archetype:generate -DarchetypeGroupId=org.apache.servicemix.tooling -DarchetypeArtifactId=servicemix-cxf-code-first-osgi-bundle -DarchetypeVersion=2013.01.0.redhat-610379 -DgroupId=org.fusesource.example -DartifactId=cxf-code-first-bundle
ProjectDir/cxf-code-first-bundle
, containing the files for the generated bundle project.
Modifying the bundle instructions
Import-Package
element generated by the servicemix-cxf-code-first-osgi-bundle
archetype is not configured to scan the project's Java source files. In most cases, however, you would want the Maven bundle plug-in to perform this automatic scanning in order to ensure that the bundle imports all of the packages needed by your code.
Import-Package
scanning feature, simply add the wildcard, *
, as the last item in the comma-separated list inside the Import-Package
element, as shown in the following example:
<project ... > ... <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> ... <Import-Package> javax.jws, javax.wsdl, javax.xml.bind, javax.xml.bind.annotation, javax.xml.namespace, javax.xml.ws, META-INF.cxf, META-INF.cxf.osgi, org.apache.cxf.bus, org.apache.cxf.bus.spring, org.apache.cxf.bus.resource, org.apache.cxf.configuration.spring, org.apache.cxf.resource, org.apache.cxf.jaxws, org.apache.cxf.transport.http_osgi, org.springframework.beans.factory.config, * </Import-Package> ... </instructions> </configuration> </plugin> </plugins> </build> ... </project>
Running the Web services bundle
cxf-code-first-bundle
project, perform the following steps:
- Build the project—open a command prompt and change directory to
ProjectDir/cxf-code-first-bundle
. Use Maven to build the demonstration by entering the following command:mvn install
If this command runs successfully, theProjectDir/cxf-code-first-bundle/target
directory should contain the bundle file,cxf-code-first-bundle-1.0-SNAPSHOT.jar
. - Install and start the cxf-code-first-bundle bundle—at the Red Hat JBoss Fuse console, enter the following command to install the bundle from your local Maven repository:
JBossFuse:karaf@root> osgi:install -s mvn:org.fusesource.example/cxf-code-first-bundle/1.0-SNAPSHOT
- Test the Web serivce—to test the Web service deployed in the previous step, you can use a web browser to query the service's WSDL. Open your favorite web browser and navigate to the following URL:
http://localhost:8181/cxf/PersonServiceCF?wsdl
When the web service receives the query,?wsdl
, it returns a WSDL description of the running service. - Stop the cxf-code-first-bundle bundle—to stop the
cxf-code-first-bundle
bundle, you first need to discover the relevant bundle number. To find the bundle number, enter the following console command:JBossFuse:karaf@root> osgi:list
At the end of the listing, you should see an entry like the following:[ 191] [Active ] [ ] [ ] [ 60] A CXF Code First OSGi Project (1.0.0.SNAPSHOT)
Where, in this example, the bundle number is 191. To stop this bundle, enter the following console command:JBossFuse:karaf@root> osgi:stop 191
Part III. The Fuse Application Bundle Deployment Model
Abstract
Chapter 11. Building a FAB
Abstract
pom.xml
file declares the complete set of dependencies for the JAR.
11.1. Generating a FAB Project
Generating FAB projects with Maven archetypes
pom.xml
file, which is always present in a Maven-generated JAR), you can use almost any Maven archetype, as long as the generated Maven project has the jar
packaging type.
Archetypes
camel-archetype-java
- Demonstrates a route defined using the Java DSL.
camel-archetype-blueprint
- Demonstrates a route defined using the XML DSL in an OSGi blueprint file.
camel-archetype-activemq
- Demonstrates how to use a message broker in a route.
camel-archetype-component
- Demonstrates how to define a custom Apache Camel component.
camel-archetype-blueprint archetype
camel-archetype-blueprint
archetype creates a project that demonstrates a simple Apache Camel route written in the XML DSL using the Blueprint injection framework. To generate a Maven project with the coordinates, GroupId:
ArtifactId:
Version, enter the following command:
mvn archetype:generate -DarchetypeGroupId=org.apache.camel.archetypes -DarchetypeArtifactId=camel-archetype-blueprint -DarchetypeVersion=2.12.0.redhat-610379 -DgroupId=GroupId -DartifactId=ArtifactId -Dversion=Version
mvn
command are shown on separate lines purely for the sake of readability. When you are entering the command at a command prompt, you must ensure that all of the parameters are on the same line.
Building the FAB
pom.xml
file), and enter the following Maven command:
mvn install
/target
directory, and then to install the generated JAR in the local Maven repository.
11.2. Class Sharing
Private class space
org.apache.camel
, org.apache.activemq
, or org.apache.cxf
, which are shared by default). This is a safe approach to deploying dependencies, because it reduces the risk of version inconsistencies. But it is also an expensive approach, in terms of resources, because it forces the JVM to maintain a dedicated copy of each dependency in memory, just for this FAB.
Shared class space
Specify shared dependencies using provided scope
provided
scope in your project's pom.xml
file. For example:
<dependency>
<groupId>org.acme.foo</groupId>
<artifactId>foo-core</artifactId>
<version>${foo-version}</version>
<scope>provided</scope>
</dependency>
Specify shared dependencies using Manifest header
FAB-Provided-Dependency:
manifest header. For example, to share all artifacts with the org.acme.foo
Maven group ID:
FAB-Provided-Dependency: org.acme.foo:* org.apache.camel:* org.apache.cxf:* org.apache.activemq:*
11.3. Modifying an Existing Maven Project
Overview
Ensure that the package type is JAR
packaging
element in your project's pom.xml
file contains the value, jar
, as shown in the following example:
<project ... >
...
<packaging>jar</packaging>
...
</project>
Customize the JDK compiler version
JAVA_HOME
and the PATH
environment variables to the correct values for your JDK, you must also modify the POM file.
maven-compiler-plugin
plug-in settings to your POM (if they are not already present):
<project ... > ... <build> <defaultGoal>install</defaultGoal> <plugins> ... <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> ... </project>
Configure class sharing
provided
, to prevent the FAB runtime from unnecessarily installing those dependencies again. This typically includes artifacts whose names match the patterns, camel-*
, cxf-*
, activemq-*
, and fabric-*
.
camel-http
artifact, you should modify the dependency by adding the scope
element as follows:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-http</artifactId>
<version>2.12.0.redhat-610379</version>
<scope>provided</scope>
</dependency>
org.apache.camel
, org.apache.cxf
, or org.apache.activemq
are shared by default (equivalent to provided
scope), so that the value of the scope
element is ignored by default. This behavior changes, however, if the FAB-Provided-Dependency
manifest header is specified explicitly—see the section called “Sharing dependencies” for details.
Mark test artifacts with the test scope
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j-version}</version>
<scope>test</scope>
</dependency>
test
scope.
Specify the requisite dependencies for WS applications
provided
scope. For example, a basic Apache CXF application that uses the JAX-WS frontend needs the following Maven dependencies:
<project> ... <dependencies> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>2.7.0.redhat-610379</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>2.7.0.redhat-610379</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-jetty</artifactId> <version>2.7.0.redhat-610379</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.0.6.RELEASE</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
Prefer Blueprint over Spring
ClassNotFound
exceptions at deploy time (FAB is not capable of parsing a Spring XML file to discover the dependencies it introduces).
Optionally configure JAR manifest headers
pom.xml
file embedded in the JAR, you can also specify FAB-specific configuration settings by adding headers to the JAR's manifest. For example:
FAB-Version-Range-Digits: 2 FAB-Provided-Dependency: org.acme.foo:* org.apache.camel:* org.apache.cxf:* org.apache.activemq:*
11.4. Configuring a FAB
Overview
Maven artifact pattern syntax
groupId[:artifactId]
*
, to match an arbitrary sequence of characters in either the group ID or the artifact ID.
org.apache.camel:camel-core org.apache.cxf:cxf-core
org.apache.camel org.apache.activemq org.apache.cxf
org.apache.* org.springframework.*
Supported manifest headers
FAB-Version-Range-Digits
FAB-Provided-Dependency
FAB-Include-Optional-Dependency
FAB-Dependency-Require-Bundle
FAB-Exclude-Dependency
Import-Package
FAB-Skip-Matching-Feature-Detection
FAB-Require-Feature-URL
,FAB-Require-Feature
FAB-Install-Provided-Bundle-Dependencies
Specifying version ranges
<dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-core</artifactId> <version>2.8.1-fuse-00-02</version> <scope>provided</scope> </dependency>
Import-Package
header, as follows:
Import-Package: org.apache.camel;version="[2.8.1-fuse-00-02,2.9)"
2.8.2
, 2.8.3
, 2.8.4
, and so on) are accepted, but minor and major upgrades are rejected.
FAB-Version-Range-Digits:
manifest header to one of the following policy values:
Value | Sample | Description |
---|---|---|
0 | [2.5.6.qual,2.5.6.qual] | Exact only. |
1 | [2.5.6.qual,2.5.7) | Allow arbitrary qualifers (order not guaranteed). |
2 | [2.5.6.qual,2.6) | Allow patch releases (default). |
3 | [2.5.6.qual,3) | Allow patch and minor releases. |
4 | [2.5.6.qual,) | Any version from 2.5.6 onwards. |
Sharing dependencies
<scope>provided</scope>
to dependencies in the pom.xml
file, you can list the shared artifacts in this manifest header. The shared artifacts are specified as a space-separated list of artifact patterns, for example:
FAB-Provided-Dependency: groupId1:artifactId1 groupId2:artifactId2 ...
*
, for the groupId or the artifactId. For example, to share all Apache Camel and Spring dependencies (transitively) in your FAB, add the following header to your manifest:
FAB-Provided-Dependency: org.apache.camel:* org.springframework:*
FAB-Provided-Dependency
manifest header, the FAB runtime implicitly adds the following default header:
FAB-Provided-Dependency: org.apache.camel:* org.apache.cxf:* org.apache.activemq:*
FAB-Provided-Dependency
manifest header explicitly, you override the default header value, which would make the org.apache.camel
, org.apache.cxf
, and org.apache.activemq
dependencies unshared again. Since you normally want these dependencies to remain shared, it is good practice to include the entries, org.apache.camel:*
org.apache.cxf:*
org.apache.activemq:*
, in your custom FAB-Provided-Dependency
manifest header.
Including optional dependencies
pom.xml
file are marked by the presence of <optional>true</optional>
in the dependency.
FAB-Include-Optional-Dependency:
manifest header.
*
. For example, to force the inclusion of all optional dependencies, add the following manifest header:
FAB-Include-Optional-Dependency: *:*
Specifying OSGi Require-Bundle
Require-Bundle
directive.
Import-Package
directive for all artifacts not selected by the FAB-Dependency-Require-Bundle
header.
*
—for example:
FAB-Dependency-Require-Bundle: groupId1:artifactId1 groupId2:artifactId2 ...
Excluding dependencies
FAB-Exclude-Dependency:
manifest header, as a space-separated list of artifact patterns, for example:
FAB-Exclude-Dependency: log4j logkit
Customising import packages
Import-Package
manifest header, is the standard OSGi mechanism for specifying dependencies. Normally, you do not have to worry about imported packages when using FABs, because the FAB runtime automatically generates the Import-Package
manifest header with the requisite entries.
Import-Package
manifest header to your FAB package. At run time, FAB merges your customized import package list with the automatically generated list of import packages.
Import-Package
header is specified using the standard OSGi format. For example, to import the package, com.acme.special
, where the version is allowed to lie in the range [1.0, 1.1)
, you could add the following header:
Import-Package: com.acme.special;version="[1.0,1.1)"
Automatic feature detection
camel-jetty
feature by entering the following console command:
JBossFuse:karaf@root> features:install camel-jetty
<dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-jetty</artifactId> <version>2.12.0.redhat-610379</version> <scope>provided</scope> </dependency>
camel-jetty
feature is not already installed in the runtime, however, it is unlikely that the FAB mechanism would be able to install all of the required transitive dependencies successfully (after all, the camel-jetty
feature was created in the first place precisely because it has third-party dependencies that are not well integrated with OSGi or FAB).
org.apache.camel/camel-jetty
Maven dependency, it automatically maps the dependency to the camel-jetty
feature and installs the camel-jetty
feature.
camel-ComponentName
, and some Apache CXF features, cxf
, cxf-sts
, and cxf-wsn
.
FAB-Skip-Matching-Feature-Detection
, specifying a space-separated list of artifact patterns. For example, to disable automatic feature detection for the Apache Camel components, add the following entry to the manifest:
FAB-Skip-Matching-Feature-Detection: org.apache.camel
Requiring features
cxf-sts
feature, add the following entries to the Manifest (noting that the Maven URL is continued on a second line, because it does not fit within the 72 byte line limit):
FAB-Require-Feature-URL: mvn:org.apache.cxf.karaf/apache-cxf/ 2.7.0.redhat-610379/xml/features FAB-Require-Feature: cxf-sts
FAB-Require-Feature-URL
header is specified as a space-separated list of URLs that give the locations of the features repositories.
FAB-Require-Feature
header is specified as a space-separated list of features, in the format, FeatureName
, or in the format, FeatureName/Version
. For example:
FAB-Require-Feature: cxf-sts/2.7.0.redhat-610379 cxf-wsn/2.7.0.redhat-610379
Respecting pre-installed features and bundles
FAB-Install-Provided-Bundle-Dependencies: true
How to set JAR manifest headers
In the POM file
pom.xml
, by configuring the Maven JAR plug-in. In the JAR plug-in's configuration/archive/manifestEntries
element, specify manifest header settings using the following syntax:
<ManifestHeaderName>HeaderValue</ManifestHeaderName>
FAB-Version-Range-Digits
manifiest header and the FAB-Provided-Dependency
manifest header in your pom.xml
file, configure the JAR plug-in as shown in Example 11.1, “Configuring FAB Manifest Headers in the POM”.
Example 11.1. Configuring FAB Manifest Headers in the POM
<project ...> ... <build> ... <plugins> ... <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <index>true</index> <manifestEntries> <FAB-Version-Range-Digits>0</FAB-Version-Range-Digits> <FAB-Provided-Dependency> org.apache.camel:* org.apache.cxf:* org.apache.activemq:* </FAB-Provided-Dependency> </manifestEntries> </archive> </configuration> </plugin> ... </plugins> </build> </project>
In the META-INF/MANIFEST.MF file
MANIFEST.MF
file directly and instruct the Maven JAR plug-in to include the provided manifest in the generated JAR (the JAR plug-in does not include the manifest by default). Configure the JAR plug-in to include the manifest file as follows:
<project ...> ... <build> ... <plugins> ... <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <!-- lets use the default META-INF/MANIFEST.MF if its there --> <useDefaultManifestFile>true</useDefaultManifestFile> </configuration> </plugin> ... </plugins> </build> </project>
MANIFEST.MF
file at the following location:
ProjectDir/src/main/resources/META-INF/MANIFEST.MF
META-INF/MANIFEST.MF
file:
FAB-Version-Range-Digits: 0 FAB-Provided-Dependency: org.apache.camel:* org.apache.cxf:* org.ac tivemq:*
- Each header is terminated by a newline.
- Line length is limited to 72 bytes (not characters), including the newline.
- Line continuation is indicated by putting a space character at the start of a line.
- The manifest file must end with a newline character.
Chapter 12. Deploying a FAB
Abstract
12.1. The FAB Deployment Model
Overview
What is a FAB?
pom.xml
file at the following location (where groupId and artifactId are the Maven coordinates of the JAR):
META-INF/maven/groupId/artifactId/pom.xml
Manifest.mf file
Manifest.mf
file. For example, the FAB-Provided-Dependency
header can be used to specify whether some or all of the FAB's dependencies are to be shared.
FAB deployment
Installing a FAB with private dependencies
Figure 12.1. FAB Installed with Private Dependencies
Fab
, and its private dependencies, which proceeds as follows:
- The user explicitly deploys the FAB,
Fab
, into the OSGi container (either by hot deploying or manually deploying). - The FAB runtime scans the embedded
pom.xml
file and figures out all of the non-optional and non-test transitive dependencies. In this case, there are five private dependencies:DepA
,DepA1
,DepB
,DepB1
, andDepB2
. The FAB runtime auto-installs these dependencies by fetching them from the Maven repository. - The dependencies are added to the FAB's private class space and the whole collection is converted into a single OSGi bundle and installed in the OSGi container.
Installing a FAB with shared dependencies
Figure 12.2. FAB Installed with Shared Dependencies
Fab
, and its shared dependencies, which proceeds as follows:
- The user explicitly deploys the FAB,
Fab
, into the OSGi container (either by hot deploying or manually deploying). - The FAB runtime scans the embedded
pom.xml
file and figures out all of the non-optional and non-test transitive dependencies. In this case, there are five shared dependencies:DepA
,DepA1
,DepB
,DepB1
, andDepB2
. The FAB runtime then auto-installs these dependencies by fetching them from the Maven repository. - The FAB,
Fab
, and its dependencies are separately converted into OSGi bundles and the requisite import and export bundle headers are automatically added. This collection of generated bundles is then installed in the OSGi container.
Optimising a FAB's shared dependencies
org.apache.camel
, org.apache.cxf
, or org.apache.activemq
). This deployment approach is relatively safe, because it minimizes the risk of version conflicts and so on. But it is also an expensive option, because it uses up a lot of system memory and resources. If you would like to experiment with sharing some of the FAB's dependencies, you can specify which artifacts to share using the FAB-Provided-Dependency:
header in the FAB's manifest, Manifest.mf
. For example:
FAB-Provided-Dependency: org.apache.camel:* org.apache.cxf:* org.apache.activemq:* org.springframework:*
Starting a FAB
Figure 12.3. FAB Start
fab:start
console command, the FAB runtime iterates over the FAB's transitive dependencies and starts every single bundle in the tree of dependencies (starting with the leaves). This contrasts with the conventional osgi:start
console command, which starts only the specified bundle.
Default install behavior of a FAB
- Plain FAB dependency (has
pom.xml
file, but no bundle headers)—by default, the plain FAB dependencies are added to the deployed FAB's private classpath and bundled together with the deployed FAB. - OSGi bundle dependency (has
pom.xml
file and bundle headers)—by default, the OSGi bundle dependencies are deployed as separate bundles (shared dependencies).
DepA
and DepA1
) and some of its dependencies are OSGi bundles (Bnd1
, Bnd2
, and Bnd3
):
Figure 12.4. Default FAB Install Behavior
fab:start
. If the dependent bundles (Bnd1
, Bnd2
, and Bnd3
) were merely added to the private classpath of the Fab
bundle, they would not be activated when fab:start
is invoked (in other words, any Spring configuration files or blueprint configuration files would fail to be activated).
12.2. FABs and Features
Overview
Requiring features
Automatic feature detection
pom.xml
file, it automatically maps certain Maven dependencies to features and installs the corresponding feature instead of the Maven dependency.
org.apache.camel/camel-jetty
artifact, it will automatically install the camel-jetty
feature.
Respecting features
12.3. Hot Deployment
Prerequisites
fabric-bundle
feature. To install this feature in the container, enter the following console command:
JBossFuse:karaf@root> features:install fabric-bundle
Hot deploy directory
.fab
, you can deploy it simply by copying it into the InstallDir/deploy
directory.
InstallDir/deploy
directory and hot deploys any files that have a recognized suffix. Each time a FAB file is copied to this directory, it is installed in the runtime and also started. You can subsequently update or delete the FABs, and the changes are handled automatically.
/target/fabulous-1.0.fab
, you can deploy this FAB by copying it to the InstallDir/deploy
directory as follows (assuming you are working on a UNIX platform):
% cp ProjectDir/target/fabulous-1.0.fab InstallDir/deploy
12.4. Manual Deployment
Overview
Prerequisites
fabric-bundle
feature. To install this feature in the container, enter the following console command:
JBossFuse:karaf@root> features:install fabric-bundle
Installing a FAB using the fab scheme
fab:
URL scheme, which is useful for installing FABs in a general context, such as a FAB URL embedded in an Apache Karaf features file. For example, to install a FAB using the osgi:install
command, prefix the FAB's URL with the fab:
scheme, as follows:
osgi:install fab:mvn:groupId/artifactId/version
Starting a FAB
osgi:list
command. You can then start the FAB using the fab:start
command (which takes the bundle ID as its argument).
A Camel FAB
, entering osgi:list
at the console prompt might produce output like the following:
... [ 175] [Active ] [ ] [Started] [ 60] ServiceMix :: FTP (2009.02.0.psc-01-00RC1) [ 180] [Installed ] [ ] [ ] [ 60] A Camel FAB (1.0.0.SNAPSHOT)
180
, by entering the following console command:
fab:start 180
fab:start
command recursively starts all of the FAB's dependent bundles, which ensures that services required by the FAB are available when the FAB starts up.
Stopping a FAB
fab:stop
console command (which takes the FAB's bundle ID as its argument).
180
, enter the following console command:
fab:stop 180
fab:stop
command recursively stops all of the FAB's dependent bundles. If you would prefer to perform a shallow stop (that is, to stop only the bundle corresponding to the FAB), use the osgi:stop
command instead.
Uninstalling a FAB
fab:uninstall
console command (which takes the FAB's bundle ID as its argument).
180
, enter the following console command:
fab:uninstall 180
fab:uninstall
command also uninstalls the FAB's unused transitive dependencies. Hence, fab:uninstall
can potentially uninstall multiple bundles from the OSGi container. If you would prefer to perform a shallow uninstall (that is, to uninstall only the bundle corresponding to the FAB), use the osgi:uninstall
command instead.
Bundle lifecycle management commands
URL schemes for locating and installing FABs
osgi:install
command, you can combine fab:
with any of the URL schemes supported by Red Hat JBoss Fuse, which includes the following scheme types:
- Maven scheme—use the combined schemes,
fab:mvn:
, as follows:fab:mvn:groupId/artifactId/version
For more details about themvn:
scheme, see Section A.3, “Mvn URL Handler”. - File scheme—use the combined schemes,
fab:file:
, as follows:fab:file:PathName
NoteOn Windows, use forward slashes,/
, instead of backslashes,\
, in the pathname, PathName.For more details about thefile:
scheme, see Section A.1, “File URL Handler”. - HTTP scheme—use the combined schemes,
fab:http:
, as follows:fab:http:Host[:Port]/[Path]
For more details about thehttp:
scheme, see Section A.2, “HTTP URL Handler”.
12.5. Configuring Maven for FAB
Overview
Maven URL handler PID
org.ops4j.pax.url.mvn
PID. See Section A.3, “Mvn URL Handler”.
org.ops4j.pax.url.mvn
PID. This PID should not be modified for purposes of configuring FAB dependency resolution. Instead, you should modify the fabric's Maven proxy as described in chapter "Configuring a Fabric's Maven Proxy" in "Configuring and Running Red Hat JBoss Fuse".
Customize the location of the local repository
org.ops4j.pax.url.mvn
PID's org.ops4j.pax.url.mvn.localRepository
property to the location of your local Maven repository. Example 12.1, “Changing the Local Repository” shows the commands.
Example 12.1. Changing the Local Repository
JBossFuse:karaf@root>
config:edit org.ops4j.pax.url.mvn
JBossFuse:karaf@root>
config:propset org.ops4j.pax.url.mvn.localRepository file:E:/Data/.m2/repository
JBossFuse:karaf@root>
config:update
Customize the list of remote repositories
org.ops4j.pax.url.mvn.repositories
property value in the org.ops4j.pax.url.mvn.cfg
PID.
Chapter 13. FAB Tutorial
Abstract
13.1. Generating and Running an EIP FAB
Overview
Prerequisites
- Maven installation—Maven is a free, open source build tool from Apache. You can download the latest version from http://maven.apache.org/download.html (minimum is 2.0.9).
- Internet connection—whilst performing a build, Maven dynamically searches external repositories and downloads the required artifacts on the fly. In order for this to work, your build machine must be connected to the Internet.
- fusesource Maven repository is configured—in order to locate the archetypes, Maven's
settings.xml
file must be configured with the location of thefusesource
Maven repository. For details of how to set this up, see the section called “Adding the Red Hat JBoss Fuse repository”.
Generating an EIP FAB
camel-archetype-blueprint
archetype creates a sample Maven project that can be deployed as a FAB. To generate a Maven project with the coordinates, org.fusesource.example:camel-fab
, enter the following command:
mvn archetype:generate -DarchetypeGroupId=org.apache.camel.archetypes -DarchetypeArtifactId=camel-archetype-blueprint -DarchetypeVersion=2.12.0.redhat-610379 -DgroupId=org.fusesource.example -DartifactId=camel-fab
ProjectDir/camel-fab
, containing the files for the generated FAB project.
Modify the POM file
camel-fab/pom.xml
file to a FAB POM, modify it as follows:
- Open the
camel-fab/pom.xml
file with your favorite text editor and change the packaging type frombundle
tojar
, as follows:<groupId>org.fusesource.example</groupId> <artifactId>camel-fab</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version>
- Add the
provided
scope to all of the dependencies (except for the dependencies that are already marked withtest
scope). Scroll down to thedependencies
element and add ascope
element to each of the dependencies as shown:... <dependencies> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-core</artifactId> <version>2.12.0.redhat-610346</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-blueprint</artifactId> <version>2.12.0.redhat-610346</version> <scope>provided</scope> </dependency> ...
- Remove the Maven bundle plug-in configuration. Scroll down to the
plugins
section and remove the completeplugin
element corresponding to themaven-bundle-plugin
plugin. - Save and close the
camel-fab/pom.xml
file.
Running the EIP FAB
camel-fab
project, perform the following steps:
- Build the project—open a command prompt and change directory to
ProjectDir/camel-fab
. Use Maven to build the demonstration by entering the following command:mvn install
If this command runs successfully, theProjectDir/camel-fab/target
directory should contain the JAR file,camel-fab-1.0-SNAPSHOT.jar
and the JAR will also be installed in the local Maven repository. - Install the fabric-bundle feature—the
fabric-bundle
feature is a prerequisite for using FABs. If it is not already installed, enter the following command:JBossFuse:karaf@root> features:install fabric-bundle
- Install and start the camel-fab JAR—at the Red Hat JBoss Fuse console, enter the following command:
JBossFuse:karaf@root> install fab:mvn:org.fusesource.example/camel-fab
NoteIt can take a minute or so for theinstall
command to finish, because the FAB runtime needs some time to evaluate the tree of dependencies associated with thecamel-fab
artifact.If the FAB is successfully installed, its bundle ID is logged to the console window. Using this bundle ID, bundleID, start the FAB by entering the following console command:JBossFuse:karaf@root> fab:start bundleID
- View the log—After entering the
fab:start
command, the Camel route starts to log messages to the container's log. To view the log, enter the following command:JBossFuse:karaf@root> log:tail -n 10
You should see messages like the following:2014-02-24 10:53:02,175 | INFO | #0 - timer://foo | timerToLog | rg.apache.camel.util.CamelLogger 176 | 136 - org.apache.camel.camel-core - 2.12.0.redhat-610349 | The message contains Hi from Camel at 2014-02-24 10:53:02 2014-02-24 10:53:07,175 | INFO | #0 - timer://foo | timerToLog | rg.apache.camel.util.CamelLogger 176 | 136 - org.apache.camel.camel-core - 2.12.0.redhat-610349 | The message contains Hi from Camel at 2014-02-24 10:53:07
To exit the log, type Ctrl-C. - Stop the camel-fab bundle—using the FAB's bundle ID, bundleID, stop the
camel-fab
bundle, as follows:JBossFuse:karaf@root> fab:stop bundleID
Part IV. WAR Deployment Model
Abstract
Chapter 14. Building a WAR
Abstract
14.1. Modifying an Existing Maven Project
Overview
Change the package type to WAR
war
in your project's pom.xml
file. Change the contents of the packaging
element to war
, as shown in the following example:
<project ... >
...
<packaging>war</packaging>
...
</project>
maven-war-plugin
, to perform packaging for this project.
Customize the JDK compiler version
JAVA_HOME
and the PATH
environment variables to the correct values for your JDK, you must also modify the POM file.
maven-compiler-plugin
plug-in settings to your POM (if they are not already present):
<project ... > ... <build> <defaultGoal>install</defaultGoal> <plugins> ... <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> ... </project>
Store resources under webapp/WEB-INF
/WEB-INF
directory in the standard WAR directory layout. In order to ensure that these resources are copied into the root of the generated WAR package, store the WEB-INF
directory under ProjectDir/src/main/webapp
in the Maven directory tree, as follows:
ProjectDir/
pom.xml
src/
main/
webapp/
WEB-INF/
web.xml
classes/
lib/
web.xml
file is stored at ProjectDir/src/main/webapp/WEB-INF/web.xml
.
Customize the Maven WAR plug-in
plugins
section of the pom.xml
file. Most of the configuration options are concerned with adding additonal resources to the WAR package. For example, to include all of the resources under the src/main/resources
directory (specified relative to the location of pom.xml
) in the WAR package, you could add the following WAR plug-in configuration to your POM:
<project ...>
...
<build>
...
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<!-- Optionally specify where the web.xml file comes from -->
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
<!-- Optionally specify extra resources to include -->
<webResources>
<resource>
<directory>src/main/resources</directory>
<targetPath>WEB-INF</targetPath>
<includes>
<include>**/*</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
...
</plugins>
</build>
</project>
webXml
- Specifies where to find the
web.xml
file in the current Maven project, relative to the location ofpom.xml
. The default issrc/main/webapp/WEB-INF/web.xml
. webResources
- Specifies additional resource files that are to be included in the generated WAR package. It can contain the following sub-elements:
webResources/resource
—each resource elements specifies a set of resource files to include in the WAR.webResources/resource/directory
—specifies the base directory from which to copy resource files, where this directory is specified relative to the location ofpom.xml
.webResources/resource/targetPath
—specifies where to put the resource files in the generated WAR package.webResources/resource/includes
—uses an Ant-style wildcard pattern to specify explicitly which resources should be included in the WAR.webResources/resource/excludes
—uses an Ant-style wildcard pattern to specify explicitly which resources should be excluded from the WAR (exclusions have priority over inclusions).
maven-war-plugin
plug-in, which has a bug that causes two copies of the web.xml
file to be inserted into the generated .war
file.
Building the WAR
pom.xml
file), and enter the following Maven command:
mvn install
ProjectDir/target
directory, and then to install the generated WAR in the local Maven repository.
14.2. Bootstrapping a CXF Servlet in a WAR
Overview
web.xml
to use the standard CXF servlet, org.apache.cxf.transport.servlet.CXFServlet
.
Example
web.xml
file shows how to configure the CXF servlet, where all Web service addresses accessed through this servlet would be prefixed by /services/
(as specified by the value of servlet-mapping/url-pattern
):
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>cxf</display-name> <description>cxf</description> <servlet> <servlet-name>cxf</servlet-name> <display-name>cxf</display-name> <description>Apache CXF Endpoint</description> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>cxf</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> <session-config> <session-timeout>60</session-timeout> </session-config> </web-app>
cxf-servlet.xml file
web.xml
file, it is also necessary to configure your Web services by defining a cxf-servlet.xml
file, which must be copied into the root of the generated WAR.
cxf-servlet.xml
in the default location, you can customize its name and location, by setting the contextConfigLocation
context parameter in the web.xml
file. For example, to specify that Apache CXF configuration is located in WEB-INF/cxf-servlet.xml
, set the following context parameter in web.xml
:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> ... <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/cxf-servlet.xml</param-value> </context-param> ... </web-app>
Reference
14.3. Bootstrapping a Spring Context in a WAR
Overview
Bootstrapping a Spring context in a WAR
web.xml
file shows how to boot up a Spring application context that is initialized by the XML file, /WEB-INF/applicationContext.xml
(which is the location of the context file in the generated WAR package):
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Camel Routes</display-name> <!-- location of spring xml files --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <!-- the listener that kick-starts Spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
Maven dependency
ContextLoaderListener
class from the Spring framework, you must add the following dependency to your project's pom.xml
file:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring-version}</version> </dependency>
spring-version
property specifies the version of the Spring framework you are using.
Chapter 15. Deploying a WAR
Abstract
web.xml
file in the bundle signals to the container that the bundle should be deployed as a Web application.
15.1. Converting the WAR Using the war Scheme
Overview
Syntax
war
scheme has the following basic syntax:
war:LocationURL[?Options]
mvn:
or a file:
URL). Options can be appended to the URL in the following format:
?Option=Value&Option=Value&...
war
URL appears in an XML file:
?Option=Value&Option=Value&...
Prerequisite
war
feature is required to convert and deploy WARs using the war: scheme. It can be installed from the container's command console using features:install war
.
Deploying a WAR file
osgi:install
command, taking a war:mvn:
URL as its argument. For example, to deploy the wicket-example WAR file from a Maven repository, where the application should be accessible from the wicket
Web application context, enter the following console command:
JBossFuse:karaf@root> install war:mvn:org.apache.wicket/wicket-examples/1.4.7/war?Web-ContextPath=wicket
war:file:
URL. For example, to deploy the WAR file, wicket-example-1.4.6.war
, enter the following console command:
JBossFuse:karaf@root> install war:file://wicket-examples-1.4.7.war?Web-ContextPath=wicket
Accessing the Web application
Web-ContextPath
option. For example, the wicket-example
WAR deployed in the preceding examples, would be accessible from the following URL:
http://localhost:8181/wicket
Default conversion parameters
Web-ContextPath
Manifest header). By default, the deployed WAR is configured as an isolated bundle (neither importing nor exporting any packages). This mimics the deployment model of a WAR inside a J2EE container, where the WAR is completely self-contained, including all of the JAR files it needs.
Customizing the conversion parameters
Bundle-ClassPath
, because the default value of Bundle-ClassPath
does not include all of the resources in the WAR file (see Table A.2, “Default Instructions for Wrapping a WAR File”).
References
web.xml
file, automatically deploys the WAR in a Web container. The War Protocol page has the original reference documentation for the War URL handler.
15.2. Configuring the Web Container
Overview
Configuration file
EsbInstallDir/etc/org.ops4j.pax.web.cfg
EsbInstallDir/etc/
directory.
Customizing the HTTP port
etc/org.ops4j.pax.web.cfg
file and setting the value of the org.osgi.service.http.port
property, as follows:
# Configure the Web container org.osgi.service.http.port=8181
Enabling SSL/TLS security
Reference
Part V. OSGi Service Layer
Abstract
Chapter 16. OSGi Services
Abstract
16.1. The Blueprint Container
Abstract
16.1.1. Blueprint Configuration
Location of blueprint files in a JAR file
OSGI-INF/blueprint
.xml
, under this directory are interpreted as blueprint configuration files; in other words, any files that match the pattern, OSGI-INF/blueprint/*.xml
.
Location of blueprint files in a Maven project
ProjectDir/src/main/resources/OSGI-INF/blueprint
Blueprint namespace and root element
http://www.osgi.org/xmlns/blueprint/v1.0.0
blueprint
, so a blueprint XML configuration file normally has the following outline form:
<?xml version="1.0" encoding="UTF-8"?> <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"> ... </blueprint>
blueprint
root element, there is no need to specify the location of the blueprint schema using an xsi:schemaLocation
attribute, because the schema location is already known to the blueprint framework.
Blueprint Manifest configuration
META-INF/MANIFEST.MF
, as follows:
Custom Blueprint file locations
OSGI-INF/blueprint/*.xml
), you can specify a comma-separated list of alternative locations in the Bundle-Blueprint
header in the manifest file—for example:
Bundle-Blueprint: lib/account.xml, security.bp, cnf/*.xml
Mandatory dependencies
availability
attribute to optional
on a reference
element or a reference-list
element). Declaring a dependency to be mandatory means that the bundle cannot function properly without that dependency and the dependency must be available at all times.
Bundle-SymbolicName
manifest header to configure the grace period:
blueprint.graceperiod
- If
true
(the default), the grace period is enabled and the blueprint container waits for mandatory dependencies to be resolved during initialization; iffalse
, the grace period is skipped and the container does not check whether the mandatory dependencies are resolved. blueprint.timeout
- Specifies the grace period timeout in milliseconds. The default is 300000 (5 minutes).
Bundle-SymbolicName
header in the manifest file:
Bundle-SymbolicName: org.fusesource.example.osgi-client; blueprint.graceperiod:=true; blueprint.timeout:= 10000
Bundle-SymbolicName
header is a semi-colon separated list, where the first item is the actual bundle symbolic name, the second item, blueprint.graceperiod:=true
, enables the grace period and the third item, blueprint.timeout:= 10000
, specifies a 10 second timeout.
16.1.2. Defining a Service Bean
Overview
bean
element. You can create all of your main application objects this way. In particular, you can use the bean
element to create a Java object that represents an OSGi service instance.
Blueprint bean element
bean
element is defined in the blueprint schema namespace, http://www.osgi.org/xmlns/blueprint/v1.0.0
. The blueprint {http://www.osgi.org/xmlns/blueprint/v1.0.0}bean
element should not be confused with the Spring {http://www.springframework.org/schema/beans}bean
selement, which has a similar syntax but is defined in a different namespace.
bean
element under the beans
root element, (as long as you define each bean
elements using the appropriate namespace prefix).
Sample beans
bean
element enables you to create objects using a similar syntax to the conventional Spring bean
element. One significant difference, however, is that blueprint constructor arguments are specified using the argument
child element, in contrast to Spring's constructor-arg
child element. The following example shows how to create a few different types of bean using blueprint's bean
element:
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"> <bean id="label" class="java.lang.String"> <argument value="LABEL_VALUE"/> </bean> <bean id="myList" class="java.util.ArrayList"> <argument type="int" value="10"/> </bean> <bean id="account" class="org.fusesource.example.Account"> <property name="accountName" value="john.doe"/> <property name="balance" value="10000"/> </bean> </blueprint>
Account
class referenced by the last bean example could be defined as follows:
// Java package org.fusesource.example; public class Account { private String accountName; private int balance; public Account () { } public void setAccountName(String name) { this.accountName = name; } public void setBalance(int bal) { this.balance = bal; } ... }
Differences between Blueprint and Spring
bean
element and the Spring bean
element are similar, there are a few differences, as you can see from Table 16.1, “Comparison of Spring bean with Blueprint bean”. In this table, the XML tags (identifiers enclosed in angle brackets) refer to child elements of bean
and the plain identifiers refer to attributes.
Table 16.1. Comparison of Spring bean with Blueprint bean
Spring DM Attributes/Tags | Blueprint Attributes/Tags |
---|---|
id | id |
name /<alias> | N/A |
class | class |
scope | scope=("singleton"|"prototype") |
lazy-init=("true"|"false") | activation=("eager"|"lazy") |
depends-on | depends-on |
init-method | init-method |
destroy-method | destroy-method |
factory-method | factory-bean |
factory-bean | factory-ref |
<constructor-arg> | <argument> |
<property> | <property> |
scope
attribute is singleton
and the default value of the blueprint activation
attribute is eager
.
References
- Spring Dynamic Modules Reference Guide v2.0 (see the blueprint chapters).
- Section 121 Blueprint Container Specification, from the OSGi Compendium Services R4.2 specification.
16.1.3. Exporting a Service
Overview
Exporting with a single interface
service
element that references the relevant service bean, using the ref
attribute, and specifies the published interface, using the interface
attribute.
SavingsAccountImpl
class under the org.fusesource.example.Account
interface name using the blueprint configuration code shown in Example 16.1, “Sample Service Export with a Single Interface”.
Example 16.1. Sample Service Export with a Single Interface
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<bean id="savings" class="org.fusesource.example.SavingsAccountImpl"/>
<service ref="savings" interface="org.fusesource.example.Account"/>
</blueprint>
ref
attribute specifies the ID of the corresponding bean instance and the interface
attribute specifies the name of the public Java interface under which the service is registered in the OSGi service registry. The classes and interfaces used in this example are shown in Example 16.2, “Sample Account Classes and Interfaces”
Example 16.2. Sample Account Classes and Interfaces
// Java package org.fusesource.example public interface Account { ... } public interface SavingsAccount { ... } public interface CheckingAccount { ... } public class SavingsAccountImpl implements SavingsAccount { ... } public class CheckingAccountImpl implements CheckingAccount { ... }
Exporting with multiple interfaces
service
element that references the relevant service bean, using the ref
attribute, and specifies the published interfaces, using the interfaces
child element.
SavingsAccountImpl
class under the list of public Java interfaces, org.fusesource.example.Account
and org.fusesource.example.SavingsAccount
, using the following blueprint configuration code:
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"> <bean id="savings" class="org.fusesource.example.SavingsAccountImpl"/> <service ref="savings"> <interfaces> <value>org.fusesource.example.Account</value> <value>org.fusesource.example.SavingsAccount</value> </interfaces> </service> ... </blueprint>
interface
attribute and the interfaces
element cannot be used simultaneously in the same service
element. You must use either one or the other.
Exporting with auto-export
auto-export
attribute.
SavingsAccountImpl
class under all of its implemented public interfaces, use the following blueprint configuration code:
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"> <bean id="savings" class="org.fusesource.example.SavingsAccountImpl"/> <service ref="savings" auto-export="interfaces"/> ... </blueprint>
interfaces
value of the auto-export
attribute indicates that blueprint should register all of the public interfaces implemented by SavingsAccountImpl
. The auto-export
attribute can have the following valid values:
disabled
- Disables auto-export. This is the default.
interfaces
- Registers the service under all of its implemented public Java interfaces.
class-hierarchy
- Registers the service under its own type (class) and under all super-types (super-classes), except for the
Object
class. all-classes
- Like the
class-hierarchy
option, but including all of the implemented public Java interfaces as well.
Setting service properties
service-properties
child element that contains one or more beans:entry
elements (one beans:entry
element for each service property).
bank.name
string property with a savings account service, you could use the following blueprint configuration:
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:beans="http://www.springframework.org/schema/beans" ...> ... <service ref="savings" auto-export="interfaces"> <service-properties> <beans:entry key="bank.name" value="HighStreetBank"/> </service-properties> </service> ... </blueprint>
bank.name
string property has the value, HighStreetBank
. It is possible to define service properties of type other than string: that is, primitive types, arrays, and collections are also supported. For details of how to define these types, see Controlling the Set of Advertised Properties. in the Spring Reference Guide.
entry
element ought to belong to the blueprint namespace. The use of the beans:entry
element in Spring's implementation of blueprint is non-standard.
Default service properties
service
element, as follows:
osgi.service.blueprint.compname
—is always set to theid
of the service'sbean
element, unless the bean is inlined (that is, the bean is defined as a child element of theservice
element). Inlined beans are always anonymous.service.ranking
—is automatically set, if the ranking attribute is non-zero.
Specifying a ranking attribute
0
being the default. You can specify the service ranking by setting the ranking
attribute on the service
element—for example:
<service ref="savings" interface="org.fusesource.example.Account" ranking="10"/>
Specifying a registration listener
registration-listener
child element to a service
element.
listenerBean
, which is referenced by a registration-listener
element, so that the listener bean receives callbacks whenever an Account
service is registered or unregistered:
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" ...> ... <bean id="listenerBean" class="org.fusesource.example.Listener"/> <service ref="savings" auto-export="interfaces"> <registration-listener ref="listenerBean" registration-method="register" unregistration-method="unregister"/> </service> ... </blueprint>
registration-listener
element's ref
attribute references the id
of the listener bean, the registration-method
attribute specifies the name of the listener method that receives the registration callback, and unregistration-method
attribute specifies the name of the listener method that receives the unregistration callback.
Listener
class that receives notifications of registration and unregistration events:
// Java package org.fusesource.example; public class Listener { public void register(Account service, java.util.Map serviceProperties) { ... } public void unregister(Account service, java.util.Map serviceProperties) { ... } }
register
and unregister
, are specified by the registration-method
and unregistration-method
attributes respectively. The signatures of these methods must conform to the following syntax:
- First method argument—any type T that is assignable from the service object's type. In other words, any supertype class of the service class or any interface implemented by the service class. This argument contains the service instance, unless the service bean declares the
scope
to beprototype
, in which case this argument isnull
(when the scope isprototype
, no service instance is available at registration time). - Second method argument—must be of either
java.util.Map
type orjava.util.Dictionary
type. This map contains the service properties associated with this service registration.
16.1.4. Importing a Service
Overview
reference
element or the reference-list
element to import an OSGi service. The key difference between these elements is not (as you might at first be tempted to think) that reference
returns a single service reference, while reference-list
returns a list of service references. Rather, the real difference is that the reference
element is suitable for accessing stateless services, while the reference-list
element is suitable for accessing stateful services.
Managing service references
Reference manager
reference
element. This element returns a single service reference and is the preferred approach for accessing stateless services. Figure 16.1, “Reference to Stateless Service” shows an overview of the model for accessing a stateless service using the reference manager.
Figure 16.1. Reference to Stateless Service
- If multiple services instances are found that match the criteria in the
reference
element, the reference manager can arbitrarily choose one of them as the backing instance (because they are interchangeable). - If the backing service disappears, the reference manager can immediately switch to using one of the other available services of the same type. Hence, there is no guarantee, from one method invocation to the next, that the proxy remains connected to the same backing service.
ServiceUnavailable
exception. The length of the timeout is configurable by setting the timeout
attribute on the reference
element.
Reference list manager
reference-list
element. This element returns a list of service references and is the preferred approach for accessing stateful services. Figure 16.2, “List of References to Stateful Services” shows an overview of the model for accessing a stateful service using the reference list manager.
Figure 16.2. List of References to Stateful Services
java.util.List
object (the provided object), which contains a list of proxy objects. Each proxy is backed by a unique service instance in the OSGi service registry. Unlike the stateless model, backing services are not considered to be interchangeable here. In fact, the lifecycle of each proxy in the list is tightly linked to the lifecycle of the corresponding backing service: when a service gets registered in the OSGi registry, a corresponding proxy is synchronously created and added to the proxy list; and when a service gets unregistered from the OSGi registry, the corresponding proxy is synchronously removed from the proxy list.
ServiceUnavailable
exception.
Matching by interface (stateless)
interface
attribute on the reference
element. The service is deemed to match, if the interface
attribute value is a super-type of the service or if the attribute value is a Java interface implemented by the service (the interface
attribute can specify either a Java class or a Java interface).
SavingsAccount
service (see Example 16.1, “Sample Service Export with a Single Interface”), define a reference
element as follows:
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"> <reference id="savingsRef" interface="org.fusesource.example.SavingsAccount"/> <bean id="client" class="org.fusesource.example.client.Client"> <property name="savingsAccount" ref="savingsRef"/> </bean> </blueprint>
reference
element creates a reference manager bean with the ID, savingsRef
. To use the referenced service, inject the savingsRef
bean into one of your client classes, as shown.
SavingsAccount
. For example, you could define the Client
class as follows:
package org.fusesource.example.client; import org.fusesource.example.SavingsAccount; public class Client { SavingsAccount savingsAccount; // Bean properties public SavingsAccount getSavingsAccount() { return savingsAccount; } public void setSavingsAccount(SavingsAccount savingsAccount) { this.savingsAccount = savingsAccount; } ... }
Matching by interface (stateful)
interface
attribute on the reference-list
element. The reference list manager then obtains a list of all the services, whose interface
attribute value is either a super-type of the service or a Java interface implemented by the service (the interface
attribute can specify either a Java class or a Java interface).
SavingsAccount
service (see Example 16.1, “Sample Service Export with a Single Interface”), define a reference-list
element as follows:
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"> <reference-list id="savingsListRef" interface="org.fusesource.example.SavingsAccount"/> <bean id="client" class="org.fusesource.example.client.Client"> <property name="savingsAccountList" ref="savingsListRef"/> </bean> </blueprint>
reference-list
element creates a reference list manager bean with the ID, savingsListRef
. To use the referenced service list, inject the savingsListRef
bean reference into one of your client classes, as shown.
savingsAccountList
bean property is a list of service objects (for example, java.util.List<SavingsAccount>
). You could define the client class as follows:
package org.fusesource.example.client; import org.fusesource.example.SavingsAccount; public class Client { java.util.List<SavingsAccount> accountList; // Bean properties public java.util.List<SavingsAccount> getSavingsAccountList() { return accountList; } public void setSavingsAccountList( java.util.List<SavingsAccount> accountList ) { this.accountList = accountList; } ... }
Matching by interface and component name
interface
attribute and the component-name
attribute on the reference
element, as follows:
<reference id="savingsRef" interface="org.fusesource.example.SavingsAccount" component-name="savings"/>
interface
attribute and the component-name
attribute on the reference-list
element, as follows:
<reference-list id="savingsRef" interface="org.fusesource.example.SavingsAccount" component-name="savings"/>
Matching service properties with a filter
filter
attribute on the reference
element or on the reference-list
element. The value of the filter
attribute must be an LDAP filter expression. For example, to define a filter that matches when the bank.name
service property equals HighStreetBank
, you could use the following LDAP filter expression:
(bank.name=HighStreetBank)
&
conjunction, which combines expressions with a logical and
.For example, to require that the foo
property is equal to FooValue
and the bar
property is equal to BarValue
, you could use the following LDAP filter expression:
(&(foo=FooValue)(bar=BarValue))
interface
and component-name
settings, in which case all of the specified conditions are required to match.
SavingsAccount
type, with a bank.name
service property equal to HighStreetBank
, you could define a reference
element as follows:
<reference id="savingsRef" interface="org.fusesource.example.SavingsAccount" filter="(bank.name=HighStreetBank)"/>
SavingsAccount
type, with a bank.name
service property equal to HighStreetBank
, you could define a reference-list
element as follows:
<reference-list id="savingsRef" interface="org.fusesource.example.SavingsAccount" filter="(bank.name=HighStreetBank)"/>
Specifying whether mandatory or optional
reference
element or a reference-list
element by setting the availability
attribute on the element. There are two possible values of the availability
attribute: mandatory
(the default), means that the dependency must be resolved during a normal blueprint container initialization; and optional
, means that the dependency need not be resolved during initialization.
reference
element shows how to declare explicitly that the reference is a mandatory dependency:
<reference id="savingsRef" interface="org.fusesource.example.SavingsAccount" availability="mandatory"/>
Specifying a reference listener
optional
availability—it is often useful to track when a backing service gets bound to the registry and when it gets unbound from the registry. To receive notifications of service binding and unbinding events, you can define a reference-listener
element as the child of either the reference
element or the reference-list
element.
savingsRef
:
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"> <reference id="savingsRef" interface="org.fusesource.example.SavingsAccount" > <reference-listener bind-method="onBind" unbind-method="onUnbind"> <bean class="org.fusesource.example.client.Listener"/> </reference-listener> </reference> <bean id="client" class="org.fusesource.example.client.Client"> <property name="savingsAcc" ref="savingsRef"/> </bean> </blueprint>
org.fusesource.example.client.Listener
type as a callback that listens for bind
and unbind
events. Events are generated whenever the savingsRef
reference manager's backing service binds or unbinds.
Listener
class:
package org.fusesource.example.client; import org.osgi.framework.ServiceReference; public class Listener { public void onBind(ServiceReference ref) { System.out.println("Bound service: " + ref); } public void onUnbind(ServiceReference ref) { System.out.println("Unbound service: " + ref); } }
onBind
and onUnbind
, are specified by the bind-method
and unbind-method
attributes respectively. Both of these callback methods take an org.osgi.framework.ServiceReference
argument.
16.2. Publishing an OSGi Service
Overview
Prerequisites
- Maven installation—Maven is a free, open source build tool from Apache. You can download the latest version from http://maven.apache.org/download.html (minimum is 2.0.9).
- Internet connection—whilst performing a build, Maven dynamically searches external repositories and downloads the required artifacts on the fly. In order for this to work, your build machine must be connected to the Internet.
Generating a Maven project
maven-archetype-quickstart
archetype creates a generic Maven project, which you can then customize for whatever purpose you like. To generate a Maven project with the coordinates, org.fusesource.example:osgi-service
, enter the following command:
mvn archetype:create -DarchetypeArtifactId=maven-archetype-quickstart -DgroupId=org.fusesource.example -DartifactId=osgi-service
ProjectDir/osgi-service
, containing the files for the generated project.
Customizing the POM file
- Follow the POM customization steps described in Section 6.1, “Generating a Bundle Project”.
- In the configuration of the Maven bundle plug-in, modify the bundle instructions to export the
org.fusesource.example.service
package, as follows:<project ... > ... <build> ... <plugins> ... <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Bundle-SymbolicName>${pom.groupId}.${pom.artifactId}</Bundle-SymbolicName> <Export-Package>org.fusesource.example.service</Export-Package> </instructions> </configuration> </plugin> </plugins> </build> ... </project>
Writing the service interface
ProjectDir/osgi-service/src/main/java/org/fusesource/example/service
sub-directory. In this directory, use your favorite text editor to create the file, HelloWorldSvc.java
, and add the code from Example 16.3, “The HelloWorldSvc Interface” to it.
Example 16.3. The HelloWorldSvc Interface
// Java package org.fusesource.example.service; public interface HelloWorldSvc { public void sayHello(); }
Writing the service class
ProjectDir/osgi-service/src/main/java/org/fusesource/example/service/impl
sub-directory. In this directory, use your favorite text editor to create the file, HelloWorldSvcImpl.java
, and add the code from Example 16.4, “The HelloWorldSvcImpl Class” to it.
Example 16.4. The HelloWorldSvcImpl Class
package org.fusesource.example.service.impl; import org.fusesource.example.service.HelloWorldSvc; public class HelloWorldSvcImpl implements HelloWorldSvc { public void sayHello() { System.out.println( "Hello World!" ); } }
Writing the blueprint file
OSGI-INF/blueprint
directory on the class path. To add a blueprint file to your project, first create the following sub-directories:
ProjectDir/osgi-service/src/main/resources ProjectDir/osgi-service/src/main/resources/OSGI-INF ProjectDir/osgi-service/src/main/resources/OSGI-INF/blueprint
src/main/resources
is the standard Maven location for all JAR resources. Resource files under this directory will automatically be packaged in the root scope of the generated bundle JAR.
HelloWorldSvc
bean, using the bean
element, and then exports the bean as an OSGi service, using the service
element.
ProjectDir/osgi-service/src/main/resources/OSGI-INF/blueprint
directory, use your favorite text editor to create the file, config.xml
, and add the XML code from Example 16.5, “Blueprint File for Exporting a Service”.
Example 16.5. Blueprint File for Exporting a Service
<?xml version="1.0" encoding="UTF-8"?> <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"> <bean id="hello" class="org.fusesource.example.service.impl.HelloWorldSvcImpl"/> <service ref="hello" interface="org.fusesource.example.service.HelloWorldSvc"/> </blueprint>
Running the service bundle
osgi-service
project, perform the following steps:
- Build the project—open a command prompt and change directory to
ProjectDir/osgi-service
. Use Maven to build the demonstration by entering the following command:mvn install
If this command runs successfully, theProjectDir/osgi-service/target
directory should contain the bundle file,osgi-service-1.0-SNAPSHOT.jar
. - Install and start the osgi-service bundle—at the Red Hat JBoss Fuse console, enter the following command:
JBossFuse:karaf@root> osgi:install -s file:ProjectDir/osgi-service/target/osgi-service-1.0-SNAPSHOT.jar
Where ProjectDir is the directory containing your Maven projects and the-s
flag directs the container to start the bundle right away. For example, if your project directory isC:\Projects
on a Windows machine, you would enter the following command:JBossFuse:karaf@root> osgi:install -s file:C:/Projects/osgi-service/target/osgi-service-1.0-SNAPSHOT.jar
NoteOn Windows machines, be careful how you format thefile
URL—for details of the syntax understood by thefile
URL handler, see Section A.1, “File URL Handler”. - Check that the service has been created—to check that the bundle has started successfully, enter the following Red Hat JBoss Fuse console command:
JBossFuse:karaf@root> osgi:list
Somewhere in this listing, you should see a line for theosgi-service
bundle, for example:[ 236] [Active ] [Created ] [ ] [ 60] osgi-service (1.0.0.SNAPSHOT)
To check that the service is registered in the OSGi service registry, enter a console command like the following:JBossFuse:karaf@root> osgi:ls 236
Where the argument to the preceding command is theosgi-service
bundle ID. You should see some output like the following at the console:osgi-service (236) provides: ---------------------------- osgi.service.blueprint.compname = hello objectClass = org.fusesource.example.service.HelloWorldSvc service.id = 272 ---- osgi.blueprint.container.version = 1.0.0.SNAPSHOT osgi.blueprint.container.symbolicname = org.fusesource.example.osgi-service objectClass = org.osgi.service.blueprint.container.BlueprintContainer service.id = 273
16.3. Accessing an OSGi Service
Overview
sayHello()
method on it.
Prerequisites
- Maven installation—Maven is a free, open source build tool from Apache. You can download the latest version from http://maven.apache.org/download.html (minimum is 2.0.9).
- Internet connection—whilst performing a build, Maven dynamically searches external repositories and downloads the required artifacts on the fly. In order for this to work, your build machine must be connected to the Internet.
Generating a Maven project
maven-archetype-quickstart
archetype creates a generic Maven project, which you can then customize for whatever purpose you like. To generate a Maven project with the coordinates, org.fusesource.example:osgi-client
, enter the following command:
mvn archetype:create -DarchetypeArtifactId=maven-archetype-quickstart -DgroupId=org.fusesource.example -DartifactId=osgi-client
ProjectDir/osgi-client
, containing the files for the generated project.
Customizing the POM file
- Follow the POM customization steps described in Section 6.1, “Generating a Bundle Project”.
- Because the client uses the
HelloWorldSvc
Java interface, which is defined in theosgi-service
bundle, it is necessary to add a Maven dependency on theosgi-service
bundle. Assuming that the Maven coordinates of theosgi-service
bundle areorg.fusesource.example:osgi-service:1.0-SNAPSHOT
, you should add the following dependency to the client's POM file:<project ... > ... <dependencies> ... <dependency> <groupId>org.fusesource.example</groupId> <artifactId>osgi-service</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> ... </project>
Writing the Blueprint file
ProjectDir/osgi-client/src/main/resources ProjectDir/osgi-client/src/main/resources/OSGI-INF ProjectDir/osgi-client/src/main/resources/OSGI-INF/blueprint
ProjectDir/osgi-client/src/main/resources/OSGI-INF/blueprint
directory, use your favorite text editor to create the file, config.xml
, and add the XML code from Example 16.6, “Blueprint File for Importing a Service”.
Example 16.6. Blueprint File for Importing a Service
<?xml version="1.0" encoding="UTF-8"?> <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"> <reference id="helloWorld" interface="org.fusesource.example.service.HelloWorldSvc"/> <bean id="client" class="org.fusesource.example.client.Client" init-method="init"> <property name="helloWorldSvc" ref="helloWorld"/> </bean> </blueprint>
reference
element creates a reference manager that finds a service of HelloWorldSvc
type in the OSGi registry. The bean
element creates an instance of the Client
class and injects the service reference as the bean property, helloWorldSvc
. In addition, the init-method
attribute specifies that the Client.init()
method is called during the bean initialization phase (that is, after the service reference has been injected into the client bean).
Writing the client class
ProjectDir/osgi-client/src/main/java/org/fusesource/example/client
directory, use your favorite text editor to create the file, Client.java
, and add the Java code from Example 16.7, “The Client Class”.
Example 16.7. The Client Class
// Java package org.fusesource.example.client; import org.fusesource.example.service.HelloWorldSvc; public class Client { HelloWorldSvc helloWorldSvc; // Bean properties public HelloWorldSvc getHelloWorldSvc() { return helloWorldSvc; } public void setHelloWorldSvc(HelloWorldSvc helloWorldSvc) { this.helloWorldSvc = helloWorldSvc; } public void init() { System.out.println("OSGi client started."); if (helloWorldSvc != null) { System.out.println("Calling sayHello()"); helloWorldSvc.sayHello(); // Invoke the OSGi service! } } }
Client
class defines a getter and a setter method for the helloWorldSvc
bean property, which enables it to receive the reference to the Hello World service by injection. The init()
method is called during the bean initialization phase, after property injection, which means that it is normally possible to invoke the Hello World service within the scope of this method.
Running the client bundle
osgi-client
project, perform the following steps:
- Build the project—open a command prompt and change directory to
ProjectDir/osgi-client
. Use Maven to build the demonstration by entering the following command:mvn install
If this command runs successfully, theProjectDir/osgi-client/target
directory should contain the bundle file,osgi-client-1.0-SNAPSHOT.jar
. - Install and start the osgi-service bundle—at the Red Hat JBoss Fuse console, enter the following command:
JBossFuse:karaf@root> osgi:install -s file:ProjectDir/osgi-client/target/osgi-client-1.0-SNAPSHOT.jar
Where ProjectDir is the directory containing your Maven projects and the-s
flag directs the container to start the bundle right away. For example, if your project directory isC:\Projects
on a Windows machine, you would enter the following command:JBossFuse:karaf@root> osgi:install -s file:C:/Projects/osgi-client/target/osgi-client-1.0-SNAPSHOT.jar
NoteOn Windows machines, be careful how you format thefile
URL—for details of the syntax understood by thefile
URL handler, see Section A.1, “File URL Handler”. - Client output—f the client bundle is started successfully, you should immediately see output like the following in the console:
Bundle ID: 239 OSGi client started. Calling sayHello() Hello World!
16.4. Integration with Apache Camel
Overview
Registry chaining
CamelContext
automatically sets up a registry chain for resolving bean instances: the registry chain consists of the OSGi registry, followed by the blueprint (or Spring) registry. Now, if you try to reference a particular bean class or bean instance, the registry resolves the bean as follows:
- Look up the bean in the OSGi registry first. If a class name is specified, try to match this with the interface or class of an OSGi service.
- If no match is found in the OSGi registry, fall back on the blueprint registry (or the Spring registry, if you are using the Spring-DM container).
Sample OSGi service interface
getGreeting()
:
// Java package org.fusesource.example.hello.boston; public interface HelloBoston { public String getGreeting(); }
Sample service export
HelloBoston
OSGi service, you could use the following blueprint configuration to export the service:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<bean id="hello" class="org.fusesource.example.hello.boston.HelloBostonImpl"/>
<service ref="hello" interface="org.fusesource.example.hello.boston.HelloBoston"/>
</blueprint>
HelloBoston
interface is implemented by the HelloBostonImpl
class (not shown).
Invoking the OSGi service from Java DSL
HelloBoston
OSGi service, you can invoke the service from a Apache Camel application using the Java DSL. In the Java DSL, you invoke the OSGi service through the Bean language, as follows:
from("timer:foo?period=5000")
.bean(org.fusesource.example.hello.boston.HelloBoston.class, "getGreeting")
.log("The message contains: ${body}")
bean
command, the first argument is the OSGi interface or class, which must match the interface exported from the OSGi service bundle. The second argument is the name of the bean method you want to invoke. For full details of the bean
command syntax, see section "Bean Integration" in "Apache Camel Development Guide".
Invoking the OSGi service from XML DSL
HelloBoston
OSGi service, but the syntax is slightly different. In the XML DSL, you invoke the OSGi service through the Bean language, using the method
element, as follows:
<beans ...> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="timer:foo?period=5000"/> <setBody> <method ref="org.fusesource.example.hello.boston.HelloBoston" method="getGreeting"/> </setBody> <log message="The message contains: ${body}"/> </route> </camelContext> </beans>
Part VI. Asynchronous Communication
Abstract
Chapter 17. JMS Broker
Abstract
17.1. Working with the Default Broker
Abstract
Overview
61616
. The broker remains installed in the container and activates whenever you restart the container.
Broker configuration
etc/activemq.xml
—a standard Apache ActiveMQ configuration file that serves as a template for the default broker's configuration. It contains property place holders, specified using the syntax${propName}
, that allow you to set the values of the actual property using the OSGi Admin service.etc/org.fusesource.mq.fabric.server-default.cfg
—the OSGi configuration file that specifies the values for the properties in the broker's template configuration file.
Broker data
data/activemq
. You can change this location using the config command to change the broker's data property as shown in Example 17.1, “Configuring the Default Broker's Data Directory”.
Example 17.1. Configuring the Default Broker's Data Directory
JBossFuse:karaf@root>
config:edit org.fusesource.mq.fabric.server.3e3d0055-1c5f-40e3-987e-024c1fac1c3f
JBossFuse:karaf@root>
config:propset data dataStore
JBossFuse:karaf@root>
config:exit
Disabling the default broker
- From the JBoss Fuse command console, delete the configuration PID using the config:delete command as shown in Example 17.2, “Deleting the Default Broker Configuration”.
Example 17.2. Deleting the Default Broker Configuration
JBossFuse:karaf@root>
config:delete org.fusesource.mq.fabric.server.xxx
xxx is the system generated ID for the broker. You can find this value using the config:list command. - From the system terminal, delete the actual configuration file
etc/org.fusesource.mq.fabric.server-default.cfg
.
17.2. JMS Endpoints in a Router Application
Overview
camel.timer
queue in the JMS broker; and then writes the messages to a specific directory in the file system.
Prerequisites
activemq-camel
feature installed in the OSGi container. The activemq-camel
component is needed for defining Apache ActiveMQ-based JMS endpoints in Apache Camel. This feature is not installed by default, so you must install it using the following console command:
JBossFuse:karaf@root> features:install activemq-camel
activemq
feature, but this feature is normally available, because Red Hat JBoss Fuse installs it by default.
camel-ComponentName
.
Router configuration
Example 17.3. Sample Route with JMS Endpoints
<?xml version="1.0"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring"> <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent"> <property name="brokerURL" value="tcp://localhost:61616"/> </bean> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="timer://MyTimer?fixedRate=true&period=4000"/> <setBody><constant>Hello World!</constant></setBody> <to uri="activemq:camel.timer"/> </route> <route> <from uri="activemq:camel.timer"/> <to uri="file:C:/temp/sandpit/timer"/> </route> </camelContext> </beans>
Camel activemq component
activemq
component, because you need to specify the connection details for connecting to the broker. The preceding example uses Spring syntax to instantiate the activemq
bean which connects to the broker URL, tcp://localhost:61616
. The broker URL must correspond to one of the transport connectors defined in the broker configuration file, deploy/test-broker.xml
.
Sample routes
- The first route uses a
timer
endpoint to generate messages at four-second intervals. ThesetBody
element places a dummy string in the body of the message (which would otherwise benull
). The messages are then sent to thecamel.timer
queue on the broker (theactivemq:camel.timer
endpoint).NoteTheactivemq
scheme inactivemq:camel.timer
is resolved by looking upactivemq
in the bean registry, which resolves to the locally instantiated bean with ID,activemq
. - The second route pulls messages off the
camel.timer
queue and then writes the messages to the specified directory,C:\temp\sandpit\timer
, in the file system.
Steps to run the example
- Using your favorite text editor, copy and paste the router configuration from Example 17.3, “Sample Route with JMS Endpoints” into a file called
camel-timer.xml
.Edit the file endpoint in the second route, in order to change the target directory to a suitable location on your file system:<route> <from uri="activemq:camel.timer"/> <to uri="file:YourDirectoryHere!"/> </route>
- Start up a local instance of the Red Hat JBoss Fuse runtime by entering the following at a command prompt:
servicemix
- Make sure the requisite features are installed in the OSGi container. To install the
activemq-camel
feature, enter the following command at the console:JBossFuse:karaf@root> features:install activemq-camel
To ensure that theactivemq-broker
feature is not installed, enter the following command at the console:JBossFuse:karaf@root> features:uninstall activemq-broker
- Use one of the following alternatives to obtain a broker instance for this demonstration:
- Use the default broker—assuming you have not disabled the default broker, you can use it for this demonstration, because it is listening on the correct port, 61616.
- Create a new broker instance using the console—if you prefer not to use the default broker, you can disable it (as described in Section 17.1, “Working with the Default Broker”) and then create a new JMS broker instance by entering the following command at the console:
JBossFuse:karaf@root> activemq:create-broker --name test
After executing this command, you should see the broker configuration file,test-broker.xml
, in theInstallDir/deploy
directory.
- Hot deploy the router configuration you created in step 1. Copy the
camel-timer.xml
file into theInstallDir/deploy
directory. - Within a few seconds, you should start to see files appearing in the target directory (which is
C:\temp\sandpit\timer
, by default). The file component automatically generates a unique filename for each message that it writes.It is also possible to monitor activity in the JMS broker by connecting to the Red Hat JBoss Fuse runtime's JMX port. To monitor the broker using JMX, perform the following steps:- To monitor the JBoss Fuse runtime, start a JConsole instance (a standard Java utility) by entering the following command:
jconsole
- Initially, a JConsole: Connect to Agent dialog prompts you to connect to a JMX port. From the Local tab, select the
org.apache.felix.karaf.main.Bootstrap
entry and click Connect. - In the main JConsole window, click on the MBeans tab and then drill down to
org.apache.activemq|test|Queue
in the MBean tree (assuming thattest
is the name of your broker). - Under the
Queue
folder, you should see thecamel.timer
queue. Click on thecamel.timer
queue to view statistics on the message throughput of this queue.
- To shut down the router application, delete the
camel-timer.xml
file from theInstallDir/deploy
directory.
Chapter 18. Inter-Bundle Communication with the NMR
Abstract
18.1. Architecture of the NMR
Overview
Figure 18.1. NMR Architecture
NMR
NMR for OSGi
Normalized messages in the JBI container
- Content—the main content of a normalized message must be in XML format, where the layout of a particular message is defined in a WSDL service description.
- Attachments—for sending binary content, you can add attachments to the normalized message.
- Properties—consist of name/value pairs.
- Security subject—identifies the sender, if security features are enabled.
Normalized messages in the OSGi container
- Content—the main content of a normalized message, which can be in any format.
- Attachments—for sending binary attachments.
- Properties—consist of name/value pairs.
- Security subject—identifies the sender, if security features are enabled.
NMR API
examples/nmr
demonstration code.
NMR component for Apache Camel
from("nmr:ExampleEndpoint")
) or at the end (for example, to("nmr:ExampleEndpoint")
) of a route. For full details of how to use the NMR component, see Section 18.2, “The Apache Camel NMR Component”.
nmr
URI scheme, whereas the JBI component (for use in a JBI context) is conventionally identified by the jbi
URI scheme.
18.2. The Apache Camel NMR Component
Overview
Installing the NMR feature
JBossFuse:karaf@root> features:install nmr
Instantiating the NMR component
OSGI-INF/blueprint/*.xml
) in order to instantiate the NMR component.
Example 18.1. Creating the NMR Component Bean
<?xml version="1.0" encoding="UTF-8"?> <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <reference id="nmrservice" interface="org.apache.servicemix.nmr.api.NMR"/> <bean id="nmr" class="org.apache.servicemix.camel.nmr.ServiceMixComponent"> <property name="nmr" ref="nmrservice"/> </bean> </blueprint>
bean
element creates an instance of the NMR component with the bean ID, nmr
, where this bean ID can then be used as the scheme prefix to create or reference NMR endpoints in your Apache Camel routes. The bean definition references two external Java packages—org.apache.servicemix.camel.nmr
and org.apache.servicemix.nmr.api
—which must therefore be imported by this bundle. Because the packages do not occur in Java source code, you must add them explicitly to the list of imported packages in the bundle instructions in the POM—see the section called “Configuring the bundle instructions” for details.
URI format for the NMR component
nmr:EndpointId
nmr
, is actually determined by the ID of the bean that instantiates the NMR component—for example, see Example 18.1, “Creating the NMR Component Bean”.
Addressing JBI endpoints
nmr:JBIAddressingURI
Determining the message exchange pattern
camel-nmr demonstration
camel-nmr
demonstration is located in the following directory:
InstallDir/examples/camel-nmr
- The first route is defined as follows:
- At the start of the route is a
timer
endpoint, which generates a heartbeat event every two seconds. - At the end of the route is an NMR endpoint, which transmits the messages to the next route.
- The second route is defined as follows:
- At the start of the second route is an NMR endpoint, which receives the messages sent by the first route.
- Next comes a callout to a transformer bean (implemented in Java), which transforms the hearbeat into a message containing the current date and time.
- At the end of the route is a
log
endpoint, which sends the transformed message to Jakarta commons logger.
Defining the route in a Blueprint XML file
camel-nmr
demonstration, taken from the Blueprint XML configuration file, OSGI-INF/blueprint/beans.xml
.
Example 18.2. Blueprint XML Defining a Route with an NMR Endpoint
<?xml version="1.0" encoding="UTF-8"?> <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <reference id="nmrservice" interface="org.apache.servicemix.nmr.api.NMR"/> <bean id="nmr" class="org.apache.servicemix.camel.nmr.ServiceMixComponent"> <property name="nmr" ref="nmrservice"/> </bean> <bean id="myTransform" class="org.apache.servicemix.examples.camel.MyTransform"> <property name="prefix" value="MyTransform"/> </bean> <camelContext xmlns="http://camel.apache.org/schema/blueprint" id="nmr-example-context"> <!-- Route periodic events into the NMR --> <route> <from uri="timer://myTimer?fixedRate=true&period=2000"/> <to uri="nmr:ExampleRouter"/> 1 </route> <!-- Route exchange from the NMR endpoint to a log endpoint --> <route> <from uri="nmr:ExampleRouter"/> 2 <bean ref="myTransform" method="transform"/> <to uri="log:ExampleRouter"/> </route> </camelContext> </blueprint>
- 1
- At the end of the first route, messages are sent to the NMR endpoint,
nmr:ExampleRouter
. - 2
- When you specify an NMR endpoint in the
uri
attribute of the<from>
tag, a new NMR endpoint is created by the NMR component. In this example, the<from>
tag implicitly creates the NMR endpoint,nmr:ExampleRouter
, which is then capable of receiving the messages sent by the first route.
Configuring the bundle instructions
org.apache.servicemix.camel.nmr
org.apache.servicemix.nmr.api
Import-Package
element that contains a list of the packages required for the NMR component:
<project ...>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
<Import-Package>org.apache.servicemix.camel.nmr,org.apache.servicemix.nmr.api,*</Import-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
Import-Package
list also includes the wildcard, *
, which instructs the bundle plug-in to scan the Java source code in order to discover further package dependencies.
Appendix A. URL Handlers
Abstract
A.1. File URL Handler
Syntax
file:
PathName, where PathName is the relative or absolute pathname of a file that is available on the Classpath. The provided PathName is parsed by Java's built-in file URL handler. Hence, the PathName syntax is subject to the usual conventions of a Java pathname: in particular, on Windows, each backslash must either be escaped by another backslash or replaced by a forward slash.
Examples
C:\Projects\camel-bundle\target\foo-1.0-SNAPSHOT.jar
, on Windows. The following example shows the correct alternatives for the file URL on Windows:
file:C:/Projects/camel-bundle/target/foo-1.0-SNAPSHOT.jar file:C:\\Projects\\camel-bundle\\target\\foo-1.0-SNAPSHOT.jar
file:C:\Projects\camel-bundle\target\foo-1.0-SNAPSHOT.jar // WRONG! file://C:/Projects/camel-bundle/target/foo-1.0-SNAPSHOT.jar // WRONG! file://C:\\Projects\\camel-bundle\\target\\foo-1.0-SNAPSHOT.jar // WRONG!
A.2. HTTP URL Handler
Syntax
http:Host[:Port]/[Path][#AnchorName][?Query]
. You can also specify a secure HTTP URL using the https
scheme. The provided HTTP URL is parsed by Java's built-in HTTP URL handler, so the HTTP URL behaves in the normal way for a Java application.
A.3. Mvn URL Handler
Overview
Syntax
mvn:[repositoryUrl!]groupId/artifactId[/[version][/[packaging][/[classifier]]]]
Omitting coordinates
org.fusesource.example
, and with the artifactId, bundle-demo
:
mvn:org.fusesource.example/bundle-demo mvn:org.fusesource.example/bundle-demo/1.1
LATEST
, which resolves to the latest version based on the available Maven metadata.
mvn:groupId/artifactId///classifier mvn:groupId/artifactId/version//classifier mvn:groupId/artifactId//packaging/classifier mvn:groupId/artifactId//packaging
Specifying a version range
[
and ]
—to denote inclusive ranges and parentheses—(
and )
—to denote exclusive ranges. For example, the range, [1.0.4,2.0)
, matches any version, v
, that satisfies 1.0.4 <= v < 2.0
. You can use this version range in an Mvn URL as follows:
mvn:org.fusesource.example/bundle-demo/[1.0.4,2.0)
Configuring the Mvn URL handler
Check the Mvn URL settings
JBossFuse:karaf@root> config:edit org.ops4j.pax.url.mvn JBossFuse:karaf@root> config:proplist
config:edit
command switches the focus of the config
utility to the properties belonging to the org.ops4j.pax.url.mvn
persistent ID. The config:proplist
command outputs all of the property settings for the current persistent ID. With the focus on org.ops4j.pax.url.mvn
, you should see a listing similar to the following:
org.ops4j.pax.url.mvn.localRepository = file:E:/Data/.m2/repository service.pid = org.ops4j.pax.url.mvn org.ops4j.pax.url.mvn.defaultRepositories = file:E:/Programs/FUSE/apache-serv icemix-4.2.0-fuse-SNAPSHOT/system@snapshots felix.fileinstall.filename = org.ops4j.pax.url.mvn.cfg org.ops4j.pax.url.mvn.repositories = http://repo1.maven.org/maven2, http://re po.fusesource.com/maven2, http://repo.fusesource.com/maven2-snapshot@snapshots@n oreleases, http://repository.apache.org/content/groups/snapshots-group@snapshots @noreleases, http://repository.ops4j.org/maven2, http://svn.apache.org/repos/asf /servicemix/m2-repo, http://repository.springsource.com/maven/bundles/release, h ttp://repository.springsource.com/maven/bundles/external
localRepository
setting shows the local repository location currently used by the handler and the repositories
setting shows the remote repository list currently used by the handler.
Edit the configuration file
InstallDir/etc/org.ops4j.pax.url.mvn.cfg
Customize the location of the local repository
org.ops4j.pax.url.mvn.cfg
configuration file, uncomment the org.ops4j.pax.url.mvn.localRepository
property and set it to the location of your local Maven repository. For example:
# Path to the local maven repository which is used to avoid downloading # artifacts when they already exist locally. # The value of this property will be extracted from the settings.xml file # above, or defaulted to: # System.getProperty( "user.home" ) + "/.m2/repository" # org.ops4j.pax.url.mvn.localRepository=file:E:/Data/.m2/repository
Reference
mvn
URL syntax, see the original Pax URL Mvn Protocol documentation.
A.4. Wrap URL Handler
Overview
Syntax
wrap:locationURL[,instructionsURL][$instructions]
&
, delimited list of Bnd properties that specify how the bundle conversion is performed.
Default instructions
META-INF/Manifest.mf
file as shown in Table A.1, “Default Instructions for Wrapping a JAR”.
Table A.1. Default Instructions for Wrapping a JAR
Manifest Header | Default Value |
---|---|
Import-Package | *;resolution:=optional |
Export-Package | All packages from the wrapped JAR. |
Bundle-SymbolicName | The name of the JAR file, where any characters not in the set [a-zA-Z0-9_-] are replaced by underscore, _ . |
Examples
commons-logging
JAR in a Maven repository and converts it to an OSGi bundle using the default Bnd properties:
wrap:mvn:commons-logging/commons-logging/1.1
E:\Data\Examples\commons-logging-1.1.bnd
:
wrap:mvn:commons-logging/commons-logging/1.1,file:E:/Data/Examples/commons-logging-1.1.bnd
Bundle-SymbolicName
property and the Bundle-Version
property explicitly:
wrap:mvn:commons-logging/commons-logging/1.1$Bundle-SymbolicName=apache-comm-log&Bundle-Version=1.1
\$
, to prevent it from being processed by the command line, as follows:
wrap:mvn:commons-logging/commons-logging/1.1\$Bundle-SymbolicName=apache-comm-log&Bundle-Version=1.1
Reference
wrap
URL handler, see the following references:
- The Bnd tool documentation, for more details about Bnd properties and Bnd instruction files.
- The original Pax URL Wrap Protocol documentation.
A.5. War URL Handler
Overview
war:
, as described here.
Syntax
war:warURL warref:instructionsURL
war
scheme, specifies a WAR file that is converted into a bundle using the default instructions. The warURL can be any URL that locates a WAR file.
warref
scheme, specifies a Bnd properties file, instructionsURL, that contains the conversion instructions (including some instructions that are specific to this handler). In this syntax, the location of the referenced WAR file does not appear explicitly in the URL. The WAR file is specified instead by the (mandatory) WAR-URL
property in the properties file.
WAR-specific properties/instructions
.bnd
instructions file are specific to the War URL handler, as follows:
WAR-URL
- (Mandatory) Specifies the location of the War file that is to be converted into a bundle.
Web-ContextPath
- Specifies the piece of the URL path that is used to access this Web application, after it has been deployed inside the Web container.NoteEarlier versions of PAX Web used the property,
Webapp-Context
, which is now deprecated.
Default instructions
META-INF/Manifest.mf
file as shown in Table A.2, “Default Instructions for Wrapping a WAR File”.
Table A.2. Default Instructions for Wrapping a WAR File
Manifest Header | Default Value |
---|---|
Import-Package | javax.*,org.xml.*,org.w3c.* |
Export-Package | No packages are exported. |
Bundle-SymbolicName | The name of the WAR file, where any characters not in the set [a-zA-Z0-9_-\.] are replaced by period, . . |
Web-ContextPath | No default value. But the WAR extender will use the value of Bundle-SymbolicName by default. |
Bundle-ClassPath |
In addition to any class path entries specified explicitly, the following entries are added automatically:
|
Examples
wicket-examples
WAR in a Maven repository and converts it to an OSGi bundle using the default instructions:
war:mvn:org.apache.wicket/wicket-examples/1.4.7/war
Web-ContextPath
explicitly:
war:mvn:org.apache.wicket/wicket-examples/1.4.7/war?Web-ContextPath=wicket
WAR-URL
property in the wicket-examples-1.4.7.bnd
file and then converts the WAR into an OSGi bundle using the other instructions in the .bnd
file:
warref:file:E:/Data/Examples/wicket-examples-1.4.7.bnd
Reference
war
URL syntax, see the original Pax URL War Protocol documentation.
Appendix B. OSGi Best Practices
Abstract
B.1. OSGi Tooling
Overview
Use the Maven bundle plug-in to generate the Manifest
Avoid using the OSGi API directly
Prefer Blueprint over Spring-DM
Use Apache Karaf features to group bundles together
Use the OSGi Configuration Admin service
- Properties integrated with Spring XML files.
- Properties automatically read from configuration files,
etc/persistendId.cfg
- Properties can be set in feature repositories.
Use PAX-Exam for testing
B.2. Building OSGi Bundles
Overview
Use package prefix as the bundle symbolic name
org.fusesource.fooProject
, use org.fusesource.fooProject
as the bundle symbolic name.
Artifact ID should be derived from the bundle symbolic name
- The artifact ID is identical to the bundle symbolic name—this enables you to define the bundle symbolic name in terms of the artifact ID, using the following Maven bundle instruction:
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
- The bundle symbolic name is composed of the group ID and the artifact ID, joined by a dot—this enables you to define the bundle symbolic name in terms of the group ID and the artifact ID, using the following Maven bundle instruction:
<Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
project.*
can be used to reference the value of any element in the current POM. To construct the name of a POM property, take the XPath name of any POM element (for example, project/artifactId
) and replace occurrences of /
with the .
character. Hence, ${project.artifactId}
references the artifactId
element from the current POM.
Always export packages with a version
maven-bundle-plugin
plug-in to export packages with the current artifact version (given by the project.version
property) as follows:
<Export-Package> ${project.artifactId}*;version=${project.version} </Export-Package>
project.artifactId
, as their package prefix. The combination of package prefix and wildcard, ${project.artifactId}*
, enables you to reference all of the source code in your bundle.
Use naming convention for private packages
${project.artifactId}.impl
or ${project.artifactId}.internal
.
Export-Package
instruction, the default behavior of the Maven bundle plug-in is to exclude any packages that contain a path segment equal to impl
or internal
.
!PackagePattern
to the Maven bundle plug-in's export instructions. The effect of this entry is to exclude any matching packages. For example, to exclude any packages prefixed by ${project.artifactId}.impl
, you could add the following instruction to the Maven bundle plug-in configuration:
<Export-Package> !${project.artifactId}.impl.*, ${project.artifactId}*;version=${project.version} </Export-Package>
Export-Package
element is significant. The first match in the list determines whether a package is included or excluded. Hence, in order for exclusions to be effective, they should appear at the start of the list.
Import packages with version ranges
- Manual version ranges—you can manually specify the version range for an imported package using the
version
qualifier, as shown in the following example:<Import-Package> org.springframework.*;version="[2.5,4)", org.apache.commons.logging.*;version="[1.1,2)", * </Import-Package>
Version ranges are specified using the standard OSGi version range syntax, where square brackets—that is,[
and]
—denote inclusive ranges and parentheses—that is,(
and)
—denote exclusive ranges. Hence the range,[2.5,4)
, means that the version,v
, is restricted to the range,2.5 <= v < 4
. Note the special case of a range written as a simple number—for example,version="2.5"
, which is equivalent to the range,[2.5,infinity)
. - Automatic version ranges—if packages are imported from a Maven dependency and if the dependency is packaged as an OSGi bundle, the Maven bundle plug-in automatically adds the version range to the import instructions.The default behavior is as follows. If your POM depends on a bundle that is identified as version 1.2.4.8, the generated manifest will import version 1.2 of the bundle's exported packages (that is, the imported version number is truncated to the first two parts, major and minor).It is also possible to customize how imported version ranges are generated from the bundle dependency. When setting the
version
property, you can use the${@}
macro (which returns the original export version) and the${version}
macro (which modifies a version number) to generate a version range. For example, consider the followingversion
settings:*;version="${@}"
- If a particular package has export version
1.2.4.8
, the generated import version resolves to1.2.4.8
. *;version="${version;==;${@}}"
- If a particular package has export version
1.2.4.8
, the generated import version resolves to1.2
. *;version="[${version;==;${@}},${version;=+;${@}})"
- If a particular package has export version
1.2.4.8
, the generated import version range resolves to[1.2,1.3)
. *;version="[${version;==;${@}},${version;+;${@}})"
- If a particular package has export version
1.2.4.8
, the generated import version range resolves to[1.2,2)
.
The middle part of the version macro—for example,==
or=+
—formats the returned version number. The equals sign,=
, returns the corresponding version part unchanged; the plus sign,+
, returns the corresponding version part plus one; and the minus sign,-
, returns the corresponding version part minus one. For more details, consult the Bnd documentation for the version macro and the -versionpolicy option.
Avoid importing packages that you export
- If the bundle is a pure library (providing interfaces and classes, but not instantiating any classes or OSGi services), do not import the packages that you export.
- If the bundle is a pure API (providing interfaces and abstract classes, but no implementation classes), do not import the packages that you export.
- If the bundle is a pure implementation (implementing and registering an OSGi service, but not providing any API), you do not need to export any packages at all.NoteThe registered OSGi service must be accessible through an API interface or class, but it is presumed that this API is provided in a separate API bundle. The implementation bundle therefore needs to import the corresponding API packages.
- A special case arises, if an implementation and its corresponding API are combined into the same bundle. In this case, the API packages must be listed amongst the export packages and amongst the import packages. This configuration is interpreted in a special way by the OSGi framework: it actually means that the API packages will either be exported or imported at run time (but not both).The reason for this special configuration is that, in a complex OSGi application, it is possible that an API package might be provided by more than one bundle. But you do not want multiple copies of an API to be exported into OSGi, because that can lead to technical problems like class cast exceptions. When a package is listed both in the exports and in the imports, the OSGi resolver proceeds as follows:
- First of all, the resolver checks whether the package has already been exported from another bundle. If so, the resolver imports the package, but does not export it.
- Otherwise, the resolver uses the local API package and exports this package, but it does not import the package.
- (Recommended) The most effective way of suppressing the import of exported packages is to append the
-noimport:=true
setting to package patterns in theExport-Package
instruction. For example:<Export-Package> ${project.artifactId}*;version=${project.version};-noimport:=true </Export-Package>
The marked packages are now not imported, irrespective of what is contained in theImport-Package
instruction. - An alternative way of avoiding the import is to add one or more package exclusions to the Maven bundle plug-in's
Import-Package
element (this was the only possibility in earlier versions of the Maven bundle plug-in). For example, the followingImport-Package
element instructs the Maven bundle plug-in to exclude all packages prefixed by the artifact ID,${project.artifactId}
:<Import-Package> !${project.artifactId}*, org.springframework.*;version="[2.5,4)", org.apache.commons.logging.*;version="[1.1,2)", * </Import-Package>
Use optional imports with caution
Import-Package
manifest header with the resolution:="optional"
setting appended to it. For example, the following example shows an Import-Package
instruction for the Maven bundle plug-in that specifies an optional import:
<Import-Package> org.springframework.*;version="[2.5,4)", org.apache.commons.logging.*;version="[1.1,2)";resolution:="optional", * </Import-Package>
Avoid using the Require-Bundle header
Require-Bundle
header, if possible. The trouble with using the Require-Bundle
header is that it forces the OSGi resolver to use packages from the specified bundle. Importing at the granularity of packages, on the other hand, allows the resolver to be more flexible, because there are fewer constraints: if a package is already available and resolved from another bundle, the resolver could use that package instead.
B.3. Sample POM File
POM file
Example B.1. Sample POM File Illustrating Best Practices
<?xml version="1.0" encoding="UTF-8"?> <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> <groupId>org.fusesource</groupId> <artifactId>org.fusesource.fooProject</artifactId> <packaging>bundle</packaging> <version>1.0-SNAPSHOT</version> <name>A fooProject OSGi Bundle</name> <url>http://www.myorganization.org</url> <dependencies>...</dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <configuration> <instructions> <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName> <Export-Package> !${project.artifactId}.impl.*, ${project.artifactId}*;version=${project.version};-noimport:=true </Export-Package> <Import-Package> org.springframework.*;version="[2.5,4)", org.apache.commons.logging.*;version="[1.1,2)", * </Import-Package> </instructions> </configuration> </plugin> </plugins> </build> </project>
Appendix C. Pax-Exam Testing Framework
Abstract
C.1. Introduction to Pax-Exam
Overview
- Set up the environment and initial options for the OSGi container.
- Start the OSGi container.
- Install the prerequisite bundles into the OSGi container (provisioning).
- Install and run the test classes.
JUnit 4 framework
- Specify which methods are the test methods by annotating them with the
@org.junit.Test
annotation. - At any point in the test method, define an assertion by calling
assertTrue()
with a boolean argument (you also need to include a static import oforg.junit.Assert.assertTrue()
in the file). The test succeeds, if the specified assertions all evaluate to true.
Integration with Pax-Exam
- Customize JUnit to run the test in the Pax-Exam test runner class—JUnit allows you to delegate control over a test run to a custom runner class (by defining a runner class that inherits from
org.junit.runner.Runner
). In order to integrate JUnit with Pax-Exam, add a@RunWith
annotation to the test class as follows:import org.junit.runner.RunWith; import org.ops4j.pax.exam.junit.JUnit4TestRunner; ... @RunWith(JUnit4TestRunner.class) public class MyTest { ... }
- Add a Pax-Exam configuration method to the test class—in order to run a test in an OSGi framework, you need to initialize the OSGi container properly and install any prerequisite bundles. These essential steps are performed by returning the appropriate options from the Pax-Exam configuration method. This method is identified by the
@Configuration
annotation as follows:import org.ops4j.pax.exam.junit.Configuration; ... @Configuration public static Option[] configuration() throws Exception { ... }
- Use the Pax-Exam fluent API to configure the OSGi framework—there are a fairly large number of settings and options that you can return from the Pax-Exam configuration method. In order to define these options efficiently, Pax-Exam provides a fluent API, which is defined mainly by the following classes:
org.ops4j.pax.exam.CoreOptions
- Provides basic options for setting up the OSGi container. For example, this class provides options to set Java system properties (
systemProperty()
), define URLs (as a string,url()
, or as an Mvn URL,maven()
), and select OSGi frameworks (for example,felix()
orequinox()
). org.ops4j.pax.exam.OptionUtils
- Provides utilities for manipulating arrays of options and composite options.
org.ops4j.pax.exam.container.def.PaxRunnerOptions
- Provides options for starting the OSGi container and for provisioning features and bundles. For example, the
scanFeatures()
andscanBundle()
methods can be used to find and install features and bundles in the OSGi container before running the test.
Integration with Apache Karaf
org.apache.karaf.testing.AbstractIntegrationTest
- Provides some helper methods, particularly the
getOsgiService()
methods which make it easy to find an OSGi service, by specifying the Java type of the service or by specifying service properties. org.apache.karaf.testing.Helper
- Provides the
Helper.getDefaultOptions()
method, which configures all of the settings needed to start up Apache Karaf in a default configuration.
Maven dependencies
Example C.1. Pax-Exam and Related Maven Dependencies
<project ...> ... <properties> <junit-version>4.4</junit-version> <pax-exam-version>1.2.0</pax-exam-version> <felix.karaf.version>1.4.0-fuse-01-00</felix.karaf.version> ... </properties> <dependencies> <!-- Pax-Exam dependencies --> <dependency> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam</artifactId> <version>${pax-exam-version}</version> </dependency> <dependency> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam-junit</artifactId> <version>${pax-exam-version}</version> </dependency> <dependency> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam-container-default</artifactId> <version>${pax-exam-version}</version> </dependency> <dependency> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam-junit-extender-impl</artifactId> <version>${pax-exam-version}</version> </dependency> <!-- JUnit dependencies --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit-version}</version> </dependency> <!-- Apache Karaf integration --> <dependency> <groupId>org.apache.karaf.tooling</groupId> <artifactId>org.apache.karaf.tooling.testing</artifactId> <version>${felix.karaf.version}</version> <scope>test</scope> </dependency> </dependencies> ... </project>
References
- JUnit 4 testing framework on the JUnit Web site.
- The Pax-Exam reference guide on the Pax-Exam Web site.
- Source code for the sample FeaturesText class.
C.2. Sample Pax-Exam Test Class
Sample test class
FeaturesText
class configures the Apache Karaf environment, installs the obr
and wrapper
features, and then runs a test against the two features (where the obr
and wrapper
features implement particular sets of commands in the command console).
Example C.2. FeaturesText Class
// Java /* * Licensed to the Apache Software Foundation (ASF) * ... */ package org.apache.karaf.shell.itests; import org.apache.karaf.testing.AbstractIntegrationTest; import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.osgi.service.blueprint.container.BlueprintContainer; import org.osgi.service.command.CommandProcessor; import org.osgi.service.command.CommandSession; import static org.junit.Assert.assertNotNull; import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.CoreOptions.maven; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.waitForFrameworkStartup; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) 1 public class FeaturesTest extends AbstractIntegrationTest { 2 @Test 3 public void testFeatures() throws Exception { // Make sure the command services are available assertNotNull(getOsgiService(BlueprintContainer.class, "osgi.blueprint.container.symbolicname=org.apache.karaf.shell.obr", 20000)); assertNotNull(getOsgiService(BlueprintContainer.class, "osgi.blueprint.container.symbolicname=org.apache.karaf.shell.wrapper", 20000)); // Run some commands to make sure they are installed properly CommandProcessor cp = getOsgiService(CommandProcessor.class); 4 CommandSession cs = cp.createSession(System.in, System.out, System.err); cs.execute("obr:listUrl"); cs.execute("wrapper:install --help"); cs.close(); } @Configuration 5 public static Option[] configuration() throws Exception{ return combine( 6 // Default karaf environment Helper.getDefaultOptions( 7 // this is how you set the default log level when using pax logging (logProfile) systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("DEBUG")), // add two features scanFeatures( 8 maven().groupId("org.apache.karaf").artifactId("apache-felix-karaf").type("xml").classifier("features").versionAsInProject(), "obr", "wrapper" ), workingDirectory("target/paxrunner/features/"), 9 waitForFrameworkStartup(), 10 // Test on the felix OSGi framework felix() 11 ); } }
- 1
- The
@RunWith
annotation instructs JUnit 4 to run the following test with the Pax-Exam test runner class,JUnit4TestRunner
. This is the key step to integrate JUnit 4 with the Pax-Exam testing framework. - 2
- In order to integrate this JUnit test properly with Apache Karaf, you are required to derive this test class from
org.apache.karaf.testing.AbstractIntegrationTest
.TheAbstractIntegrationTest
base class also provides some helper methods that access the bundle context:getOsgiService()
methods, for obtaining a reference to an OSGi service, and thegetInstalledBundle()
method, for obtaining a reference to anorg.osgi.framework.bundle
object. - 3
- The
@Test
annotation is a standard JUnit 4 annotation that identifies the following method as a test method that is to be executed in the testing framework. - 4
- This line gives an example of how to use the
getOsgiService()
helper method to obtain an OSGi service from the OSGi container. In this example, the service is identified by specifying its Java type,org.osgi.service.command.CommandProcessor
. TheCommandProcessor
service is the Apache Karaf service that has the capability to process console commands. - 5
- The
@Configuration
annotation is a Pax-Exam-specific annotation that marks the following the method as the configuration method that sets Pax-Exam testing options. The configuration method must be declared aspublic static
and must have a return value of type,org.ops4j.pax.exam.Option[]
. - 6
- The
OptionUtils.combine()
method combines a given options array (ofOption[]
type) in the first argument with the options in the remaining arguments, returning an options array that contains all of the options. - 7
- The
getDefaultOptions()
method from theorg.apache.karaf.testing.Helper
class returns an options array containing all of the system property settings and option settings required to initialize Apache Karaf for the Pax-Exam testing framework.If there are any Java system properties in the Apache Karaf environment that you would like to customize, you can pass the properties as optional arguments to thegetDefaultOptions()
method. In the example shown here, the system property for the Pax logging level is set toDEBUG
. - 8
- The Pax-Exam framework supports the concept of Apache Karaf features (see Chapter 8, Deploying Features). You can use the
PaxRunnerOptions.scanFeatures()
method to install specific features in the OSGi container before the test is run.The location of the relevant features repository is specified by passing a Pax URL as the first argument toscanFeatures()
. In this example, the URL is constructed by creating a Pax Mvn URL (see Section A.3, “Mvn URL Handler”) with the fluent API from theCoreOptions
class. Subsequent arguments specify which features to install—in this example, theobr
andwrapper
features. - 9
- The
workingDirectory()
option specifies the directory where the Pax Runner provisioning module looks for OSGi bundles. - 10
- The
waitForFrameworkStartup()
specifies that the testing framework should wait for a default length of time (five minutes) for the OSGi framework to start up before timing out. To specify the timeout explicitly, you could use thewaitForFrameworkStartupFor(long millis)
method instead, where the timeout is specified in milliseconds. - 11
- The
felix()
option is used to specify that the test should be run in the Felix OSGI framework.
Index
A
- activemq.xml, Broker configuration
- artifacts
- loading to a fabric, Loading artifacts into the fabric's repository
B
- Bundle-Name, Setting a bundle's name
- Bundle-SymbolicName, Setting a bundle's symbolic name
- Bundle-Version, Setting a bundle's version
- bundles, OSGi Bundles
- exporting packages, Specifying exported packages
- importing packages, Specifying imported packages
- lifecycle states, Bundle lifecycle states
- name, Setting a bundle's name
- private packages, Specifying private packages
- symbolic name, Setting a bundle's symbolic name
- version, Setting a bundle's version
C
- class loading, Class Loading in OSGi
- Conditional Permission Admin service, OSGi framework services
- Configuration Admin service, OSGi Compendium services
- console, Red Hat JBoss Fuse
D
- default broker
- configuration, Broker configuration
- data directory, Broker data
- disabling, Disabling the default broker
- default repositories, Default repositories
E
- execution environment, OSGi architecture
- Export-Package, Specifying exported packages
F
- fabric
- loading artifacts, Loading artifacts into the fabric's repository
- locating artifacts, Procedure for locating artifacts
I
- Import-Package, Specifying imported packages
L
- lifecycle layer, OSGi architecture
- lifecycle states, Bundle lifecycle states
M
- Maven
- installing to a fabric, Loading artifacts into the fabric's repository
- local repository, Local repository
- remote repositories, Remote repositories
- module layer, OSGi architecture
O
- org.fusesource.mq.fabric.server-default.cfg, Broker configuration
- org.ops4j.pax.url.mvn.localRepository.localRepository, Local repository
- org.ops4j.pax.url.mvn.localRepository.settings, Local repository
- org.ops4j.pax.url.mvn.repositories, Default repositories, Remote repositories
- OSGi Compendium services, OSGi Compendium services
- Configuration Admin service, OSGi Compendium services
- OSGi framework, OSGi Framework
- bundles, OSGi architecture
- execution environment, OSGi architecture
- lifecycle layer, OSGi architecture
- module layer, OSGi architecture
- security layer, OSGi architecture
- service layer, OSGi architecture
- OSGi framework services, OSGi framework services
- Conditional Permission Admin service, OSGi framework services
- Package Admin service, OSGi framework services
- Permission Admin service, OSGi framework services
- Start Level service, OSGi framework services
- URL Handlers service, OSGi framework services
- OSGi service registry, OSGi service registry
- OSGi services, OSGi Services
- service invocation model, Service invocation model
- service registry, OSGi service registry
P
- Package Admin service, OSGi framework services
- Permission Admin service, OSGi framework services
- Private-Package, Specifying private packages
R
- Red Hat JBoss Fuse, Red Hat JBoss Fuse
- console, Red Hat JBoss Fuse
- remote repositories, Remote repositories
- repositories
- default, Default repositories
- remote, Remote repositories
S
- security layer, OSGi architecture
- service layer, OSGi architecture
- Start Level service, OSGi framework services
U
- URL Handlers service, OSGi framework services
Legal Notice
Trademark Disclaimer
Legal Notice
Third Party Acknowledgements
- JLine (http://jline.sourceforge.net) jline:jline:jar:1.0License: BSD (LICENSE.txt) - Copyright (c) 2002-2006, Marc Prud'hommeaux
mwp1@cornell.edu
All rights reserved.Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
- Neither the name of JLine nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - Stax2 API (http://woodstox.codehaus.org/StAX2) org.codehaus.woodstox:stax2-api:jar:3.1.1License: The BSD License (http://www.opensource.org/licenses/bsd-license.php)Copyright (c) <YEAR>, <OWNER> All rights reserved.Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - jibx-run - JiBX runtime (http://www.jibx.org/main-reactor/jibx-run) org.jibx:jibx-run:bundle:1.2.3License: BSD (http://jibx.sourceforge.net/jibx-license.html) Copyright (c) 2003-2010, Dennis M. Sosnoski.All rights reserved.Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
- Neither the name of JiBX nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - JavaAssist (http://www.jboss.org/javassist) org.jboss.javassist:com.springsource.javassist:jar:3.9.0.GA:compileLicense: MPL (http://www.mozilla.org/MPL/MPL-1.1.html)
- HAPI-OSGI-Base Module (http://hl7api.sourceforge.net/hapi-osgi-base/) ca.uhn.hapi:hapi-osgi-base:bundle:1.2License: Mozilla Public License 1.1 (http://www.mozilla.org/MPL/MPL-1.1.txt)