<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;C0ABQn0_fip7ImA9WhBUGUQ.&quot;"><id>tag:blogger.com,1999:blog-32637828</id><updated>2013-05-08T06:42:33.346+01:00</updated><category term="uname" /><category term="logging" /><category term="fork-bomb" /><category term="jaxb" /><category term="bug" /><category term="maven" /><category term="permgen" /><category term="Windows MSN Messenger 7.5 software tips tweaks hack" /><category term="Windows" /><category term="scribd" /><category term="Apple" /><category term="guava" /><category term="sybase" /><category term="bios" /><category term="sed" /><category term="nintendo ds" /><category term="eid" /><category term="restore" /><category term="stairs" /><category term="awk" /><category term="pmc" /><category term="factorial" /><category term="personality" /><category term="git" /><category term="multitail" /><category term="rss" /><category term="relational algebra" /><category term="xpath" /><category term="email" /><category term="JMS" /><category term="autosys" /><category term="solaris" /><category term="work" /><category term="crontab" /><category term="scripting" /><category term="facebook" /><category term="system" /><category term="restoration" /><category term="SSH" /><category term="waol.exe" /><category term="cobertura" /><category term="property" /><category term="holiday" /><category term="vivisection" /><category term="humour" /><category term="shutdownhook" /><category term="core-dump" /><category term="memory" /><category term="2007" /><category term="concurrency" /><category term="record" /><category term="read" /><category term="multiplication" /><category term="interview" /><category term="alert" /><category term="&quot;eid in the square&quot;" /><category term="shutdown" /><category term="highlighting" /><category term="network" /><category term="bit-shifting" /><category term="error" /><category term="google" /><category term="feeds" /><category term="moving" /><category term="Vista" /><category term="technology" /><category term="intern" /><category term="Microsoft" /><category term="trafalgar" /><category term="tmux" /><category term="perl" /><category term="fuser" /><category term="serialization" /><category term="pidgin" /><category term="bcp" /><category term="Oracle" /><category term="recover" /><category term="jcommander" /><category term="isobuster" /><category term="ganymede" /><category term="excel" /><category term="plugin" /><category term="shell" /><category term="uptime" /><category term="coursera" /><category term="computer" /><category term="stanford" /><category term="canvas" /><category term="SSL" /><category term="code" /><category term="infinity" /><category term="spoj" /><category term="e-learning" /><category term="cinema imax films" /><category term="hardware" /><category term="promotion" /><category term="alias" /><category term="charts" /><category term="&quot;google chart api&quot;" /><category term="gdb" /><category term="btrace" /><category term="aol" /><category term="howto" /><category term="sqlite" /><category term="associative arrays" /><category term="picitup" /><category term="files" /><category term="version" /><category term="join" /><category term="extrovert" /><category term="regex" /><category term="essay" /><category term="epoch" /><category term="sql" /><category term="Javadoc" /><category term="Linux" /><category term="twitter" /><category term="garbage collection" /><category term="juno" /><category term="commons-config" /><category term="samba" /><category term="Ubuntu" /><category term="questions" /><category term="xstream" /><category term="completion" /><category term="install" /><category term="pictures" /><category term="templates" /><category term="quartz" /><category term="climb" /><category term="space travel" /><category term="funny" /><category term="html5" /><category term="swing" /><category term="searchplugin" /><category term="args4j" /><category term="junit" /><category term="clob" /><category term="rare award" /><category term="sqlplus" /><category term="open source" /><category term="date" /><category term="globbing" /><category term="ocs" /><category term="exceptions" /><category term="stackoverflow" /><category term="firefox" /><category term="dell" /><category term="parallelarray" /><category term="introvert" /><category term="LRO" /><category term="mocking" /><category term="spring" /><category term="tips" /><category term="favicon" /><category term="javaconfig" /><category term="performance" /><category term="vim" /><category term="eclipse" /><category term="review" /><category term="bonus" /><category term="CollabNet" /><category term="cpu" /><category term="laptop" /><category term="java7" /><category term="skip" /><category term="scala" /><category term="wrapper" /><category term="SMTPAppender" /><category term="security" /><category term="shirt" /><category term="animal testing" /><category term="CVS" /><category term="XML" /><category term="algorithm" /><category term="game" /><category term="bash" /><category term="compile" /><category term="fibonacci" /><category term="RMI" /><category term="xmllint" /><category term="hsqldb" /><category term="organise" /><category term="software" /><category term="html" /><category term="weblogic" /><category term="certificate" /><category term="commons-cli" /><category term="release" /><category term="testing" /><category term="studio" /><category term="UNIX" /><category term="whitespace" /><category term="design patterns" /><category term="jdbc" /><category term="IFS" /><category term="moon" /><category term="XP" /><category term="connection" /><category term="firefox3" /><category term="social" /><category term="graphs" /><category term="photos" /><category term="kill" /><category term="vimrc" /><category term="console" /><category term="download" /><category term="find" /><category term="commands" /><category term="delete" /><category term="python" /><category term="browser" /><category term="PS2" /><category term="internet" /><category term="logback" /><category term="mbeans" /><category term="singapore" /><category term="age" /><category term="csv" /><category term="syntaxhighlighter" /><category term="file" /><category term="mockito" /><category term="addon" /><category term="jmx" /><category term="database" /><category term="brain training" /><category term="debug" /><category term="sharing" /><category term="Islam" /><category term="hibernate" /><category term="ant" /><category term="sso" /><category term="process" /><category term="programming" /><category term="document" /><category term="mount" /><category term="broadband" /><category term="&quot;vertical rush&quot; stairs climb" /><category term="webdesign" /><category term="hampton court" /><category term="grc" /><category term="Java" /><category term="trip" /><category term="null" /><category term="life" /><category term="keytool" /><category term="log4j" /><category term="OPML" /><category term="pro/con" /><category term="food" /><category term="search" /><category term="house" /><category term="vtd-xml" /><category term="GC" /><category term="Kawashima" /><category term="slashdot" /><category term="&quot;vertical rush&quot;" /><category term="tweaks" /><category term="jconsole" /><category term="reader" /><category term="profiling" /><category term="fork-join" /><category term="NASA" /><category term="deadlock" /><category term="utilities" /><category term="hermes" /><category term="profile" /><category term="jdk7" /><title>fahd.blog</title><subtitle type="html">Let the code do the talking...</subtitle><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://fahdshariff.blogspot.com/" /><link rel="next" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default?start-index=26&amp;max-results=25&amp;redirect=false&amp;v=2" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>274</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/Fahdblog" /><feedburner:info uri="fahdblog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>Fahdblog</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><entry gd:etag="W/&quot;CUIFSHs6fSp7ImA9WhBUEUg.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-3661005358446319766</id><published>2013-04-28T13:51:00.000+01:00</published><updated>2013-04-28T13:51:59.515+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-04-28T13:51:59.515+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="UNIX" /><category scheme="http://www.blogger.com/atom/ns#" term="commands" /><category scheme="http://www.blogger.com/atom/ns#" term="shell" /><category scheme="http://www.blogger.com/atom/ns#" term="scripting" /><title>Useless Use of Grep</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
Most of us are familiar with the infamous &lt;a href="http://partmaps.org/era/unix/award.html"&gt;Useless Use of Cat Award&lt;/a&gt; which is awarded for unnecessary use of the &lt;code&gt;cat&lt;/code&gt; command. A while back, I also wrote about &lt;a href="http://fahdshariff.blogspot.co.uk/2012/12/useless-use-of-echo.html"&gt;Useless Use of Echo&lt;/a&gt; in which I advised using &lt;a href="http://linux.die.net/abs-guide/x15683.html"&gt;here-strings&lt;/a&gt; and &lt;a href="http://en.wikipedia.org/wiki/Here_document"&gt;here-docs&lt;/a&gt; instead of the &lt;code&gt;echo&lt;/code&gt; command. In a similar vein, this post is about the useless use of the &lt;code&gt;grep&lt;/code&gt; command.
&lt;p/&gt;
&lt;b&gt;&lt;font color="#000099"&gt;Useless use of &lt;code&gt;grep | awk&lt;/code&gt; &lt;/font&gt;&lt;/b&gt;&lt;/br&gt;
&lt;code&gt;awk&lt;/code&gt; can match patterns, so there is no need to pipe the output of &lt;code&gt;grep&lt;/code&gt; to &lt;code&gt;awk&lt;/code&gt;. For example, the following:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;grep pattern file | awk '{commands}'&lt;/font&gt;&lt;/pre&gt;
can be re-written as:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;awk '/pattern/{commands}' file&lt;/font&gt;&lt;/pre&gt;
Similarly:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;grep -v pattern file | awk '{commands}'&lt;/font&gt;&lt;/pre&gt;
can be re-written as:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;awk '!/pattern/{commands}' file&lt;/font&gt;&lt;/pre&gt;

&lt;p/&gt;
&lt;b&gt;&lt;font color="#000099"&gt;Useless use of &lt;code&gt;grep | sed&lt;/code&gt; &lt;/font&gt;&lt;/b&gt;&lt;/br&gt;
&lt;code&gt;sed&lt;/code&gt; can match patterns, so you don't need to pipe the output of &lt;code&gt;grep&lt;/code&gt; to &lt;code&gt;sed&lt;/code&gt;. For example, the following:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;grep pattern file | sed 's/foo/bar/g'&lt;/font&gt;&lt;/pre&gt;
can be re-written as:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;sed -n '/pattern/{s/foo/bar/p}' file&lt;/font&gt;&lt;/pre&gt;
Similarly:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;grep -v pattern file | sed 's/foo/bar/g'&lt;/font&gt;&lt;/pre&gt;
can be re-written as:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;sed -n '/pattern/!{s/foo/bar/p}' file&lt;/font&gt;&lt;/pre&gt;
&lt;p/&gt;

&lt;b&gt;&lt;font color="#000099"&gt;Useless use of &lt;code&gt;grep&lt;/code&gt; in conditions&lt;/font&gt;&lt;/b&gt;&lt;/br&gt;
If you find yourself using &lt;code&gt;grep&lt;/code&gt; in conditional statements to check if a string variable matches a certain pattern, consider using bash's in-built string matching instead. For example, the following:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;if grep -q pattern &lt;&lt;&lt; "$var"; then
    # do something
fi
&lt;/font&gt;&lt;/pre&gt;
can be re-written as:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;if [[ $var == *pattern* ]]; then
    # do something
fi
&lt;/font&gt;&lt;/pre&gt;
or, if your pattern is a regex, rather than a fixed string, use:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;if [[ $var =~ pattern ]]; then
    # do something
fi
&lt;/font&gt;&lt;/pre&gt;
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/PczwsNkU_VQ" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/3661005358446319766/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/04/useless-use-of-grep.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/3661005358446319766?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/3661005358446319766?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/PczwsNkU_VQ/useless-use-of-grep.html" title="Useless Use of Grep" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/04/useless-use-of-grep.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEYGSXc-fip7ImA9WhBUEEs.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-4069876524450157200</id><published>2013-04-27T12:28:00.000+01:00</published><updated>2013-04-27T12:28:48.956+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-04-27T12:28:48.956+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="commons-config" /><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><title>Adding Java System Properties from a Properties File</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
&lt;a href="http://commons.apache.org/proper/commons-configuration/"&gt;Apache Commons Configuration&lt;/a&gt; provides a very easy way to load a properties file into the system properties:
&lt;pre class="brush:java; gutter:false;"&gt;
try {
  final PropertiesConfiguration propsConfig = new PropertiesConfiguration(
                                              Foo.class.getResource("foo.properties"));
  SystemConfiguration.setSystemProperties(propsConfig);
} catch (Exception e) {
  throw new RuntimeException("Failed to load config file: " + propsFile, e);
}
&lt;/pre&gt;
If you are unable to use this library, then you will have to use the longer, more tedious approach of loading the properties file, iterating over the properties and setting each one into the system properties. This is shown below:
&lt;pre class="brush:java; gutter:false;"&gt;
final Properties props = new Properties();
final InputStream in = Foo.class.getResourceAsStream("foo.properties");
try {
  props.load(in);
  for (final Entry&amp;lt;Object, Object&amp;gt; entry : props.entrySet()) {
    System.setProperty(entry.getKey().toString(), entry.getValue().toString());
  }
} catch (IOException e) {
  throw new RuntimeException("Failed to load properties", e);
}
finally {
  try {
    in.close();
  } catch (IOException e) {
    // don't care
  }
}
&lt;/pre&gt;
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/7O5uzxMa574" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/4069876524450157200/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/04/adding-java-system-properties-from.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/4069876524450157200?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/4069876524450157200?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/7O5uzxMa574/adding-java-system-properties-from.html" title="Adding Java System Properties from a Properties File" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/04/adding-java-system-properties-from.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEAAQXg6eCp7ImA9WhBXGEw.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-6259533377894691040</id><published>2013-04-01T11:39:00.000+01:00</published><updated>2013-04-01T11:39:00.610+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-04-01T11:39:00.610+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="shutdownhook" /><category scheme="http://www.blogger.com/atom/ns#" term="spring" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><title>Gracefully Shutting Down Spring Applications</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
To gracefully shutdown your spring (non-web) application, you should do two things:
&lt;p/&gt;
&lt;b&gt;&lt;font color="#000099"&gt;1. Register a shutdown hook &lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
Call &lt;a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/support/AbstractApplicationContext.html#registerShutdownHook()"&gt;&lt;code&gt;registerShutdownHook()&lt;/code&gt;&lt;/a&gt; that is declared in the &lt;a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/support/AbstractApplicationContext.html"&gt;&lt;code&gt;AbstractApplicationContext&lt;/code&gt;&lt;/a&gt; class in order to register a shutdown hook with the JVM. I wrote about Shutdown Hooks in a &lt;a href="http://fahdshariff.blogspot.co.uk/2008/06/shutting-down-java-apps-howto.html"&gt;previous post&lt;/a&gt;. They allow your application to perform "clean up" when the JVM exits either naturally or with a &lt;code&gt;kill&lt;/code&gt;/Ctrl+C signal. Spring's shutdown hook closes your application context and hence calls the relevant destroy methods on your beans so that all resources are released (provided that the destroy callbacks have been implemented correctly!). Also, note that no guarantee can be made about whether or not any shutdown hooks will be run if the JVM aborts with the SIGKILL signal (kill -9) on Unix or the TerminateProcess call on MS Windows.
&lt;p/&gt;
&lt;b&gt;&lt;font color="#000099"&gt;2. Close the context in a &lt;code&gt;finally&lt;/code&gt; block&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
You should also call &lt;code&gt;close()&lt;/code&gt; on your application context in a &lt;code&gt;finally&lt;/code&gt; block. This is because if your application throws an unhandled &lt;code&gt;RuntimeException&lt;/code&gt;, you might have background threads, started by some beans, still running and your JVM will not terminate. That's why you need to explicitly close the application context.
&lt;p/&gt;
Putting these two steps together, you get the following code:
 
&lt;pre class="brush:java; gutter:false;"&gt;
public static void main(final String... args) {
  AbstractApplicationContext appContext = null;
  try {
    appContext = new AnnotationConfigApplicationContext("my.app.package");
    appContext.registerShutdownHook();
    final MyApp app = appContext.getBean(MyApp.class);
    app.doSomething();
  } catch (final Exception e) {
    // handle exceptions properly here
    e.printStackTrace();
  } finally {
    if (appContext != null) {
      ((AnnotationConfigApplicationContext) appContext).close();
    }
  }
}
&lt;/pre&gt;
 
&lt;b&gt;&lt;font color="#000099"&gt;Related Posts:&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;a href="http://fahdshariff.blogspot.co.uk/2008/06/shutting-down-java-apps-howto.html"&gt;Shutting Down Java Apps [Howto]&lt;/a&gt;
 
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/CvZJCMioUUo" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/6259533377894691040/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/04/gracefully-shutting-down-spring.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/6259533377894691040?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/6259533377894691040?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/CvZJCMioUUo/gracefully-shutting-down-spring.html" title="Gracefully Shutting Down Spring Applications" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/04/gracefully-shutting-down-spring.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkMBR3k9fyp7ImA9WhBXF0g.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-3959143976904350961</id><published>2013-03-31T19:27:00.001+01:00</published><updated>2013-03-31T19:27:36.767+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-03-31T19:27:36.767+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><category scheme="http://www.blogger.com/atom/ns#" term="junit" /><title>JUnit: Creating Temporary Files using the TemporaryFolder @Rule</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
If you have an application that writes out files, how do you test that the generated file is correct?
&lt;p/&gt;
One approach, is to configure the application to write out to some pre-defined temporary location such as &lt;code&gt;/tmp&lt;/code&gt; (on *nix based systems) and then delete the files after the test. But this requires a lot of boilerplate code in your unit tests and can be error prone. Sometimes, developers forget to clean up these temporary files and leave a mess behind. I have also seen cases where unit tests have written temporary files to the current directory (which contains test code) and developers have accidently checked them into source control, which definitely shouldn't happen!
&lt;p/&gt;
The right way to deal with temporary files in unit tests is by using &lt;a href="http://junit-team.github.com/junit/javadoc/4.10/org/junit/rules/TemporaryFolder.html"&gt;JUnit's &lt;code&gt;TemporaryFolder&lt;/code&gt; Rule&lt;/a&gt;. With it, you no longer need to worry about where to create your temporary files or deleting them after the test succeeds or fails. JUnit handles all of that for you.
&lt;p/&gt;
The following example shows you how to use the &lt;code&gt;TemporaryFolder&lt;/code&gt; Rule:

&lt;pre class="brush:java; gutter:false;"&gt;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class MyTest {

  @Rule
  public TemporaryFolder tempFolder = new TemporaryFolder();

  @Test
  public void testWrite() throws IOException {
    // Create a temporary file.
    // This is guaranteed to be deleted after the test finishes.
    final File tempFile = tempFolder.newFile("myfile.txt");

    // Write something to it.
    FileUtils.writeStringToFile(tempFile, "hello world");

    // Read it.
    final String s = FileUtils.readFileToString(tempFile);

    // Check that what was written is correct.
    assertThat("hello world", is(s));
  }
}
&lt;/pre&gt;
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/T3yprijWRZQ" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/3959143976904350961/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/03/junit-creating-temporary-files-using.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/3959143976904350961?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/3959143976904350961?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/T3yprijWRZQ/junit-creating-temporary-files-using.html" title="JUnit: Creating Temporary Files using the TemporaryFolder @Rule" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/03/junit-creating-temporary-files-using.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUcCQXs-eSp7ImA9WhBXF04.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-807073972485106391</id><published>2013-03-31T13:28:00.000+01:00</published><updated>2013-03-31T13:31:00.551+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-03-31T13:31:00.551+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><category scheme="http://www.blogger.com/atom/ns#" term="junit" /><title>JUnit: Naming Individual Test Cases in a Parameterized Test</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
A couple of years ago I wrote about &lt;a href="http://fahdshariff.blogspot.co.uk/2011/06/parameterized-tests-in-junit.html"&gt;JUnit Parameterized Tests&lt;/a&gt;. One of the things I didn't like about them was that JUnit named the invidividual test cases using numbers, so if they failed you had no idea which test parameters caused the failure. The following Eclipse screenshot will show you what I mean:
&lt;p/&gt;
&lt;center&gt;&lt;a href="http://2.bp.blogspot.com/-K0tGnNsjT0E/UVgqEUAViuI/AAAAAAAAC5U/-eDFt7sRcsw/s1600/junit_before.png" imageanchor="1" &gt;&lt;img alt="A parameterised test without names" border="0" src="http://2.bp.blogspot.com/-K0tGnNsjT0E/UVgqEUAViuI/AAAAAAAAC5U/-eDFt7sRcsw/s1600/junit_before.png" /&gt;&lt;/a&gt;&lt;/center&gt;
&lt;p/&gt;
However, in JUnit 4.11, the &lt;code&gt;@Parameters&lt;/code&gt; annotation now takes a &lt;code&gt;name&lt;/code&gt; argument which can be used to display the parameters in the test name and hence, make them more descriptive. You can use the following placeholders in this argument and they will be replaced by actual values at runtime by JUnit:
&lt;ul&gt;
  &lt;li&gt;&lt;code&gt;{index}&lt;/code&gt;: the current parameter index&lt;/li&gt;
  &lt;li&gt;&lt;code&gt;{0}&lt;/code&gt;, &lt;code&gt;{1}&lt;/code&gt;, ...: the first, second, and so on, parameter value&lt;/li&gt;
&lt;/ul&gt;
Here is an example:
&lt;p/&gt;
&lt;pre class="brush:java; gutter:false;"&gt;
import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class StringSortTest {

  @Parameters(name = "{index}: sort[{0}]={1}")
  public static Collection&amp;lt;Object[]&amp;gt; data() {
    return Arrays.asList(new Object[][] {
          { "abc", "abc"},
          { "cba", "abc"},
          { "abcddcba", "aabbccdd"},
          { "a", "a"},
          { "aaa", "aaa"},
          { "", ""}
        });
  }

  private final String input;
  private final String expected;

  public StringSortTest(final String input, final String expected){
    this.input = input;
    this.expected = expected;
  }

  @Test
  public void testSort(){
    assertEquals(expected, sort(input));
  }

  private static String sort(final String s) {
    final char[] charArray = s.toCharArray();
    Arrays.sort(charArray);
    return new String(charArray);
  }
}
&lt;/pre&gt;
When you run the test, you will see individual test cases named as shown in the Eclipse screenshot below, so it is easy to identify the parameters used in each test case.
&lt;p/&gt;
&lt;center&gt;&lt;a href="http://2.bp.blogspot.com/-obv2c4EDJJQ/UVgqGiCBLaI/AAAAAAAAC5c/sqbXOTlZIqo/s1600/junit_after.png" imageanchor="1" &gt;&lt;img alt="A parameterised test with individual test case naming" border="0" src="http://2.bp.blogspot.com/-obv2c4EDJJQ/UVgqGiCBLaI/AAAAAAAAC5c/sqbXOTlZIqo/s1600/junit_after.png" /&gt;&lt;/a&gt;&lt;/center&gt;
&lt;p/&gt;
Note that due to a &lt;a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=102512"&gt;bug&lt;/a&gt; in Eclipse, names containing brackets are truncated. That's why I had to use &lt;code&gt;sort[{0}]&lt;/code&gt;, instead of &lt;code&gt;sort({0})&lt;/code&gt;.
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/ZgtT7ljzuAk" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/807073972485106391/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/03/junit-naming-individual-test-cases-in.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/807073972485106391?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/807073972485106391?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/ZgtT7ljzuAk/junit-naming-individual-test-cases-in.html" title="JUnit: Naming Individual Test Cases in a Parameterized Test" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/-K0tGnNsjT0E/UVgqEUAViuI/AAAAAAAAC5U/-eDFt7sRcsw/s72-c/junit_before.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/03/junit-naming-individual-test-cases-in.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUAASHg-eCp7ImA9WhBXEEk.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-1125013531354093140</id><published>2013-03-23T13:02:00.000Z</published><updated>2013-03-23T13:02:29.650Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-03-23T13:02:29.650Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><category scheme="http://www.blogger.com/atom/ns#" term="jaxb" /><title>JAXB MarshalException: Missing an @XmlRootElement Annotation</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;

When marshalling JAXB objects you might get an exception about a missing &lt;code&gt;@XmlRootElement&lt;/code&gt; annotation. For example:

&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;color:red"&gt;
javax.xml.bind.MarshalException - with linked exception: 
[com.sun.istack.SAXException2: unable to marshal type "FooType"
as an element because it is missing an @XmlRootElement annotation]
&lt;/pre&gt;

In order to resolve this issue, use the &lt;a href="http://jaxb.java.net/2.1.2/docs/vendorCustomizations.html#simple"&gt;&lt;code&gt;simple&lt;/code&gt;&lt;/a&gt; binding mode to generate your JAXB classes.
&lt;p/&gt;
Create the following binding file:

&lt;pre class="brush:xml; gutter:false;"&gt;
&amp;lt;jaxb:bindings jaxb:extensionBindingPrefixes="xjc" version="2.1"
  xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
  xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"&amp;gt;
  &amp;lt;jaxb:globalBindings&amp;gt;
    &amp;lt;xjc:simple/&amp;gt;
  &amp;lt;/jaxb:globalBindings&amp;gt;
&amp;lt;/jaxb:bindings&amp;gt;
&lt;/pre&gt;

Pass this file to &lt;code&gt;xjc&lt;/code&gt; or &lt;code&gt;wsdl2java&lt;/code&gt; using the &lt;code&gt;-b&lt;/code&gt; option.
&lt;p/&gt;
You should now see &lt;code&gt;@XmlRootElement&lt;/code&gt; annotations on your classes.
&lt;p/&gt;
&lt;/span&gt;
&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/ymEzBjS5wcg" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/1125013531354093140/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/03/jaxb-marshalexception-missing.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/1125013531354093140?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/1125013531354093140?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/ymEzBjS5wcg/jaxb-marshalexception-missing.html" title="JAXB MarshalException: Missing an @XmlRootElement Annotation" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>2</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/03/jaxb-marshalexception-missing.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkUNSH49fyp7ImA9WhBSFk8.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-1518368106031271122</id><published>2013-02-23T11:51:00.000Z</published><updated>2013-02-23T11:51:39.067Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-02-23T11:51:39.067Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="sqlite" /><title>Comparing CSV Data Files Using SQLite</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
Whenever I have to compare large datasets generated by two different environments, such as Production and QA, I tend to load the data into a &lt;a href="http://www.sqlite.org"&gt;SQLite&lt;/a&gt; database first and then run SQL queries to diff the data.
&lt;p/&gt;
The code below shows how you can import CSV files into SQLite:

&lt;pre class="brush:sql; gutter:false;"&gt;
-- create the tables to hold the data
CREATE TABLE dataProd (id text, price numeric);
CREATE TABLE dataQA   (id text, price numeric);

-- import the data
.separator ","
.import /path/prod/data.csv dataProd
.import /path/qa/data.csv dataQA

.headers ON

-- find differences between data
SELECT p.id,
       p.price as prodPrice,
       q.price as qaPrice,
       abs(p.price-q.price) as diff
FROM dataProd p, dataQA q
WHERE p.id = q.id
AND p.price &amp;lt;&amp;gt; q.price
&lt;/pre&gt;
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/r3A1TCVccII" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/1518368106031271122/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/02/comparing-csv-data-files-using-sqlite.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/1518368106031271122?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/1518368106031271122?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/r3A1TCVccII/comparing-csv-data-files-using-sqlite.html" title="Comparing CSV Data Files Using SQLite" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/02/comparing-csv-data-files-using-sqlite.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CU8ASHc6fSp7ImA9WhBSEUw.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-5595879891888282992</id><published>2013-02-17T15:10:00.001Z</published><updated>2013-02-17T15:10:49.915Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-02-17T15:10:49.915Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="spring" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><title>Retrying Operations using Spring's RetryTemplate</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
Back in 2009, I blogged about &lt;a href="http://fahdshariff.blogspot.com/2009/08/retrying-operations-in-java.html"&gt;Retrying Operations in Java&lt;/a&gt; in which I covered three different approaches to retrying operations on failure. Here is another alternative:
&lt;p/&gt;
If your application is using &lt;a href="http://www.springsource.org/"&gt;Spring&lt;/a&gt; then it is easier to use the Spring Framework's &lt;a href="http://static.springsource.org/spring-batch/reference/html/retry.html"&gt;&lt;code&gt;RetryTemplate&lt;/code&gt;&lt;/a&gt;.
&lt;p/&gt;
The example below shows how you can use a &lt;code&gt;RetryTemplate&lt;/code&gt; to lookup a remote object. If the remote call fails, it will be retried five times with exponential backoff.
&lt;pre class="brush:java; gutter:false;"&gt;
// import the necessary classes
import org.springframework.batch.retry.RetryCallback;
import org.springframework.batch.retry.RetryContext;
import org.springframework.batch.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.batch.retry.policy.SimpleRetryPolicy;
import org.springframework.batch.retry.support.RetryTemplate;
...

// create the retry template
final RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new SimpleRetryPolicy(5));
final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(1000L);
template.setBackOffPolicy(backOffPolicy);

// execute the operation using the retry template
template.execute(new RetryCallback&amp;lt;Remote&amp;gt;() {
  @Override
  public Remote doWithRetry(final RetryContext context) throws Exception {
    return (Remote) Naming.lookup("rmi://somehost:2106/MyApp");
  }
});
&lt;/pre&gt;
&lt;b&gt;&lt;font color="#000099"&gt;Related Posts:&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;a href="http://fahdshariff.blogspot.com/2009/08/retrying-operations-in-java.html"&gt;Retrying Operations in Java&lt;/a&gt;


&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/SOCF0d8Acr4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/5595879891888282992/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/02/retrying-operations-using-springs.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/5595879891888282992?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/5595879891888282992?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/SOCF0d8Acr4/retrying-operations-using-springs.html" title="Retrying Operations using Spring's RetryTemplate" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/02/retrying-operations-using-springs.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEUER38_fCp7ImA9WhBSEE0.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-3748361918259646403</id><published>2013-02-16T09:16:00.002Z</published><updated>2013-02-16T09:16:46.144Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-02-16T09:16:46.144Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="stackoverflow" /><title>stackoverflow - 50k rep</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
Five months after crossing the &lt;a href="http://fahdshariff.blogspot.co.uk/2012/09/stackoverflow-40k-rep.html"&gt;40k milestone&lt;/a&gt;, I've now reached a reputation of &lt;b&gt;50k&lt;/b&gt; on &lt;a href="http://stackoverflow.com"&gt;stackoverflow&lt;/a&gt;!
&lt;p/&gt;
The following table shows some stats about my journey so far:
&lt;table cellpadding="2" style="background-color:#f8f8f8; border-collapse:collapse; border-width:1px; font-size:12px;margin:18px 0pt !important; border:1px solid #BBBBBB; padding:5px;"&gt;
  &lt;tr&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt; &lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt;0-10k&lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt;10-20k&lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt;20-30k&lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt;30-40k&lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt;40-50k&lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt;Total&lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Date achieved&lt;/td&gt;
    &lt;td&gt;01/2011&lt;/td&gt;
    &lt;td&gt;05/2011&lt;/td&gt;
    &lt;td&gt;01/2012&lt;/td&gt;
    &lt;td&gt;09/2012&lt;/td&gt;
    &lt;td&gt;02/2013&lt;/td&gt;
    &lt;td&gt; &lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Questions answered&lt;/td&gt;
    &lt;td&gt;546&lt;/td&gt;
    &lt;td&gt;376&lt;/td&gt;
    &lt;td&gt;253&lt;/td&gt;
    &lt;td&gt;139&lt;/td&gt;
    &lt;td&gt;192&lt;/td&gt;
    &lt;td&gt;1506&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Questions asked&lt;/td&gt;
    &lt;td&gt;46&lt;/td&gt;
    &lt;td&gt;1&lt;/td&gt;
    &lt;td&gt;6&lt;/td&gt;
    &lt;td&gt;0&lt;/td&gt;
    &lt;td&gt;1&lt;/td&gt;
    &lt;td&gt;54&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Tags covered&lt;/td&gt;
    &lt;td&gt;609&lt;/td&gt;
    &lt;td&gt;202&lt;/td&gt;
    &lt;td&gt;83&lt;/td&gt;
    &lt;td&gt;10&lt;/td&gt;
    &lt;td&gt;42&lt;/td&gt;
    &lt;td&gt;946&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Badges &lt;br/&gt;(gold, silver, bronze)&lt;/td&gt;
    &lt;td&gt;35&lt;br/&gt;(2, 10, 23)&lt;/td&gt;
    &lt;td&gt;14&lt;br/&gt;(0, 4, 10)&lt;/td&gt;
    &lt;td&gt;33&lt;br/&gt;(2, 8, 23)&lt;/td&gt;
    &lt;td&gt;59&lt;br/&gt;(3, 20, 36)&lt;/td&gt;
    &lt;td&gt;49&lt;br/&gt;(0, 19, 30)&lt;/td&gt;
    &lt;td&gt;190&lt;br/&gt;(7, 61, 122)&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
As I mentioned &lt;a href="http://fahdshariff.blogspot.co.uk/2012/09/stackoverflow-40k-rep.html"&gt;before&lt;/a&gt;, I have really enjoyed being a member of stackoverflow. For me, it has not simply been a quest for reputation, but more about learning new technologies and picking up advice from other people on the site. I like to take on challenging questions, rather than the easy ones, because it pushes me to do research into areas I have never looked at before, and I learn so much during the process.
&lt;p/&gt;
Next stop, 60k!
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/oaJVmfsxui0" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/3748361918259646403/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/02/stackoverflow-50k-rep.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/3748361918259646403?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/3748361918259646403?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/oaJVmfsxui0/stackoverflow-50k-rep.html" title="stackoverflow - 50k rep" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/02/stackoverflow-50k-rep.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0YDRXY6fip7ImA9WhBTFE4.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-5312365989683570145</id><published>2013-02-09T18:39:00.000Z</published><updated>2013-02-09T18:39:34.816Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-02-09T18:39:34.816Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="UNIX" /><category scheme="http://www.blogger.com/atom/ns#" term="commands" /><title>Selecting Specific Lines of a File Using Head, Tail and Sed</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
This post contains a few handy commands used to select specific lines from a file.
&lt;p/&gt;
&lt;b&gt;&lt;font color="#000099"&gt;Print the first N lines&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;head -N file&lt;/font&gt;&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;Print the last N lines&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;tail -N file&lt;/font&gt;&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;Print all EXCEPT the first N lines&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;tail +$((N+1)) file&lt;/font&gt;&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;Print all EXCEPT the last N lines&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;head -n -N file&lt;/font&gt;&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;Print lines N to M (inclusive)&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;sed -n 'N,Mp' file&lt;/font&gt;&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;Print line N&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;sed 'Nq;d' file&lt;/font&gt;&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;Print all EXCEPT line N&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;sed 'Nd' file&lt;/font&gt;&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;Print multiple lines, I, J, K etc&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
Assuming I &amp;gt; J &amp;gt;  K:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;font color="green"&gt;sed 'Ip;Jp;Kq;d' file&lt;/font&gt;&lt;/pre&gt;
The last &lt;code&gt;q&lt;/code&gt; tells &lt;code&gt;sed&lt;/code&gt; to quit when it reaches the Kth line instead of looping over the remaining lines that we are not interested in.

&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/Qj-OV7M0Btc" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/5312365989683570145/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/02/selecting-specific-lines-of-file-using.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/5312365989683570145?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/5312365989683570145?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/Qj-OV7M0Btc/selecting-specific-lines-of-file-using.html" title="Selecting Specific Lines of a File Using Head, Tail and Sed" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/02/selecting-specific-lines-of-file-using.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkQCRH0-fyp7ImA9WhNaGE0.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-7121499307654283603</id><published>2013-02-02T11:26:00.000Z</published><updated>2013-02-02T11:26:05.357Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-02-02T11:26:05.357Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><category scheme="http://www.blogger.com/atom/ns#" term="guava" /><title>Guava Table</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
Guava's &lt;code&gt;&lt;a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html"&gt;Table&amp;lt;R, C, V&amp;gt;&lt;/a&gt;&lt;/code&gt; is a useful alternative to nested maps of the form &lt;code&gt;Map&amp;lt;R, Map&amp;lt;C, V&amp;gt;&amp;gt;&lt;/code&gt;. For example, if you want to store a collection of &lt;code&gt;Person&lt;/code&gt; objects keyed on both &lt;code&gt;firstName&lt;/code&gt; and &lt;code&gt;lastName&lt;/code&gt;, instead of using something like a &lt;code&gt;Map&amp;lt;FirstName, Map&amp;lt;LastName, Person&amp;gt;&amp;gt;&lt;/code&gt;, it is easier to use a &lt;code&gt;Table&amp;lt;FirstName, LastName, Person&amp;gt;&lt;/code&gt;.
&lt;p/&gt;
Here is an example:

&lt;pre class="brush:java; gutter:false;"&gt;
final Table&amp;lt;String, String, Person&amp;gt; table = HashBasedTable.create();
table.put("Alice", "Smith", new Person("Alice", "Smith"));
table.put("Bob", "Smith", new Person("Bob", "Smith"));
table.put("Charlie", "Jones", new Person("Charlie", "Jones"));
table.put("Bob", "Jones", new Person("Bob", "Jones"));

// get all persons with a surname of Smith
final Collection&amp;lt;Person&amp;gt; smiths = table.column("Smith").values();

// get all persons with a firstName of Bob
final Collection&amp;lt;Person&amp;gt; bobs = table.row("Bob").values();

// get a specific person
final Person alice = table.get("Alice", "Smith");
&lt;/pre&gt;
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/sva2ccdDrLc" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/7121499307654283603/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/02/guava-table.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/7121499307654283603?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/7121499307654283603?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/sva2ccdDrLc/guava-table.html" title="Guava Table" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/02/guava-table.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0UMR30zfyp7ImA9WhNUFU0.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-2167661372538295738</id><published>2013-01-06T19:41:00.000Z</published><updated>2013-01-06T19:41:26.387Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-01-06T19:41:26.387Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="e-learning" /><category scheme="http://www.blogger.com/atom/ns#" term="coursera" /><category scheme="http://www.blogger.com/atom/ns#" term="scala" /><title>Coursera class: Functional Programming Principles in Scala</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
I thought I'd mention that one of my highlights of last year was completing the "&lt;a href="https://class.coursera.org/progfun-2012-001/class"&gt;Functional Programming Principles in Scala&lt;/a&gt;" class led by &lt;a href="http://en.wikipedia.org/wiki/Martin_Odersky"&gt;Martin Odersky&lt;/a&gt;, the designer of &lt;a href="http://www.scala-lang.org/"&gt;Scala&lt;/a&gt;. This &lt;a href="https://www.coursera.org"&gt;Coursera&lt;/a&gt; class started in September 2012 and was around 7 weeks long. Learning about functional programming was a rewarding experience and I found the course and assignments quite challenging, but immensely enjoyable. I even managed to get a distinction! I believe this course will be running again this year and I'd highly recommend it to people who wish to discover functional programming and Scala.
&lt;p/&gt;
I have committed my assignment solutions to my &lt;a href="https://github.com/sharfah/scala-coursera"&gt;GitHub repository&lt;/a&gt;.
&lt;p/&gt;
I am now looking forward to starting some &lt;a href="https://www.coursera.org/"&gt;new classes&lt;/a&gt; in 2013!
&lt;p/&gt;
&lt;b&gt;&lt;font color="#000099"&gt;Related posts:&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;a href="http://fahdshariff.blogspot.com/2011/12/stanfords-online-courses-ml-class-ai.html"&gt;Stanford's Online Courses: ml-class, ai-class and db-class&lt;/a&gt;
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/Keqb6OmUQ1s" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/2167661372538295738/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/01/coursera-class-functional-programming.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/2167661372538295738?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/2167661372538295738?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/Keqb6OmUQ1s/coursera-class-functional-programming.html" title="Coursera class: Functional Programming Principles in Scala" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/01/coursera-class-functional-programming.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0MDSHgyfCp7ImA9WhNUEEg.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-3499678399014995334</id><published>2013-01-01T15:51:00.000Z</published><updated>2013-01-01T15:51:19.694Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2013-01-01T15:51:19.694Z</app:edited><title>fahd.blog in 2012</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
&lt;b&gt;&lt;font color="#000099"&gt;Happy 2013!&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
I'd like to wish everyone a great start to an even greater new year!
&lt;p/&gt;
During 2012, I posted 31 new entries on &lt;a href="http://fahshariff.blogspot.com"&gt;fahd.blog&lt;/a&gt;. I am also thrilled that I have more readers from all over the world too! Thanks for reading and especially for giving feedback.
&lt;p/&gt;
&lt;b&gt;&lt;font color="#000099"&gt;Top 5 posts of 2012:&lt;/font&gt;&lt;/b&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://fahdshariff.blogspot.com/2012/08/analysing-java-core-dump.html"&gt;Analysing a Java Core Dump&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://fahdshariff.blogspot.com/2012/09/spring-3-javaconfig-loading-properties.html"&gt;Spring 3 - JavaConfig: Loading a Properties File&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://fahdshariff.blogspot.com/2012/04/using-namedquery-with-composite-id-in.html"&gt;Using a NamedQuery with a Composite ID in Hibernate&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://fahdshariff.blogspot.com/2012/04/sybase-how-to-bcp-data-in-and-out-of.html"&gt;Sybase: How to BCP data in and out of databases&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://fahdshariff.blogspot.com/2012/08/java-7-forkjoin-framework-example.html"&gt;Java 7: Fork/Join Framework Example&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
I'm going to be writing a lot more this year, so stay tuned for more great techie tips, tricks and hacks! :)
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/x8jL8VTXhmA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/3499678399014995334/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2013/01/fahdblog-in-2012.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/3499678399014995334?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/3499678399014995334?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/x8jL8VTXhmA/fahdblog-in-2012.html" title="fahd.blog in 2012" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2013/01/fahdblog-in-2012.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEUNRX8zeyp7ImA9WhNVGUw.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-8333046435080174536</id><published>2012-12-31T00:04:00.001Z</published><updated>2012-12-31T00:04:54.183Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-12-31T00:04:54.183Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="UNIX" /><category scheme="http://www.blogger.com/atom/ns#" term="commands" /><category scheme="http://www.blogger.com/atom/ns#" term="sed" /><title>Sed: Mutli-Line Replacement Between Two Patterns</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
This post has some useful &lt;code&gt;sed&lt;/code&gt; commands which can be used to perform replacements and deletes between two patterns across multiple lines.
For example, consider the following file:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;b&gt;$&lt;/b&gt; cat file
&lt;font color="green"&gt;line 1
line 2
foo
line 3
line 4
line 5
bar
line 6
line 7&lt;/font&gt;&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;1) Replace text on each line between two patterns (inclusive):&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
To perform a replacement on each line between &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, &lt;i&gt;including&lt;/i&gt; the lines containing &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, use the following:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;b&gt;$&lt;/b&gt; sed '/foo/,/bar/{s/./x/g}' file
&lt;font color="green"&gt;line 1
line 2
xxx
xxxxxx
xxxxxx
xxxxxx
xxx
line 6
line 7&lt;/font&gt;&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;2) Replace text on each line between two patterns (exclusive):&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
To perform a replacement on each line between &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, &lt;i&gt;excluding&lt;/i&gt; the lines containing &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, use the following:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;b&gt;$&lt;/b&gt; sed '/foo/,/bar/{/foo/n;/bar/!{s/./x/g}}' file
&lt;font color="green"&gt;line 1
line 2
foo
xxxxxx
xxxxxx
xxxxxx
bar
line 6
line 7&lt;/font&gt;&lt;/pre&gt;


&lt;b&gt;&lt;font color="#000099"&gt;3) Delete lines between two patterns (inclusive):&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
To delete all lines between &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, &lt;i&gt;including&lt;/i&gt; the lines containing &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, use the same replacement &lt;code&gt;sed&lt;/code&gt; command as shown above, but simply change the replacement expression to a delete.
&lt;p/&gt;
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;b&gt;$&lt;/b&gt; sed '/foo/,/bar/d' file
&lt;font color="green"&gt;line 1
line 2
line 6
line 7&lt;/font&gt;&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;4) Delete lines between two patterns (exclusive):&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
To delete all lines between &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, &lt;i&gt;excluding&lt;/i&gt; the lines containing &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, use the same replacement &lt;code&gt;sed&lt;/code&gt;  command as shown above, but simply change the replacement expression to a delete.
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;b&gt;$&lt;/b&gt; sed '/foo/,/bar/ {/foo/n;/bar/!d}' file
&lt;font color="green"&gt;line 1
line 2
foo
bar
line 6
line 7&lt;/font&gt;
&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;5) Replace all lines between two patterns (inclusive):&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
To perform a replacement on a block of lines between &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, &lt;i&gt;including&lt;/i&gt; the lines containing &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, use:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;b&gt;$&lt;/b&gt; sed -n '/foo/{:a;N;/bar/!ba;N;s/.*\n/REPLACEMENT\n/};p' file
&lt;font color="green"&gt;line 1
line 2
REPLACEMENT
line 6
line 7&lt;/font&gt;
&lt;/pre&gt;

&lt;b&gt;How it works:&lt;/b&gt;&lt;br/&gt;
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
/foo/{                   # when "foo" is found
  :a                     # create a label "a"
    N                    # store the next line
  /bar/!ba               # goto "a" and keep looping and storing lines until "bar" is found
  N                      # store the line containing "bar"
  s/.*\n/REPLACEMENT\n/  # delete the lines
}
p                        # print
&lt;/pre&gt;


&lt;b&gt;&lt;font color="#000099"&gt;6) Replace all lines between two patterns (exclusive):&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
To perform a replacement on a block of lines between &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, &lt;i&gt;excluding&lt;/i&gt; the lines containing &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt;, use:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;b&gt;$&lt;/b&gt; sed -n '/foo/{p;:a;N;/bar/!ba;s/.*\n/REPLACEMENT\n/};p' file
&lt;font color="green"&gt;line 1
line 2
foo
REPLACEMENT
bar
line 6
line 7&lt;/font&gt;
&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;References:&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;a href="http://www.grymoire.com/Unix/Sed.html"&gt;Sed - An Introduction and Tutorial by Bruce Barnett&lt;/a&gt;
&lt;/span&gt;

&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/YMY-HzwT8ds" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/8333046435080174536/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/12/sed-mutli-line-replacement-between-two.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/8333046435080174536?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/8333046435080174536?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/YMY-HzwT8ds/sed-mutli-line-replacement-between-two.html" title="Sed: Mutli-Line Replacement Between Two Patterns" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/12/sed-mutli-line-replacement-between-two.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0MCRXc4fCp7ImA9WhNVEk0.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-2487835129915161765</id><published>2012-12-22T09:59:00.001Z</published><updated>2012-12-22T19:44:24.934Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-12-22T19:44:24.934Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="bash" /><category scheme="http://www.blogger.com/atom/ns#" term="commands" /><category scheme="http://www.blogger.com/atom/ns#" term="shell" /><category scheme="http://www.blogger.com/atom/ns#" term="scripting" /><title>Useless Use of Echo</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
Most of us are familiar with the &lt;a href="http://partmaps.org/era/unix/award.html"&gt;Useless Use of Cat Award&lt;/a&gt; which is awarded for unnecessary use of the &lt;code&gt;cat&lt;/code&gt; command. For example, in nearly all cases, &lt;code&gt;cat file | command arg&lt;/code&gt; can be rewritten as &lt;code&gt;&amp;lt;file command arg&lt;/code&gt;.
&lt;p/&gt;
In a similar vein, this post is about the useless use of the &lt;code&gt;echo&lt;/code&gt; command. In nearly all cases:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;&lt;font color="green"&gt;echo string | command arg&lt;/font&gt;&lt;/pre&gt;
can be rewritten using a &lt;a href="http://en.wikipedia.org/wiki/Here_document"&gt;heredoc&lt;/a&gt;:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;&lt;font color="green"&gt;command arg &amp;lt;&amp;lt; END
string
END&lt;/font&gt;&lt;/pre&gt;
or, using a &lt;a href="http://linux.die.net/abs-guide/x15683.html"&gt;here-string&lt;/a&gt;:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;&lt;font color="green"&gt;command arg &amp;lt;&amp;lt;&amp;lt; string&lt;/font&gt;&lt;/pre&gt;
&lt;b&gt;Note:&lt;/b&gt; Here-strings are &lt;a href="http://wiki.bash-hackers.org/scripting/nonportable"&gt;not portable&lt;/a&gt; (but most modern shells support them) so use the heredoc alternative shown above if you are writing a portable script!
&lt;p/&gt;
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/a4KfLQ1TqrI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/2487835129915161765/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/12/useless-use-of-echo.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/2487835129915161765?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/2487835129915161765?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/a4KfLQ1TqrI/useless-use-of-echo.html" title="Useless Use of Echo" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/12/useless-use-of-echo.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUEGRHYzcCp7ImA9WhNXE0s.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-529965506960377768</id><published>2012-12-01T12:07:00.000Z</published><updated>2012-12-01T12:07:05.888Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-12-01T12:07:05.888Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="spring" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><title>Spring: Creating a java.util.Properties Bean</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
The easiest way to create a &lt;code&gt;java.util.Properties&lt;/code&gt; bean in Spring is with a &lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/config/PropertiesFactoryBean.html"&gt;&lt;code&gt;PropertiesFactoryBean&lt;/code&gt;&lt;/a&gt; as shown in the example below:

&lt;pre class="brush:xml; gutter:false;"&gt;
&amp;lt;bean id="emailProperties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean"&amp;gt;
  &amp;lt;property name="properties"&amp;gt;
    &amp;lt;value&amp;gt;
        smtp.host=mail.host.com
        from=joe.bloggs@domain.com
        to=${mail.recipients}
    &amp;lt;/value&amp;gt;
  &amp;lt;/property&amp;gt;
&amp;lt;/bean&amp;gt;
&lt;/pre&gt;

Spring will parse the &lt;code&gt;key=value&lt;/code&gt; pairs and put them into the &lt;code&gt;Properties&lt;/code&gt; object.
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/tJGUA2WklNg" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/529965506960377768/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/12/spring-creating-javautilproperties-bean.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/529965506960377768?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/529965506960377768?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/tJGUA2WklNg/spring-creating-javautilproperties-bean.html" title="Spring: Creating a java.util.Properties Bean" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/12/spring-creating-javautilproperties-bean.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DU4FSXs_eip7ImA9WhNQF0Q.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-9209444935888473728</id><published>2012-11-24T17:07:00.000Z</published><updated>2012-11-24T22:58:38.542Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-11-24T22:58:38.542Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="csv" /><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><title>Parsing a CSV file into JavaBeans using OpenCSV</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
&lt;a href="http://opencsv.sourceforge.net/"&gt;opencsv&lt;/a&gt; is a very useful CSV parsing library for Java.
&lt;p/&gt;
The following generic utility method shows how you can parse a CSV file into a list of JavaBeans.
&lt;pre class="brush:java; gutter:false;"&gt;
/**
 * Parses a csv file into a list of beans.
 *
 * @param &amp;lt;T&amp;gt; the type of the bean
 * @param filename the name of the csv file to parse
 * @param fieldDelimiter the field delimiter
 * @param beanClass the bean class to map csv records to
 * @return the list of beans or an empty list there are none
 * @throws FileNotFoundException if the file does not exist
 */
public static &amp;lt;T&amp;gt; List&amp;lt;T&amp;gt; parseCsvFileToBeans(final String filename,
                          final char fieldDelimiter,
                          final Class&amp;lt;T&amp;gt; beanClass) throws FileNotFoundException {
  CSVReader reader = null;
  try {
    reader = new CSVReader(new BufferedReader(new FileReader(filename)),
                           fieldDelimiter);
    final HeaderColumnNameMappingStrategy&amp;lt;T&amp;gt; strategy =
                                         new HeaderColumnNameMappingStrategy&amp;lt;T&amp;gt;();
    strategy.setType(beanClass);
    final CsvToBean&amp;lt;T&amp;gt; csv = new CsvToBean&amp;lt;T&amp;gt;();
    return csv.parse(strategy, reader);
  } finally {
    if (reader != null) {
      try {
          reader.close();
      } catch (final IOException e) {
          // ignore
      }
    }
  }
}
&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;Example:&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;

Consider the following CSV file containing person information:

&lt;pre&gt;
FirstName,LastName,Age
Joe,Bloggs,25
John,Doe,30
&lt;/pre&gt;

Create the following &lt;code&gt;Person&lt;/code&gt; bean to bind each CSV record to:
&lt;pre class="brush:java; gutter:false;"&gt;
public class Person {

  private String firstName;
  private String lastName;
  private int age;

  public Person() {
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
}
&lt;/pre&gt;
Now, you can parse the CSV file into a list of &lt;code&gt;Person&lt;/code&gt; beans with this one-liner:
&lt;pre class="brush:java; gutter:false;"&gt;
List&amp;lt;Person&amp;gt; persons = Utils.parseCsvFileToBeans("/path/to/persons.csv", 
                                                 ',', Person.class);
&lt;/pre&gt;
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/Fv8xDclCEnQ" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/9209444935888473728/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/11/parsing-csv-file-into-javabeans-using.html#comment-form" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/9209444935888473728?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/9209444935888473728?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/Fv8xDclCEnQ/parsing-csv-file-into-javabeans-using.html" title="Parsing a CSV file into JavaBeans using OpenCSV" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>3</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/11/parsing-csv-file-into-javabeans-using.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUMHSHo-fSp7ImA9WhNTF0k.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-7957855199481439483</id><published>2012-10-20T16:37:00.000+01:00</published><updated>2012-10-20T16:37:19.455+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-10-20T16:37:19.455+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="UNIX" /><category scheme="http://www.blogger.com/atom/ns#" term="join" /><category scheme="http://www.blogger.com/atom/ns#" term="commands" /><title>Joining Two Files with the Unix join Command</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
The &lt;a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?join"&gt;&lt;code&gt;join&lt;/code&gt;&lt;/a&gt; command is a useful tool for joining two files on a common field. It allows you to join two files, similar to the way you would join two tables in a SQL database.
&lt;p/&gt;
The following example illustrates the power of the &lt;code&gt;join&lt;/code&gt; command. You have two files, one containing a list of employees with their department ids and the other containing departments and their ids. You want to find out the names of the departments for each employee. You MUST first sort the files on the department id column (using the &lt;code&gt;sort&lt;/code&gt; command) and then join them on that column.

&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;b&gt;$&lt;/b&gt; cat employees.txt
&lt;font color="green"&gt;Jones,33
Steinberg,33
Robinson,34
Smith,34
Rafferty,31
John,
&lt;/font&gt;
&lt;b&gt;$&lt;/b&gt; cat departments.txt
&lt;font color="green"&gt;31,Sales
33,Engineering
34,Clerical
35,Marketing
&lt;/font&gt;
&lt;b&gt;$&lt;/b&gt; join -a 1 -t, -1 2 -2 1 -o 1.1 2.2 &lt;(sort -t, -k2 employees.txt) &lt;(sort -t, -k1 departments.txt)
&lt;font color="green"&gt;John,
Rafferty,Sales
Jones,Engineering
Steinberg,Engineering
Robinson,Clerical
Smith,Clerical
&lt;/font&gt;
&lt;/pre&gt;


&lt;b&gt;&lt;font color="#000099"&gt;Joining on multiple columns&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
The &lt;code&gt;join&lt;/code&gt; command joins on a single field. What do you do if you want to join on multiple fields? You create a composite field by combining the multiple fields together! This can be done using &lt;code&gt;awk&lt;/code&gt;. For example:
&lt;pre style="font-family: Consolas,Courier New,Courier,mono,serif; font-size:12px;"&gt;
&lt;b&gt;$&lt;/b&gt; cat employees2.txt
&lt;font color="green"&gt;Jones,33,50
Steinberg,33,51
Robinson,34,50
Smith,34,50
Rafferty,31,51
&lt;/font&gt;
&lt;b&gt;$&lt;/b&gt; awk -F, '{print $2"_"$3","$0}' employees2.txt
&lt;font color="green"&gt;33_50,Jones,33,50
33_51,Steinberg,33,51
34_50,Robinson,34,50
34_50,Smith,34,50
31_51,Rafferty,31,51
&lt;/font&gt;
&lt;/pre&gt;
As you can see, an additional field has been created by concatenating the second and third fields of the file. Now you can &lt;code&gt;join&lt;/code&gt; the files on the new composite field.
&lt;p/&gt;
(File data courtesy of &lt;a href="http://en.wikipedia.org/wiki/Join_%28SQL%29"&gt;Wikipedia&lt;/a&gt;.)
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/VZcP8pxZvCA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/7957855199481439483/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/10/joining-two-files-with-unix-join-command.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/7957855199481439483?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/7957855199481439483?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/VZcP8pxZvCA/joining-two-files-with-unix-join-command.html" title="Joining Two Files with the Unix join Command" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/10/joining-two-files-with-unix-join-command.html</feedburner:origLink></entry><entry gd:etag="W/&quot;AkcHQHY-fyp7ImA9WhNQF0Q.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-7701252915991140492</id><published>2012-10-07T15:55:00.000+01:00</published><updated>2012-11-24T23:00:31.857Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-11-24T23:00:31.857Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><title>Java: Find an Available Port Number</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
In some cases, such as in unit tests, you might need to start up a server or an rmiregistry. What port number do you use? You cannot hardcode the port number because when your unit test runs on a continuous build server or on a colleague's machine, it might already be in use. Instead, you need a way to find an available port on the current machine.
&lt;p/&gt;
According to &lt;a href="http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml"&gt;IANA (Internet Assigned Numbers Authority)&lt;/a&gt;, the ports that we are free to use lie in the range 1024-49151:
 
&lt;blockquote&gt;&lt;i&gt;
Port numbers are assigned in various ways, based on three ranges: System
Ports (0-1023), User Ports (1024-49151), and the Dynamic and/or Private
Ports (49152-65535)
&lt;/i&gt;&lt;/blockquote&gt;
 
The following utility class can help find an available port on your local machine:
&lt;pre class="brush:java; gutter:false;"&gt;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;
 
/**
 * Finds an available port on localhost.
 */
public class PortFinder {
 
  // the ports below 1024 are system ports
  private static final int MIN_PORT_NUMBER = 1024;
 
  // the ports above 49151 are dynamic and/or private
  private static final int MAX_PORT_NUMBER = 49151;
 
  /**
   * Finds a free port between 
   * {@link #MIN_PORT_NUMBER} and {@link #MAX_PORT_NUMBER}.
   *
   * @return a free port
   * @throw RuntimeException if a port could not be found
   */
  public static int findFreePort() {
    for (int i = MIN_PORT_NUMBER; i &lt;= MAX_PORT_NUMBER; i++) {
      if (available(i)) {
        return i;
      }
    }
    throw new RuntimeException("Could not find an available port between " + 
                               MIN_PORT_NUMBER + " and " + MAX_PORT_NUMBER);
  }
 
  /**
   * Returns true if the specified port is available on this host.
   *
   * @param port the port to check
   * @return true if the port is available, false otherwise
   */
  private static boolean available(final int port) {
    ServerSocket serverSocket = null;
    DatagramSocket dataSocket = null;
    try {
      serverSocket = new ServerSocket(port);
      serverSocket.setReuseAddress(true);
      dataSocket = new DatagramSocket(port);
      dataSocket.setReuseAddress(true);
      return true;
    } catch (final IOException e) {
      return false;
    } finally {
      if (dataSocket != null) {
        dataSocket.close();
      }
      if (serverSocket != null) {
        try {
          serverSocket.close();
        } catch (final IOException e) {
          // can never happen
        }
      }
    }
  }
}
&lt;/pre&gt;
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/L-eY4_D6oZU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/7701252915991140492/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/10/java-find-available-port-number.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/7701252915991140492?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/7701252915991140492?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/L-eY4_D6oZU/java-find-available-port-number.html" title="Java: Find an Available Port Number" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/10/java-find-available-port-number.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkACQ3czcCp7ImA9WhJaEEw.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-637667454921881463</id><published>2012-09-30T14:12:00.000+01:00</published><updated>2012-09-30T14:12:42.988+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-09-30T14:12:42.988+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="email" /><category scheme="http://www.blogger.com/atom/ns#" term="spring" /><category scheme="http://www.blogger.com/atom/ns#" term="mocking" /><category scheme="http://www.blogger.com/atom/ns#" term="javaconfig" /><title>Testing Email with a Mock MailSender</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
If you have an application which sends out email, you don't want your unit tests doing that too, so you need to use a "mock mail sender". You can create one by extending &lt;a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/mail/javamail/JavaMailSenderImpl.html"&gt;&lt;code&gt;JavaMailSenderImpl&lt;/code&gt;&lt;/a&gt; and overriding the &lt;code&gt;send&lt;/code&gt; method so that it doesn't &lt;i&gt;really&lt;/i&gt; send an email. Here is an example:

&lt;pre class="brush:java; gutter:false;"&gt;
import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.springframework.mail.MailException;
import org.springframework.mail.MailPreparationException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessagePreparator;

public class MockMailSender extends JavaMailSenderImpl {

  @Override
  public void send(final MimeMessagePreparator mimeMessagePreparator) throws MailException {
    final MimeMessage mimeMessage = createMimeMessage();
    try {
      mimeMessagePreparator.prepare(mimeMessage);
      final String content = (String) mimeMessage.getContent();
      final Properties javaMailProperties = getJavaMailProperties();
      javaMailProperties.setProperty("mailContent", content);
    } catch (final Exception e) {
      throw new MailPreparationException(e);
    }
  }
}
&lt;/pre&gt;

The mock shown above stores the email body into the mail properties object. This is a quick-and-dirty way of getting access to the content of the email just in case you want to check it in your unit test.
&lt;p/&gt;
Here is the associated Spring Java-based configuration:
&lt;pre class="brush:java; gutter:false;"&gt;
@Configuration
public class MailConfig {

  @Bean
  public JavaMailSender mailSender() {
    final JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost("mail.host.com");
    return sender;
  }

  @Bean
  public Notifier notifier() {
    return new Notifier(mailSender());
  }
}
&lt;/pre&gt;
The unit-test configuration:
&lt;pre class="brush:java; gutter:false;"&gt;
@Configuration
@Profile("unit-test")
public class UnitTestMailConfig extends MailConfig {
  @Override
  @Bean
  public JavaMailSender mailSender() {
   return new MockMailSender();
  }
}
&lt;/pre&gt;

For more information about sending emails with Spring 3, see the documentation &lt;a href="http://static.springsource.org/spring/docs/3.0.x/reference/mail.html"&gt;here&lt;/a&gt;.
&lt;p/&gt;
&lt;b&gt;&lt;font color="#000099"&gt;Related Posts:&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;a href="http://fahdshariff.blogspot.co.uk/2012/09/spring-3-javaconfig-unit-testing-using.html"&gt;Spring 3 - JavaConfig: Unit Testing&lt;/a&gt;
&lt;/span&gt;
&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/Up2Hugrv2F8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/637667454921881463/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/09/testing-email-with-mock-mailsender.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/637667454921881463?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/637667454921881463?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/Up2Hugrv2F8/testing-email-with-mock-mailsender.html" title="Testing Email with a Mock MailSender" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/09/testing-email-with-mock-mailsender.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DU8FQHs7eSp7ImA9WhJbGUw.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-2788155587768180327</id><published>2012-09-29T12:23:00.001+01:00</published><updated>2012-09-29T12:23:31.501+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-09-29T12:23:31.501+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="juno" /><category scheme="http://www.blogger.com/atom/ns#" term="eclipse" /><category scheme="http://www.blogger.com/atom/ns#" term="scala" /><title>Installing Scala IDE for Eclipse Juno</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
Just spent ages trying to get the &lt;a href="http://scala-ide.org"&gt;Scala IDE&lt;/a&gt; plugin working in &lt;a href="http://eclipse.org/juno/"&gt;Eclipse Juno (4.2)&lt;/a&gt;.
&lt;p/&gt;
Here are the links that finally worked for me:
&lt;ul&gt;
&lt;li&gt;Scala IDE: &lt;a href="http://download.scala-ide.org/nightly-update-juno-master-29x"&gt;http://download.scala-ide.org/nightly-update-juno-master-29x&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Scala Worksheet: &lt;a href="http://download.scala-ide.org/nightly-build-worksheet-scalaide21-29/site"&gt;http://download.scala-ide.org/nightly-build-worksheet-scalaide21-29/site&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
To install them go to &lt;b&gt;Eclipse &amp;gt; Help &amp;gt; Install new software...&lt;/b&gt; and enter the URL in the &lt;b&gt;Work with...&lt;/b&gt; textfield.
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/jOlqoW-GCZE" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/2788155587768180327/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/09/installing-scala-ide-for-eclipse-juno.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/2788155587768180327?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/2788155587768180327?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/jOlqoW-GCZE/installing-scala-ide-for-eclipse-juno.html" title="Installing Scala IDE for Eclipse Juno" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/09/installing-scala-ide-for-eclipse-juno.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0UHRXs7fip7ImA9WhJbGU0.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-7428561469594887020</id><published>2012-09-29T09:58:00.000+01:00</published><updated>2012-09-29T10:00:34.506+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-09-29T10:00:34.506+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="stackoverflow" /><title>stackoverflow - 40k rep</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
Eight months after crossing the &lt;a href="http://fahdshariff.blogspot.com/2012/01/stackoverflow-30k-rep.html"&gt;30k milestone&lt;/a&gt;, I've now achieved a reputation of 40k on &lt;a href="http://stackoverflow.com"&gt;stackoverflow&lt;/a&gt;! The following table shows some interesting stats about my journey so far:
&lt;table cellpadding="2" style="background-color:#f8f8f8; border-collapse:collapse; border-width:1px; font-size:12px;margin:18px 0pt !important; border:1px solid #BBBBBB; padding:5px;"&gt;
  &lt;tr&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt; &lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt;0-10k&lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt;10-20k&lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt;20-30k&lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt;30-40k&lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
    &lt;td&gt;
      &lt;b&gt;
        &lt;font color="#000099"&gt;Total&lt;/font&gt;
      &lt;/b&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Date achieved&lt;/td&gt;
    &lt;td&gt;01/2011&lt;/td&gt;
    &lt;td&gt;05/2011&lt;/td&gt;
    &lt;td&gt;01/2012&lt;/td&gt;
    &lt;td&gt;09/2012&lt;/td&gt;
    &lt;td&gt; &lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Questions answered&lt;/td&gt;
    &lt;td&gt;546&lt;/td&gt;
    &lt;td&gt;376&lt;/td&gt;
    &lt;td&gt;253&lt;/td&gt;
    &lt;td&gt;139&lt;/td&gt;
    &lt;td&gt;1314&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Questions asked&lt;/td&gt;
    &lt;td&gt;46&lt;/td&gt;
    &lt;td&gt;1&lt;/td&gt;
    &lt;td&gt;6&lt;/td&gt;
    &lt;td&gt;0&lt;/td&gt;
    &lt;td&gt;53&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Tags covered&lt;/td&gt;
    &lt;td&gt;609&lt;/td&gt;
    &lt;td&gt;202&lt;/td&gt;
    &lt;td&gt;83&lt;/td&gt;
    &lt;td&gt;10&lt;/td&gt;
    &lt;td&gt;904&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Badges &lt;br/&gt;(gold, silver, bronze)&lt;/td&gt;
    &lt;td&gt;35&lt;br/&gt;(2, 10, 23)&lt;/td&gt;
    &lt;td&gt;14&lt;br/&gt;(0, 4, 10)&lt;/td&gt;
    &lt;td&gt;33&lt;br/&gt;(2, 8, 23)&lt;/td&gt;
    &lt;td&gt;59&lt;br/&gt;(3, 20, 36)&lt;/td&gt;
    &lt;td&gt;141&lt;br/&gt;(7, 42, 92)&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
As I mentioned &lt;a href="http://fahdshariff.blogspot.com/2012/01/stackoverflow-30k-rep.html"&gt;before&lt;/a&gt;, I have really enjoyed being a member of stackoverflow. For me, it has not simply been a quest for reputation, but more about learning new technologies and picking up advice from other experts on the site. I like to take on challenging questions, rather than the easy ones, because it pushes me to do research into areas I have never looked at before, and I learn so much during the process.
&lt;p/&gt;
You can probably tell by the number of questions answered, that I haven't spent much time on stackoverflow recently. I've been busy at work and have also been participating in other stackexchange sites like &lt;a href="http://superuser.com"&gt;superuser&lt;/a&gt;, &lt;a href="http://serverfault.com"&gt;serverfault&lt;/a&gt; and &lt;a href="http://unix.stackexchange.com"&gt;Unix and Linux&lt;/a&gt;.
&lt;p/&gt;
50k, here I come!
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/QQLmY3rJaMU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/7428561469594887020/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/09/stackoverflow-40k-rep.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/7428561469594887020?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/7428561469594887020?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/QQLmY3rJaMU/stackoverflow-40k-rep.html" title="stackoverflow - 40k rep" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/09/stackoverflow-40k-rep.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0QGQn4zfyp7ImA9WhJbE0Q.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-8736754730333067174</id><published>2012-09-23T11:15:00.000+01:00</published><updated>2012-09-23T11:15:23.087+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-09-23T11:15:23.087+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="spring" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><category scheme="http://www.blogger.com/atom/ns#" term="javaconfig" /><title>Spring 3 - JavaConfig: Unit Testing using a Different Profile</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
In unit tests, you should not connect to an external database or webservice. Instead, you should use an in-memory database like &lt;a href="http://hsqldb.org/"&gt;hsqldb&lt;/a&gt; and mock any other external system dependencies. In order to do so, you need to inject test beans into the Spring container instead of using real ones. This example shows how you can use a different configuration for unit testing using Spring &lt;a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java"&gt;Java-based &lt;/a&gt; configuration.
&lt;p/&gt;
Let's start with the following configuration:
&lt;pre class="brush:java; gutter:false;"&gt;
/**
 * Configuration for an external oracle database.
 */
@Configuration
public class DatabaseConfig {

  @Bean
  public DataSource personDataSource() {
    DataSource ds = new org.apache.commons.dbcp.BasicDataSource();
    ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
    ds.setUrl("jdbc:oracle:thin:@firefly:1521:HRP2");
    ds.setUsername("scott");
    ds.setPassword("tiger");
    return ds;
  }
}

/**
 * Main application config.
 */
@Configuration
@Import(DatabaseConfig.class)
public class AppConfig {

  @Bean
  public PersonDao personDao() {
    return new PersonDao(personDataSource());
  }
}
&lt;/pre&gt;
In order to use a different database for your unit tests, you need to create a separate unit test database configuration as shown below. This configuration returns an HSQL data source and, more importantly, is decorated with a &lt;code&gt;@Profile&lt;/code&gt; annotation which indicates that it will be only be used when the "unit-test" profile is active.
&lt;pre class="brush:java; gutter:false;"&gt;
/**
 * Configuration for an embedded HSQL database used by unit tests.
 */
@Configuration
@Profile("unit-test")
public class UnitTestDatabaseConfig extends DatabaseConfig {

  @Override
  @Bean
  public DataSource personDataSource() {
    return new EmbeddedDatabaseBuilder()
               .setType(EmbeddedDatabaseType.HSQL)
               .addScript("person.sql")
               .build();
  }
}
&lt;/pre&gt;
Now, write your unit test as shown below. The &lt;code&gt;@ActiveProfiles&lt;/code&gt; annotation tells Spring which profile to use when loading beans for the test classes. Since it is set to "unit-test", the HSQL DataSource will be used.
&lt;pre class="brush:java; gutter:false;"&gt;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class, UnitTestDatabaseConfig.class })
@ActiveProfiles("unit-test")
public class PersonDaoTest {

  @Autowired
  private PersonDao personDao;

  @Test
  public void testGetPerson() {
    Person p = personDao.getPerson("Joe");
  }
}
&lt;/pre&gt;
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/6p1ZvDWDHMQ" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/8736754730333067174/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/09/spring-3-javaconfig-unit-testing-using.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/8736754730333067174?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/8736754730333067174?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/6p1ZvDWDHMQ/spring-3-javaconfig-unit-testing-using.html" title="Spring 3 - JavaConfig: Unit Testing using a Different Profile" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/09/spring-3-javaconfig-unit-testing-using.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0MNRHkyfyp7ImA9WhJbE0w.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-6948079456975078637</id><published>2012-09-22T14:11:00.000+01:00</published><updated>2012-09-22T14:11:35.797+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-09-22T14:11:35.797+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="spring" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><category scheme="http://www.blogger.com/atom/ns#" term="javaconfig" /><title>Spring 3 - JavaConfig: Loading a Properties File</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
This example shows how you can load a properties file using Spring &lt;a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java"&gt;Java-based&lt;/a&gt; configuration and then use those properties in &lt;code&gt;${...}&lt;/code&gt; placeholders in other beans in your configuration.
&lt;p/&gt;
First, you need to create a &lt;code&gt;PropertySourcesPlaceholderConfigurer&lt;/code&gt; bean as shown below:

&lt;pre class="brush:java; gutter:false;"&gt;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

/**
 * Loads properties from a file called ${APP_ENV}.properties
 * or default.properties if APP_ENV is not set.
 */
@Configuration
@PropertySource("classpath:${APP_ENV:default}.properties")
public class PropertyPlaceholderConfig {

  @Bean
  public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
  }
}
&lt;/pre&gt;

Next, import this configuration into your main application config and use &lt;code&gt;@Value&lt;/code&gt; to resolve the &lt;code&gt;${...}&lt;/code&gt; placeholders. For example, in the code below, the &lt;code&gt;databaseUrl&lt;/code&gt; variable will be set from the &lt;code&gt;db.url&lt;/code&gt; property in the properties file.

&lt;pre class="brush:java; gutter:false;"&gt;
import javax.sql.DataSource;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@Import(PropertyPlaceholderConfig.class)
public class AppConfig {

  @Value("${db.url}")      private String databaseUrl;
  @Value("${db.user}")     private String databaseUser;
  @Value("${db.password}") private String databasePassword;

  @Bean
  public DataSource personDataSource(){
    final DataSource ds = new org.apache.commons.dbcp.BasicDataSource();
    ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
    ds.setUrl(databaseUrl);
    ds.setUsername(databaseUser);
    ds.setPassword(databasePassword);
    return ds;
  }

  @Bean
  public PersonDao personDao() {
    return new PersonDao(personDataSource());
  }
}
&lt;/pre&gt;
&lt;b&gt;&lt;font color="#000099"&gt;Alternative approach: &lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
Alternatively, you can load the properties file into the Spring &lt;code&gt;Environment&lt;/code&gt; and then lookup the properties you need when creating your beans:

&lt;pre class="brush:java; gutter:false;"&gt;
import javax.sql.DataSource;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:${APP_ENV:default}.properties")
public class AppConfig {

  @Autowired
  private Environment env;

  @Bean
  public DataSource personDataSource() {
    final DataSource ds = new org.apache.commons.dbcp.BasicDataSource();
    ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
    ds.setUrl(env.getProperty("db.url"));
    ds.setUsername(env.getProperty("db.user"));
    ds.setPassword(env.getProperty("db.password"));
    return ds;
  }

  @Bean
  public PersonDao personDao() {
    return new PersonDao(personDataSource());
  }
}
&lt;/pre&gt;
A minor downside of this approach is that you need to autowire the &lt;code&gt;Environment&lt;/code&gt; into all your configs which require properties from the properties file.
&lt;p/&gt;
&lt;b&gt;&lt;font color="#000099"&gt;Related posts: &lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;a href="http://fahdshariff.blogspot.co.uk/2012/09/spring-3-javaconfig-vs-xml-config.html"&gt;Spring 3: JavaConfig vs XML Config&lt;/a&gt;
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/a2F6F7yL8K8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/6948079456975078637/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/09/spring-3-javaconfig-loading-properties.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/6948079456975078637?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/6948079456975078637?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/a2F6F7yL8K8/spring-3-javaconfig-loading-properties.html" title="Spring 3 - JavaConfig: Loading a Properties File" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/09/spring-3-javaconfig-loading-properties.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkEDSHY5fyp7ImA9WhJUGE8.&quot;"><id>tag:blogger.com,1999:blog-32637828.post-6334329626192224650</id><published>2012-09-16T19:37:00.001+01:00</published><updated>2012-09-16T19:37:59.827+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-09-16T19:37:59.827+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="spring" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><category scheme="http://www.blogger.com/atom/ns#" term="javaconfig" /><title>Spring 3: JavaConfig vs XML Config</title><content type="html">&lt;span style="font-family: arial,sans-serif;"&gt;
&lt;a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java"&gt;Spring JavaConfig&lt;/a&gt; allows you to configure the Spring IoC container and define your beans purely in Java rather than XML. I have been using Java-based configuration in all my new projects now and prefer it over the traditional XML-based configuration.
&lt;p/&gt;
Here is a small example illustrating what the XML and Java configurations look like:
&lt;p&gt;
&lt;b&gt;&lt;font color="#000099"&gt;XML Config&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;pre class="brush:xml; gutter:false;"&gt;
&amp;lt;beans&amp;gt;
  &amp;lt;bean id="personDataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"&amp;gt;
    &amp;lt;property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/&amp;gt;
    &amp;lt;property name="url" value="jdbc:oracle:thin:@firefly:1521:HRP2"/&amp;gt;
    &amp;lt;property name="username" value="scott"/&amp;gt;
    &amp;lt;property name="password" value="tiger"/&amp;gt;
  &amp;lt;/bean&amp;gt;
  &amp;lt;bean id="personDao" class="com.example.PersonDao"&amp;gt;
    &amp;lt;property name="dataSource" ref="personDataSource"/&amp;gt;
  &amp;lt;/bean&amp;gt;
&amp;lt;/beans&amp;gt;
&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;Java Config&lt;/font&gt;&lt;/b&gt;&lt;br/&gt;
&lt;pre class="brush:java; gutter:false;"&gt;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
  
  @Bean
  public DataSource personDataSource(){
    DataSource ds = new org.apache.commons.dbcp.BasicDataSource();
    ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
    ds.setUrl("jdbc:oracle:thin:@firefly:1521:HRP2");
    ds.setUsername("scott");
    ds.setPassword("tiger");
    return ds;
  }
  
  @Bean
  public PersonDao personDao() {
    return new PersonDao(personDataSource());
  }
}
&lt;/pre&gt;

&lt;b&gt;&lt;font color="#000099"&gt;Why I like JavaConfig:&lt;/font&gt;&lt;/b&gt;&lt;p/&gt;
Here are a few reasons, in no particular order, as to why I like the Java-based configuration:
&lt;ol&gt;
&lt;li&gt;&lt;b&gt;Easy to learn:&lt;/b&gt; With XML, I have always found myself copying the app-context.xml from the last project I did, to start off with. I also have a hard time remembering what the XML schema is. However, JavaConfig is so intuitive that you can easily start writing your configuration from scratch - all you need to remember are a few annotations. Java-based configuration is more succint than XML. It is also more "readable". This makes it easier to see, at a glance, how your spring container is configured as compared to reading a lot of XML.&lt;/li&gt;&lt;br/&gt;

&lt;li&gt;&lt;b&gt;Quicker to write:&lt;/b&gt; It is faster to write JavaConfig because your Java IDE will help you complete class names and methods.&lt;/li&gt;&lt;br/&gt;

&lt;li&gt;&lt;b&gt;Type safety:&lt;/b&gt; In XML, it is easy to type the name of a class or property incorrectly, but with JavaConfig this is not possible because you will be using code completion in your Java IDE. Even if you are not, you will get a compiler error and can fix it straightaway.&lt;/li&gt;&lt;br/&gt;

&lt;li&gt;&lt;b&gt;Faster navigation:&lt;/b&gt; It is quicker to jump from one bean to another, track bean references etc because, since they are just Java classes and methods, you can use your IDE shortcuts to find types, go into method declarations and view call hierarchies.&lt;/li&gt;&lt;br/&gt;

&lt;li&gt;&lt;b&gt;No context switching:&lt;/b&gt; Another advantage of JavaConfig is that your brain (and IDE) does not have to keep switching between XML and Java. You can stay happily in the Java world.&lt;/li&gt;&lt;br/&gt;

&lt;li&gt;&lt;b&gt;No more XML!&lt;/b&gt; I hate XML in general. I find Spring XML verbose and hard to follow. It does not "belong" in a Java project. Sorry, but I don't think I will ever be using it again.&lt;/li&gt;&lt;br/&gt;
&lt;/ol&gt;

Oh, and YMMV :)
&lt;/span&gt;&lt;img src="http://feeds.feedburner.com/~r/Fahdblog/~4/RXB1Rj2raYY" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://fahdshariff.blogspot.com/feeds/6334329626192224650/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://fahdshariff.blogspot.com/2012/09/spring-3-javaconfig-vs-xml-config.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/6334329626192224650?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/32637828/posts/default/6334329626192224650?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Fahdblog/~3/RXB1Rj2raYY/spring-3-javaconfig-vs-xml-config.html" title="Spring 3: JavaConfig vs XML Config" /><author><name>Fahd Shariff</name><uri>http://www.blogger.com/profile/00919911016127601294</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="20" height="32" src="http://photos1.blogger.com/blogger/4160/916/320/me_2006.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://fahdshariff.blogspot.com/2012/09/spring-3-javaconfig-vs-xml-config.html</feedburner:origLink></entry></feed>
