camel Java to xml_《Camel in Action》学习笔记

########

Camel知识

########

~~~~~~~~~~~~~~~~

Apache Camel简化SOA实施进程 http://yangzb.iteye.com/blog/494571

~~~~~~~~~~~~~~~~

有一套设计模式在业界引起了注意,那就是Hohpe 和 Woolf's企业整合模式。

这些模式包含了一些技术上无关的词汇来描述大量整合的解决方案。

他们并不是侧重于低层次的编程,而是采取自上而下的方案来开 发一个异步的、以信息为基础的架构。

一致的词汇是很好的,而易于使用的框架在实际建立基础架构的时候岂不是更好吗?

这正是Apache 的开源Camel项目背后的理念。

现在,行之有效的并且真实的一套模式已可以获得了,很明显,

下一步就是要去创造一个能够以最简单的方式来实施这个模式的驱动器。

Camel 是一个代码先行的工具,它允许开发者在无须学习厂商定制和复杂的底层技术的情况下进行精密的大规模集成。

Apache Camel是从Apache其他项目尤其是Apache ActiveMQ 以及Apache ServiceMix的代码和灵感有机的衍生出来的。

Camel 概况:

建立Camel的第一步是解偶底层框架中的模式。

Camel的最初也是主要的优势在于开发团队无须为了连接系统在容器上下功夫。

(最后给出一个简单的camel例子,使用了camel的template等)

~~~~~~~~~~~~~

Apache Camel的特点 http://www.booksir.com.cn/n73230

~~~~~~~~~~~~~

Apache Camel是一个非常强大的基于规则的路由以及媒介引擎,

该引擎提供了一个基于POJO的 企业应用模式(Enterprise Integration Patterns)的实现,

可以采用其异常强大且十分易用的API 来配置其路由或者中介的规则。

~~~~~~~~~~~~~

Apache Camel http://www.doc88.com/p-77281075343.html http://wenku.baidu.com/view/211a8438376baf1ffc4fadd2.html

~~~~~~~~~~~~~

(EIP 举例

提到了一个邮件系统作为路由目的地的例子

)

~~~~~~~~~~~~~~~~~~~

camel in action

~~~~~~~~~~~~~~~~~~~

Abbreviation:

MEP: message exchange patterns, includes InONly and InOut.

CBR: Content-Based Router

(chapter 11 developing camel projects can read directly after reading chapter 1)

Chapter 4 has a complete discussion of using beans within Camel.

1.1 Introducing Camel

NOTE We used Maven 2.2.1 during the development of the book. Newer versions of Maven may not work or appear exactly as we’ve shown.

(

For an in-depth look at Maven, we recommend reading Maven by Example and Maven: The Complete Reference,

both of which are freely available from http://www.sonatype.com/book.

)

1.3 Camel’s message model

In Camel, there are two abstractions for modeling messages:

a. org.apache.camel.Message—The fundamental entity containing the data being carried and routed in Camel

b. org.apache.camel.Exchange—The Camel abstraction for an exchange of messages.

This exchange of messages has an “in” message and as a reply, an “out” message

1.3.1 Message

Figure 1.4 A message can contain headers, attachments, and a body.

Attachments in message are optional, which are typically used for the web service and email components.

1.3.2 Exchange

An exchange in Camel is the message’s container during routing.

The Camel exchange holds a pattern property(MEP) that can be either

a. InOnly — For example, JMS messaging is often one-way messaging.

b. InOut — For example, HTTP-based transports are often request reply,

where a client requests to retrieve a web page, waiting for the reply from the server.

1.4 Camel’s architecture

(

high level architecture diagram in page 15

)

Figure 1.6 At a high level, Camel is composed of processors, components, and routes.

All of these are contained within the CamelContext.

1.4.2 Camel concepts

camelcontext

routing engine

routes

domain-specific language(DSL)

processor

component

endpoint

producer

consumer

Note:

Processor

Many of the processors are implementations of EIPs,

but one could easily implement their own custom processor and insert it into a route.

COMPONENT

Components are the main extension point in Camel.

To date, there are over 80 components in the Camel ecosystem that range in function

from data transports, to DSLs, data formats, and so on.

Figure 1.9 Endpoint URIs are divided into three parts: a scheme, a context path, and options.

CONSUMER

In Camel there are two kinds of consumers: event-driven consumers and polling consumers.

Table 1.1 The services that the CamelContext provides

Components

Endpoints

Routes

Type converters

Data formats

Registry

Languages

Note:

Registry

contains registry that allows you to look up beans

By defaults, this will be a JNDI registry.

if you're using Camel from Spring, this will be the Spring ApplicationContext.

It can also be an OSGi registry if you use an OSGi container.

(fully discussed in chapter 4)

~~~~~~~~~~~~~~~~

Chapter2 Routing with Camel

One of the most important features of Camel is routing;

without it, Camel would essentially be a library of transport connectors.

2.1 Introducing Rider Auto Parts (example requirement)

(

Our fictional motorcycle parts business, Rider Auto Parts, supplies parts to motorcycle

manufacturers. Over the years, they’ve changed the way they receive orders several

times. Initially, orders were placed by uploading comma-separated value (CSV) files to

an FTP server. The message format was later changed to XML. Currently they provide a

website through which orders are submitted as XML messages over HTTP.

Rider Auto Parts asks new customers to use the web interface to place orders, but

because of service level agreements (SLAs) with existing customers, they must keep all

the old message formats and interfaces up and running. All of these messages are converted

to an internal Plain Old Java Object (POJO) format before processing. A highlevel

view of the order processing system is shown in figure 2.2.

Rider Auto Parts faces a pretty common problem: over years of operation, they have

acquired software baggage in the form of transports and data formats that were popular

at the time. This is no problem for an integration framework like Camel, though.

In this chapter, and throughout the book, you’ll help Rider Auto Parts implement

their current requirements and new functionality using Camel.

)

2.2.1 Working with files over FTP

To download new orders from the FTP server, you need to do the following:

1 Connect to the rider.com FTP server on the default FTP port of 21

2 Provide a username of “rider” and password of “secret”

3 Change the directory to “orders”

4 Download any new order files

The FtpComponent isn’t part of the camel-core module,

so you have to add an additional dependency to your project.

Using Maven you just have to add the following dependency to the POM:

org.apache.camel

camel-ftp

2.5.0

For the FTP component, you can also specify the username and password in the context path of the URI.

So the following URI is equivalent to the one in figure 2.3:

ftp://rider:[email protected]/orders.

In a from node of Camel’s DSL:

from("ftp://rider.com/orders?username=rider&password=secret")

2.2.2 Sending to a JMS queue

(

ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

The vm://localhost URI means that you should connect to an embedded broker

named “localhost” running inside the current JVM.

The vm transport connector in ActiveMQ creates a broker on demand if one isn’t running already,

so it’s very handy for quickly testing JMS applications;

)

(See chapter 7 for details, such as connection pooling)

The JMS component and the ActiveMQ-specific connection factory aren’t part of the camel-core module.

org.apache.camel

camel-jms

2.5.0

org.apache.activemq

activemq-core

5.3.2

Note:

FTP component at http://camel.apache.org/jms.html

2.3.2 The Java DSL

ADDING A PROCESSOR

The Processor interface in Camel is an important building block of complex routes.

This gives you full access to the message exchange, letting you do pretty much

whatever you want with the payload or headers.

All EIPs in Camel are implemented as processors.

Note:

FTP component at http://camel.apache.org/ftp2.html

2.4 Creating routes with Spring

...

2.5 Routing and EIPs

2.5.1 Using a content-based router (CBR)

The content could be a message header, the payload data type, part of the payload itself

—pretty much anything in the message exchange.

from("jms:incomingOrders")

.choice()

.when(predicate)

.to("jms:xmlOrders")

.when(predicate)

.to("jms:csvOrders");

Note:

A predicate in Camel is a simple interface that only has a matches method:

public interface Predicate {

boolean matches(Exchange exchange);

}

predicates are often built up from expressions, and expressions are used to extract a result

from an exchange based on the expression content.

in Camel, some of EL include Simple, EL, JXPath, Mvel, OGNL, PHP, BeanShell, JavaScript, Groovy, Python, Ruby,

XPath, and XQuery.

Note:

Spring DSL requires Simple expression instead of the Java-based predicate.

2.5.2 Using message filters

from("jms:xmlOrders").filter(xpath("/order[not(@test)]")).process(new Processor(){...}

2.5.3 Using multicasting

from("jms:xmlOrders").multicast().to("jms:accounting", "jms:production");

(

For dealing with responses from services invoked in a multicast, an

aggregator is used. See more about aggregation in chapter 8.

)

PARALLEL MULTICASTING

ExecutorService executor = Executors.newFixedThreadPool(16);

from("jms:xmlOrders")

.multicast().parallelProcessing().executorService(executor)

.to("jms:accounting", "jms:production");

2.5.4 Using recipient lists

2.5.5 Using the wireTap method

The wire tap is a pretty useful monitoring tool, but it leaves most of the work up to you.

We’ll discuss some of Camel’s more powerful tracing and auditing tools in chapter 12.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Chapter3 Transforming data with Camel

3.1 Data transformation overview

Data transformation is a broad term that covers two types of transformation:

a. Data format transformation

The data format of the message body is transformed from one form to another.

For example, a CSV record is formatted as XML.

b. Data type transformation

The data type of the message body is transformed from one type to another.

For example a java.lang.String is transformed into a javax.jms.TextMessage.

Note:

In most cases, the data transformation you’ll face with Camel is format transformation,

where you have to mediate between two protocols.

Camel has a builtin type-converter mechanism that can automatically convert between types,

which greatly reduces the need for end users to deal with type transformations.

3.1.1 Data transformation with Camel

In Camel, data transformation typically takes places in the six ways

in routes

using components

using data formats

using templates

type transformation using Camel's type-converter mechanism

in components adapters

3.2 Transforming data using EIPs and Java

3.2.1 Using the Message Translator EIP

(aka Adapter pattern from GoF)

Camel provides three ways of using this pattern:

Using a Processor

Using beans

Using

3.2.2 Using the Content Enricher EIP

3.3 Transforming XML

Camel provides two ways to perform XML transformations:

XSLT component—For transforming an XML payload into another format using XSLT stylesheets

XML marshaling—For marshaling and unmarshaling objects to and from XML

3.3.1 Transforming XML with XSLT

from("file://rider/inbox")

.to("xslt://camelinaction/transform.xsl")

.to("activemq:queue:transformed")

3.3.2 Transforming XML with object marshaling

In Camel, this marshaling process is provided in ready-to-use components known as data formats.

Here we’ll take aquick look at the XStream and JAXB data formats

(

JAXB annotations:

First you define @XmlRootElement B as a class-level annotation to indicate that this class is an XML element.

Then you define the @Xml-AccessorType to let JAXB access fields directly.

To expose the fields of this model object as XML attributes, you mark them with the @XmlAttribute annotation.

)

3.4 Transforming with data formats

In Camel, data formats are pluggable transformers that can transform messages from one form to another and vice versa.

Each data format is represented in Camel as an interface in org.apace.camel.spi.DataFormat containing two methods:

a. marshal—For marshaling a message into another form, such as marshaling Java objects to XML, CSV, EDI, HL7, or other well-known data models

b. unmarshal—For performing the reverse operation, which turns data from wellknown formats back into a message

3.4.1 Data formats provided with Camel

3.4.2 Using Camel’s CSV data format

3.4.3 Using Camel’s Bindy data format

3.4.4 Using Camel’s JSON data format

3.4.5 Configuring Camel data formats

3.4.6 Writing your own data format

3.5 Transforming with templates

3.6 About Camel type converters

3.6.1 How the Camel type-converter mechanism works

3.6.2 Using Camel type converters

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Chapter4 Using beans with Camel

4.1.3 Using beans the easy way

from("direct:hello").beanRef("helloBean", "hello");

from("direct:hello").bean(HelloBean.class);

4.2 The Service Activator pattern

The service activator acts as a mediator between the requester and the POJO service.

the service is the POJO and the service activator is something in Camel

that can adapt the request and invoke the service.

That something is the Camel Bean component,

which eventually uses the org.apache.camel.component.bean.BeanProcessor to do the work.

4.3 Camel’s bean registries

Camel’s philosophy is to leverage the best of the available frameworks,

so it uses a pluggable registry architecture to integrate them.

Spring is one such framework

4.3.1 SimpleRegistry

4.3.2 JndiRegistry

4.3.3 ApplicationContextRegistry

4.3.4 OsgiServiceRegistry

(NOTE We’ll look at OSGi again when we cover Camel deployment in chapter 13.)

4.4 Selecting bean methods

4.5 Bean parameter binding

4.6 Summary and best practices

If you hit a problem that you can’t work around or figure out how to resolve using Camel and EIPs,

you can always resort to using a bean and letting Camel invoke it.

~~~~~~~~~~~~~~~~~~~~~~~

Chapter5 Error handling

Chapter6 Testing with Camel

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

5/5:

Chapter7 Understanding components

P188

7.1 Overview of Camel components

Components are the primary extension point in Camel.

From an API point of view, a Camel component is simple,

consisting of a class implementing the Component interface

The main responsibility of a component is to be a factory for endpoints.

There are two main ways in which components are added to a Camel runtime:

by manually adding them to the CamelContext and through autodiscovery.

The camel-core module has 13 useful components built in, though.

1. Bean

2. Browse

3. DataSet

4. Direct

5. File

6. Language

7. Log

8. Mock

9. Properties

10. Ref

11. SEDA

12. Timer

13. VM

7.2 Working with files (File and FTP components)

7.2.2 Accessing remote files with the FTP component

Probably the most common way to access remote files is by using FTP,

and Camel supports three flavors of FTP:

a. Plain FTP mode transfer

b. SFTP for secure transfer

c. FTPS (FTP Secure) for transfer with the Transport Layer Security (TLS)

and Secure Sockets Layer (SSL) cryptographic protocols enabled

the FTP component isn’t part of the camel-core module, you need to add an additional dependency to your project.

org.apache.camel

camel-ftp

2.5.0

7.3 Asynchronous messaging (JMS component)

By specifying an InOut MEP, Camel will send the message to the validate queue

and wait for a reply on a temporary queue that it creates automatically.

JMS messaging applications are typically used within an organization—users

outside the corporate firewall rarely send JMS messages to internal systems.

For messaging with the external world, web services can be used.

7.4 Web services (CXF component)

Tip:

In the web services world, a consumer is typically a client that calls a remote service.

In Camel, a consumer is a server, so the definition is reversed!

org.apache.camel

camel-cxf

2.5.0

org.apache.cxf

cxf-rt-transports-http-jetty

2.2.10

7.6 Working with databases (JDBC and JPA components)

7.6.1 Accessing data with the JDBC component

Chapter8 Enterprise integration patterns

一本书提到的EIP

Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions

written by Gregor Hohpe and Bobby Woolf

65 EIPs

categorize to:

Integration Style (4)

Messaging Endpoints (12)

Message Construction (10)

Channel (10)

Message Routing (14)

Message Transformation (7)

System Management (8)

你可能感兴趣的:(camel,Java,to,xml)