Ebook Camel in Action 1St Edition Claus Ibsen Jonathan Anstey Online PDF All Chapter
Ebook Camel in Action 1St Edition Claus Ibsen Jonathan Anstey Online PDF All Chapter
Jonathan Anstey
Visit to download the full and correct content document:
https://ebookmeta.com/product/camel-in-action-1st-edition-claus-ibsen-jonathan-anst
ey/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...
https://ebookmeta.com/product/climate-adaptation-modelling-1st-
edition-claus-kondrup/
https://ebookmeta.com/product/dirty-claus-1st-edition-m-k-moore/
https://ebookmeta.com/product/real-negotiations-driving-values-
and-handling-complexities-2nd-edition-robert-ibsen/
https://ebookmeta.com/product/sociologists-in-action-on-
inequalities-race-class-gender-and-sexuality-1st-edition-shelley-
k-white-jonathan-m-white-kathleen-odell-korgen/
Articulating the Action Figure Essays on the Toys and
Their Messages Jonathan Alexandratos Editor
https://ebookmeta.com/product/articulating-the-action-figure-
essays-on-the-toys-and-their-messages-jonathan-alexandratos-
editor/
https://ebookmeta.com/product/scientific-publishing-and-
presentation-claus-ascheron/
https://ebookmeta.com/product/hapi-js-in-action-1st-edition-matt-
harrison/
https://ebookmeta.com/product/terraform-in-action-1st-edition-
scott-winkler/
https://ebookmeta.com/product/pandas-in-action-1st-edition-boris-
paskhaver/
Camel in Action
Camel in Action
CLAUS IBSEN
JONATHAN ANSTEY
MANNING
Greenwich
(74° w. long.)
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books are
printed on paper that is at least 15 percent recycled and processed without the use of elemental
chlorine.
ISBN 978-1-935182-36-8
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – MAL – 15 14 13 12 11 10
To the Apache Camel community
May this book be a helpful companion on your journeys with Camel
brief contents
PART 1 FIRST STEPS . ...................................................................1
1 ■ Meeting Camel 3
2 ■ Routing with Camel 22
vii
contents
foreword xvii
foreword xix
preface xxi
acknowledgments xxiii
about this book xxv
about the cover illustration xxix
about the authors xxxi
1 Meeting Camel 3
1.1 Introducing Camel
■
4
What is Camel? 4 Why use Camel? 5 Getting ■
ix
x CONTENTS
wireTap method 55
2.6 Summary and best practices 57
The Aggregator and Splitter EIPs 238 The Routing Slip and■
238
up the JMS broker and the database 287 The story of the lost ■
message 288
9.2 Transaction basics 289
About Spring’s transaction support 290 Adding ■
fails 306
9.5 Compensating for unsupported transactions 309
Introducing UnitOfWork 309 Using Synchronization
■
ExecutorServiceStrategy 329
10.3 Using concurrency with EIPs 330
Using concurrency with the Threads EIP 331 Using concurrency ■
with the Multicast EIP 332 Using concurrency with the Wire
■
component 356
10.7 Summary and best practices 358
CONTENTS xv
logging 394 ■
Using Tracer 398 Using notifications 402
■
xvii
xviii FOREWORD
source messaging and enterprise service bus (ESB) products. These tools embrace the
EIP vocabulary by implementing many patterns directly in the platform. With Apache
Camel, a Splitter pattern translates directly into a “split” element in the Camel DSL.
We couldn’t have wished for a more direct translation of the pattern language into an
implementation platform.
Claus and Jon bring the saga to a grand finale by showing us how to use the Camel
pattern language to compose real-life messaging solutions. In doing so, they not only
cover fundamental concepts like routing and transformation, but also dig into often-
neglected parts of the development process, including testing, monitoring, and deploy-
ing. They find the right balance of the pattern language, Camel core concepts, and run-
ning code to help you build easy-to-understand and robust messaging solutions.
GREGOR HOHPE
COAUTHOR OF ENTERPRISE INTEGRATION PATTERNS
WWW.EAIPATTERNS.COM
foreword
I was one of the original founders of both Apache ActiveMQ (an open source high-
performance message broker) and ServiceMix (an open source ESB based on JBI and
OSGi). I found that Enterprise Integration Patterns were becoming increasingly cen-
tral to what we were doing on these projects and how we were using them; the only dif-
ference was the context and technologies with which we were using the patterns.
There have been many libraries and frameworks over the years to help with inte-
gration. But frequently the concepts behind the Enterprise Integration Patterns get
transformed into some complex class hierarchies or objects that need to be wired
together just so, and the original intentions and patterns are often lost. The developer
is forced from then on to focus on the low-level detail and some complex class library
API, losing the bigger picture and patterns.
Integration is hard and once you start down the path of integrating things together
the code can very easily mushroom; being able to easily comprehend, communicate,
adapt, and maintain integration solutions is vital to be able to solve integration prob-
lems efficiently in an agile way.
So we decided it was time for a new integration framework that put the EIPs at its
core and tried to raise the abstraction level so that developers could describe declara-
tively in very concise terms what Enterprise Integration Patterns they wanted to use in
a simple domain-specific language. Using a convention over configuration approach,
developers would declaratively describe what they wanted to do, using the Enterprise
Integration Pattern language; it would be both quick and easy to get things done and
xix
xx FOREWORD
also very easy for any developer on a team (including the developer himself months
after writing the code!) to understand and adapt the code.
There are many different places we wanted to use the EIPs; whether in a stand-
alone application, a web services stack, an enterprise message broker like Apache
ActiveMQ, or inside a full-blown ESB like Apache ServiceMix, so we wanted a light-
weight framework that was middleware agnostic that users could embed anywhere
they wanted it. We also wanted developers to focus on the Enterprise Integration Pat-
terns first and foremost and not to get lost in the weeds of different middleware APIs
and technologies.
We also wanted developers to be able to use whatever DSL flavor they wished
(whether Java, XML, Groovy, Ruby, Scala, or whatever) and yet, at runtime, still be able
to introspect the framework and understand all of the EIPs that were being used. They
would be able to visualize the core patterns to the team at any point in the project life-
cycle, auto-document the patterns, or even support things like graphical editing of the
Enterprise Integration Patterns at design time or runtime.
So Apache Camel was born, and since then we’ve seen the codebase, community,
and number of components, technologies, and data formats grow massively as more
and more developers have found Apache Camel an ideal way to design, implement,
and maintain the Enterprise Integration Patterns.
In this book Claus and Jon describe the Enterprise Integration Patterns and the
concepts which underlie Apache Camel. Then they walk you through how to take the
concepts and apply them to many real-life scenarios to provide scalable and efficient
solutions that are easy to understand and quick to adapt to your integration needs. I
hope you’ll enjoy reading this book as much as I did!
JAMES STRACHAN
CO-FOUNDER OF APACHE ACTIVEMQ
CAMEL, AND SERVICEMIX
TECHNICAL DIRECTOR FUSESOURCE.COM
HTTP://MACSTRAC.BLOGSPOT.COM
preface
Developers who have done integration work know what a difficult task it can be. IT sys-
tems may not have been designed to be accessible from other systems, and if they were
designed for interoperability, they may not speak the protocol you need. As a devel-
oper, you end up spending a considerable amount of time working with the plumbing
of the integration protocols to open up the IT systems to the outside world.
In Enterprise Integration Patterns, Gregor Hohpe and Bobby Woolf gave us a standard
way to describe, document, and implement complex integration problems. Develop-
ers and architects alike can use this common language and catalog of solutions to
tackle their integration problems. But although Hohpe and Woolf gave us the theory,
the industry still needed an open source implementation of the book.
James Strachan, Rob Davies, Guillaume Nodet, and Hiram Chirino, within the
open source communities of Apache ActiveMQ and Apache ServiceMix, brought the
idea of Camel to life. Apache Camel is essentially an implementation of the EIP book,
and in the summer of 2007 version 1.0 was released.
Apache Camel is an integration framework whose main goal is to make integration
easier. It implements many of the EIP patterns and allows you to focus on solving busi-
ness problems, freeing you from the burden of plumbing. Using connectivity compo-
nents has never been easier, because you don’t have to implement JMS message
listeners or FTP clients, deal with converting data between protocols, or mess with the
raw details of HTTP requests. All of this is taken care of by Camel, which makes media-
tion and routing as easy as writing a few lines of Java code or XML in a Spring XML file.
xxi
xxii PREFACE
Apache Camel has since become very popular and today has an ever-growing com-
munity. As with many open source projects that become popular, a logical next step is
for someone to write a book about the project. Hadrian Zbarcea, the Project Manage-
ment Committee chair of the Apache Camel project, realized this, and in early 2009
he contacted Manning to discuss the need for such a book. Hadrian got in touch with
me (Claus Ibsen), inviting me in as a coauthor. It was perfect timing, as I was taking
over from James Strachan as the lead on Apache Camel. Later that year, Hadrian had
to step down as an author, but he invited Jonathan Anstey in as his replacement, to
ensure the project could continue.
Jonathan and I are both integration specialists working for FuseSource, which is
the professional company that offers enterprise services around various Apache proj-
ects. This book is written by the people who wrote the Camel code, which ensures you
have the most updated Camel book on the market.
Writing this book has been a very intense journey, proven by the fact that we were
able to complete the manuscript in a year. It took a long time to implement the exam-
ples and to ensure that the accompanying source code is of the highest standard. But
the result is a great source of examples that should inspire you to get the best out of
Camel, and it should be a good starting point for your Camel projects. While we were
writing this book, we were also implementing new features in Camel, which often
meant we had to go back and revise the material along the way. But we have kept up,
and this book uses the latest Camel release at the time of writing (Camel 2.5).
We hope this book brings great value to you and helps you prosper in the Camel
community.
CLAUS IBSEN
acknowledgments
We first want to thank Cynthia Kane, our development editor at Manning, who put up
with our many missed deadlines and gave great feedback during the writing process.
We’d also like to thank our awesome copy editor, Andy Carroll, for catching an amaz-
ing number of grammatical errors in the early revisions of the book. The greater Man-
ning team deserves kudos as well; they’ve made for a very pleasant writing experience
over the past year and a half.
Big thanks to our team of reviewers, who provided invaluable feedback during var-
ious stages of the book’s development: Bruce Snyder, Charles Moulliard, Christophe
Avare, Christopher Hunt, Domingo Suarez Torres, Doug Tillman, Fintan Bolton, Gor-
don Dickens, Gregor Hohpe, Jeroen Benckhuijsen, John S. Griffon, Kevin Jackson,
Marco Ughetti, Martin Gilday, Martin Krasser, Michael Nash, Mick Knutson, Roman
Kalukiewicz, Tijs Rademakers, and Willem Jiang.
Special thanks to Willem Jiang for being our technical proofreader, catching those
bugs we missed, and helping improve the source code for the book.
Thanks to Martin Krasser for contributing appendix E, which is all about using
Camel from the Akka project. We couldn’t think of a better person to write about
Camel and Akka.
We’d also like to thank Hadrian Zbarcea for getting this book project started—who
knows when this book would have been written or by whom if he hadn’t gotten us
together!
We’d like to thank Gregor Hohpe and James Strachan for writing the forewords to
our book. Gregor’s book, Enterprise Integration Patterns, has been one of our favorite
xxiii
xxiv ACKNOWLEDGMENTS
tech books for years now, so it’s an honor to have Gregor on board to write the fore-
word. Without the EIP book, Apache Camel would look a lot different than it does
today, if it existed at all.
In our opinion, James is an inspiration to many developers out there—including
us. He has co-founded tons of successful open source projects; Camel is just one of
them. If James and the other Apache Camel co-founders had not decided to create
Camel, we wouldn’t be writing this book. So, again, thanks!
Finally, we’d like to give a big warm thank you to the community. Without the com-
munity, the Apache Camel project wouldn’t be as successful as it is today. In fact, with-
out the success, both of us would have different kinds of jobs today, which wouldn’t
involve hacking on Camel all day along.
CLAUS
I would like to thank my beautiful wife, Christina, for her understanding of the long
hours I needed to spend during evenings and weekends working on the book. Knowing
that you would never let my hand go, that the family life is safe and secure, is exactly the
support any writer needs in taking up such a big challenge as writing a book.
A warm thank you goes to our dog, Bambi, who patiently sleeps in my office, and occa-
sionally wakes up and politely “asks” me for a break and a walk. I must admit many of
the ideas and thoughts behind this book came to me during my walks with Bambi.
JON
I would like to thank my amazing wife, Lisa, for the patience, support, and encourage-
ment I needed throughout the writing of this book. It simply would not have hap-
pened if it wasn’t for you. To Georgia, my beautiful daughter: thank you for cheering
me up when the writing got the better of me. I love you both!
about this book
Apache Camel exists because integration is hard and Camel’s creators wanted to make
things easier for users. Camel’s online documentation serves as a reference for its
many features and components. In contrast, this book aims to guide readers through
these features, starting with the simple points and building up to advanced Camel
usage by the end of the book. Throughout the book, Camel’s features are put into
action in real-life scenarios.
Roadmap
The book is divided into three parts:
■
Part 1—First steps
■
Part 2—Core Camel
■
Part 3—Out in the wild
Part 1 starts off simple by introducing you to Camel’s core functionality and concepts,
and it presents some basic examples.
■
Chapter 1 introduces you to Camel and explains what Camel is and where it fits
into the bigger enterprise software picture. You’ll also learn the concepts and
terminology of Camel.
■
Chapter 2 covers Camel’s main feature, which is message routing. The Java DSL
and Spring DSL are covered as are several enterprise integration patterns
(EIPs). EIPs are basically canned solutions to integration problems.
xxv
xxvi ABOUT THIS BOOK
Building on part 1’s foundation, part 2 covers the core features of Camel. You’ll need
many of these features when using Camel.
■
Chapter 3 explains how Camel can help you transform your data to different
formats while it’s being routed.
■
In chapter 4 we take a look at how you can use Java beans in Camel.
■
Chapter 5 covers all of Camel’s error-handling features.
■
In chapter 6 we look at the testing facilities shipped with Camel. You can use
these features for testing your own Camel applications or applications based on
other stacks.
■
Chapter 7 covers the most heavily used components among Camel’s large selec-
tion of components.
■
Chapter 8 looks in depth at five of the most complex EIPs.
In part 3 we cover the topics that are useful when you’ve gained a better understand-
ing of Camel from the earlier chapters.
■
Chapter 9 explains how you can use transactions in your Camel applications.
■
In chapter 10 we discuss how to deal with concurrency and scalability in your
Camel applications.
■
Chapter 11 explains how to create new Camel projects, which could be Camel
applications, custom components, or interceptors. This chapter doesn’t require
much additional Camel knowledge, so you could read this right after part 1.
The Scala DSL is also touched on here.
■
In chapter 12 we cover how to manage and monitor Camel applications.
Among other things, how to read the Camel logs and how to control Camel
with JMX are covered.
■
In chapter 13 we discuss the many ways to start and stop Camel. Deployment to
several of the most popular containers is also discussed.
■
Chapter 14 covers what we consider extra features of Camel: routing with beans
and using remoting to hide Camel APIs. We consider this extra because these
features do routing without using any of Camel’s DSLs and in some cases with
no Camel APIs. They take a different approach than what was discussed
throughout the book.
The appendixes at the end of the book contain useful reference material on the Sim-
ple expression language, expressions and predicates, the producer and consumer
templates, and the Camel community. Appendix E is written by Martin Krasser and
shows how to use Akka with Camel.
is a great way to start learning about Camel. Experienced engineers and architects are
also encouraged to read this book, as it explains advanced Camel concepts that you
just can’t find elsewhere. Test and Q&A engineers will find Camel and this book useful
as a means of driving tests that require communication with various transports and
APIs. System administrators, too, may find the management, monitoring, and deploy-
ment topics of great value.
Camel’s features are focused on the enterprise business community and its needs,
but it’s also a generic and very useful integration toolkit. Any Java developer who
needs to send a message somewhere will probably find Camel and this book useful.
Code conventions
The code examples in this book are abbreviated in the interest of space. In particular,
some of the namespace declarations in the XML configurations and package imports
in Java classes have been omitted. We encourage you to use the source code when
working with the examples. The line lengths of some of the examples exceed the page
width, and in cases like these, the ➥ marker is used to indicate that a line has been
wrapped for formatting.
All source code in listings or in text is in a fixed-width font like this to separate
it from ordinary text. Code annotations accompany many of the listings, highlighting
important concepts. In some cases, numbered bullets link to explanations that follow
the listing.
Software requirements
The following software is required to run the examples:
■
JDK 5 or better
■
Maven 2.2.1 or better
■
Apache Camel 2.5 or better
Apache Camel can be downloaded from its official website: http://camel.apache.org/
download.html.
All the examples can be run using Maven. Chapter 1 shows you how to get started
with Maven and run the examples.
Author Online
The purchase of Camel in Action includes free access to a private web forum run by Man-
ning Publications, where you can make comments about the book, ask technical ques-
tions, and receive help from the authors and from other users. To access the forum and
xxviii ABOUT THIS BOOK
xxix
xxx ABOUT THE COVER ILLUSTRATION
The pictures from the Ottoman collection, like the other illustrations that appear
on our covers, bring to life the richness and variety of dress customs of two centuries
ago. They recall the sense of isolation and distance of that period—and of every other
historic period except our own hyperkinetic present. Dress codes have changed since
then and the diversity by region, so rich at the time, has faded away. It is now often
hard to tell the inhabitant of one continent from another. Perhaps, trying to view it
optimistically, we have traded a cultural and visual diversity for a more varied personal
life. Or a more varied and interesting intellectual and technical life.
We at Manning celebrate the inventiveness, the initiative, and, yes, the fun of the
computer business with book covers based on the rich diversity of regional life of two
centuries ago‚ brought back to life by the pictures from this collection.
about the authors
CLAUS IBSEN has worked as a software engineer and architect for more than 13 years.
He has often worked with integration in various forms, from integrating with legacy
systems on AS/400s to building custom in-house integration frameworks. Claus has
designed and architected a large solution for custom clearance for the district of
Shanghai, China. He tracks the trends in the open source integration space and it led
him to Camel in late 2007. He became a committer in March 2008.
He currently holds a position as principal software engineer at FuseSource, as proj-
ect lead on Apache Camel. Claus has ambitions to pick up speaking engagements, so
you will likely be able to catch up with him at various conferences.
Claus lives in Sweden near Malmo with his wife and dog, which is spoiled as the
only child in the family. He is Danish by nationality.
JONATHAN ANSTEY is a software engineer with varied experience in manufacturing con-
trol systems, build infrastructure, and enterprise integration. He got involved in the
Apache Camel project in early 2008 and hasn’t looked back since. Most recently, Jon
has been working on Apache Camel and other Apache open source projects
at FuseSource.
When Jon is not hacking on Camel, he likes to spend time with his wife and daugh-
ter in St. John’s, Newfoundland.
xxxi
Part 1
First steps
Building complex systems from scratch is a very costly endeavor, and one that’s almost
never successful. An effective and less risky alternative is to assemble a system like a
jigsaw puzzle from existing, proven components. We depend daily on a multitude of
such integrated systems, making possible everything from phone communications,
financial transactions, and healthcare to travel planning and entertainment.
You can’t finalize a jigsaw puzzle until you have a complete set of pieces that plug
into each other simply, seamlessly, and robustly. That holds true for system integra-
tion projects as well. But whereas jigsaw puzzle pieces are made to plug into each
other, the systems we integrate rarely are. Integration frameworks aim to fill this gap.
As an integrator, you’re less concerned about how the system you integrate works and
more focused on how to interoperate with it from the outside. A good integration
framework provides simple, manageable abstractions for the complex systems you’re
integrating and the “glue” for plugging them together seamlessly.
Apache Camel is such an integration framework. In this book, we’ll help you
understand what Camel is, how to use it, and why we think it’s one of the best inte-
gration frameworks out there.
3
4 CHAPTER 1 Meeting Camel
This chapter will start off by introducing Camel and highlighting some of its core
features. We’ll then take a look at the Camel distribution and explain how you can run
the Camel examples in the book. We’ll round off the chapter by bringing core Camel
concepts to the table so you can understand Camel’s architecture.
Are you ready? Let’s meet Camel.
container or a reliable message bus, but it can be deployed in one, such as Open-
ESB or the previously mentioned ServiceMix. For that reason, we prefer to call
Camel an integration framework rather than an ESB.
To understand what Camel is, it helps to look at its main features. So let’s take a
look at them.
These examples are real code, and they show how easily you can route files from a
folder to a JMS queue. Because there’s a real programming language underneath, you
can use the existing tooling support, such as code completion and compiler error
detection, as illustrated in figure 1.1.
Figure 1.1 Camel DSLs use real programming languages like Java, so you can use existing tooling support.
Introducing Camel 7
Here you can see how the Eclipse IDE’s autocomplete feature can give us a list of DSL
terms that are valid to use.
EXTENSIVE COMPONENT LIBRARY
Camel provides an extensive library of more than 80 components. These components
enable Camel to connect over transports, use APIs, and understand data formats.
PAYLOAD-AGNOSTIC ROUTER
Camel can route any kind of payload—you aren’t restricted to carrying XML payloads.
This freedom means that you don’t have to transform your payload into a canonical
format to facilitate routing.
MODULAR AND PLUGGABLE ARCHITECTURE
Camel has a modular architecture, which allows any component to be loaded into
Camel, regardless of whether the component ships with Camel, is from a third party,
or is your own custom creation.
POJO MODEL
Beans (or POJOs) are considered first-class citizens in Camel, and Camel strives to let
you use beans anywhere and anytime in your integration projects. This means that in
many places you can extend Camel’s built-in functionality with your own custom code.
Chapter 4 has a complete discussion of using beans within Camel.
EASY CONFIGURATION
The convention over configuration paradigm is followed whenever possible, which mini-
mizes configuration requirements. In order to configure endpoints directly in routes,
Camel uses an easy and intuitive URI configuration.
For example, you could configure a file consumer to scan recursively in a sub-
folder and include only a .txt file, as follows:
from("file:data/inbox?recursive=true&include=*.txt")...
EE application, JBI container, OSGi bundle, Java Web Start, or on the Google App
engine. Camel was designed not to be a server or ESB but instead to be embedded in
whatever platform you choose.
TEST KIT
Camel provides a Test Kit that makes it easier for you to test your own Camel applica-
tions. The same Test Kit is used extensively to test Camel itself, and it includes more
than 6,000 unit tests. The Test Kit contains test-specific components that, for example,
can help you mock real endpoints. It also contains setup expectations that Camel can
use to determine whether an application satisfied the requirements or failed. Chap-
ter 6 covers testing with Camel.
VIBRANT COMMUNITY
Camel has an active community. This is essential if you intend to use any open source
project in your application. Inactive projects have little community support, so if you
run into issues, you’re on your own. With Camel, if you’re having any trouble, users
and developers alike will come to your aid promptly. For more information on
Camel’s community, see appendix D.
Now that you’ve seen the main features that make up Camel, we’ll get a bit more
hands on by looking at the Camel distribution and trying out an example.
As you can see, the distribution is pretty small, and you can probably guess what each
directory contains already. Here are the details:
Getting started 9
■ doc—Contains the Camel Manual in PDF and HTML formats. This user guide is
a download of a large portion of the Apache Camel wiki at the time of release.
As such, it’s a great reference for those not able to browse to the Camel website.
■ examples—Includes 27 Camel examples. You’ll see an example shortly.
■ lib—Contains all Camel libraries and third-party dependencies needed for the
core of Camel to run. You’ll see later in the chapter how Maven can be used to
easily grab dependencies for the components outside the core.
■ LICENSE.txt—Contains the license of the Camel distribution. Because this is an
Apache project, the license is the Apache License, version 2.0.
■ NOTICE.txt—Contains copyright information about the third-party dependen-
cies included in the Camel distribution.
■ README.txt—Contains a short intro to what Camel is and a list of helpful links
to get new users up and running fast.
Now let’s try out one of the Camel examples.
Listing 1.1 Routing files from one folder to another in plain Java
public class FileCopier {
public static void main(String args[]) throws Exception {
File inboxDirectory = new File("data/inbox");
File outboxDirectory = new File("data/outbox");
10 CHAPTER 1 Meeting Camel
outboxDirectory.mkdir();
File[] files = inboxDirectory.listFiles();
for (File source : files) {
if (source.isFile()) {
File dest = new File(
outboxDirectory.getPath()
+ File.separator
+ source.getName());
copyFIle(source, dest);
}
}
}
private static void copyFile(File source, File dest)
throws IOException {
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[(int) source.length()];
FileInputStream in = new FileInputStream(source);
in.read(buffer);
try {
out.write(buffer);
} finally {
out.close();
in.close();
}
}
}
The FileCopier example in listing 1.1 is a pretty simple use case, but it still results
in 34 lines of code. You have to use low-level file APIs and ensure that resources get
closed properly, a task that can easily go wrong. Also, if you wanted to poll the data/
inbox directory for new files, you’d need to set up a timer and also keep track of
which files you’ve already copied. This simple example is getting more complex.
Integration tasks like these have been done thousands of times before—you
shouldn’t ever need to code something like this by hand. Let’s not reinvent the wheel
here. Let’s see what a polling solution looks like if you use an integration framework
like Apache Camel.
Listing 1.2 Routing files from one folder to another with Apache Camel
public class FileCopierWithCamel {
public static void main(String args[]) throws Exception {
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
public void configure() {
from("file:data/inbox?noop=true")
.to("file:data/outbox");
B Routes files from
inbox to outbox
}
});
context.start();
Thread.sleep(10000);
context.stop();
}
}
Getting started 11
Most of this code is boilerplate stuff when using Camel. Every Camel application uses
a CamelContext that’s subsequently started and then stopped. You also add a sleep
method to allow your simple Camel application time to copy the files. What you
should really focus on in listing 1.2 is the route B.
Routes in Camel are defined in such a way that they flow when read. This route can
be read like this: consume messages from file location data/inbox with the noop
option set, and send to file location data/outbox. The noop option tells Camel to
leave the source file as is. If you didn’t use this option, the file would be moved. Most
people who have never seen Camel before will be able to understand what this route
does. You may also want to note that, excluding the boilerplate code, you created a
file-polling route in just one line of Java code B.
To run this example, you’ll need to download and install Apache Maven from the
Maven site at http://maven.apache.org/download.html. Once you have Maven up
and working, open a terminal and browse to the chapter1/file-copy directory of the
book’s source. If you take a directory listing here, you’ll see several things:
■ data—Contains the inbox directory, which itself contains a single file named
message1.xml.
■ src—Contains the source code for the listings shown in this chapter.
■ pom.xml—Contains information necessary to build the examples. This is the
Maven Project Object Model (POM) XML file.
NOTE We used Maven 2.2.1 during the development of the book. Newer ver-
sions of Maven may not work or appear exactly as we’ve shown.
Listing 1.3 The Maven POM required to use Camel’s core library
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent> B
Parent POM
<groupId>com.camelinaction</groupId>
<artifactId>chapter1</artifactId>
<version>1.0</version>
</parent>
<artifactId>file-copy</artifactId>
Maven itself is a complex topic, and we won’t go into great detail here. We’ll give you
enough information to be productive with the examples in this book. For an in-depth
look at Maven, we recommend reading Maven by Example and Maven: The Complete Ref-
erence, both of which are freely available from http://www.sonatype.com/book. We’ll
also discuss using Maven to develop Camel applications in chapter 11, so there’s a
good deal of information there too.
The Maven POM in listing 1.3 is probably one of the shortest POMs you’ll ever
see—almost everything uses the defaults provided by Maven. Besides those defaults,
there are also some settings configured in the parent POM B. Probably the most
important section to point out here is the dependency on the Camel library C. This
dependency element tells Maven to do the following:
1 Create a search path based on the groupId, artifactId, and version. The ver-
sion element is set to the camel-version property, which is defined in the POM
referenced in the parent element B, and will resolve to 2.5.0. The type of depen-
dency was not specified, so the JAR file type will be assumed. The search path will
be org/apache/camel/camel-core/2.5.0/camel-core-2.5.0.jar.
2 Because listing 1.3 defined no special places for Maven to look for the Camel
dependencies, it will look in Maven’s central repository, located at http://
repo1.maven.org/maven2.
3 Combining the search path and the repository URL, Maven will try to down-
load http://repo1.maven.org/maven2/org/apache/camel/camel-core/2.5.0/
camel-core-2.5.0.jar.
4 This JAR will be saved to Maven’s local download cache, which is typically located
in the home directory under .m2/repository. This would be ~/.m2/repository on
Linux/Unix and C:\Documents and Settings\<Username>\.m2\ repository on
Windows XP, and C:\Users\<Username>\.m2\repository on Windows Vista/7.
5 When the application code in listing 1.2 is started, the Camel JAR will be added
to the classpath.
To run the example in listing 1.2, use the following command:
mvn compile exec:java -Dexec.mainClass=camelinaction.FileCopierWithCamel
This instructs Maven to compile the source in the src directory and to execute the
FileCopierWithCamel class with the camel-core JAR on the classpath.
NOTE In order to run any of the examples in this book you’ll need an Inter-
net connection. A broadband speed connection is preferable because Apache
Maven will download many JAR dependencies of the examples, some of which
are large. The whole set of examples will download about 140 MB of libraries.
Run the Maven command from the chapter1/file-copy directory, and after it completes,
browse to the data/outbox folder to see the file copy that has just been made. Congrat-
ulations, you’ve just run your first Camel example! It was a simple example, but knowing
how it’s set up will enable you to run pretty much any of the book’s examples.
Another random document with
no related content on Scribd:
Minä menin sanomaan hänelle jäähyväisiä.
"Tules tänne, niin saat nähdä, Sonja!" sanoi Varvara. "Tuo pikku
notaari kävelee lakkaamatta tästä ohitse."
Minä olin hyvin kauan, melkein ihan lapsuudesta asti ollut hyvä tuttu
Jakov Pasinkovin kanssa. Hän oli ollut kasvatettavana samassa
yksityisessä oppilaitoksessa Moskovassa, saksalaisen Winterkellerin
luona, jossa minäkin olin viettänyt kolme vuotta.
Jakovin isä, joka oli köyhä, virasta eronnut majori ja muuten hyvin
rehellinen, mutta hiukan heikkomielinen mies, oli tullut herra
Winterkellerin luo pienen, silloin seitsenvuotisen poikansa kanssa,
maksanut hänestä vuoden maksun, mutta sitte matkustanut pois
Moskovasta ja kadonnut, antamatta enää mitään tietoa itsestään.
Tuon tuostakin kuului hämäriä kummallisia huhuja hänen
vaiheistansa. Vasta kahdeksan vuoden kuluttua saatiin varmasti
tietää hänen hukkuneen Irtish-joen tulvaan. Ei kukaan tiennyt, mikä
hänet oli vienyt Siperiaan.
Kuin minä näin hänet ensi kerran, oli hän kuudentoista vuoden
ijässä ja minä olin äsken täyttänyt kolmetoista. Minä olin silloin hyvin
itserakas ja lellitelty poika, rikkaassa kodissa kasvanut. Niinpä minä
heti kouluun tultuani kiiruhdin tekemään lähempää tuttavuutta erään
ruhtinaan pojan kanssa, josta herra Winterkeller piti aivan erityistä
huolta, ja parin muun ylhäissukuisen pojan kanssa. Kaikki muut
pidätin minä kaukana itsestäni enkä Pasinkovia ottanut edes
huomioonikaan. Sitä pitkää ja hoikkaa poikaa rumassa nutussaan ja
lyhyissä housuissa, joiden alta näkyi karkeat, kuluneet puolisukat,
katselin minä köyhän työmiehen pojan tai sellaisen palveluspojan
vertaiseksi, jonka isäni oli minulle valinnut kotitilustemme maaorjain
joukosta.
*****
Sofia aikoi nyt nousta pois pianon edestä. Mutta Varvara pyysi
häntä soittamaan edelleen, meni Pasinkovin luo ja ojentaen hänelle
kätensä, sanoi hämillään hymyillen:
"Tahdotteko?"
Minä ilostuin hyvin Pasinkovin tulosta, mutta kun ajattelin, mitä olin
tehnyt edellisenä päivänä, jouduin niin häpeihini, että käännyin
jälleen seinään päin, sanomatta hänelle sanaakaan.
"Niin, minä tarkoitan yhtä tosi asiaa", vastasi hän pannen eri
painoa joka sanalle. "Eilen minä näytin teille lompakkoani, jossa oli
erään henkilön kirjeitä minulle. Tänään te olette nenäkkäästi ja
sopimattomasti nuhdellen — huomatkaa tarkkaan: nenäkkäästi ja
sopimattomasti nuhdellen — maininneet samalle henkilölle
muutamia sanoja niistä kirjeistä, vaikka teillä ei ole ollut mitään
oikeuden tapaistakaan sellaiseen, lievimmiten sanoen, kömpelöön
käytökseen. Minä haluan sen tähden kuulla, miten te aiotte selittää
tuon kaikin puolin moitittavan käytöksenne."
"Ja minä haluan tietää, mikä oikeus teillä on tällä tavoin tutkistella
minua", vastasin minä, vavisten sekä häpeästä että kiukusta. "Jos te
huviksenne sopimattomasti kerskailette ylhäisistä tuttavuuksistanne
ja huvittavasta kirjeenvaihdostanne, mitä se minuun koskee? Vai
eivätkö ehkä kaikki kirjeenne teillä enää ole tallella?"
"Minä tiedän nyt, mitä minun tulee ajatella", sanoi hän. "Teidän
muotonne todistaa kyllin selvästi teitä vastaan. Mutta minä sanon
teille, että oikea aatelismies ei tee sillä tavalla. Varkain lukea toisten
kirjeitä ja sitte mennä nuoren, ylhäis-sukuisen naisen luo
häiritsemään hänen rauhaansa…"
"Rakastan."