Stream
Since Camel 1.3
Both producer and consumer are supported
The Stream component provides access to the System.in, System.out and System.err streams as well as allowing streaming of file.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-stream</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI format
stream:in[?options] stream:out[?options] stream:err[?options] stream:header[?options] stream:file?fileName=/foo/bar.txt stream:http?httpUrl=http:myserver:8080/data
If the stream:header URI is specified, the stream header is used to find the stream to write to. This option is available only for stream producers (that is, it cannot appear in from()). A message without a stream header, or with one that is not a java.io.OutputStream, fails with a NoSuchHeaderException.
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Stream component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean |
Endpoint Options
The Stream endpoint is configured using URI syntax:
stream:kind
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The kind of stream. The consumer reads from in (System.in), file (the file of fileName) or http (the URL of httpUrl). The producer writes to out (System.out), err (System.err), file (the file of fileName) or header (the java.io.OutputStream in the stream header of the message). Any other kind fails when the consumer or producer is created. Enum values:
| String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The name of the charset of text, for example UTF-8. The consumer uses it to read lines with kind in or file, reads lines of kind http with the JVM default charset, and does not use it with readLine=false. The producer uses it to write a body that is a String or that cannot be converted to byte[]. If not set, the JVM default charset is used. | String | ||
The path of the file that kind file reads or writes. The consumer reads the file from the beginning; without scanStream, a file that cannot be read fails the start of the consumer. The producer appends to the file, and creates it and its parent directories when they do not exist. | String | ||
Whether the consumer watches the directory of fileName with the JDK WatchService for the creation or modification of the file, for example when it is overwritten or rolled over. Only for kind file, and only used with scanStream and retry: the consumer then opens the file again at its end only when it changed. A fileName without a directory is not watched. | false | boolean | |
The number of lines that the consumer puts in one exchange, whose body is the result of groupStrategy, by default a List of the lines. If 0, each line is one exchange. Without scanStream, the lines left at the end of the stream are sent as a smaller group, and with scanStream a group is sent only when it is full. With kind in and without scanStream, each line is sent alone. Not used with readLine=false. | int | ||
The org.apache.camel.component.stream.GroupStrategy that turns a group of lines into the message body. Only used when groupLines is set. The default returns the List of the lines as is. | GroupStrategy | ||
The request headers that the consumer sends to httpUrl, as a comma-separated list of name=value or name:value pairs, for example Accept:application/json. Whitespace around each name and value is removed. A value that contains a comma, = or : is not supported. | String | ||
The URL that kind http reads from, which the consumer opens with java.net.URLConnection. Without scanStream, the consumer opens it when it starts, so a URL that cannot be reached fails the start. | String | ||
The delay in milliseconds before the first prompt of promptMessage, used in place of promptDelay. It keeps the prompt apart from the log output that is written to System.out while the application starts. If 0, the first prompt waits promptDelay. | 2000 | long | |
The delay in milliseconds before each prompt of promptMessage, except the first one when initialPromptDelay is set. | long | ||
The text that the consumer prints to System.out before it reads each line from System.in, for example Enter a command: (no new line is added). Only printed for kind in, and not with scanStream. | String | ||
Whether the consumer reads the stream line by line and creates an exchange with a String body for each line, or for each group of groupLines lines. If false, the consumer reads the stream to its end and creates one exchange with all the bytes as byte[] body; with scanStream, each exchange holds the bytes read in one scan. | true | boolean | |
Whether the consumer opens the stream again at its end and after it failed to open or read it, somewhat like tail --retry. Only used with scanStream. A file is then read again from the beginning, and the request to httpUrl is sent again. Without fileWatcher this happens at each end of the stream, so enable fileWatcher to read a file again only after it changed. | false | boolean | |
Whether the consumer keeps reading the stream after its end, like the Unix tail -f command, and waits scanStreamDelay each time it finds no new data. The consumer opens the stream in its reading thread, so a file that does not exist yet or a URL that cannot be reached does not fail the start, and is opened again later only with retry. A scanned stream never completes, so the CamelStreamComplete header is always false. | false | boolean | |
The delay in milliseconds before the consumer reads again when it finds no new data in the stream. Only used with scanStream. After the stream could not be opened or read, the consumer waits at least one second. | long | ||
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
Whether the producer writes the line separator of the operating system (System.lineSeparator()) after each message body. | true | boolean | |
The number of messages after which the producer closes the file of kind file. The next message opens the file again for another batch of messages. If 0, the producer keeps the file open until it stops. System.out and System.err are never closed, and the stream of kind header is closed after each message. | int | ||
Whether the producer closes the file of kind file after the last message of a Splitter, which is the message with the exchange property CamelSplitComplete set to true. The next message opens the file again. Without it and autoCloseCount, the producer keeps the file open until it stops. | false | boolean | |
The delay in milliseconds before the producer writes each message. | long | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Not used: the component applies no read timeout to any stream, including the connection to httpUrl. | int |
Message Headers
The Stream component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The index of the exchange in the stream, starting at 0 and counting each exchange that the consumer creates: a line, a group of lines, or the bytes of one read. With scanStream and retry, the count goes on after the stream is opened again. | long | |
CamelStreamComplete (consumer) Constant: | Whether the exchange is the last one of the stream. The consumer reads one line ahead to know it, except for kind in, where it is true for each line. Always false with scanStream, as a scanned stream never ends. | boolean |
Message Body
The message body at each side of the Stream component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| Each line of the stream as text. With groupLines, a List of the lines; with readLine=false, all the bytes of the stream (with scanStream, the bytes read in one scan).
Not known when |
Producer input |
| Text in the encoding, or bytes, a stream or a file as bytes, followed by a new line; no body writes nothing. A Map or a POJO is written as its toString() and a List fails: marshal it first. |
Producer output |
|
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Usage
Message content
The Stream component writes text, bytes, a stream or a file: text in the encoding, and the others as bytes, each followed by a new line unless appendNewLine is false. A message with a null body writes nothing. Another body, such as a Map, is written as its toString(), so marshal it first.
The special stream:header URI is used for custom output streams. Just add a java.io.OutputStream object to message.in.header in the key stream.
See samples for an example.
Examples
In the following sample we route messages from the direct:in endpoint to the System.out stream:
-
Java
-
XML
-
YAML
from("direct:in").to("stream:out"); <route>
<from uri="direct:in"/>
<to uri="stream:out"/>
</route> - route:
from:
uri: direct:in
steps:
- to:
uri: stream:out The following sample demonstrates how the header type can be used to determine which stream to use. In the sample we use our own output stream, MyOutputStream.
The following sample demonstrates how to continuously read a file stream (analogous to the UNIX tail command):
-
Java
-
XML
-
YAML
from("stream:file?fileName=/server/logs/server.log&scanStream=true&scanStreamDelay=1000")
.to("bean:logService?method=parseLogLine"); <route>
<from uri="stream:file?fileName=/server/logs/server.log&scanStream=true&scanStreamDelay=1000"/>
<to uri="bean:logService?method=parseLogLine"/>
</route> - route:
from:
uri: stream:file
parameters:
fileName: /server/logs/server.log
scanStream: true
scanStreamDelay: 1000
steps:
- to:
uri: bean:logService
parameters:
method: parseLogLine If you want to re-load the file if it roll over/rewritten then you should also turn on the fileWatcher and retry options.
-
Java
-
XML
-
YAML
from("stream:file?fileName=/server/logs/server.log&scanStream=true&scanStreamDelay=1000&retry=true&fileWatcher=true")
.to("bean:logService?method=parseLogLine"); <route>
<from uri="stream:file?fileName=/server/logs/server.log&scanStream=true&scanStreamDelay=1000&retry=true&fileWatcher=true"/>
<to uri="bean:logService?method=parseLogLine"/>
</route> - route:
from:
uri: stream:file
parameters:
fileName: /server/logs/server.log
scanStream: true
scanStreamDelay: 1000
retry: true
fileWatcher: true
steps:
- to:
uri: bean:logService
parameters:
method: parseLogLine When a scanned stream cannot be opened or read (such as a stream:http server that is down, or a lost connection), the first failure in a row goes to the exception handler and the next ones are logged at DEBUG until data is read again, and with retry the stream is opened again, at least one second after the failure.
Reading HTTP server side streaming
The camel-stream component has basic support for connecting to a remote HTTP server and read streaming data (chunk of data separated by new-line).
-
Java
-
XML
-
YAML
from("stream:http?scanStream=true&httpUrl=http://localhost:8500")
.to("log:input"); <route>
<from uri="stream:http?scanStream=true&httpUrl=http://localhost:8500"/>
<to uri="log:input"/>
</route> - route:
from:
uri: stream:http
parameters:
scanStream: true
httpUrl: "http://localhost:8500"
steps:
- to:
uri: log:input