Visit https://ebookultra.com to download the full version and
explore more ebooks or textbooks
Osgi in Action Creating Modular Applications in
Java Unedited Draft 1st Edition Richard Hall
_____ Click the link below to download _____
https://ebookultra.com/download/osgi-in-action-creating-
modular-applications-in-java-unedited-draft-1st-edition-
richard-hall/
Explore and download more ebooks or textbooks at ebookultra.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Enterprise OSGi in Action With examples using Apache Aries
Holly Cummins
https://ebookultra.com/download/enterprise-osgi-in-action-with-
examples-using-apache-aries-holly-cummins/
Modular Java 1st Edition Craig Walls
https://ebookultra.com/download/modular-java-1st-edition-craig-walls/
Java Internationalization Creating International
Applications Java Series First Edition David Czarnecki
https://ebookultra.com/download/java-internationalization-creating-
international-applications-java-series-first-edition-david-czarnecki/
Integrative Psychotherapy in Action Richard G Erskine
https://ebookultra.com/download/integrative-psychotherapy-in-action-
richard-g-erskine/
Java Persistence with Hibernate Second Edition of
Hibernate in Action Christian Bauer
https://ebookultra.com/download/java-persistence-with-hibernate-
second-edition-of-hibernate-in-action-christian-bauer/
Professional Flash Mobile Development Creating Android and
iPhone Applications 1st Edition Richard Wagner
https://ebookultra.com/download/professional-flash-mobile-development-
creating-android-and-iphone-applications-1st-edition-richard-wagner/
Consumed by War European Conflict in the 20th Century
Richard C. Hall
https://ebookultra.com/download/consumed-by-war-european-conflict-in-
the-20th-century-richard-c-hall/
Quantum Dots Applications in Biology 1st Edition Richard
L. Ornberg
https://ebookultra.com/download/quantum-dots-applications-in-
biology-1st-edition-richard-l-ornberg/
POJOs in Action Developing Enterprise Applications with
Lightweight Frameworks 1st Edition Chris Richardson
https://ebookultra.com/download/pojos-in-action-developing-enterprise-
applications-with-lightweight-frameworks-1st-edition-chris-richardson/
Osgi in Action Creating Modular Applications in Java
Unedited Draft 1st Edition Richard Hall Digital Instant
Download
Author(s): Richard Hall, Karl Pauls, Stuart McCulloch, David Savage
ISBN(s): 9781933988917, 1933988916
Edition: 1
File Details: PDF, 4.90 MB
Year: 2011
Language: english
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
MEAP Edition
Manning Early Access Program
Copyright 2010 Manning Publications
For more information on this and other Manning titles go to www.manning.com
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
Table of Contents
1. OSGi Revealed
2. Mastering Modularity
3. Learning Lifecycle
4. Studying Services
5. Delving Deeper into Modularity
6. Moving Toward Bundles
7. Managing Bundles and Applications
8. Testing Applications
9. Debugging Applications
10. Component Models
11. Launching and Embedding an OSGi
Framework
12. Security
13. Web Applications and Services
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
1
OSGi Revealed
The Java™ platform is an unqualified success story. It is used to develop applications for
small mobile devices to massive enterprise endeavors. This is a testament to its well thought
out design and continued evolution. However, this success has come in spite of the fact that
Java does not have explicit support for building modular systems beyond ordinary object-
oriented data encapsulation.
So, what does this mean to you? If Java is a success despite its lack of advanced
modularization support, then you might wonder if its absence is a problem. Most well
managed projects have to build up a repertoire of comparable, but project specific,
techniques to compensate for the lack of modularization in Java. These include:
 Programming practices,
 Tricks with multiple class loaders, and
 Serialization between in-process components.
However these techniques are inherently brittle and error prone since they are not
enforceable via any specific compile-time or run-time checks. The end result has detrimental
impacts on multiple stages of an application's lifecycle:
 Development – you are unable to clearly and explicitly partition development into
independent pieces.
 Deployment – you are unable to easily analyze, understand, and resolve requirements
imposed by the collection of independently developed pieces that make up the
system.
 Execution – you are unable to manage and evolve the constituent pieces of a running
system, nor minimize the impact of doing so.
It is definitely possible to manage these issues in Java, and lots of projects do so using
the custom techniques mentioned above, but it is much more difficult than it should be.
We're tying ourselves in knots to work around the lack of a fundamental feature. If Java had
explicit support for modularity, then you would be freed from such issues and could
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
concentrate on what you really want to do, which is developing the functionality of your
application.
Welcome to the OSGi™ Service Platform. The OSGi Service Platform is an industry
standard defined by the OSGi Alliance to specifically address the lack of support for
modularity in the Java platform. Additionally, it also introduces a new service-oriented
programming model, referred to by some as “SOA in a VM.” This chapter will give you an
overview of the OSGi Service Platform and the issues it is intended to address. Once we have
finished this chapter we will have enough background knowledge to start digging into the
details in chapter 2.
1.1 The what and why of OSGi
The sixty-four-thousand dollar question is, “What is OSGi?” The simplest answer to this
question is it is a modularity layer for the Java platform. Of course, the next question that
might spring to mind is, “What do you mean by modularity?” Here we use modularity more
or less in the traditional computer science sense, where the code of your software application
is divided into logical parts representing separate concerns as in Figure 1.1.1. If your
software is modular, then you can simplify development and improve maintainability by
enforcing the logical module boundaries; we will discuss more modularity details in Chapter
2.
The notion of modularity is not new. The concept actually became fashionable back in the
1970s. So, why is OSGi all the rage right now? To better understand what OSGi can do for
you, it is worthwhile to understand what Java is not doing for you with respect to modularity.
Once you understand that, then you can see how OSGi can help.
1.1.1 Java's modularity limitations
Java was never intended to support modular programming, so we admit that criticizing its
inability to do so is a little unfair. Java has been promoted as a platform for building all sorts
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
Figure 1.1.1 Modularity refers to the logical
decomposition of a large system into smaller
collaborating pieces
Module
A
Module
B
Module
C
uses
uses
uses
u
s
e
s
of applications for all sorts of domains ranging from mobile phone to enterprise applications.
Most of these endeavors require, or could at least benefit from, modularity, so Java's lack of
explicit support does cause some amount of pain for developers. From this point of view, we
do feel the following criticisms are valid.
LOW-LEVEL CODE VISIBILITY CONTROL
While Java provides a fair complement of access modifiers to control visibility (e.g., public,
protected, private, and package private), these tend to address low-level object-
oriented encapsulation and do not really address logical system partitioning. Java has the
notion of a package, which is typically used for partitioning code. For code to be visible from
one Java package to another, the code must be declared public (or protected if using
inheritance). Sometimes the logical structure of your application calls for specific code to
belong in different packages, but then this means any dependencies among the packages
must be exposed as public, which makes it accessible to everyone else too. Often this can
expose implementation details, which makes future evolution more difficult since users may
end up with dependencies on your non-public API.
To illustrate this, let's consider a trivial hello world application that provides a public
interface in one package, a private implementation in another and a main class in yet
another.
Listing 1.1.1 Trivial example of the limitations of Java's object-orientated encapsulation
package org.foo.hello;
public interface Greeting { #1
void sayHello();
}
package org.foo.hello.impl;
import org.foo.hello.Greeting;
public class GreetingImpl implements Greeting {
final String m_name;
public GreetingImpl(String name) { #2
m_name = name;
}
public void sayHello() {
System.out.println("Hello, " + m_name + "!");
}
}
package org.foo.hello.main;
import org.foo.hello.Greeting;
import org.foo.hello.impl.GreetingImpl;
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
public class Main {
public static void main(String[] args) {
Greeting greet = new GreetingImpl(“Hello World”); #3
greet.sayHello();
}
}
I n Listing 1.1.1, the author may have intended a third party to only interact with the
application via the Greeting interface at (#1). He or she may mention this in Javadoc,
tutorials, blogs, or even email rants, but there is nothing actually stopping a third party from
constructing a new GreetingImpl using its public constructor at (#2) as is done at (#3).
You might argue that the constructor should not be public and there is no need to split
the application into multiple packages, which could well be true in this trivial example. But in
real-world applications class-level visibility when combined with packaging turns out to be a
very crude tool for ensuring API coherency. Seeing how a supposedly private implementation
can be accessed by third-parties developers, now you need to worry about changes to
private implementation signatures as well as that of public interfaces when making updates.
This problem stems from the fact that although Java packages appear to have a logical
relationship via nested packages, they actually do not. A common misconception for people
first learning Java is to assume that the parent-child package relationship bestows special
visibility privileges on the involved packages. Two packages involved in a nested relationship
are equivalent to two packages that are not. Nested packages are largely useful for avoiding
name clashes and provide only partial support for the logical code partitioning.
What this all means is in Java you are regularly forced to decide between:
1. Impairing your application's logical structure by lumping unrelated classes into the
same package to avoid exposing non-public API or
2. Keeping your application's logical structure by using multiple packages at the expense
of exposing non-public API so it can be accessed by classes in different packages.
Neither choice is particularly palatable.
ERROR-PRONE CLASS PATH CONCEPT
The Java platform also inhibits good modularity practices. The main culprit is the Java class
path. Why does the class path pose problems for modularity? Largely due to all of the issues
that it hides, such as code versions, dependencies, and consistency. Applications are
generally composed of various versions of libraries and components. The class path pays no
attention to code versions, it simply returns the first version that it finds. Even if it did pay
attention, there is no way to explicitly specify dependencies. The process of setting up your
class path is largely trial and error; you just keep adding libraries until the VM stops
complaining about missing classes.
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
Figure 1.1.2 shows the sort of “class path Hell” that can often be found when more than
one JAR file provides a given set of classes. Even though each JAR file may have been
compiled to work as a unit, when merged at run time the Java class path pays no attention
to the logical partitioning of the components. This tends to lead to such hard to predict
errors, such as NoSuchMethodError, when a class from one JAR file interacts with an
incompatible class from another one.
In large applications, created from independently developed components, it is not
uncommon to have dependencies on different versions of the same component, such as
logging or XML parsing mechanisms. The class path forces you to choose just one version in
such situations, which may not always work for all parts of the application if there are
incompatibilities between versions. Worse, if you happen to have multiple versions of the
same package on the class path, either on purpose or accidentally, they are treated as split
packages by Java and are implicitly merged based on order of appearance. Overall, the class
path approach lacks any form of consistency checking. You just get whatever classes have
been made available by the system administrator, which is very likely only an approximation
of what the developer actually expected. This hardly inspires confidence.
LIMITED DEPLOYMENT AND MANAGEMENT SUPPORT
Java also lacks support when it comes to deploying and managing your application. There is
no easy way in Java to deploy the proper transitive set of versioned code dependencies and
execute your application. Likewise for evolving your application and its components after
deployment. Consider the common requirement of wanting to support a dynamic plugin
mechanism. The only way to achieve such a benign request is to use class loaders, which are
low level and error prone. Class loaders were never intended to be a common tool for
application developers, but so many of today's systems require their use. A properly defined
modularity layer for Java can deal with these issues by making the module concept explicit
and raising the level of abstraction for code partitioning.
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
Figure 1.1.2 Multiple JARs containing the “same” class are merged based on their order of appearance
in the class path paying no respect to logical coherency between archives
Jar 2
Jar 1
Classpath
Jar 3
With this better understanding of the limitations of Java when it comes to modularity, we
can ponder whether OSGi is the right solution for your projects.
1.1.2 Can OSGi help you?
Nearly all but the simplest of applications can benefit from the modularity features OSGi
provides, so if you are wondering if OSGi is something you should be interested in, the
answer is most likely, “Yes!” Still not convinced? Here are some common scenarios that you
may have encountered where OSGi can be helpful:
 If you ever received ClassNotFoundExceptions when starting your application
because the class path was not correct. OSGi can help you here by ensuring that code
dependencies are satisfied before allowing the code to execute.
 If you ever encountered run-time errors when executing your application due to the
wrong version of a dependent library on the class path. OSGi verifies that the set of
dependencies are consistent with respect to required versions and other constraints.
 If you ever wanted to share classes between modules without worrying about
constraints implied by hierarchical class loading schemes; put in a more concrete way,
the dreaded appearance of “foo instanceof Foo == false” when sharing
objects between two servlet contexts.
 If you ever wanted to package your application as logically independent JAR files and
be able to deploy only those pieces you actually need for a given installation. This
pretty much describes the purpose of OSGi.
 If you ever wanted to package your application as logically independent JAR files and
also wanted to declare which code is accessible from each JAR file and have this
visibility enforced. OSGi enables a new level of code visibility for JAR files that allows
you to specify what is and what is not visible externally.
 If you ever wanted to define an extensibility mechanism for your application, like a
plugin mechanism. OSGi modularity is particularly suited to providing a powerful
extensibility mechanism, including support for run-time dynamism.
As you can see, these scenarios cover a lot of use cases, but are by no means
exhaustive. The simple and non-intrusive nature of OSGi tends to make you discover more
ways to apply it the more you use it. Having explored some of the limitations of the standard
Java class path we'll now properly introduce you to OSGi.
1.2 A quick OSGi overview
The OSGi Service Platform is composed of two parts: the OSGi framework and OSGi standard
services (depicted in Figure 1.1.3). The framework is the runtime that implements and
provides OSGi functionality. The standard services define reusable APIs for common tasks,
such as Logging and Preferences.
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
The OSGi specifications for the framework and standard services are managed by the
OSGi Alliance (http://www.osgi.org). The alliance is an industry backed non-profit
corporation founded in March 1999. The framework specification is now on it's fourth major
revision and is stable. Technology based on this specification is in use in a range of large
scale industry applications including (but not limited to) automotive, mobile devices, desktop
applications, and more recently enterprise application servers.
NOTE
Once upon a time, the letters “OSGi” were an acronym that stood for the Open Services
Gateway Initiative. This acronym highlights the lineage of the technology, but has fallen
out of favor. After the third specification release, the OSGi Alliance officially dropped the
acronym and “OSGi” is now simply a trademark for the technology.
In the bulk of this book we will discuss the OSGi framework, its capabilities, and how to
leverage these capabilities. Since there are so many standard services, we will only discuss
the most relevant and useful services where appropriate. For any service we miss, you can
get more information from the OSGi specifications themselves. Let's continue our overview of
OSGi by introducing the broad features of the OSGi framework.
1.2.1 The OSGi Framework
The OSGi framework plays a central role when creating OSGi-based applications, since it is
the application's execution environment. The OSGi Alliance's framework specification defines
the proper behavior of the framework, which gives you a well-defined API to program
against. The specification also enables the creation of multiple implementations of the core
framework to give you some freedom of choice; there are a handful of well-known open
source projects, such as Apache Felix, Eclipse Equinox, and Knopflerfish. This ultimately
benefits you, since you are not tied to a particular vendor and are able to program against
the behavior defined in the specification. It's sort of like the reassuring feeling you get by
knowing you can go into any McDonald's anywhere in the world and get the same meal.
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
Figure 1.1.3 The OSGi Service Platform
specification is divided into two halves, one for the
OSGi framework and one for standard services
Framework
Standard services
OSGi SERVICE PLATFORM
The OSGi specification conceptually divides the framework into three layers (see Figure
1.1.4):
 Module layer – this layer is concerned with packaging and sharing code.
 Lifecycle layer – this layer is concerned with providing run-time module management
and access to the underlying OSGi framework.
 Service layer – this layer is concerned with interaction and communication among
modules, specifically the components contained in them.
Like typical layered architectures, each layer is dependent upon the layers beneath it.
Therefore, it is possible for you to use lower OSGi layers without using upper ones, but not
vice versa. The next three chapters discuss these layers in detail, but we will give an
overview of each here.
1.2.2 Module layer
The module layer defines the OSGi module concept, called a bundle, which is simply a JAR
file with extra metadata (i.e., data about data) as depicted in Figure 1.1.5. A bundle contains
your class files and their related resources. Bundles are typically not an entire application
packaged into a single JAR file; rather, they are the logical modules that combine to form a
given application. Bundles are more powerful than standard JAR files, since you are able to
explicitly declare which contained packages are externally visible (i.e., exported packages).
In this sense, bundles extend the normal access modifiers (i.e., public, private, and
protected) associated with the Java language.
Another important advantage of bundles over standard JAR files is that you are also able
to explicitly declare on which external packages your bundle depends (i.e., imported
packages). The main benefit of explicitly declaring your bundles' exported and imported
packages is that the OSGi framework can manage and verify the consistency of your bundles
automatically; this process is called bundle resolution and involves matching exported
packages to imported packages. Bundle resolution ensures consistency among bundles with
respect to versions and other constraints, which we will discuss in detail in Chapter 2.
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
Figure 1.1.4 OSGi layered architecture
MODULE
LIFECYCLE
SERVICE
1.2.3 Lifecycle layer
The lifecycle layer defines how bundles are dynamically installed and managed in the OSGi
framework. If we were building a house, the module layer provides the foundation and
structure, while the lifecycle layer is the electrical wiring – it makes everything go.
The lifecycle layer serves two different purposes. External to your application, the
lifecycle layer precisely defines the bundle lifecycle operations (e.g., install, update, start,
stop, and uninstall). These lifecycle operations allow you to dynamically administer, manage,
and evolve your application in a well-defined way. This means that bundles can be safely
added and removed from the framework without restarting the application process. Internal
to your application, the lifecycle layer defines how your bundles gain access to their
execution context, which provides them with a way to interact with the OSGi framework and
the facilities it provides during execution. This overall approach to the lifecycle layer is
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
Figure 1.1.6 The service-oriented interaction pattern. Providers
publish services into a registry where requesters can discover
which services are available for use.
Publish Find
Interact
Service
Registry
Service
Provider
Service
Requester
Service
Description
Figure 1.1.5 A bundle contains code,
resources, and metadata
Bundle
.class
class files
.xml,
.jpeg,
etc.
resource files
MANI
FEST
.MF
metadata
powerful since it allows you to create externally (and remotely) managed applications or
completely self-managed applications (or any combination of the two).
1.2.4 Service layer
Finally, the service layer supports and promotes a flexible application programming model
that incorporates concepts popularized by service-oriented computing (although, these
concepts were part of the OSGi framework before SOA became popular). The main concepts
revolve around the service-oriented publish, find, and bind interaction pattern: service
providers publish their services into a service registry, while service clients search the
registry to find available services to use (see Figure 1.1.6). Nowadays, SOA is largely
associated with web services, but OSGi services are local to a single VM, which is why some
people refer to it as “SOA in a VM”.
The OSGi service layer is very intuitive, since it promotes an interface-based development
approach, which is generally considered good practice. Specifically, it promotes the
separation of interface and implementation. OSGi services are simply Java interfaces that
represent a conceptual contract between service providers and service clients. This makes
the service layer very lightweight, since service providers are simply Java objects accessed
via direct method invocation. Additionally, the service layer expands the bundle-based
dynamism of the lifecycle layer with service-based dynamism, i.e., services can appear or
disappear at any time. The result is a programming model that eschews the monolithic and
brittle approaches of the past, in favor of being modular and flexible.
Certainly, this sounds all well and good, but you might still be wondering how these three
layers all fit together and how you go about using them to create an application on top of
them. Fair enough, in the next couple of sections we'll explore how these layers fit together
using some small example programs.
1.2.5 Putting it all together
The OSGi framework is made up of layers, but how do we use these layers in application
development? Let's try to make it a little clearer by outlining the general approach you will
use when creating an OSGi-based application:
3. Design your application by breaking it down into service interfaces (i.e., normal
interface-based programming) and clients of those interfaces.
4. Implement your service provider and client components using your preferred tools and
practices.
5. Package your service provider and client components into [usually] separate JAR files,
augmenting each JAR file with the appropriate OSGi metadata.
6. Start the OSGi framework.
7. Install and start all of your component JAR files from step 3.
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
If you are already following an interface-based approach, then the OSGi approach will feel
very familiar to you. The main difference will be how you locate your interface
implementations (i.e., your services). Normally, you might instantiate implementations and
pass around references to initialize clients. In the OSGi world, your services will publish
themselves in the service registry and your clients will look up available services in the
registry. Once your bundles are installed and started, your application will start and execute
like normal, but with several advantages. Underneath, the OSGi framework is providing more
rigid modularity and consistency checking and its dynamic nature opens up a whole world of
possibilities.
Don't fret if you don't or can't use an interfaced-based approach for your development.
The first two layers of the OSGi framework still provide a lot of functionality for you; in truth,
the bulk of OSGi framework functionality lies in these first two layers, so keep reading.
Enough talk, let's look at some code.
1.3 “Hello, world!” examples
Since OSGi functionality is divided over the three layers mentioned previously (modularity,
lifecycle, and service), we will show you three different “Hello, world!” examples that
illustrate each of these layers.
1.3.1 Modularity layer
The modularity layer is actually not related to code creation as such; rather, it is related to
the packaging of your code into bundles. There are certain code-related issues of which you
need to be aware when developing, but by and large you prepare your code for the
modularity layer by adding packaging metadata to your project's generated JAR files. For
example, suppose you want to share the class in Listing 1.1.2.
Listing 1.1.2 Basic greeting implementation
package org.foo.hello;
public class Greeting {
final String m_name;
public Greeting(String name) {
m_name = name;
}
public void sayHello() {
System.out.println("Hello, " + m_name + "!");
}
}
During the build process you would compile the source code and put the generated class
file into a JAR file. To leverage the OSGi modularity layer you must add some metadata into
your JAR file's META-INF/MANIFEST.MF file, such as the following snippet:
Bundle-ManifestVersion: 2 #A
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
Bundle-Name: Greeting API #B
Bundle-SymbolicName: org.foo.hello #C
Bundle-Version: 1.0 #C
Export-Package: org.foo.hello;version="1.0" #D
#A Indicates the OSGi metadata syntax version
#B Human-readable name, not strictly necessary
#C Symbolic name and version bundle identifier
#D Share packages with other bundles
In this small example, the bulk of the metadata is largely related to bundle identification.
The important part is the Export-Package statement, since this extends the functionality
of a typical JAR file with the ability for you to explicitly declare which packages contained in
the JAR are visible to the users of it. In this particular example, only the contents of the
org.foo.hello package are externally visible; if there were other packages in our
example, they would not be externally visible. So what does this really mean? It means when
you run your application, other modules will not be able to accidentally (or intentionally)
depend on packages that your module doesn't explicit expose.
To use this shared code in another module you would again add metadata, this time using
the Import-Package statement to explicitly declare which external packages are required
by the code contained in the client JAR. The following snippet illustrates this:
Bundle-ManifestVersion: 2 #A
Bundle-Name: Greeting Client #B
Bundle-SymbolicName: org.foo.hello.client #C
Bundle-Version: 1.0 #C
Import-Package: org.foo.hello;version="[1.0,2.0)" #D
#A Indicates the OSGi metadata syntax version
#B Human-readable name, not strictly necessary
#C Symbolic name and version bundle identifier
#D Specify dependency on an external package
To see this example in action, go into the greeting-example/modularity/ directory
for Chapter 1 in the accompanying code and type “ant” to build it and “java -jar
main.jar” to run it. Although this example is simple, it illustrates that creating OSGi
bundles out of your existing JAR files is a reasonably non-intrusive process. In addition, there
are tools that can help you create your bundle metadata, which we will discuss in [ref xx],
but in reality no special tools are required to create a bundle other than what you normally
use to create a JAR file. Chapter [ref ch2] will go into all of the juicy details of OSGi
modularity and how to take advantage of it in your applications.
1.3.2 Lifecycle layer
In the last subsection we saw that it is possible to leverage OSGi functionality in a non-
invasive way by simply adding metadata to your existing JAR files. Such a simple approach is
sufficient for most reusable libraries, but sometimes we need or want to go further to meet
specific requirements or to use additional OSGi features. The lifecycle layer moves us deeper
into the OSGi world.
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
Perhaps you want to create a module that performs some initialization task, such as
starting a background thread or initializing a driver; the lifecycle layer makes this possible.
Bundles may declare a given class as an “activator,” which is the bundle's hook into its own
lifecycle management. We will discuss the full lifecycle of a bundle later in chapter [ref ch3],
but first let's look at a simple example to give you an idea of what we are talking about. In
Listing 1.1.3, we extend our previous Greeting class to provide a singleton instance.
Listing 1.1.3 Extended greeting implementation
package org.foo.hello;
public class Greeting {
static Greeting instance; #A
final String m_name;
Greeting(String name) { #B
m_name = name;
}
public static Greeting get() { #C
return instance;
}
public void sayHello() {
System.out.println("Hello, " + m_name + "!");
}
}
#A singleton instance to be managed
#B constructor is now package private
#C clients can only use the singleton
Listing 1.1.4 implements a bundle activator that initializes the Greeting class singleton
when the bundle is started and clears it when it is stopped. The client can now use the pre-
configured singleton instead of creating its own instance.
Listing 1.1.4 OSGi bundle activator
package org.foo.hello;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator { #A
public void start(BundleContext ctx) { #B
Greeting.instance = new Greeting("lifecycle");
}
public void stop(BundleContext ctx) { #C
Greeting.instance = null;
}
}
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
You can see at #A that a bundle activator must implement a simple OSGi interface, which
comprises the two methods depicted at #B and #C. At execution time, the framework will
construct an instance of this class and invoke the start() method when the bundle is
started and the stop() method when the bundle is stopped. What we precisely mean by
“starting” or “stopping” a bundle will become clearer in chapter [ref ch3]. Because the
framework uses the same activator instance while the bundle is active, you can share
member variables between the start() and stop() methods.
The inquisitive among you might be wondering what the single parameter of type
BundleContext in the start() and stop() methods is all about. This is how the bundle
gets access to the OSGi framework in which it is executing. From this context object, the
module has access to all of the OSGi functionality for modularity, lifecycle, and services. In
short, it is a fairly important object for most bundles, but we will defer a detailed introduction
of it until later when we discuss the lifecycle layer. The important point to take away from
this example is that bundles have a simple way to hook into their overall lifecycle and gain
access to the underlying OSGi framework.
Of course, it is not sufficient to just create this bundle activator implementation, you
actually have to tell the framework about it. Luckily, this is quite simple. If you have an
existing JAR file you are converting to be a module, then you must add the activator
implementation to the existing project so the class is included in the resulting JAR file. If you
are creating a bundle from scratch, then you just need to compile the class and put the
result in a JAR file. You also need to tell the OSGi framework about the bundle activator by
adding another piece of metadata to the JAR file manifest. For our example, we would add
the following metadata to the JAR manifest:
Bundle-Activator: org.foo.hello.Activator
Import-Package: org.osgi.framework
Notice we also need to import the org.osgi.framework package, since our bundle
activator has a dependency on it. Otherwise, it is pretty simple to make bundles lifecycle
aware. To see this example in action, go into the greeting-example/lifecycle/
directory for Chapter 1 in the accompanying code and type “ant” to build it and “java
-jar main.jar” to run it.
We've now introduced how to create OSGi bundles out of your existing JAR files using the
modularity layer and how to make your bundles lifecycle aware so that they can leverage
framework functionality. The last example in this section demonstrates the service-oriented
application programming approach promoted by OSGi.
1.3.3 Service layer
If you follow an interfaced-based approach in your development, the OSGi service approach
will feel quite natural to you. To illustrate, consider the Greeting interface depicted below:
package org.foo.hello;
public interface Greeting {
void sayHello();
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
}
For any given implementation of the Greeting interface, when the sayHello() method
is invoked a greeting will be displayed. In general, a service represents a contract between a
provider and prospective clients; the semantics of the contract are typically described in a
separate, human readable document, like a specification. The service interface above
represents the syntactic contract of all Greeting implementations. The notion of a contract
is necessary so that clients can be assured of getting the functionality they expect when
using a Greeting service. The precise details of how any given Greeting implementation
performs its task is not known to the client. For example, one implementation may print its
greeting textually, while another may display its greeting in a GUI dialog box. The code in
Listing 1.1.5 depicts a simple text-based implementation.
Listing 1.1.5 Greeting implementation
package org.foo.hello.impl;
import org.foo.hello.Greeting;
public class GreetingImpl implements Greeting {
final String m_name;
GreetingImpl(String name) {
m_name = name;
}
public void sayHello() {
System.out.println("Hello, " + m_name + "!");
}
}
Your might be thinking that nothing in the service interface or Listing 1.1.5 indicate we
are defining an OSGi service. Well, you'd be correct. That's what makes the OSGi's service
approach so natural if you are already following an interface-based approach, since your
code will largely stay the same. There are two places where your development will be a little
different. One is how you make a service instance available to the rest of your application
and the other is how the rest of your application discovers the available service.
All service implementations will ultimately be packaged into a bundle and that bundle will
need to be lifecycle aware in order to register the service; this means that we need to create
a bundle activator for our example service as depicted in Listing 1.1.6.
Listing 1.1.6 OSGi bundle activator with service registration
package org.foo.hello.impl;
import org.foo.hello.Greeting;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
public void start(BundleContext ctx) { #A
ctx.registerService(Greeting.class.getName(),
new GreetingImpl("service"), null);
}
public void stop(BundleContext ctx) {} #B
}
This time in the start() method at #A, instead of storing the Greeting
implementation as a singleton, we use the provided bundle context to register it as a service
with the service registry. The first parameter we need to provide is the interface name(s)
that the service implements, followed by the actual service instance, and finally the service
properties. In the stop() method at #B we could unregister the service implementation
before stopping the bundle, but in practice you don't need to do this. The OSGi framework
will automatically unregister any registered services when a bundle stops.
We've seen how to register a service, but what about discovering a service? Listing 1.1.7
shows a very simplistic client, which does not handle missing services and suffers from
potential race conditions. A more robust way to access services will be discussed in chapter
[ref ch4].
Listing 1.1.7 OSGi bundle activator with service discovery
package org.foo.hello.client;
import org.foo.hello.Greeting;
import org.osgi.framework.*;
public class Client implements BundleActivator {
public void start(BundleContext ctx) {
ServiceReference ref =
ctx.getServiceReference(Greeting.class.getName()); #A
((Greeting) ctx.getService(ref)).sayHello(); #B
}
public void stop(BundleContext ctx) {}
}
The first thing you'll notice is that accessing a service in OSGi is a two-step process. First
at #A, a indirect reference is retrieved from the service registry, which points to the earliest
active service that was registered under the given interface name. Second at #B, this
indirect reference is used to access the actual service object instance. The service reference
can safely be stored in a member variable, but in general you should never store service
object instances since this will make your application less dynamic and stop bundles from
being cleanly uninstalled. We say “in general” since there are certain advanced use cases
discussed in later chapters [ref xx] where you may wish to store a reference to a service. But
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
in these situations you must be very careful to de-reference the service when the OSGi
framework tells you it is no longer valid.
Also note that the client code only needs to declare an import for the Greeting
interface, it has no direct or explicit dependency on the actual service implementation(s).
This makes it very easy to swap services dynamically without restarting the client bundle.
Both the service implementation and client should be packaged into separate bundle JAR
files. Each bundle will name an activator in their respective bundle metadata, but only the
service implementation will export the org.foo.hello package, whereas the client will
import it. To see this example in action, go into the greeting-example/service/
directory for Chapter 1 in the accompanying code and type “ant” to build it and “java
-jar main.jar” to run it.
Now that we have seen some examples, it is possible for us to better understand how
each layer of the OSGi framework builds on the previous one. Each layer gives you additional
capabilities when building your application, but OSGi technology is flexible enough for you to
adopt it according to your specific needs. If you only want better modularity in your project,
then use the modularity layer. If you want a way to initialize your modules and interact with
the modularity layer, then use both the modularity and lifecycle layer. If you want a dynamic,
interface-based development approach, then use all three layers. The choice is yours.
1.3.4 Setting the stage
To help introduce the concepts of each layer in the OSGi framework in the next three
chapters, we will use a simple paint program, whose user interface is depicted in Figure
1.1.7. The paint program is not intended to be independently useful; rather, it is used to
demonstrate common issues and best practices. From a functionality perspective, the paint
program only allows the user to paint various shapes, such as a circles, squares, and
triangles. The shapes are painted in predefined colors. Available shapes are displayed as
buttons in the main window's toolbar. To draw a shape, the user selects it in the toolbar and
then clicks anywhere in the canvas to draw it. The same shape can be drawn repeatedly by
clicking in the canvas numerous times. The user can drag drawn shapes to reposition them.
This sounds simple enough. The value of using a visual program for demonstrating these
concepts will become evident when we start introducing run-time dynamism.
We have finished our overview of the OSGi framework and are ready to delve into the
details, but before we do let's try to put OSGi in context by discussing similar or related
technologies. While no Java technology fills the exact same niche as OSGi, there are several
treading similar ground, so it is worth understanding their relevance before moving forward.
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=507
Other documents randomly have
different content
69
Chapter XII
Frithiof’s Return
The winter passed, and again were hill and valley, grove
and forest, clothed with bloom and verdure. Then
Frithiof thanked his host, and, bidding him farewell, was
soon speeding joyously away across the foaming main.
Six times the sun rose and set, and the seventh
morning found him near his journey’s end. Consumed
with longing, Frithiof rose early and mounted to the
deck. There, veiled in the mists of dawn, he saw his
native shores and heard the familiar rushing of its
mountain streams. Light as a bird flew “Ellida” o’er the
dancing waves and in her swelling sails the western
breezes sang like nightingales. Just as the first ray of
sunlight fell on land and sea they entered the well-
known haven.
“Past the green birch woods now,” cried Frithiof to
Björn, “and Framnäs greets me!”
With beating heart and gleaming eyes he waited—but
what is this? Is he bewitched? There lies the open space
where his forefathers built their dwelling, yet naught is
to be seen of it. Do his eyes deceive him? He rubs them
and looks again at the familiar spot; but neither house
nor building of any kind is there, only a tall blackened
chimney stands out dark against the sky. Looking closer,
70
where Framnäs stood, he sees a great pile of ruins,
from which the ashes whirl aloft.
“Ellida’s” anchor is dropped, and silently Frithiof
approaches the scene of devastation. Stones and
charred beams are strewn around or heaped together in
confusion; fruit trees stretch forth their shrivelled
branches; about the levelled grave-mounds lie the
bones of heroes. As Frithiof stands spellbound amid the
desolation, his faithful hound Bran comes bounding to
meet him. Yelping with joy he leaps upon his master,
while out from the dale trots a milk-white courser,
neighing and tossing his gold-knotted mane. Frithiof
stroked the dog’s head and patted his favorite’s glossy
neck; but the shadow on his brow remained unaltered.
Then he saw Hilding, his aged foster-father coming
toward him with mournful look.
“Welcome, father, to the ruins of Framnäs!” he cried,
and then added bitterly: “But why should this sight
surprise me? ’Tis when the eagle is flown that boys
plunder his nest. So thus doth King Helge guard the hut
of the peasant; thus he keeps his royal oath! Rage at
his dastardly act more moves me than grief for what is
lost. But tell me first of all, good father, where is
Ingeborg?”
“Alas! my son,” replied Hilding, “I fear my tidings will but
aggravate thy woe, yet listen to what has passed.
Scarce wert thou gone when King Ring invaded the
country, his force outnumbering ours full five to one. In
the Disardale we met, and bloody was the battle. The
waters of the stream ran red with gore. Halfdan, as
ever, laughed and jested; but so bravely did he bear
him, my heart was gladdened at the sight, and twice did
my shield protect him from a death-stroke. The victory
71
72
might even have been ours, had not King Helge, seized
with panic, fled; whereat the people’s courage, too,
forsook them, and, flinging down their arms, they
scattered far and wide. But in his flight King Helge
paused to fire thy house. Ring then demanded of the
brothers lands and crown, or that they yield him up
their sister’s hand. Messengers went often to and fro,
and in the end King Ring bore Ingeborg homeward as
his Queen.”
Frithiof laughed wildly: “Who now,” he cried, “dare talk
to me of woman’s truth, since she whom I deemed true
as Nanna’s self hath proven faithless? Hereafter naught
but hate for mankind shall my bosom harbor;
henceforth the seas shall have their fill of blood, for
none who cross my path shall Angurvadel spare!”
“Nay, son,” said Hilding sorrowfully, “abate thy wrath,
nor seek to revenge thy wrongs upon the innocent.
Rather accuse the Norns, whose doom on thee hath
fallen. What Ingeborg doth suffer I alone can tell.
Before all others her despair was dumb as is the turtle
dove that mourns her mate. So doth the sea fowl,
pierced by death’s arrow, sink beneath the waves, in
those cool depths to pour away her life. ‘Atonement’—so
she spake—‘hath been decreed by Balder for Frithiof’s
violation of his holy place; nor may I, faint-hearted,
seek to shun the sacrifice. To death he dooms me, not
swift,—ah! that were easy,—but lingering—slow, to
waste away with grief. To that decree I yield. Reveal to
no one what I suffer. I desire pity from none. But be
thou the bearer of my last farewell to Frithiof.’
“At last the wedding day was come (Oh, would that evil
day had never dawned!); to Balder’s temple walked a
train of white-robed maidens, led by a bard whose
73
74
mournful chant moved every heart to woe. Amid them,
on a coal-black steed rode Ingeborg, like that pale spirit
which surmounts the thunder cloud. Before the doors of
the temple I lifted my lily from her saddle and led her to
the altar. With unfaltering tongue she spoke her vows;
but unto Balder then she prayed in such heart-rending
tones that every eye save hers was filled with tears.
Then for the first time Helge marked the ring she wore.
With a furious glance he tore it from her and placed thy
gift upon the arm of Balder. But thereat I could no
longer suppress my rage, and, snatching my sword from
out its sheath, approached the King as he stood before
the image of the god. Of as little worth was he to me at
that moment as the lowest of his people, and verily a
crime would have been committed in that sacred place
had not a whisper reached my ears from Ingeborg.
“‘Nay, stay thy hand. Stain not thy spotless blade! My
brother might indeed have spared me this; but much a
heart can suffer ere it break, and the All-Father shall
one day judge between us!’”
“Ay, Ingeborg,” cried Frithiof, “thou speakest truly—the
All-Father will one day judge between us! But he also
metes out justice here below by mortal hand, and ’tis in
my heart that I am hither led to be the judge of one. Is
not to-day the Midsummer feast of Balder, that Helge
celebrates within his temple? Now, crowned priest, thou
who hast sold thy sister, thou who hast robbed me of
my bride, behold to-day thy judge!”
75
Chapter XIII
The Burning of the Temple
It was midnight. Low across the mountains burned the
blood-red sun, which in far northern Scandinavia never
sets on the longest day of the year. Neither day nor
night was it—an awful twilight reigned. Within the
temple Balder’s great feast was being celebrated. High
in the air shot the flames from the sacred hearthstone,
while pale, white-bearded priests raked the brands till
showers of crackling sparks flew upward. Clad in his
royal robes, Helge presided at the altar.
Suddenly the clash of arms sounded without, and a
voice was heard: “Björn, hold fast the door! Let none
escape! If any strive by force to pass thee, cleave his
skull!” Helge grew deadly pale; he knew that voice too
well. Then in strode Frithiof and addressed him:
“Here is the tribute thou didst order me to bring thee
from Augantyr. Take it! And now, for life or death we’ll
strive before this altar. One of us twain must burn on
Balder’s pyre. Shieldless we’ll fight and thou, as befits a
King, shalt have first stroke. But beware, I say, for I
strike second. Nay—gaze not fearfully about, nor seek
escape, King Fox! Caught in thy hole art thou at last.
Remember Framnäs that thou didst lay waste, and think
of Ingeborg’s cheeks, blanched by thee!”
76
Beside himself with fury, Frithiof tore the heavy purse of
gold from his belt and hurled it at the head of the King,
who straightway sank swooning on the altar steps,
blood gushing from his mouth and nose.
“What! canst thou not bear the weight of thine own
gold?” shouted Frithiof. “Shame! shame! thou coward
King! Truly my sword is far too noble for thee, nor shall
it taste of blood so base as thine. Silence, ye pale
priests of moonlight, nor dare to lift your sacrificial
knives! Back, back, I say, for thirsty grows my blade!”
He lifted his eyes to the image of Balder. “Thou shining
god, frown not so darkly on me!” Then, perceiving the
arm-ring he had given to Ingeborg, his anger blazed up
fiercer than before.
“Nay—by thy leave,” he cried; “that ring came not in
lawful fashion on thy arm! Not for thee did Vaunlund
forge its wonders; and he who is its master claims his
own.”
He pulled at the ring, but it seemed grown fast to
Balder’s arm. Putting forth all his strength, at last he
tore it loose; but therewith down crashed the image of
the god into the fire below. Higher and higher leaped
the flames, till beam and rafter kindled. Horror-stricken,
Frithiof stood for a moment motionless; then turning to
the door, he shouted:
“Open, Björn! Let all depart! The feast is over. The
temple blazes; bring water! Hasten, all, to quench the
flames!”
Quickly a chain of men to the sea is formed. From hand
to hand the buckets fly, while high up among the rafters
stands Frithiof, calm amid the mounting flames, and
77
78
directs his comrades. But vain are all their efforts. The
golden plates of the roof melt and drop down into the
fiery sands.
“All is lost!” shout the people. “See the red fire-cock,
how he stands upon the roof-tree and ever wider
spreads his glowing wings!”
A strong wind arose and whirled the flaming brands into
the treetops, dry from the summer heats. Raging from
branch to branch it leaped, and soon the whole grove
was one sea of fire. When morning broke, Balder’s
Grove and Temple lay in ashes, while Frithiof sat within
his dragon ship and wept.
79
Chapter XIV
Frithiof in Exile
As “Ellida” passed the strand, Frithiof gazed from the
deck with gloomy brow upon the scene of conflagration,
from which the thick smoke still ascended, and anguish
filled his breast.
“Woe, woe is me!” he cried to himself; “in accusation
rises yonder smoke to Odin’s halls! Banished was I by
Helge but for a brief space; now must I forever leave
my native land. Be thou, O sea, from hence my country.
On thy blue billows will I make my home. Framnäs no
longer is my dwelling; thou, swift ‘Ellida,’ shalt be now
my house. My bride, too, art thou in thy black garb,
since she in lily robes is lost to me forever. Free dost
thou roll, O mighty ocean! No tyrant’s will can ever do
thee wrong; the only King thou callest master is he who
looks upon thee calmly when thy white breast heaves in
wildest fury, and thunder peals are swallowed in thy
voice. No grave-mound e’er shall rise above me; thy
tossing waves shall cover deep my bones.”
Here Björn approached and touched his shoulder,
saying, “Look! yonder King Helge makes his way amid
the rocks. Methinks he hath yet a word to speak with
thee.” Ten dragon ships were seen approaching. Frithiof
80
sprang to his feet and bade his men prepare for battle.
Joyously they shouted:
“King Helge wearies of the crown. His soul thirsts for
Valhalla’s delights. Now shall he fall; bold Frithiof leads
us unto victory.”
On came the ships in a half-circle, surrounding “Ellida.”
Helge had given orders to slay Frithiof and all his men,
but to capture the ship as their prize. Suddenly a
strange sight met the eyes of Frithiof and his warriors
and filled them with amazement: nine of the ships sank
slowly down beneath the waves, while Helge himself
escaped with difficulty to the shore. Björn laughed.
“’Twas I that scuttled the ships last night, unseen. A
good trick it was, and all befell as I had hoped, save
that King Helge has escaped!”
Now all the sails were spread and the ship sped swiftly
out to sea. Backward gazing, Frithiof watched the fast
receding shore and chanted a song that moved all
hearts to sadness:
Farewell! mounds dreaming
By wavelets blue,
Where west winds streaming
White blossoms strew!
Odin revealeth
And doometh well
What man concealeth;—
Farewell! Farewell!
Farewell, ye bowers,
Ye limpid streams,
Where ’mid spring flowers,
Youth wandered in dreams.
81
Ye friends of childhood
Who loved me well,—
Till death remembered,—
Farewell! Farewell!
My love insulted,
My dwelling brent,
My honor tarnished,
In exile sent,—
Heart bideth in sadness
Norns’ fatal spell.
To Life’s young gladness
Farewell! Farewell!
Chapter XV
Frithiof’s Viking Life
Thus Frithiof became a viking, the sea his only home;
and these are the laws he made for his followers:
“Pitch no tent on thy ship; seek no slumber below.
On his shield sleeps the viking, his sword in his
hand. His tent is the blue dome of heaven.
“Short be thy sword, like the hammer of Thor;
strike close to the foe.
“When the storm roars on high, spread wider the
sails: The sea in its wrath fills the viking with joy; a
coward is he who would furl.
“Wine is drink of the gods. Enjoy thou the gift, but
drown not thy senses—beware! He who falls on the
land rises quickly again; who staggers here is the
death-goddess’ prey!
“Protect the merchant ship on the high seas so due
tribute it doth not refuse. Thou art lord of the
waves; he’s a slave to his pelf. Thy steel is as good
as his gold. By lot shall the booty be shared among
all; complain not however it falls. The Sea King
82
himself throws no dice on the deck; he seeks only
glory from his foes.
“Heaves a viking in sight, then come boarding and
strife; from us he is banished who yields. Mercy fits
him who conquers; he who lays down his arms at
thy feet is no longer thy foe.
“Prayer is Valhalla’s child, and a scoundrel is he
who, ruthless, refuses to hear it.
“The viking’s rewards are his wounds; before all, on
the brow and the breast are they glorious. He who
seeketh ere issue of battle to bind them no longer
is comrade of viking.”
Thus ran the code of Frithiof, and no laws of Odin were
more strictly obeyed. Many a battle did these heroes
fight and win, for there was not their like on all the
seas; and soon their fame spread far and wide. But
naught of this had power to gladden Frithiof’s heart; he
would sit, helm in hand, for hours with clouded brow,
gazing out over the rolling waters. Only in battle did the
shadow vanish, as with flashing eyes and fiercely
swelling breast he led his men to victory.
For three years they sailed the seas northward and
westward; then turning south, his dragon anchored one
day off the coast of Greek-land (Greece). With wonder
Frithiof gazed upon that beauteous land, with its noble
ruined temples rising amid fragrant groves. The tales his
father had been wont to tell of those fair isles still
lingered in his memory like some lovely vision—a dream
that now was realized. Hither had he once thought to
flee with Ingeborg from the haughty Helge, here with
her to found an abode of bliss, but the noble maiden
83
84
had denied his prayers and shrunk from such a breach
of duty and of custom. Amid these fair scenes memories
of his native land awoke afresh within him, and he
longed to see it once again. But most of all he yearned
for a sight of Ingeborg and to visit his father’s grave-
mound.
“Why do I linger here in strange seas and stain my
hands with blood?” he asked himself. “Enough of glory
have I won, and I care not for gold. North points the
flag on the masthead. To the Northland the home of my
youth! Up, ‘Ellida’! no longer we’ll tarry, but follow that
token from Heaven!”
85
Chapter XVI
Frithiof comes to King Ring’s Court
On his high-seat sat King Ring, celebrating the great
Yule tide feast that fell on the winter solstice, and
beside him Ingeborg, his wife, like chilly Autumn with
the youthful Spring. The mead-horn went round, and
joyous shouts and laughter filled the hall. Suddenly
through the doorway entered an old man, tall of stature
and wrapped from head to foot in a great bearskin. In
his hand he bore a staff and walked as if bowed with
age. None knew him, and he quietly took his place on
the bench near the door, reserved for the poor. The
courtiers smiled to one another and pointed jeeringly at
the shaggy figure, while one playfully approached with
intent to make sport of him for the amusement of the
others. With flashing eyes the stranger seized the rash
youth, whirled him about in the air, and set him again
on his feet unharmed; whereat the courtiers’ smiles
deserted them, and they fell straightway silent.
“What noise is that down yonder?” cried Ring sternly.
“Come hither, old man, who thus disturbest our kingly
peace! Who art thou? What brings thee here? Whence
comest thou?”
“Much dost thou ask, O King,” replied the stranger, “yet
all will I tell thee save my name,—that concerneth none
86
but me. In Penitence was I reared; Want was my
inheritance; my latest bed a Wolf’s lair. Astride my
dragon, with its mighty wings, I flew swiftly hither from
afar; now my good ship lies frozen in upon thy shores. I
came to hear thy words of wisdom, famed through all
the land. When thy people just now sought to mock me,
I seized a vain fool and swung him round about—but I
did him no harm. Forgive me, King!”
“Truly,” the monarch cried,—“thou speakest well, and
wisdom’s teachings bid us honor age. Come, sit at the
board. But first, I pray thee, doff thy strange
disguisement and show thyself in thy true form, for
deception is ever wont to be the foe of gladness.”
At this the stranger let fall his hairy covering, and there,
in place of an old man, appeared a youth of noble
stature, his loft brow shaded with bright flowing locks. A
blue mantle hung from his mighty shoulders, and his
tunic was held in place by a wide silver belt, on which,
with cunning skill, beasts of the forest were embossed.
Heavy gold armlets encircled his arm; at his left side
hung a sword that gleamed like lightning. Fair as Balder,
like to the mighty Thor in strength of limb, he stood
before the King and his astonished court. For a moment
his keen glance wandered about the hall, then he
seated himself calmly at the board. The blood rushed to
the cheeks of the Queen till she glowed as crimson as
the ice-fields lit by flaring Northern lights.
But now the trumpets sounded the signal for silence. It
was the hour of the vow, and the crowned boar was
borne into the hall on a silver charger and placed upon
the board. Touching the head of the boar, Ring said:
87
88
“Hearken, ye warriors, to my vow! I swear to conquer
Frithiof, howsoever stout a champion he be; so help me
Odin, Thor, and Frey!”
The stranger rose with a frown and dashed his sword
upon the board with such a clang that all the warriors
sprang from their seats.
“Hear thou me likewise, good Sir King,” he cried: “That
Frithiof whom thou namest is my friend and kinsman:
and him I swear to guard with life and limb, so help me
Norns and my good sword!”
The King smiled. “Thou speakest boldly,” he answered,
“but words are free in Northland’s royal halls. Fill for
him, Queen, yon horn with draught of welcome. I hope
he’ll tarry with us as our guest till Spring returns.”
This horn was a precious heirloom of the house, broken
from the forehead of the urus. Its feet were of silver
wonderfully wrought, while the golden rings about it
were carven with strange runes. With downcast eyes
Ingeborg handed it to the guest, but she trembled so
that the wine was spilled, and red drops gleamed on her
white hand like evening’s purple blushes on a lily.
Unmoved, the hero took the mighty horn, lifted it to his
lips and at one draught drained it to the honor of his
host. Then at a sign from the King, the scald smote on
his harpstrings and chanted many a heart-stirring song
and legend. In lofty words he sang of love and
friendship, of freedom and the country’s glory, of the
high gods and Valhalla’s wonders, till fire shot forth from
every eye, and involuntarily each warrior grasped the
handle of his sword.
89
Deeply they drank throughout the night, and many a
champion, like a tower of strength in battle, was
vanquished by the sweetly foaming mead.
90
Chapter XVII
The Sledge Excursion
“Ho for a sledge ride over the frozen lake!” cried Ring
one day; and the servitors hastened to loose one of the
pawing steeds from the royal stables and harness it
before a splendid sledge, over the seat of which was
thrown a silky sealskin.
“’Tis not safe on the lake,” said the stranger. “The ice is
thin and weak in some parts, and should it give way, full
cold and deep would be thy bath!”
“Nay, not so easily do monarchs drown,” replied the
King; “let him who fears it, go around the shore!”
The stranger said no more, but frowning darkly,
hastened to fasten on his steel skates, while the
impatient courser pawed the air and whinnied loudly.
“Speed on, my steed,” cried Ring, “and let us see if thou
art sprung from Sleipner’s blood!”
Away dashed the sledge with the speed of the
whirlwind, the stout-hearted old king exulting in the
motion and heeding not the entreaties of his wife; but
swift as they flew, the stranger still outstripped them,
circling about in wide curves or cutting figures on the
ice. Meanwhile, false Ran, the spouse of the Sea-god,
91
has marked what is passing above. She cleaves a broad
fissure in the sea’s silvery roof, and into the up-foaming
waves plunge horse and sledge. But swift as the wind
flies the stranger thither. Fixing his steel shoes firmly in
the ice, he seizes the horse by the mane and with a
mighty jerk, pulls it and sledge together back on to the
ice.
“In sooth,” said the King, “that deed doth merit praise;
e’en Frithiof himself could do no better. And now, my
Fleet-of-foot, let us back to the palace again.”
92
Chapter XVIII
Frithiof’s Temptation
Spring is come once more; birds warble in the treetops;
freed from their icy bonds, the streams leap gaily
downward to the vales below; the roses part their
delicate sheaths and blossom red as Frigga’s cheeks.
King Ring will now go hunting, and forthwith a joyous
stir pervades the court. Bows twang, quivers rattle, fiery
coursers paw the ground, the hooded falcon screams for
its victim, and scarce can the huntsmen keep in leash
the eager hounds. Fair as Frigga, dazzling as the battle-
maiden Rota, sits the Queen upon her milk-white steed
like a star on a summer cloud. Her hunting dress is of
green, embroidered with gold, and blue plumes wave
from her velvet cap.
Led by the royal pair, the gay train wends its way into
the forest, and soon the sport begins. Loud bay the
hounds; up mount the hawks into the clear sky; horns
sound; the frightened game seeks lair and covert; and
the eager huntsmen scatter in pursuit.
King Ring has fallen behind; old and feeble, he can no
longer follow the lengthening chase, while beside him
silent and thoughtful, rides his guest. At last they
reached a rocky glen shut in by thick-clustering trees
93
and thickets, and here the King dismounted from his
courser, saying:
“Full weary am I, stranger; here will I rest me in this
pleasant spot.”
“Nay, sleep not on the cold hard ground,” replied the
other; “I had better lead thee back to thy own halls.”
“Sweet slumber comes when least expected; ’tis the
way of the gods,” said Ring. “Surely thou dost not
grudge thy host an hour of rest!”
Without further words, the stranger spread his cloak
upon the ground and seated himself on a fallen tree-
trunk, while Ring, stretching himself out upon the
mantle, laid his head against the other’s knees. His eyes
closed and soon he slept, sweetly as an infant cradled in
its mother’s arms. As the stranger gazed gloomily down
on the face of the King, he heard a rustling in the
branches above him to the left, and lifting his eyes he
saw a coal-black bird, which began to sing:
Haste thee, Frithiof, slay the dotard, with one sword-
stroke grant him rest!
Take the Queen; she’s thine; her sacred kiss of
plighted troth she gave.
Here no human eye can see thee—silent is the deep,
dark grave!
Scarce had the sound ceased when from a bough on
the right, a snow-white bird began:
Though no human eye should see thee, Odin would
the death-stroke view.
Wouldst thou murder him in slumber? Cowardly thy
bright sword stain?
94
95
Know, whate’er besides thou winnest, hero-fame thou
ne’er shalt gain!
Thus sang the two birds, while contending thoughts
struggled within the listener. Suddenly he seized his
sword by the handle and flung it far from him into the
shadow of the forest. Whereupon the black bird, with
heavy flapping of its wings, flew back to the dark halls
of Night, the abode of perjurers and assassins; while,
blithely warbling, upward the white bird took its flight
and vanished at last in the blue of heaven. At that
moment the King awoke and rising to his feet, said:
“Sweet indeed hath been my slumber. Well they rest
whom valor’s sword doth guard. But where is thy war
blade, stranger? Methought the Brother of Lightning
never left thy side. Say, who hath parted you?”
“Little boots it,” answered the other; “swords are plenty
in the Northland. The sword is not always a good
companion. Its tongue is sharp and it speaketh few
words of peace. In steel there dwells an evil spirit,
sprung from Loke’s dark abode, to whom not even sleep
is sacred, nor the silver locks of age.”
“Hearken, youth!” began the King. “I slept not. ’Twas
but to try thee I did feign to slumber—a fool is he who
trusts a man or a blade untried. Thou art Frithiof! I
knew thee even when thou didst cross my threshold.
But wherefore didst thou creep nameless and in such
disguise into my palace? Wherefore, if not to rob me of
my wife? Honor comes not nameless to the banquet,
Frithiof! Ever open-faced she meets men’s glances, clear
as sunlight is her shield. The fame of Frithiof’s deeds
has reached us,—a terror both of gods and men;
careless alike of cloven shield or burning temple; the
96
97
mightiest warrior known in all the land. And this bold
hero, this fierce viking, creeps, a beggar, to our hall!
Nay, cast not down thy eyes before me. I, too, have
once been young and felt as thou. Youth, well I know,
hath fiery passions. Much have I thought on thee, O
Frithiof. I have pitied and have pardoned thee. Hearken
now! I am growing old and feeble, and soon for me the
grave shall open. Then take unto thyself my kingdom
and my wife. Until that time, be thou a son to me and
guard my house as thou hast done before. And now, my
son, let there be no more feud between us!”
“Not as a thief did I enter thy halls, O King,” replied
Frithiof proudly. “Had I come to seize thy Queen, who
could have withstood me? ’Twas but to behold once
again her who before the altar gave me her betrothal
kiss. But ah, what slumbering fires my rashness hath
awakened! Too long already have I tarried. Upon my
head the gods have poured their wrath. Even the gentle
Balder, lover of all mankind, spurns my prayers. ’Twas I
who burned his temple. ‘Wolf in the Sanctuary,’ am I
called. All joy ceases when my name is spoken. The
child clings trembling to its father’s knees. Once more
will I seek the broad, free ocean, whither earth and man
have banished me. Out, out, my dragon! Too long in
idleness thou hast lain. Again to the storm wind shalt
thou spread thy pinions, and bathe thy black breast in
the dashing spray! All—all on earth is lost to me forever;
the tempest’s roar, the clash of arms shall whisper
comfort to my soul once more! So will I live, so will I
fighting fall; and mounting then to Odin’s throne, the
gods, appeased, shall speak my pardon.”
98
Chapter XIX
Death of King Ring
Pale on his throne sat the aged monarch, for he felt his
end approaching. Ingeborg, trembling, stood beside
him, and a circle of silent warriors stood about the royal
pair. Sorrowfully Frithiof entered to say farewell.
“This day for the last time do ye behold me,” he said;
“for the last time my foot doth tread the soil of earth.
Henceforth, till the Norns shall send their summons the
ocean’s boundless wastes shall be my home. Take back
the ring round which such memories cluster, Ingeborg;
let it be a parting token from me. And thou, O King, go
not with thy Queen by moonlight to the strand, nor
when the pale stars shine, for at your feet the waves
might chance to toss my bleaching bones.”
“Nay, Frithiof,” replied the King, “such mournful plaints
become not men; in maids they may be pardoned. For
me the death song soundeth, not for thee. ’Tis I must
hence, not thou! Take thou my realm and guard it well.
Take Ingeborg as thy wife, and be a father to my infant
son. Ever through life hath peace been dearest to me;
well have I loved to sit with friends about the board; yet
with a strong hand have I guarded throne and honor,
and cloven many a shield on sea and land; nor ever
hath man seen my cheek turn pale. Victory hath been
99
mine, and glory. One boon only have the gods denied
me—to mount to Valhalla from the battle-field. Death by
the sword is the death of heroes; to linger on,—the
straw death,—never such will Ring live to endure!” And
therewith he plunged his sword into his breast. As the
life-blood gushed forth he had his horn brought to him,
and raising it aloft, with glowing face he cried:
“To thy glory I drain this, my country, thou Northland!
Ye gods of Valhalla, all hail, all hail!”
KING RING’S Death
Silence reigned within the hall; none gave way to grief
lest the dying man’s last moments should be saddened.
Sinking back on his cushions, the King clasped
Ingeborg’s hand for the last time—greeted his friend
100
and son with a parting glance, and sighing, his soul
ascended to the All-Father. Great was the mourning for
him throughout the kingdom; amid universal
lamentations the good King’s mound was heaped above
him, while scalds with sounding dirges glorified his
memory.
101
Chapter XX
The Election to the Kingdom
“To the Ting! To the Ting!” The message flies o’er hill
and vale; the people are summoned to elect their King.
Champions try their swords, vassals polish their lord’s
helm and buckler till they shine like the sun. Thus with
clang of arms the warriors assembled on the open plain.
In their midst on the wide Ting-stone stood Frithiof, and
at his side King Ring’s son, a fair child with golden hair.
“Too young is Ring’s heir,” was murmured through the
multitude; “no chief is he to lead us into battle, or sit in
judgment on the Ting-stone.”
But Frithiof placed the child upon his shield and held
him high aloft, saying: “Northmen, behold your King, a
vigorous offshoot of the fallen oak! Doth he not bear
him well upon the shield? Hear now my vow: I swear to
guard for him his Kingdom, till with his father’s circlet he
shall one day here be crowned.” Then raising his eyes to
heaven, he added: “Forsete, son of Balder, be my
witness! O thou who judgest justly, strike me dead if
e’er I break my word!”
Meanwhile the King’s son sat on Frithiof’s gleaming
shield, gazing about him proudly; but at length he
began to weary of it, and with one bound sprang lightly
to the ground. A shout went up from all the Ting:
102
“Ha, that was indeed a royal leap! Aye, shield-borne,
thee we choose to be our King! And thou, O Frithiof,
who shalt guard his crown and kingdom, take Ingeborg,
our Queen, to be thy wife!”
At these words Frithiof’s brow darkened. “To choose a
King are you come,” he answered; “my bride I woo of
my own choice. In anger still doth Balder look upon me.
’Twas he that took my Ingeborg from me, and he alone
can give her back to me.”
103
Chapter XXI
The Reconciliation
No peace was there yet in Frithiof’s heart. As fire had
once consumed the temple, so within him still blazed
the flames of his remorse that by his act had Balder’s
earthly dwelling been destroyed. Betaking himself to his
father’s grave-mound he sat all night alone upon the
cairn, beseeching Balder to smile upon him once again.
And lo! in the darkness a wondrous vision grew before
his eyes. In Balder’s Grove he saw a gleaming temple
slowly rise; but scarcely had he gazed upon it in
amazement, when again ’twas swallowed in the gloom
of night.
Roused by fresh hope of winning the offended god’s
forgiveness, he hastily returned to Ring’s dominions and
summoned architects to plan for the building of a new
temple. Just as he had seen it in his vision should the
home of Balder actually rise. So filled was he with this
one thought that nothing else had power to move him,
neither feast, nor chase, nor sounding minstrel lay.
At last the work was finished, and like the far-famed
shrine of Upsal, the great temple stood a wonder to all
eyes. A brazen portal richly carved led to the sanctuary;
two rows of lofty columns supported the arching roof,
like a great shield of gold. Facing the doorway stood the
104
high altar, hewn from a single block of Northern marble
and polished with rare skill; round about it were graven
runes of solemn import. Above, in a spacious niche, was
Balder’s august image, wrought all of purest silver. On a
rocky hillside rose the building, its reflection mirrored in
the sea below, while round about on three sides
stretched a smiling valley, known as Balder’s Dale. Leafy
groves adorned the flowery meadows. No sound but
happy bird songs broke the silence; all nature breathed
of peace.
With deep emotion Frithiof trod those holy precincts.
Twelve rosy-cheeked maidens, priestesses of the
temple, robed all in white, advanced to the high altar
and chanted a holy song in praise of Balder. They sang
how beloved was the gentle god by every creature; and
when he fell by evil Loke’s malice, how heaven itself
with earth and ocean wept. And as leaning on his sword
the hero listened, the dark shadow, that so long had
lain upon his spirit, lifted. Tender memories of his
childhood woke within him, while calm and serene as
the moon in the skies of Summer, Balder the Good
looked down upon him and filled his soul with peace.
Then with slow steps approached the high-priest of the
temple, not young and fair like the god at whose shrine
he worshipped, but tall and majestic, his noble features
stamped with heavenly mildness and graced with
flowing beard and locks of silver. With unwonted
reverence Frithiof bent his haughty head before the
seer, who thus began:
“Welcome, son Frithiof, to this holy temple. Long have I
looked for thee to come, for force, though restless over
land and sea it wanders, turns ever, wearied, home
again at last. Oft did the mighty Thor wend thus to
Jötunheim, the giants’ kingdom; yet despite his godlike
105
106
belt and magic gauntlets, the giant King still sits upon
his throne. Evil, itself a force, yields not to evil. Virtue
without strength is but child’s play, the glancing
sunbeam on the shield, a wavering shadow on the
earth’s broad breast. Yet neither may strength without
virtue long survive. It consumes itself, like rusting sword
in some dark grave-mound—a debauch from which he
who yieldeth to it wakens filled with shame.
“Behold the mighty earth! It is the body of Ymir, the
world-giant from whom all strength proceeds—its
rushing streams his blue veins; its iron and brass his
sinews; yet all is barren, bare, and empty till heaven’s
bright sun-rays stream upon it from afar. Then springs
the grass; fair blossoms deck the verdant meadows, and
fresh leaves, the trees; the swelling buds burst forth; all
nature breathes new life from the abundant earth. Thus
is it with man’s strength: it yields naught but blessing
when transfigured by the heavenly rays of virtue.
“What the sun is to the earth, was Balder to Valhalla.
His pure soul was the gem that fastened the wreath
divine. When, slain by evil Loke, he descended to pale
Hel’s realm, Odin’s wisdom straight began to languish,
and the strength of mighty Thor to dwindle; the
prisoned forces of evil, once mastered by the gods,
stirred in their abysses; the dragon Nidhögg gnawed at
the roots of the Tree of Life, and its leafy crown fast
withered. Again the war broke out ’twixt good and evil—
the strife that through all creation still endures.
“This is but the emblem of what passes in every human
breast. Hast thou forgotten, my son, those days when
Balder dwelt within thy spirit? Pure then was every
thought and feeling, thy whole life glad as a woodland
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookultra.com

Osgi in Action Creating Modular Applications in Java Unedited Draft 1st Edition Richard Hall

  • 1.
    Visit https://ebookultra.com todownload the full version and explore more ebooks or textbooks Osgi in Action Creating Modular Applications in Java Unedited Draft 1st Edition Richard Hall _____ Click the link below to download _____ https://ebookultra.com/download/osgi-in-action-creating- modular-applications-in-java-unedited-draft-1st-edition- richard-hall/ Explore and download more ebooks or textbooks at ebookultra.com
  • 2.
    Here are somerecommended products that we believe you will be interested in. You can click the link to download. Enterprise OSGi in Action With examples using Apache Aries Holly Cummins https://ebookultra.com/download/enterprise-osgi-in-action-with- examples-using-apache-aries-holly-cummins/ Modular Java 1st Edition Craig Walls https://ebookultra.com/download/modular-java-1st-edition-craig-walls/ Java Internationalization Creating International Applications Java Series First Edition David Czarnecki https://ebookultra.com/download/java-internationalization-creating- international-applications-java-series-first-edition-david-czarnecki/ Integrative Psychotherapy in Action Richard G Erskine https://ebookultra.com/download/integrative-psychotherapy-in-action- richard-g-erskine/
  • 3.
    Java Persistence withHibernate Second Edition of Hibernate in Action Christian Bauer https://ebookultra.com/download/java-persistence-with-hibernate- second-edition-of-hibernate-in-action-christian-bauer/ Professional Flash Mobile Development Creating Android and iPhone Applications 1st Edition Richard Wagner https://ebookultra.com/download/professional-flash-mobile-development- creating-android-and-iphone-applications-1st-edition-richard-wagner/ Consumed by War European Conflict in the 20th Century Richard C. Hall https://ebookultra.com/download/consumed-by-war-european-conflict-in- the-20th-century-richard-c-hall/ Quantum Dots Applications in Biology 1st Edition Richard L. Ornberg https://ebookultra.com/download/quantum-dots-applications-in- biology-1st-edition-richard-l-ornberg/ POJOs in Action Developing Enterprise Applications with Lightweight Frameworks 1st Edition Chris Richardson https://ebookultra.com/download/pojos-in-action-developing-enterprise- applications-with-lightweight-frameworks-1st-edition-chris-richardson/
  • 5.
    Osgi in ActionCreating Modular Applications in Java Unedited Draft 1st Edition Richard Hall Digital Instant Download Author(s): Richard Hall, Karl Pauls, Stuart McCulloch, David Savage ISBN(s): 9781933988917, 1933988916 Edition: 1 File Details: PDF, 4.90 MB Year: 2011 Language: english
  • 6.
    ©Manning Publications Co.Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 7.
    MEAP Edition Manning EarlyAccess Program Copyright 2010 Manning Publications For more information on this and other Manning titles go to www.manning.com ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 8.
    Table of Contents 1.OSGi Revealed 2. Mastering Modularity 3. Learning Lifecycle 4. Studying Services 5. Delving Deeper into Modularity 6. Moving Toward Bundles 7. Managing Bundles and Applications 8. Testing Applications 9. Debugging Applications 10. Component Models 11. Launching and Embedding an OSGi Framework 12. Security 13. Web Applications and Services ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 9.
    1 OSGi Revealed The Java™platform is an unqualified success story. It is used to develop applications for small mobile devices to massive enterprise endeavors. This is a testament to its well thought out design and continued evolution. However, this success has come in spite of the fact that Java does not have explicit support for building modular systems beyond ordinary object- oriented data encapsulation. So, what does this mean to you? If Java is a success despite its lack of advanced modularization support, then you might wonder if its absence is a problem. Most well managed projects have to build up a repertoire of comparable, but project specific, techniques to compensate for the lack of modularization in Java. These include:  Programming practices,  Tricks with multiple class loaders, and  Serialization between in-process components. However these techniques are inherently brittle and error prone since they are not enforceable via any specific compile-time or run-time checks. The end result has detrimental impacts on multiple stages of an application's lifecycle:  Development – you are unable to clearly and explicitly partition development into independent pieces.  Deployment – you are unable to easily analyze, understand, and resolve requirements imposed by the collection of independently developed pieces that make up the system.  Execution – you are unable to manage and evolve the constituent pieces of a running system, nor minimize the impact of doing so. It is definitely possible to manage these issues in Java, and lots of projects do so using the custom techniques mentioned above, but it is much more difficult than it should be. We're tying ourselves in knots to work around the lack of a fundamental feature. If Java had explicit support for modularity, then you would be freed from such issues and could ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 10.
    concentrate on whatyou really want to do, which is developing the functionality of your application. Welcome to the OSGi™ Service Platform. The OSGi Service Platform is an industry standard defined by the OSGi Alliance to specifically address the lack of support for modularity in the Java platform. Additionally, it also introduces a new service-oriented programming model, referred to by some as “SOA in a VM.” This chapter will give you an overview of the OSGi Service Platform and the issues it is intended to address. Once we have finished this chapter we will have enough background knowledge to start digging into the details in chapter 2. 1.1 The what and why of OSGi The sixty-four-thousand dollar question is, “What is OSGi?” The simplest answer to this question is it is a modularity layer for the Java platform. Of course, the next question that might spring to mind is, “What do you mean by modularity?” Here we use modularity more or less in the traditional computer science sense, where the code of your software application is divided into logical parts representing separate concerns as in Figure 1.1.1. If your software is modular, then you can simplify development and improve maintainability by enforcing the logical module boundaries; we will discuss more modularity details in Chapter 2. The notion of modularity is not new. The concept actually became fashionable back in the 1970s. So, why is OSGi all the rage right now? To better understand what OSGi can do for you, it is worthwhile to understand what Java is not doing for you with respect to modularity. Once you understand that, then you can see how OSGi can help. 1.1.1 Java's modularity limitations Java was never intended to support modular programming, so we admit that criticizing its inability to do so is a little unfair. Java has been promoted as a platform for building all sorts ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507 Figure 1.1.1 Modularity refers to the logical decomposition of a large system into smaller collaborating pieces Module A Module B Module C uses uses uses u s e s
  • 11.
    of applications forall sorts of domains ranging from mobile phone to enterprise applications. Most of these endeavors require, or could at least benefit from, modularity, so Java's lack of explicit support does cause some amount of pain for developers. From this point of view, we do feel the following criticisms are valid. LOW-LEVEL CODE VISIBILITY CONTROL While Java provides a fair complement of access modifiers to control visibility (e.g., public, protected, private, and package private), these tend to address low-level object- oriented encapsulation and do not really address logical system partitioning. Java has the notion of a package, which is typically used for partitioning code. For code to be visible from one Java package to another, the code must be declared public (or protected if using inheritance). Sometimes the logical structure of your application calls for specific code to belong in different packages, but then this means any dependencies among the packages must be exposed as public, which makes it accessible to everyone else too. Often this can expose implementation details, which makes future evolution more difficult since users may end up with dependencies on your non-public API. To illustrate this, let's consider a trivial hello world application that provides a public interface in one package, a private implementation in another and a main class in yet another. Listing 1.1.1 Trivial example of the limitations of Java's object-orientated encapsulation package org.foo.hello; public interface Greeting { #1 void sayHello(); } package org.foo.hello.impl; import org.foo.hello.Greeting; public class GreetingImpl implements Greeting { final String m_name; public GreetingImpl(String name) { #2 m_name = name; } public void sayHello() { System.out.println("Hello, " + m_name + "!"); } } package org.foo.hello.main; import org.foo.hello.Greeting; import org.foo.hello.impl.GreetingImpl; ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 12.
    public class Main{ public static void main(String[] args) { Greeting greet = new GreetingImpl(“Hello World”); #3 greet.sayHello(); } } I n Listing 1.1.1, the author may have intended a third party to only interact with the application via the Greeting interface at (#1). He or she may mention this in Javadoc, tutorials, blogs, or even email rants, but there is nothing actually stopping a third party from constructing a new GreetingImpl using its public constructor at (#2) as is done at (#3). You might argue that the constructor should not be public and there is no need to split the application into multiple packages, which could well be true in this trivial example. But in real-world applications class-level visibility when combined with packaging turns out to be a very crude tool for ensuring API coherency. Seeing how a supposedly private implementation can be accessed by third-parties developers, now you need to worry about changes to private implementation signatures as well as that of public interfaces when making updates. This problem stems from the fact that although Java packages appear to have a logical relationship via nested packages, they actually do not. A common misconception for people first learning Java is to assume that the parent-child package relationship bestows special visibility privileges on the involved packages. Two packages involved in a nested relationship are equivalent to two packages that are not. Nested packages are largely useful for avoiding name clashes and provide only partial support for the logical code partitioning. What this all means is in Java you are regularly forced to decide between: 1. Impairing your application's logical structure by lumping unrelated classes into the same package to avoid exposing non-public API or 2. Keeping your application's logical structure by using multiple packages at the expense of exposing non-public API so it can be accessed by classes in different packages. Neither choice is particularly palatable. ERROR-PRONE CLASS PATH CONCEPT The Java platform also inhibits good modularity practices. The main culprit is the Java class path. Why does the class path pose problems for modularity? Largely due to all of the issues that it hides, such as code versions, dependencies, and consistency. Applications are generally composed of various versions of libraries and components. The class path pays no attention to code versions, it simply returns the first version that it finds. Even if it did pay attention, there is no way to explicitly specify dependencies. The process of setting up your class path is largely trial and error; you just keep adding libraries until the VM stops complaining about missing classes. ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 13.
    Figure 1.1.2 showsthe sort of “class path Hell” that can often be found when more than one JAR file provides a given set of classes. Even though each JAR file may have been compiled to work as a unit, when merged at run time the Java class path pays no attention to the logical partitioning of the components. This tends to lead to such hard to predict errors, such as NoSuchMethodError, when a class from one JAR file interacts with an incompatible class from another one. In large applications, created from independently developed components, it is not uncommon to have dependencies on different versions of the same component, such as logging or XML parsing mechanisms. The class path forces you to choose just one version in such situations, which may not always work for all parts of the application if there are incompatibilities between versions. Worse, if you happen to have multiple versions of the same package on the class path, either on purpose or accidentally, they are treated as split packages by Java and are implicitly merged based on order of appearance. Overall, the class path approach lacks any form of consistency checking. You just get whatever classes have been made available by the system administrator, which is very likely only an approximation of what the developer actually expected. This hardly inspires confidence. LIMITED DEPLOYMENT AND MANAGEMENT SUPPORT Java also lacks support when it comes to deploying and managing your application. There is no easy way in Java to deploy the proper transitive set of versioned code dependencies and execute your application. Likewise for evolving your application and its components after deployment. Consider the common requirement of wanting to support a dynamic plugin mechanism. The only way to achieve such a benign request is to use class loaders, which are low level and error prone. Class loaders were never intended to be a common tool for application developers, but so many of today's systems require their use. A properly defined modularity layer for Java can deal with these issues by making the module concept explicit and raising the level of abstraction for code partitioning. ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507 Figure 1.1.2 Multiple JARs containing the “same” class are merged based on their order of appearance in the class path paying no respect to logical coherency between archives Jar 2 Jar 1 Classpath Jar 3
  • 14.
    With this betterunderstanding of the limitations of Java when it comes to modularity, we can ponder whether OSGi is the right solution for your projects. 1.1.2 Can OSGi help you? Nearly all but the simplest of applications can benefit from the modularity features OSGi provides, so if you are wondering if OSGi is something you should be interested in, the answer is most likely, “Yes!” Still not convinced? Here are some common scenarios that you may have encountered where OSGi can be helpful:  If you ever received ClassNotFoundExceptions when starting your application because the class path was not correct. OSGi can help you here by ensuring that code dependencies are satisfied before allowing the code to execute.  If you ever encountered run-time errors when executing your application due to the wrong version of a dependent library on the class path. OSGi verifies that the set of dependencies are consistent with respect to required versions and other constraints.  If you ever wanted to share classes between modules without worrying about constraints implied by hierarchical class loading schemes; put in a more concrete way, the dreaded appearance of “foo instanceof Foo == false” when sharing objects between two servlet contexts.  If you ever wanted to package your application as logically independent JAR files and be able to deploy only those pieces you actually need for a given installation. This pretty much describes the purpose of OSGi.  If you ever wanted to package your application as logically independent JAR files and also wanted to declare which code is accessible from each JAR file and have this visibility enforced. OSGi enables a new level of code visibility for JAR files that allows you to specify what is and what is not visible externally.  If you ever wanted to define an extensibility mechanism for your application, like a plugin mechanism. OSGi modularity is particularly suited to providing a powerful extensibility mechanism, including support for run-time dynamism. As you can see, these scenarios cover a lot of use cases, but are by no means exhaustive. The simple and non-intrusive nature of OSGi tends to make you discover more ways to apply it the more you use it. Having explored some of the limitations of the standard Java class path we'll now properly introduce you to OSGi. 1.2 A quick OSGi overview The OSGi Service Platform is composed of two parts: the OSGi framework and OSGi standard services (depicted in Figure 1.1.3). The framework is the runtime that implements and provides OSGi functionality. The standard services define reusable APIs for common tasks, such as Logging and Preferences. ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 15.
    The OSGi specificationsfor the framework and standard services are managed by the OSGi Alliance (http://www.osgi.org). The alliance is an industry backed non-profit corporation founded in March 1999. The framework specification is now on it's fourth major revision and is stable. Technology based on this specification is in use in a range of large scale industry applications including (but not limited to) automotive, mobile devices, desktop applications, and more recently enterprise application servers. NOTE Once upon a time, the letters “OSGi” were an acronym that stood for the Open Services Gateway Initiative. This acronym highlights the lineage of the technology, but has fallen out of favor. After the third specification release, the OSGi Alliance officially dropped the acronym and “OSGi” is now simply a trademark for the technology. In the bulk of this book we will discuss the OSGi framework, its capabilities, and how to leverage these capabilities. Since there are so many standard services, we will only discuss the most relevant and useful services where appropriate. For any service we miss, you can get more information from the OSGi specifications themselves. Let's continue our overview of OSGi by introducing the broad features of the OSGi framework. 1.2.1 The OSGi Framework The OSGi framework plays a central role when creating OSGi-based applications, since it is the application's execution environment. The OSGi Alliance's framework specification defines the proper behavior of the framework, which gives you a well-defined API to program against. The specification also enables the creation of multiple implementations of the core framework to give you some freedom of choice; there are a handful of well-known open source projects, such as Apache Felix, Eclipse Equinox, and Knopflerfish. This ultimately benefits you, since you are not tied to a particular vendor and are able to program against the behavior defined in the specification. It's sort of like the reassuring feeling you get by knowing you can go into any McDonald's anywhere in the world and get the same meal. ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507 Figure 1.1.3 The OSGi Service Platform specification is divided into two halves, one for the OSGi framework and one for standard services Framework Standard services OSGi SERVICE PLATFORM
  • 16.
    The OSGi specificationconceptually divides the framework into three layers (see Figure 1.1.4):  Module layer – this layer is concerned with packaging and sharing code.  Lifecycle layer – this layer is concerned with providing run-time module management and access to the underlying OSGi framework.  Service layer – this layer is concerned with interaction and communication among modules, specifically the components contained in them. Like typical layered architectures, each layer is dependent upon the layers beneath it. Therefore, it is possible for you to use lower OSGi layers without using upper ones, but not vice versa. The next three chapters discuss these layers in detail, but we will give an overview of each here. 1.2.2 Module layer The module layer defines the OSGi module concept, called a bundle, which is simply a JAR file with extra metadata (i.e., data about data) as depicted in Figure 1.1.5. A bundle contains your class files and their related resources. Bundles are typically not an entire application packaged into a single JAR file; rather, they are the logical modules that combine to form a given application. Bundles are more powerful than standard JAR files, since you are able to explicitly declare which contained packages are externally visible (i.e., exported packages). In this sense, bundles extend the normal access modifiers (i.e., public, private, and protected) associated with the Java language. Another important advantage of bundles over standard JAR files is that you are also able to explicitly declare on which external packages your bundle depends (i.e., imported packages). The main benefit of explicitly declaring your bundles' exported and imported packages is that the OSGi framework can manage and verify the consistency of your bundles automatically; this process is called bundle resolution and involves matching exported packages to imported packages. Bundle resolution ensures consistency among bundles with respect to versions and other constraints, which we will discuss in detail in Chapter 2. ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507 Figure 1.1.4 OSGi layered architecture MODULE LIFECYCLE SERVICE
  • 17.
    1.2.3 Lifecycle layer Thelifecycle layer defines how bundles are dynamically installed and managed in the OSGi framework. If we were building a house, the module layer provides the foundation and structure, while the lifecycle layer is the electrical wiring – it makes everything go. The lifecycle layer serves two different purposes. External to your application, the lifecycle layer precisely defines the bundle lifecycle operations (e.g., install, update, start, stop, and uninstall). These lifecycle operations allow you to dynamically administer, manage, and evolve your application in a well-defined way. This means that bundles can be safely added and removed from the framework without restarting the application process. Internal to your application, the lifecycle layer defines how your bundles gain access to their execution context, which provides them with a way to interact with the OSGi framework and the facilities it provides during execution. This overall approach to the lifecycle layer is ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507 Figure 1.1.6 The service-oriented interaction pattern. Providers publish services into a registry where requesters can discover which services are available for use. Publish Find Interact Service Registry Service Provider Service Requester Service Description Figure 1.1.5 A bundle contains code, resources, and metadata Bundle .class class files .xml, .jpeg, etc. resource files MANI FEST .MF metadata
  • 18.
    powerful since itallows you to create externally (and remotely) managed applications or completely self-managed applications (or any combination of the two). 1.2.4 Service layer Finally, the service layer supports and promotes a flexible application programming model that incorporates concepts popularized by service-oriented computing (although, these concepts were part of the OSGi framework before SOA became popular). The main concepts revolve around the service-oriented publish, find, and bind interaction pattern: service providers publish their services into a service registry, while service clients search the registry to find available services to use (see Figure 1.1.6). Nowadays, SOA is largely associated with web services, but OSGi services are local to a single VM, which is why some people refer to it as “SOA in a VM”. The OSGi service layer is very intuitive, since it promotes an interface-based development approach, which is generally considered good practice. Specifically, it promotes the separation of interface and implementation. OSGi services are simply Java interfaces that represent a conceptual contract between service providers and service clients. This makes the service layer very lightweight, since service providers are simply Java objects accessed via direct method invocation. Additionally, the service layer expands the bundle-based dynamism of the lifecycle layer with service-based dynamism, i.e., services can appear or disappear at any time. The result is a programming model that eschews the monolithic and brittle approaches of the past, in favor of being modular and flexible. Certainly, this sounds all well and good, but you might still be wondering how these three layers all fit together and how you go about using them to create an application on top of them. Fair enough, in the next couple of sections we'll explore how these layers fit together using some small example programs. 1.2.5 Putting it all together The OSGi framework is made up of layers, but how do we use these layers in application development? Let's try to make it a little clearer by outlining the general approach you will use when creating an OSGi-based application: 3. Design your application by breaking it down into service interfaces (i.e., normal interface-based programming) and clients of those interfaces. 4. Implement your service provider and client components using your preferred tools and practices. 5. Package your service provider and client components into [usually] separate JAR files, augmenting each JAR file with the appropriate OSGi metadata. 6. Start the OSGi framework. 7. Install and start all of your component JAR files from step 3. ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 19.
    If you arealready following an interface-based approach, then the OSGi approach will feel very familiar to you. The main difference will be how you locate your interface implementations (i.e., your services). Normally, you might instantiate implementations and pass around references to initialize clients. In the OSGi world, your services will publish themselves in the service registry and your clients will look up available services in the registry. Once your bundles are installed and started, your application will start and execute like normal, but with several advantages. Underneath, the OSGi framework is providing more rigid modularity and consistency checking and its dynamic nature opens up a whole world of possibilities. Don't fret if you don't or can't use an interfaced-based approach for your development. The first two layers of the OSGi framework still provide a lot of functionality for you; in truth, the bulk of OSGi framework functionality lies in these first two layers, so keep reading. Enough talk, let's look at some code. 1.3 “Hello, world!” examples Since OSGi functionality is divided over the three layers mentioned previously (modularity, lifecycle, and service), we will show you three different “Hello, world!” examples that illustrate each of these layers. 1.3.1 Modularity layer The modularity layer is actually not related to code creation as such; rather, it is related to the packaging of your code into bundles. There are certain code-related issues of which you need to be aware when developing, but by and large you prepare your code for the modularity layer by adding packaging metadata to your project's generated JAR files. For example, suppose you want to share the class in Listing 1.1.2. Listing 1.1.2 Basic greeting implementation package org.foo.hello; public class Greeting { final String m_name; public Greeting(String name) { m_name = name; } public void sayHello() { System.out.println("Hello, " + m_name + "!"); } } During the build process you would compile the source code and put the generated class file into a JAR file. To leverage the OSGi modularity layer you must add some metadata into your JAR file's META-INF/MANIFEST.MF file, such as the following snippet: Bundle-ManifestVersion: 2 #A ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 20.
    Bundle-Name: Greeting API#B Bundle-SymbolicName: org.foo.hello #C Bundle-Version: 1.0 #C Export-Package: org.foo.hello;version="1.0" #D #A Indicates the OSGi metadata syntax version #B Human-readable name, not strictly necessary #C Symbolic name and version bundle identifier #D Share packages with other bundles In this small example, the bulk of the metadata is largely related to bundle identification. The important part is the Export-Package statement, since this extends the functionality of a typical JAR file with the ability for you to explicitly declare which packages contained in the JAR are visible to the users of it. In this particular example, only the contents of the org.foo.hello package are externally visible; if there were other packages in our example, they would not be externally visible. So what does this really mean? It means when you run your application, other modules will not be able to accidentally (or intentionally) depend on packages that your module doesn't explicit expose. To use this shared code in another module you would again add metadata, this time using the Import-Package statement to explicitly declare which external packages are required by the code contained in the client JAR. The following snippet illustrates this: Bundle-ManifestVersion: 2 #A Bundle-Name: Greeting Client #B Bundle-SymbolicName: org.foo.hello.client #C Bundle-Version: 1.0 #C Import-Package: org.foo.hello;version="[1.0,2.0)" #D #A Indicates the OSGi metadata syntax version #B Human-readable name, not strictly necessary #C Symbolic name and version bundle identifier #D Specify dependency on an external package To see this example in action, go into the greeting-example/modularity/ directory for Chapter 1 in the accompanying code and type “ant” to build it and “java -jar main.jar” to run it. Although this example is simple, it illustrates that creating OSGi bundles out of your existing JAR files is a reasonably non-intrusive process. In addition, there are tools that can help you create your bundle metadata, which we will discuss in [ref xx], but in reality no special tools are required to create a bundle other than what you normally use to create a JAR file. Chapter [ref ch2] will go into all of the juicy details of OSGi modularity and how to take advantage of it in your applications. 1.3.2 Lifecycle layer In the last subsection we saw that it is possible to leverage OSGi functionality in a non- invasive way by simply adding metadata to your existing JAR files. Such a simple approach is sufficient for most reusable libraries, but sometimes we need or want to go further to meet specific requirements or to use additional OSGi features. The lifecycle layer moves us deeper into the OSGi world. ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 21.
    Perhaps you wantto create a module that performs some initialization task, such as starting a background thread or initializing a driver; the lifecycle layer makes this possible. Bundles may declare a given class as an “activator,” which is the bundle's hook into its own lifecycle management. We will discuss the full lifecycle of a bundle later in chapter [ref ch3], but first let's look at a simple example to give you an idea of what we are talking about. In Listing 1.1.3, we extend our previous Greeting class to provide a singleton instance. Listing 1.1.3 Extended greeting implementation package org.foo.hello; public class Greeting { static Greeting instance; #A final String m_name; Greeting(String name) { #B m_name = name; } public static Greeting get() { #C return instance; } public void sayHello() { System.out.println("Hello, " + m_name + "!"); } } #A singleton instance to be managed #B constructor is now package private #C clients can only use the singleton Listing 1.1.4 implements a bundle activator that initializes the Greeting class singleton when the bundle is started and clears it when it is stopped. The client can now use the pre- configured singleton instead of creating its own instance. Listing 1.1.4 OSGi bundle activator package org.foo.hello; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; public class Activator implements BundleActivator { #A public void start(BundleContext ctx) { #B Greeting.instance = new Greeting("lifecycle"); } public void stop(BundleContext ctx) { #C Greeting.instance = null; } } ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 22.
    You can seeat #A that a bundle activator must implement a simple OSGi interface, which comprises the two methods depicted at #B and #C. At execution time, the framework will construct an instance of this class and invoke the start() method when the bundle is started and the stop() method when the bundle is stopped. What we precisely mean by “starting” or “stopping” a bundle will become clearer in chapter [ref ch3]. Because the framework uses the same activator instance while the bundle is active, you can share member variables between the start() and stop() methods. The inquisitive among you might be wondering what the single parameter of type BundleContext in the start() and stop() methods is all about. This is how the bundle gets access to the OSGi framework in which it is executing. From this context object, the module has access to all of the OSGi functionality for modularity, lifecycle, and services. In short, it is a fairly important object for most bundles, but we will defer a detailed introduction of it until later when we discuss the lifecycle layer. The important point to take away from this example is that bundles have a simple way to hook into their overall lifecycle and gain access to the underlying OSGi framework. Of course, it is not sufficient to just create this bundle activator implementation, you actually have to tell the framework about it. Luckily, this is quite simple. If you have an existing JAR file you are converting to be a module, then you must add the activator implementation to the existing project so the class is included in the resulting JAR file. If you are creating a bundle from scratch, then you just need to compile the class and put the result in a JAR file. You also need to tell the OSGi framework about the bundle activator by adding another piece of metadata to the JAR file manifest. For our example, we would add the following metadata to the JAR manifest: Bundle-Activator: org.foo.hello.Activator Import-Package: org.osgi.framework Notice we also need to import the org.osgi.framework package, since our bundle activator has a dependency on it. Otherwise, it is pretty simple to make bundles lifecycle aware. To see this example in action, go into the greeting-example/lifecycle/ directory for Chapter 1 in the accompanying code and type “ant” to build it and “java -jar main.jar” to run it. We've now introduced how to create OSGi bundles out of your existing JAR files using the modularity layer and how to make your bundles lifecycle aware so that they can leverage framework functionality. The last example in this section demonstrates the service-oriented application programming approach promoted by OSGi. 1.3.3 Service layer If you follow an interfaced-based approach in your development, the OSGi service approach will feel quite natural to you. To illustrate, consider the Greeting interface depicted below: package org.foo.hello; public interface Greeting { void sayHello(); ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 23.
    } For any givenimplementation of the Greeting interface, when the sayHello() method is invoked a greeting will be displayed. In general, a service represents a contract between a provider and prospective clients; the semantics of the contract are typically described in a separate, human readable document, like a specification. The service interface above represents the syntactic contract of all Greeting implementations. The notion of a contract is necessary so that clients can be assured of getting the functionality they expect when using a Greeting service. The precise details of how any given Greeting implementation performs its task is not known to the client. For example, one implementation may print its greeting textually, while another may display its greeting in a GUI dialog box. The code in Listing 1.1.5 depicts a simple text-based implementation. Listing 1.1.5 Greeting implementation package org.foo.hello.impl; import org.foo.hello.Greeting; public class GreetingImpl implements Greeting { final String m_name; GreetingImpl(String name) { m_name = name; } public void sayHello() { System.out.println("Hello, " + m_name + "!"); } } Your might be thinking that nothing in the service interface or Listing 1.1.5 indicate we are defining an OSGi service. Well, you'd be correct. That's what makes the OSGi's service approach so natural if you are already following an interface-based approach, since your code will largely stay the same. There are two places where your development will be a little different. One is how you make a service instance available to the rest of your application and the other is how the rest of your application discovers the available service. All service implementations will ultimately be packaged into a bundle and that bundle will need to be lifecycle aware in order to register the service; this means that we need to create a bundle activator for our example service as depicted in Listing 1.1.6. Listing 1.1.6 OSGi bundle activator with service registration package org.foo.hello.impl; import org.foo.hello.Greeting; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; public class Activator implements BundleActivator { ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 24.
    public void start(BundleContextctx) { #A ctx.registerService(Greeting.class.getName(), new GreetingImpl("service"), null); } public void stop(BundleContext ctx) {} #B } This time in the start() method at #A, instead of storing the Greeting implementation as a singleton, we use the provided bundle context to register it as a service with the service registry. The first parameter we need to provide is the interface name(s) that the service implements, followed by the actual service instance, and finally the service properties. In the stop() method at #B we could unregister the service implementation before stopping the bundle, but in practice you don't need to do this. The OSGi framework will automatically unregister any registered services when a bundle stops. We've seen how to register a service, but what about discovering a service? Listing 1.1.7 shows a very simplistic client, which does not handle missing services and suffers from potential race conditions. A more robust way to access services will be discussed in chapter [ref ch4]. Listing 1.1.7 OSGi bundle activator with service discovery package org.foo.hello.client; import org.foo.hello.Greeting; import org.osgi.framework.*; public class Client implements BundleActivator { public void start(BundleContext ctx) { ServiceReference ref = ctx.getServiceReference(Greeting.class.getName()); #A ((Greeting) ctx.getService(ref)).sayHello(); #B } public void stop(BundleContext ctx) {} } The first thing you'll notice is that accessing a service in OSGi is a two-step process. First at #A, a indirect reference is retrieved from the service registry, which points to the earliest active service that was registered under the given interface name. Second at #B, this indirect reference is used to access the actual service object instance. The service reference can safely be stored in a member variable, but in general you should never store service object instances since this will make your application less dynamic and stop bundles from being cleanly uninstalled. We say “in general” since there are certain advanced use cases discussed in later chapters [ref xx] where you may wish to store a reference to a service. But ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 25.
    in these situationsyou must be very careful to de-reference the service when the OSGi framework tells you it is no longer valid. Also note that the client code only needs to declare an import for the Greeting interface, it has no direct or explicit dependency on the actual service implementation(s). This makes it very easy to swap services dynamically without restarting the client bundle. Both the service implementation and client should be packaged into separate bundle JAR files. Each bundle will name an activator in their respective bundle metadata, but only the service implementation will export the org.foo.hello package, whereas the client will import it. To see this example in action, go into the greeting-example/service/ directory for Chapter 1 in the accompanying code and type “ant” to build it and “java -jar main.jar” to run it. Now that we have seen some examples, it is possible for us to better understand how each layer of the OSGi framework builds on the previous one. Each layer gives you additional capabilities when building your application, but OSGi technology is flexible enough for you to adopt it according to your specific needs. If you only want better modularity in your project, then use the modularity layer. If you want a way to initialize your modules and interact with the modularity layer, then use both the modularity and lifecycle layer. If you want a dynamic, interface-based development approach, then use all three layers. The choice is yours. 1.3.4 Setting the stage To help introduce the concepts of each layer in the OSGi framework in the next three chapters, we will use a simple paint program, whose user interface is depicted in Figure 1.1.7. The paint program is not intended to be independently useful; rather, it is used to demonstrate common issues and best practices. From a functionality perspective, the paint program only allows the user to paint various shapes, such as a circles, squares, and triangles. The shapes are painted in predefined colors. Available shapes are displayed as buttons in the main window's toolbar. To draw a shape, the user selects it in the toolbar and then clicks anywhere in the canvas to draw it. The same shape can be drawn repeatedly by clicking in the canvas numerous times. The user can drag drawn shapes to reposition them. This sounds simple enough. The value of using a visual program for demonstrating these concepts will become evident when we start introducing run-time dynamism. We have finished our overview of the OSGi framework and are ready to delve into the details, but before we do let's try to put OSGi in context by discussing similar or related technologies. While no Java technology fills the exact same niche as OSGi, there are several treading similar ground, so it is worth understanding their relevance before moving forward. ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=507
  • 26.
    Other documents randomlyhave different content
  • 27.
    69 Chapter XII Frithiof’s Return Thewinter passed, and again were hill and valley, grove and forest, clothed with bloom and verdure. Then Frithiof thanked his host, and, bidding him farewell, was soon speeding joyously away across the foaming main. Six times the sun rose and set, and the seventh morning found him near his journey’s end. Consumed with longing, Frithiof rose early and mounted to the deck. There, veiled in the mists of dawn, he saw his native shores and heard the familiar rushing of its mountain streams. Light as a bird flew “Ellida” o’er the dancing waves and in her swelling sails the western breezes sang like nightingales. Just as the first ray of sunlight fell on land and sea they entered the well- known haven. “Past the green birch woods now,” cried Frithiof to Björn, “and Framnäs greets me!” With beating heart and gleaming eyes he waited—but what is this? Is he bewitched? There lies the open space where his forefathers built their dwelling, yet naught is to be seen of it. Do his eyes deceive him? He rubs them and looks again at the familiar spot; but neither house nor building of any kind is there, only a tall blackened chimney stands out dark against the sky. Looking closer,
  • 28.
    70 where Framnäs stood,he sees a great pile of ruins, from which the ashes whirl aloft. “Ellida’s” anchor is dropped, and silently Frithiof approaches the scene of devastation. Stones and charred beams are strewn around or heaped together in confusion; fruit trees stretch forth their shrivelled branches; about the levelled grave-mounds lie the bones of heroes. As Frithiof stands spellbound amid the desolation, his faithful hound Bran comes bounding to meet him. Yelping with joy he leaps upon his master, while out from the dale trots a milk-white courser, neighing and tossing his gold-knotted mane. Frithiof stroked the dog’s head and patted his favorite’s glossy neck; but the shadow on his brow remained unaltered. Then he saw Hilding, his aged foster-father coming toward him with mournful look. “Welcome, father, to the ruins of Framnäs!” he cried, and then added bitterly: “But why should this sight surprise me? ’Tis when the eagle is flown that boys plunder his nest. So thus doth King Helge guard the hut of the peasant; thus he keeps his royal oath! Rage at his dastardly act more moves me than grief for what is lost. But tell me first of all, good father, where is Ingeborg?” “Alas! my son,” replied Hilding, “I fear my tidings will but aggravate thy woe, yet listen to what has passed. Scarce wert thou gone when King Ring invaded the country, his force outnumbering ours full five to one. In the Disardale we met, and bloody was the battle. The waters of the stream ran red with gore. Halfdan, as ever, laughed and jested; but so bravely did he bear him, my heart was gladdened at the sight, and twice did my shield protect him from a death-stroke. The victory
  • 29.
    71 72 might even havebeen ours, had not King Helge, seized with panic, fled; whereat the people’s courage, too, forsook them, and, flinging down their arms, they scattered far and wide. But in his flight King Helge paused to fire thy house. Ring then demanded of the brothers lands and crown, or that they yield him up their sister’s hand. Messengers went often to and fro, and in the end King Ring bore Ingeborg homeward as his Queen.” Frithiof laughed wildly: “Who now,” he cried, “dare talk to me of woman’s truth, since she whom I deemed true as Nanna’s self hath proven faithless? Hereafter naught but hate for mankind shall my bosom harbor; henceforth the seas shall have their fill of blood, for none who cross my path shall Angurvadel spare!” “Nay, son,” said Hilding sorrowfully, “abate thy wrath, nor seek to revenge thy wrongs upon the innocent. Rather accuse the Norns, whose doom on thee hath fallen. What Ingeborg doth suffer I alone can tell. Before all others her despair was dumb as is the turtle dove that mourns her mate. So doth the sea fowl, pierced by death’s arrow, sink beneath the waves, in those cool depths to pour away her life. ‘Atonement’—so she spake—‘hath been decreed by Balder for Frithiof’s violation of his holy place; nor may I, faint-hearted, seek to shun the sacrifice. To death he dooms me, not swift,—ah! that were easy,—but lingering—slow, to waste away with grief. To that decree I yield. Reveal to no one what I suffer. I desire pity from none. But be thou the bearer of my last farewell to Frithiof.’ “At last the wedding day was come (Oh, would that evil day had never dawned!); to Balder’s temple walked a train of white-robed maidens, led by a bard whose
  • 30.
    73 74 mournful chant movedevery heart to woe. Amid them, on a coal-black steed rode Ingeborg, like that pale spirit which surmounts the thunder cloud. Before the doors of the temple I lifted my lily from her saddle and led her to the altar. With unfaltering tongue she spoke her vows; but unto Balder then she prayed in such heart-rending tones that every eye save hers was filled with tears. Then for the first time Helge marked the ring she wore. With a furious glance he tore it from her and placed thy gift upon the arm of Balder. But thereat I could no longer suppress my rage, and, snatching my sword from out its sheath, approached the King as he stood before the image of the god. Of as little worth was he to me at that moment as the lowest of his people, and verily a crime would have been committed in that sacred place had not a whisper reached my ears from Ingeborg. “‘Nay, stay thy hand. Stain not thy spotless blade! My brother might indeed have spared me this; but much a heart can suffer ere it break, and the All-Father shall one day judge between us!’” “Ay, Ingeborg,” cried Frithiof, “thou speakest truly—the All-Father will one day judge between us! But he also metes out justice here below by mortal hand, and ’tis in my heart that I am hither led to be the judge of one. Is not to-day the Midsummer feast of Balder, that Helge celebrates within his temple? Now, crowned priest, thou who hast sold thy sister, thou who hast robbed me of my bride, behold to-day thy judge!”
  • 31.
    75 Chapter XIII The Burningof the Temple It was midnight. Low across the mountains burned the blood-red sun, which in far northern Scandinavia never sets on the longest day of the year. Neither day nor night was it—an awful twilight reigned. Within the temple Balder’s great feast was being celebrated. High in the air shot the flames from the sacred hearthstone, while pale, white-bearded priests raked the brands till showers of crackling sparks flew upward. Clad in his royal robes, Helge presided at the altar. Suddenly the clash of arms sounded without, and a voice was heard: “Björn, hold fast the door! Let none escape! If any strive by force to pass thee, cleave his skull!” Helge grew deadly pale; he knew that voice too well. Then in strode Frithiof and addressed him: “Here is the tribute thou didst order me to bring thee from Augantyr. Take it! And now, for life or death we’ll strive before this altar. One of us twain must burn on Balder’s pyre. Shieldless we’ll fight and thou, as befits a King, shalt have first stroke. But beware, I say, for I strike second. Nay—gaze not fearfully about, nor seek escape, King Fox! Caught in thy hole art thou at last. Remember Framnäs that thou didst lay waste, and think of Ingeborg’s cheeks, blanched by thee!”
  • 32.
    76 Beside himself withfury, Frithiof tore the heavy purse of gold from his belt and hurled it at the head of the King, who straightway sank swooning on the altar steps, blood gushing from his mouth and nose. “What! canst thou not bear the weight of thine own gold?” shouted Frithiof. “Shame! shame! thou coward King! Truly my sword is far too noble for thee, nor shall it taste of blood so base as thine. Silence, ye pale priests of moonlight, nor dare to lift your sacrificial knives! Back, back, I say, for thirsty grows my blade!” He lifted his eyes to the image of Balder. “Thou shining god, frown not so darkly on me!” Then, perceiving the arm-ring he had given to Ingeborg, his anger blazed up fiercer than before. “Nay—by thy leave,” he cried; “that ring came not in lawful fashion on thy arm! Not for thee did Vaunlund forge its wonders; and he who is its master claims his own.” He pulled at the ring, but it seemed grown fast to Balder’s arm. Putting forth all his strength, at last he tore it loose; but therewith down crashed the image of the god into the fire below. Higher and higher leaped the flames, till beam and rafter kindled. Horror-stricken, Frithiof stood for a moment motionless; then turning to the door, he shouted: “Open, Björn! Let all depart! The feast is over. The temple blazes; bring water! Hasten, all, to quench the flames!” Quickly a chain of men to the sea is formed. From hand to hand the buckets fly, while high up among the rafters stands Frithiof, calm amid the mounting flames, and
  • 33.
    77 78 directs his comrades.But vain are all their efforts. The golden plates of the roof melt and drop down into the fiery sands. “All is lost!” shout the people. “See the red fire-cock, how he stands upon the roof-tree and ever wider spreads his glowing wings!” A strong wind arose and whirled the flaming brands into the treetops, dry from the summer heats. Raging from branch to branch it leaped, and soon the whole grove was one sea of fire. When morning broke, Balder’s Grove and Temple lay in ashes, while Frithiof sat within his dragon ship and wept.
  • 34.
    79 Chapter XIV Frithiof inExile As “Ellida” passed the strand, Frithiof gazed from the deck with gloomy brow upon the scene of conflagration, from which the thick smoke still ascended, and anguish filled his breast. “Woe, woe is me!” he cried to himself; “in accusation rises yonder smoke to Odin’s halls! Banished was I by Helge but for a brief space; now must I forever leave my native land. Be thou, O sea, from hence my country. On thy blue billows will I make my home. Framnäs no longer is my dwelling; thou, swift ‘Ellida,’ shalt be now my house. My bride, too, art thou in thy black garb, since she in lily robes is lost to me forever. Free dost thou roll, O mighty ocean! No tyrant’s will can ever do thee wrong; the only King thou callest master is he who looks upon thee calmly when thy white breast heaves in wildest fury, and thunder peals are swallowed in thy voice. No grave-mound e’er shall rise above me; thy tossing waves shall cover deep my bones.” Here Björn approached and touched his shoulder, saying, “Look! yonder King Helge makes his way amid the rocks. Methinks he hath yet a word to speak with thee.” Ten dragon ships were seen approaching. Frithiof
  • 35.
    80 sprang to hisfeet and bade his men prepare for battle. Joyously they shouted: “King Helge wearies of the crown. His soul thirsts for Valhalla’s delights. Now shall he fall; bold Frithiof leads us unto victory.” On came the ships in a half-circle, surrounding “Ellida.” Helge had given orders to slay Frithiof and all his men, but to capture the ship as their prize. Suddenly a strange sight met the eyes of Frithiof and his warriors and filled them with amazement: nine of the ships sank slowly down beneath the waves, while Helge himself escaped with difficulty to the shore. Björn laughed. “’Twas I that scuttled the ships last night, unseen. A good trick it was, and all befell as I had hoped, save that King Helge has escaped!” Now all the sails were spread and the ship sped swiftly out to sea. Backward gazing, Frithiof watched the fast receding shore and chanted a song that moved all hearts to sadness: Farewell! mounds dreaming By wavelets blue, Where west winds streaming White blossoms strew! Odin revealeth And doometh well What man concealeth;— Farewell! Farewell! Farewell, ye bowers, Ye limpid streams, Where ’mid spring flowers, Youth wandered in dreams.
  • 36.
    81 Ye friends ofchildhood Who loved me well,— Till death remembered,— Farewell! Farewell! My love insulted, My dwelling brent, My honor tarnished, In exile sent,— Heart bideth in sadness Norns’ fatal spell. To Life’s young gladness Farewell! Farewell!
  • 37.
    Chapter XV Frithiof’s VikingLife Thus Frithiof became a viking, the sea his only home; and these are the laws he made for his followers: “Pitch no tent on thy ship; seek no slumber below. On his shield sleeps the viking, his sword in his hand. His tent is the blue dome of heaven. “Short be thy sword, like the hammer of Thor; strike close to the foe. “When the storm roars on high, spread wider the sails: The sea in its wrath fills the viking with joy; a coward is he who would furl. “Wine is drink of the gods. Enjoy thou the gift, but drown not thy senses—beware! He who falls on the land rises quickly again; who staggers here is the death-goddess’ prey! “Protect the merchant ship on the high seas so due tribute it doth not refuse. Thou art lord of the waves; he’s a slave to his pelf. Thy steel is as good as his gold. By lot shall the booty be shared among all; complain not however it falls. The Sea King
  • 38.
    82 himself throws nodice on the deck; he seeks only glory from his foes. “Heaves a viking in sight, then come boarding and strife; from us he is banished who yields. Mercy fits him who conquers; he who lays down his arms at thy feet is no longer thy foe. “Prayer is Valhalla’s child, and a scoundrel is he who, ruthless, refuses to hear it. “The viking’s rewards are his wounds; before all, on the brow and the breast are they glorious. He who seeketh ere issue of battle to bind them no longer is comrade of viking.” Thus ran the code of Frithiof, and no laws of Odin were more strictly obeyed. Many a battle did these heroes fight and win, for there was not their like on all the seas; and soon their fame spread far and wide. But naught of this had power to gladden Frithiof’s heart; he would sit, helm in hand, for hours with clouded brow, gazing out over the rolling waters. Only in battle did the shadow vanish, as with flashing eyes and fiercely swelling breast he led his men to victory. For three years they sailed the seas northward and westward; then turning south, his dragon anchored one day off the coast of Greek-land (Greece). With wonder Frithiof gazed upon that beauteous land, with its noble ruined temples rising amid fragrant groves. The tales his father had been wont to tell of those fair isles still lingered in his memory like some lovely vision—a dream that now was realized. Hither had he once thought to flee with Ingeborg from the haughty Helge, here with her to found an abode of bliss, but the noble maiden
  • 39.
    83 84 had denied hisprayers and shrunk from such a breach of duty and of custom. Amid these fair scenes memories of his native land awoke afresh within him, and he longed to see it once again. But most of all he yearned for a sight of Ingeborg and to visit his father’s grave- mound. “Why do I linger here in strange seas and stain my hands with blood?” he asked himself. “Enough of glory have I won, and I care not for gold. North points the flag on the masthead. To the Northland the home of my youth! Up, ‘Ellida’! no longer we’ll tarry, but follow that token from Heaven!”
  • 40.
    85 Chapter XVI Frithiof comesto King Ring’s Court On his high-seat sat King Ring, celebrating the great Yule tide feast that fell on the winter solstice, and beside him Ingeborg, his wife, like chilly Autumn with the youthful Spring. The mead-horn went round, and joyous shouts and laughter filled the hall. Suddenly through the doorway entered an old man, tall of stature and wrapped from head to foot in a great bearskin. In his hand he bore a staff and walked as if bowed with age. None knew him, and he quietly took his place on the bench near the door, reserved for the poor. The courtiers smiled to one another and pointed jeeringly at the shaggy figure, while one playfully approached with intent to make sport of him for the amusement of the others. With flashing eyes the stranger seized the rash youth, whirled him about in the air, and set him again on his feet unharmed; whereat the courtiers’ smiles deserted them, and they fell straightway silent. “What noise is that down yonder?” cried Ring sternly. “Come hither, old man, who thus disturbest our kingly peace! Who art thou? What brings thee here? Whence comest thou?” “Much dost thou ask, O King,” replied the stranger, “yet all will I tell thee save my name,—that concerneth none
  • 41.
    86 but me. InPenitence was I reared; Want was my inheritance; my latest bed a Wolf’s lair. Astride my dragon, with its mighty wings, I flew swiftly hither from afar; now my good ship lies frozen in upon thy shores. I came to hear thy words of wisdom, famed through all the land. When thy people just now sought to mock me, I seized a vain fool and swung him round about—but I did him no harm. Forgive me, King!” “Truly,” the monarch cried,—“thou speakest well, and wisdom’s teachings bid us honor age. Come, sit at the board. But first, I pray thee, doff thy strange disguisement and show thyself in thy true form, for deception is ever wont to be the foe of gladness.” At this the stranger let fall his hairy covering, and there, in place of an old man, appeared a youth of noble stature, his loft brow shaded with bright flowing locks. A blue mantle hung from his mighty shoulders, and his tunic was held in place by a wide silver belt, on which, with cunning skill, beasts of the forest were embossed. Heavy gold armlets encircled his arm; at his left side hung a sword that gleamed like lightning. Fair as Balder, like to the mighty Thor in strength of limb, he stood before the King and his astonished court. For a moment his keen glance wandered about the hall, then he seated himself calmly at the board. The blood rushed to the cheeks of the Queen till she glowed as crimson as the ice-fields lit by flaring Northern lights. But now the trumpets sounded the signal for silence. It was the hour of the vow, and the crowned boar was borne into the hall on a silver charger and placed upon the board. Touching the head of the boar, Ring said:
  • 42.
    87 88 “Hearken, ye warriors,to my vow! I swear to conquer Frithiof, howsoever stout a champion he be; so help me Odin, Thor, and Frey!” The stranger rose with a frown and dashed his sword upon the board with such a clang that all the warriors sprang from their seats. “Hear thou me likewise, good Sir King,” he cried: “That Frithiof whom thou namest is my friend and kinsman: and him I swear to guard with life and limb, so help me Norns and my good sword!” The King smiled. “Thou speakest boldly,” he answered, “but words are free in Northland’s royal halls. Fill for him, Queen, yon horn with draught of welcome. I hope he’ll tarry with us as our guest till Spring returns.” This horn was a precious heirloom of the house, broken from the forehead of the urus. Its feet were of silver wonderfully wrought, while the golden rings about it were carven with strange runes. With downcast eyes Ingeborg handed it to the guest, but she trembled so that the wine was spilled, and red drops gleamed on her white hand like evening’s purple blushes on a lily. Unmoved, the hero took the mighty horn, lifted it to his lips and at one draught drained it to the honor of his host. Then at a sign from the King, the scald smote on his harpstrings and chanted many a heart-stirring song and legend. In lofty words he sang of love and friendship, of freedom and the country’s glory, of the high gods and Valhalla’s wonders, till fire shot forth from every eye, and involuntarily each warrior grasped the handle of his sword.
  • 43.
    89 Deeply they drankthroughout the night, and many a champion, like a tower of strength in battle, was vanquished by the sweetly foaming mead.
  • 44.
    90 Chapter XVII The SledgeExcursion “Ho for a sledge ride over the frozen lake!” cried Ring one day; and the servitors hastened to loose one of the pawing steeds from the royal stables and harness it before a splendid sledge, over the seat of which was thrown a silky sealskin. “’Tis not safe on the lake,” said the stranger. “The ice is thin and weak in some parts, and should it give way, full cold and deep would be thy bath!” “Nay, not so easily do monarchs drown,” replied the King; “let him who fears it, go around the shore!” The stranger said no more, but frowning darkly, hastened to fasten on his steel skates, while the impatient courser pawed the air and whinnied loudly. “Speed on, my steed,” cried Ring, “and let us see if thou art sprung from Sleipner’s blood!” Away dashed the sledge with the speed of the whirlwind, the stout-hearted old king exulting in the motion and heeding not the entreaties of his wife; but swift as they flew, the stranger still outstripped them, circling about in wide curves or cutting figures on the ice. Meanwhile, false Ran, the spouse of the Sea-god,
  • 45.
    91 has marked whatis passing above. She cleaves a broad fissure in the sea’s silvery roof, and into the up-foaming waves plunge horse and sledge. But swift as the wind flies the stranger thither. Fixing his steel shoes firmly in the ice, he seizes the horse by the mane and with a mighty jerk, pulls it and sledge together back on to the ice. “In sooth,” said the King, “that deed doth merit praise; e’en Frithiof himself could do no better. And now, my Fleet-of-foot, let us back to the palace again.”
  • 46.
    92 Chapter XVIII Frithiof’s Temptation Springis come once more; birds warble in the treetops; freed from their icy bonds, the streams leap gaily downward to the vales below; the roses part their delicate sheaths and blossom red as Frigga’s cheeks. King Ring will now go hunting, and forthwith a joyous stir pervades the court. Bows twang, quivers rattle, fiery coursers paw the ground, the hooded falcon screams for its victim, and scarce can the huntsmen keep in leash the eager hounds. Fair as Frigga, dazzling as the battle- maiden Rota, sits the Queen upon her milk-white steed like a star on a summer cloud. Her hunting dress is of green, embroidered with gold, and blue plumes wave from her velvet cap. Led by the royal pair, the gay train wends its way into the forest, and soon the sport begins. Loud bay the hounds; up mount the hawks into the clear sky; horns sound; the frightened game seeks lair and covert; and the eager huntsmen scatter in pursuit. King Ring has fallen behind; old and feeble, he can no longer follow the lengthening chase, while beside him silent and thoughtful, rides his guest. At last they reached a rocky glen shut in by thick-clustering trees
  • 47.
    93 and thickets, andhere the King dismounted from his courser, saying: “Full weary am I, stranger; here will I rest me in this pleasant spot.” “Nay, sleep not on the cold hard ground,” replied the other; “I had better lead thee back to thy own halls.” “Sweet slumber comes when least expected; ’tis the way of the gods,” said Ring. “Surely thou dost not grudge thy host an hour of rest!” Without further words, the stranger spread his cloak upon the ground and seated himself on a fallen tree- trunk, while Ring, stretching himself out upon the mantle, laid his head against the other’s knees. His eyes closed and soon he slept, sweetly as an infant cradled in its mother’s arms. As the stranger gazed gloomily down on the face of the King, he heard a rustling in the branches above him to the left, and lifting his eyes he saw a coal-black bird, which began to sing: Haste thee, Frithiof, slay the dotard, with one sword- stroke grant him rest! Take the Queen; she’s thine; her sacred kiss of plighted troth she gave. Here no human eye can see thee—silent is the deep, dark grave! Scarce had the sound ceased when from a bough on the right, a snow-white bird began: Though no human eye should see thee, Odin would the death-stroke view. Wouldst thou murder him in slumber? Cowardly thy bright sword stain?
  • 48.
    94 95 Know, whate’er besidesthou winnest, hero-fame thou ne’er shalt gain! Thus sang the two birds, while contending thoughts struggled within the listener. Suddenly he seized his sword by the handle and flung it far from him into the shadow of the forest. Whereupon the black bird, with heavy flapping of its wings, flew back to the dark halls of Night, the abode of perjurers and assassins; while, blithely warbling, upward the white bird took its flight and vanished at last in the blue of heaven. At that moment the King awoke and rising to his feet, said: “Sweet indeed hath been my slumber. Well they rest whom valor’s sword doth guard. But where is thy war blade, stranger? Methought the Brother of Lightning never left thy side. Say, who hath parted you?” “Little boots it,” answered the other; “swords are plenty in the Northland. The sword is not always a good companion. Its tongue is sharp and it speaketh few words of peace. In steel there dwells an evil spirit, sprung from Loke’s dark abode, to whom not even sleep is sacred, nor the silver locks of age.” “Hearken, youth!” began the King. “I slept not. ’Twas but to try thee I did feign to slumber—a fool is he who trusts a man or a blade untried. Thou art Frithiof! I knew thee even when thou didst cross my threshold. But wherefore didst thou creep nameless and in such disguise into my palace? Wherefore, if not to rob me of my wife? Honor comes not nameless to the banquet, Frithiof! Ever open-faced she meets men’s glances, clear as sunlight is her shield. The fame of Frithiof’s deeds has reached us,—a terror both of gods and men; careless alike of cloven shield or burning temple; the
  • 49.
    96 97 mightiest warrior knownin all the land. And this bold hero, this fierce viking, creeps, a beggar, to our hall! Nay, cast not down thy eyes before me. I, too, have once been young and felt as thou. Youth, well I know, hath fiery passions. Much have I thought on thee, O Frithiof. I have pitied and have pardoned thee. Hearken now! I am growing old and feeble, and soon for me the grave shall open. Then take unto thyself my kingdom and my wife. Until that time, be thou a son to me and guard my house as thou hast done before. And now, my son, let there be no more feud between us!” “Not as a thief did I enter thy halls, O King,” replied Frithiof proudly. “Had I come to seize thy Queen, who could have withstood me? ’Twas but to behold once again her who before the altar gave me her betrothal kiss. But ah, what slumbering fires my rashness hath awakened! Too long already have I tarried. Upon my head the gods have poured their wrath. Even the gentle Balder, lover of all mankind, spurns my prayers. ’Twas I who burned his temple. ‘Wolf in the Sanctuary,’ am I called. All joy ceases when my name is spoken. The child clings trembling to its father’s knees. Once more will I seek the broad, free ocean, whither earth and man have banished me. Out, out, my dragon! Too long in idleness thou hast lain. Again to the storm wind shalt thou spread thy pinions, and bathe thy black breast in the dashing spray! All—all on earth is lost to me forever; the tempest’s roar, the clash of arms shall whisper comfort to my soul once more! So will I live, so will I fighting fall; and mounting then to Odin’s throne, the gods, appeased, shall speak my pardon.”
  • 50.
    98 Chapter XIX Death ofKing Ring Pale on his throne sat the aged monarch, for he felt his end approaching. Ingeborg, trembling, stood beside him, and a circle of silent warriors stood about the royal pair. Sorrowfully Frithiof entered to say farewell. “This day for the last time do ye behold me,” he said; “for the last time my foot doth tread the soil of earth. Henceforth, till the Norns shall send their summons the ocean’s boundless wastes shall be my home. Take back the ring round which such memories cluster, Ingeborg; let it be a parting token from me. And thou, O King, go not with thy Queen by moonlight to the strand, nor when the pale stars shine, for at your feet the waves might chance to toss my bleaching bones.” “Nay, Frithiof,” replied the King, “such mournful plaints become not men; in maids they may be pardoned. For me the death song soundeth, not for thee. ’Tis I must hence, not thou! Take thou my realm and guard it well. Take Ingeborg as thy wife, and be a father to my infant son. Ever through life hath peace been dearest to me; well have I loved to sit with friends about the board; yet with a strong hand have I guarded throne and honor, and cloven many a shield on sea and land; nor ever hath man seen my cheek turn pale. Victory hath been
  • 51.
    99 mine, and glory.One boon only have the gods denied me—to mount to Valhalla from the battle-field. Death by the sword is the death of heroes; to linger on,—the straw death,—never such will Ring live to endure!” And therewith he plunged his sword into his breast. As the life-blood gushed forth he had his horn brought to him, and raising it aloft, with glowing face he cried: “To thy glory I drain this, my country, thou Northland! Ye gods of Valhalla, all hail, all hail!” KING RING’S Death Silence reigned within the hall; none gave way to grief lest the dying man’s last moments should be saddened. Sinking back on his cushions, the King clasped Ingeborg’s hand for the last time—greeted his friend
  • 52.
    100 and son witha parting glance, and sighing, his soul ascended to the All-Father. Great was the mourning for him throughout the kingdom; amid universal lamentations the good King’s mound was heaped above him, while scalds with sounding dirges glorified his memory.
  • 53.
    101 Chapter XX The Electionto the Kingdom “To the Ting! To the Ting!” The message flies o’er hill and vale; the people are summoned to elect their King. Champions try their swords, vassals polish their lord’s helm and buckler till they shine like the sun. Thus with clang of arms the warriors assembled on the open plain. In their midst on the wide Ting-stone stood Frithiof, and at his side King Ring’s son, a fair child with golden hair. “Too young is Ring’s heir,” was murmured through the multitude; “no chief is he to lead us into battle, or sit in judgment on the Ting-stone.” But Frithiof placed the child upon his shield and held him high aloft, saying: “Northmen, behold your King, a vigorous offshoot of the fallen oak! Doth he not bear him well upon the shield? Hear now my vow: I swear to guard for him his Kingdom, till with his father’s circlet he shall one day here be crowned.” Then raising his eyes to heaven, he added: “Forsete, son of Balder, be my witness! O thou who judgest justly, strike me dead if e’er I break my word!” Meanwhile the King’s son sat on Frithiof’s gleaming shield, gazing about him proudly; but at length he began to weary of it, and with one bound sprang lightly to the ground. A shout went up from all the Ting:
  • 54.
    102 “Ha, that wasindeed a royal leap! Aye, shield-borne, thee we choose to be our King! And thou, O Frithiof, who shalt guard his crown and kingdom, take Ingeborg, our Queen, to be thy wife!” At these words Frithiof’s brow darkened. “To choose a King are you come,” he answered; “my bride I woo of my own choice. In anger still doth Balder look upon me. ’Twas he that took my Ingeborg from me, and he alone can give her back to me.”
  • 55.
    103 Chapter XXI The Reconciliation Nopeace was there yet in Frithiof’s heart. As fire had once consumed the temple, so within him still blazed the flames of his remorse that by his act had Balder’s earthly dwelling been destroyed. Betaking himself to his father’s grave-mound he sat all night alone upon the cairn, beseeching Balder to smile upon him once again. And lo! in the darkness a wondrous vision grew before his eyes. In Balder’s Grove he saw a gleaming temple slowly rise; but scarcely had he gazed upon it in amazement, when again ’twas swallowed in the gloom of night. Roused by fresh hope of winning the offended god’s forgiveness, he hastily returned to Ring’s dominions and summoned architects to plan for the building of a new temple. Just as he had seen it in his vision should the home of Balder actually rise. So filled was he with this one thought that nothing else had power to move him, neither feast, nor chase, nor sounding minstrel lay. At last the work was finished, and like the far-famed shrine of Upsal, the great temple stood a wonder to all eyes. A brazen portal richly carved led to the sanctuary; two rows of lofty columns supported the arching roof, like a great shield of gold. Facing the doorway stood the
  • 56.
    104 high altar, hewnfrom a single block of Northern marble and polished with rare skill; round about it were graven runes of solemn import. Above, in a spacious niche, was Balder’s august image, wrought all of purest silver. On a rocky hillside rose the building, its reflection mirrored in the sea below, while round about on three sides stretched a smiling valley, known as Balder’s Dale. Leafy groves adorned the flowery meadows. No sound but happy bird songs broke the silence; all nature breathed of peace. With deep emotion Frithiof trod those holy precincts. Twelve rosy-cheeked maidens, priestesses of the temple, robed all in white, advanced to the high altar and chanted a holy song in praise of Balder. They sang how beloved was the gentle god by every creature; and when he fell by evil Loke’s malice, how heaven itself with earth and ocean wept. And as leaning on his sword the hero listened, the dark shadow, that so long had lain upon his spirit, lifted. Tender memories of his childhood woke within him, while calm and serene as the moon in the skies of Summer, Balder the Good looked down upon him and filled his soul with peace. Then with slow steps approached the high-priest of the temple, not young and fair like the god at whose shrine he worshipped, but tall and majestic, his noble features stamped with heavenly mildness and graced with flowing beard and locks of silver. With unwonted reverence Frithiof bent his haughty head before the seer, who thus began: “Welcome, son Frithiof, to this holy temple. Long have I looked for thee to come, for force, though restless over land and sea it wanders, turns ever, wearied, home again at last. Oft did the mighty Thor wend thus to Jötunheim, the giants’ kingdom; yet despite his godlike
  • 57.
    105 106 belt and magicgauntlets, the giant King still sits upon his throne. Evil, itself a force, yields not to evil. Virtue without strength is but child’s play, the glancing sunbeam on the shield, a wavering shadow on the earth’s broad breast. Yet neither may strength without virtue long survive. It consumes itself, like rusting sword in some dark grave-mound—a debauch from which he who yieldeth to it wakens filled with shame. “Behold the mighty earth! It is the body of Ymir, the world-giant from whom all strength proceeds—its rushing streams his blue veins; its iron and brass his sinews; yet all is barren, bare, and empty till heaven’s bright sun-rays stream upon it from afar. Then springs the grass; fair blossoms deck the verdant meadows, and fresh leaves, the trees; the swelling buds burst forth; all nature breathes new life from the abundant earth. Thus is it with man’s strength: it yields naught but blessing when transfigured by the heavenly rays of virtue. “What the sun is to the earth, was Balder to Valhalla. His pure soul was the gem that fastened the wreath divine. When, slain by evil Loke, he descended to pale Hel’s realm, Odin’s wisdom straight began to languish, and the strength of mighty Thor to dwindle; the prisoned forces of evil, once mastered by the gods, stirred in their abysses; the dragon Nidhögg gnawed at the roots of the Tree of Life, and its leafy crown fast withered. Again the war broke out ’twixt good and evil— the strife that through all creation still endures. “This is but the emblem of what passes in every human breast. Hast thou forgotten, my son, those days when Balder dwelt within thy spirit? Pure then was every thought and feeling, thy whole life glad as a woodland
  • 58.
    Welcome to ourwebsite – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookultra.com