<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jayway Team Blog &#187; apache</title>
	<atom:link href="http://blog.jayway.com/tag/apache/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Dynamic FTP Client using Apache Camel and Spring</title>
		<link>http://blog.jayway.com/2010/08/12/dynamic-ftp-client-using-apache-camel-and-spring/</link>
		<comments>http://blog.jayway.com/2010/08/12/dynamic-ftp-client-using-apache-camel-and-spring/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 16:48:45 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[camel]]></category>
		<category><![CDATA[FTP]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5743</guid>
		<description><![CDATA[I was recently asked to develop an FTP client that could transmit files to various FTP servers as a part of a delivery system in a Java enterprise application. The requirements dictated a flexible implementation: Three different FTP protocols should be supported, namely FTP, FTPS and SFTP It should be possible to transmit different files [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently asked to develop an FTP client that could transmit files to various FTP servers as a part of a delivery system in a Java enterprise application. The requirements dictated a flexible implementation:</p>
<ul>
<li>Three different FTP protocols should be supported, namely <a href="#FTP">FTP</a>, <a href="#FTPS">FTPS</a> and <a href="#SFTP">SFTP</a></li>
<li>It should be possible to transmit different files to several different servers</li>
<li>The files to be sent were generated in runtime, they had different file names and were stored in different directories</li>
</ul>
<p>Basically, I should implement the following interface:</p>
<h4>FtpSender.java</h4>
<p><a name="FtpSender"></a></p>
<pre class="brush:java">
public interface FtpSender {

    /**
     * Uses the {@code ftpProperties} to transmit the provided {@code file} to a remote server
     *
     * @param ftpProperties The FTP properties of the remote server
     * @param file The file to transmit
     */
    void sendFile(FtpProperties ftpProperties, File file);
}
</pre>
<p>where the FtpProperties was another interface:</p>
<h4>FtpProperties.java</h4>
<pre class="brush:java">
public interface FtpProperties {

    /**
     * Gets the protocol
     * @return One of {@code ftp}, {@code ftps} or {@code sftp}
     */
    String getProtocol();

    /**
     * Gets the user name
     * @return The name of the user
     */
    String getUserName();

    /**
     * Gets the password
     * @return The password
     */
    String getPassword();

    /**
     * Gets the FTP host
     * @return The FTP host
     */
    String getHost();

    /**
     * Gets the name of the directory on the server where the file will be transferred
     * @return The name of the remote directory
     */
    String getRemoteDirectory();

    /**
     * Gets the passive mode, e.g. if the server is behind a firewall
     * @return whether or not passive mode should be used
     */
    boolean getPassiveMode();
}
</pre>
<p>Rather than implementing the entire FTP client from scratch, I investigated the capabilities of existing frameworks. Most solutions recommend using an existing FTP framework such as <a href="http://commons.apache.org/net/">Apache Commons / Jakarta Commons Net</a> for FTP and FTPS and then wrap it in a SSH layer like <a href="http://www.jcraft.com/jsch/">Jsch / Java Secure Channel</a> for SFTP. However, soon I discovered <a href="http://camel.apache.org/">Apache Camel</a>, "a powerful open source integration framework based on known Enterprise Integration Patterns with powerful Bean Integration" (their words). They support a various range of <a href="http://camel.apache.org/components.html">components</a>, anything from XQuery and Atom to XSLT and SQL, just to name a few. To my luck, they also support all three FTP protocols that I needed. </p>
<h2>Fundamentals</h2>
<p>What does the <a href="http://camel.apache.org/ftp2.html">Camel FTP</a> API look like? In its basic form it is a little more than a one-liner:</p>
<h4>FtpRouteBuilder.java</h4>
<p><a name="FtpRouteBuilder"></a></p>
<pre class="brush:java">
public class FtpRouteBuilder extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("file://localDirectory").to("ftp://user@host.com/remoteDirectory?password=secret&passiveMode=true");
    }
}
</pre>
<p>So what is going on here? The <a href="http://camel.apache.org/routebuilder.html">RouteBuilder</a> is one of Camel's core classes that defines the Camel specific <a href="http://camel.apache.org/dsl.html">DSL</a>. In this example, a <a href="http://camel.apache.org/routes.html">Route</a> from the <code>localDirectory</code> to a <code>remoteDirectory</code> over FTP with the provided credentials has been created. As can be seen, it is easy to create and configure different endpoints using <code>String</code> URIs. It should also be mentioned that it is possible to fetch files from the remote FTP server by swapping the URIs in the <code>to</code> and <code>from</code> methods.</p>
<p>A few more lines are needed to activate the route:</p>
<pre class="brush:java">
public static void main(String[]args) throws Exception {
    CamelContext camelContext = new DefaultCamelContext();
    try {
        camelContext.addRoutes(new FtpRouteBuilder());
        camelContext.start();
        // do other stuff...
    }
    finally {
        camelContext.stop();
    }
}
</pre>
<p>A <a href="http://camel.apache.org/camelcontext.html">CamelContext</a> is created for managing the route. The previously described <a href="#FtpRouteBuilder">FtpRouteBuilder</a> is instantiated and added to the camelContext which is subsequently started. As a consequence, any file that is placed in the "localDirectory" folder will be automatically transferred to the "remoteDirectory" of the FTP server while the program is running. </p>
<h2>Adding Configurability</h2>
<p>The requirement of supporting different FTP protocols is solved by changing the URI from <code>ftp://</code> to <code>ftps://</code> or <code>sftp://</code> respectively. It is just as easy to fulfill the second requirement of multiple server support by changing the host, user, port and other parameters of the URI. Likewise, additional settings may be configured by adding more options if needed, see the <a href="http://camel.apache.org/ftp2.html">Camel FTP</a> documentation.</p>
<h2>Adding Dynamism</h2>
<p>The last challenge was to add the dynamic support of selecting source files and destination servers during runtime. The easiest solution is to use another of Camel's base classes, the <a href="http://camel.apache.org/producertemplate.html">ProducerTemplate</a>. Again, the solution is a one-liner:</p>
<pre class="brush:java">
producerTemplate.sendBodyAndHeader("ftp://user@host.com/remoteDirectory?password=secret", file, Exchange.FILE_NAME, file.getName());
</pre>
<p>The <code>sendBodyAndHeader()</code> method name reveals a glimpse of Camel's underlying messaging architecture. The parameters used are the destination URI with additional options, the message body, i.e. the <code>File</code> to be sent, a message header parameter that identifies the last parameter as the name of the file it will have on the remote server once it has been transferred.</p>
<h2>Spring Integration</h2>
<p>With some refactoring and a little Spring magic we have all the bits and pieces needed to implement the previously defined <a href="#FtpSender">FtpSender</a> interface:</p>
<h4>FtpSenderImpl.java</h4>
<pre class="brush:java">
@Service
class FtpSenderImpl implements FtpSender {

    /** Camel URI, format is ftp://user@host/fileName?password=secret&passiveMode=true */
    private static final String CAMEL_FTP_PATTERN = "{0}://{1}@{2}/{3}?password={4}&passiveMode={5}";

    private final ProducerTemplate producerTemplate;

    /**
      * Constructor
      * @param producerTemplate The producer template to be be used
      */
    @Autowired
    FtpSenderImpl(ProducerTemplate producerTemplate) {
        this.producerTemplate = producerTemplate;
    }

    @Override
    public void sendFile(FtpProperties ftpProperties, File file) throws RuntimeException {
        producerTemplate.sendBodyAndHeader(createFtpUri(ftpProperties), file, Exchange.FILE_NAME, fileName);
    }

    /**
      * Creates a Camel FTP URI based on the provided FTP properties
      * @param ftpProperties The properties to be used
      */
    private String createFtpUri(FtpProperties ftpProperties) {
        return MessageFormat.format(CAMEL_FTP_PATTERN,
                ftpProperties.getProtocol(),
                ftpProperties.getUserName(),
                ftpProperties.getHost(),
                ftpProperties.getRemoteDirectory(),
                ftpProperties.getPassword(),
                ftpProperties.getPassiveMode());
    }
}
</pre>
<p>Using the <a href="http://camel.apache.org/spring.html">Camel namespace</a>, the required plumbing work is delegated to the Spring application config:</p>
<h4>spring-config.xml</h4>
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"&gt;

    &lt;!-- Let Spring create the Camel context and the Camel template, including lifecycle management such as starting and stopping them --&gt;
    &lt;camel:camelContext id="camelContext"&gt;
        &lt;camel:template id="camelTemplate" /&gt;
    &lt;/camel:camelContext&gt;

    &lt;!-- Use Spring component scan to find the FtpSenderImpl implementation --&gt;
    &lt;context:component-scan base-package="com.jayway.ftp" /&gt;

&lt;/beans&gt;
</pre>
<h2>Conclusions</h2>
<p>Camel and Spring provide a simple, yet configurable, way of implementing a dynamic FTP client.</p>
<h2>Acknowledgments</h2>
<p>Thanks to Claus Ibsen and other members of the <a href="http://camel.apache.org/discussion-forums.html">Apache Camel Forums</a> for providing valuable and rapid support.</p>
<h2>Glossary</h2>
<ul>
<li><a name="FTP"></a><code>FTP</code> File Transfer Protocol</li>
<li><a name="FTPS"></a><code>FTPS</code> FTP Secure is an extension to FTP that adds support for the TLS, Transport Layer Security, and the SSL, Secure Sockets Layer, cryptographic protocols</li>
<li><a name="SFTP"></a><code>SFTP</code> SSH File Transfer Protocol, i.e. FTP over the Secure Shell protocol</li>
</ul>
<h2>References</h2>
<p><a href="http://camel.apache.org/maven/camel-2.2.0/camel-core/apidocs/index.html">Camel API</a><br />
<a href="http://camel.apache.org/components.html">Camel Components</a><br />
<a href="http://camel.apache.org/ftp2.html">Camel FTP</a><br />
<a href="http://camel.apache.org/producertemplate.html">Camel ProducerTemplate</a><br />
<a href="http://camel.apache.org/spring.html">Camel Spring</a><br />
<a href="http://camel.apache.org/why-does-camel-use-too-many-threads-with-producertemplate.html">Camel ProducerTemplate and Spring</a><br />
<a href="http://camel.apache.org/enterprise-integration-patterns.html">Camel Enterprise Integration Patterns</a><br />
<a href="http://camel.apache.org/discussion-forums.html">Camel Forums</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/08/12/dynamic-ftp-client-using-apache-camel-and-spring/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Configuring Timeout with Apache HttpClient 4.0</title>
		<link>http://blog.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/</link>
		<comments>http://blog.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 15:49:23 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[4.0]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[httpclient]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[timeout]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1174</guid>
		<description><![CDATA[Great news everyone: just recently an all-new version of Apache HttpClient was released. HttpClient is now part of the new initiative Apache HttpComponents, which seems to aim for a complete approach to Http programming in Java; server side as well as client side. I've used Commons HttpClient in older versions on several occasions in the [...]]]></description>
			<content:encoded><![CDATA[<p>Great news everyone: just recently an all-new version of <a href="http://hc.apache.org/httpcomponents-client/index.html">Apache HttpClient</a> was released. HttpClient is now part of the new initiative <a href="http://hc.apache.org/">Apache HttpComponents</a>, which seems to aim for a complete approach to Http programming in Java; server side as well as client side.</p>
<p>I've used Commons HttpClient in older versions on several occasions in the past and have found it to be extremely useful. I've only just started working with the new version, but there seems to quite a lot of good stuff in there. For example I'm thrilled to see that the Template pattern, heavily used in Spring, has now made its way to the Apache world (e.g. <a href="http://hc.apache.org/httpcomponents-client/httpclient/apidocs/org/apache/http/client/ResponseHandler.html">ResponseHandler</a>, a callback interface to be used with <a href="http://hc.apache.org/httpcomponents-client/httpclient/apidocs/org/apache/http/client/HttpClient.html">HttpClient</a> for handling results).</p>
<p>Now, configuration of <code>HttpClient</code> has always been a little bit tricky. There are so many features in there, and most of these are configured using generic parameters (<code>HttpParams</code>), basically name-value pairs of a setting identifier and its value. This has not been made that much easier in the new version.</p>
<p>In my current project I was struggling to find the appropriate parameters for configuring timeouts with the new version of the framework. It turned out to be quite difficult to find clear information on this - the documentation on the 4.0 version of <code>HttpClient</code> is still quite sparse. Since it took me a while to find out how to do this I figured I wasn't alone, so here goes:</p>
<p>My original solution for this problem - being completely unable to find the proper way to do it - was to use the hard-coded property values and set them as parameters in <code>HttpParams</code>. Fortunately, a reader with signature 'BoD' (see below) knew the right way to do this and was kind enough to share. </p>
<p>Right, the code looks as follows:</p>
<pre class="java">&nbsp;
DefaultHttpClient httpClient = <span style="color: #000000; font-weight: bold;">new</span> DefaultHttpClient<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
HttpParams params = httpClient.<span style="color: #006600;">getParams</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
HttpConnectionParams.<span style="color: #006600;">setConnectionTimeout</span><span style="color: #66cc66;">&#40;</span>httpParams, connectionTimeoutMillis<span style="color: #66cc66;">&#41;</span>;
HttpConnectionParams.<span style="color: #006600;">setSoTimeout</span><span style="color: #66cc66;">&#40;</span>httpParams, socketTimeoutMillis<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Simple as that - hard to understand why that should take me so long to figure out <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Thanks again to 'BoD' for setting me straight on this.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>

