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

<channel>
	<title>Jayway Team Blog &#187; Tips &amp; Tricks</title>
	<atom:link href="http://blog.jayway.com/category/tips-tricks/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to really fix the too many open files problem for Tomcat in Ubuntu</title>
		<link>http://blog.jayway.com/2012/02/11/how-to-really-fix-the-too-many-open-files-problem-for-tomcat-in-ubuntu/</link>
		<comments>http://blog.jayway.com/2012/02/11/how-to-really-fix-the-too-many-open-files-problem-for-tomcat-in-ubuntu/#comments</comments>
		<pubDate>Sat, 11 Feb 2012 10:31:17 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[devops]]></category>
		<category><![CDATA[tomcat]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11989</guid>
		<description><![CDATA[A couple of days ago we ran into the infamous "too many open files" when our Tomcat web server was under load. There are several blogs around the internet that tries to deal with this issue but none of them seemed to do the trick for us. Usually what you do is to set the [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of days ago we ran into the infamous "too many open files" when our Tomcat web server was under load. There are several blogs around the internet that tries to deal with this issue but none of them seemed to do the trick for us. Usually what you do is to set the ulimit to a greater value (it's something like 1024 by default). But in order to make it permanent after reboot the first thing suggested is to update the <code>/proc/sys/fs/file-max</code> file and set it to a greater value and then edit <code>/etc/security/limits.conf</code> and add the following line <code>* - nofile 2048</code> (see <a href="http://tech-torch.blogspot.com/2009/07/linux-ubuntu-tomcat-too-many-open-files.html">here</a> for more details). But none of this worked for us. We saw that when doing </p>
<pre>
cat /proc/<tomcat pid>/limits
</pre>
<p>the limit was still set to the initial value of 1024:</p>
<pre>
Limit                     Soft Limit           Hard Limit           Units
Max cpu time              unlimited            unlimited            seconds
Max file size             unlimited            unlimited            bytes
Max data size             unlimited            unlimited            bytes
Max stack size            8388608              unlimited            bytes
Max core file size        0                    unlimited            bytes
Max resident set          unlimited            unlimited            bytes
Max processes             63810                63810                processes
<b>Max open files                1024                     1024                    files</b>
Max locked memory         65536                65536                bytes
Max address space         unlimited            unlimited            bytes
Max file locks            unlimited            unlimited            locks
Max pending signals       63810                63810                signals
Max msgqueue size         819200               819200               bytes
Max nice priority         0                    0
Max realtime priority     0                    0
Max realtime timeout      unlimited            unlimited            us
</pre>
<p>It was not until we found <a href="http://ubuntuforums.org/showthread.php?t=1583041">this</a> thread that the reason and solution became clear. Our Tomcat instance was started as a service during boot and there's a <a href="http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=302079">bug</a> discovered and filed (with patch) in 2005 that doesn't seem to have been resolved yet. The bug reveals itself by ignoring the max number of open files limit when starting daemons in Ubuntu/Debain. So the work-around suggested by "BOK" was to edit <code>/etc/init.d/tomcat</code> and add:</p>
<pre>
ulimit -Hn 16384
ulimit -Sn 16384
</pre>
<p>Finally the max number of open files for Tomcat was increased!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/02/11/how-to-really-fix-the-too-many-open-files-problem-for-tomcat-in-ubuntu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How you list the available goals for a maven plugin</title>
		<link>http://blog.jayway.com/2012/02/11/how-you-list-the-available-goals-for-a-maven-plugin/</link>
		<comments>http://blog.jayway.com/2012/02/11/how-you-list-the-available-goals-for-a-maven-plugin/#comments</comments>
		<pubDate>Sat, 11 Feb 2012 10:18:47 +0000</pubDate>
		<dc:creator>Tobias Södergren</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[goals]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11976</guid>
		<description><![CDATA[I've been attending an excellent lab by Sune Simonsen which was about how to create a Javascript twitter client. The lab utilizes the maven-lab-plugin, which can be used to create step-by-step labs using Maven. During the lab, i wanted to know which step I was at and I figured that there should be a goal [...]]]></description>
			<content:encoded><![CDATA[<p>I've been attending an excellent lab by <a href="https://twitter.com/#!/sunesimonsen">Sune Simonsen</a> which was about how to create a Javascript twitter client.</p>
<p/>
The lab utilizes the <a href="https://github.com/jayway/maven-lab-plugin">maven-lab-plugin</a>, which can be used to create step-by-step labs using Maven.</p>
<p/>
During the lab, i wanted to know which step I was at and I figured that there should be a goal for that. To list the available goals for a maven plugin you can use the goal <code>help:describe</code> like this:</p>
<pre>
  $ maven help:describe -DgroupId=com.jayway.maven.plugins.lab -DartifactId=maven-lab-plugin
</pre>
<p>This will give you an output like:</p>
<pre>
Name: maven-lab-plugin Maven Mojo
Description: Maven plugin used to create labs that provide more code once a
  step has been completed. Labs are a useful way to learn new technologies,
  frameworks and tools.
Group Id: com.jayway.maven.plugins.lab
Artifact Id: maven-lab-plugin
Version: 1.0.0.RELEASE
Goal Prefix: lab

This plugin has 7 goals:

lab:create
  Description: Goal to chunkify

lab:currentStep
  Description: Get the current step no

lab:findMax
  Description: Goal to find the max version

lab:init
  Description: Goal to create and initialize a lab.

lab:next
  Description: Change to next step

lab:reset
  Description: Goal to create and initialize a lab.

lab:setStep
  Description: Change version to versionNo

For more information, run 'mvn help:describe [...] -Ddetail'
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/02/11/how-you-list-the-available-goals-for-a-maven-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Builder pattern with a twist</title>
		<link>http://blog.jayway.com/2012/02/07/builder-pattern-with-a-twist/</link>
		<comments>http://blog.jayway.com/2012/02/07/builder-pattern-with-a-twist/#comments</comments>
		<pubDate>Tue, 07 Feb 2012 10:49:05 +0000</pubDate>
		<dc:creator>Uzi Landsmann</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[builder]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11940</guid>
		<description><![CDATA[The builder pattern is great, isn't it? It lets you create nice immutable classes without the need for multiple constructors and it gives the API users freedom in choosing which arguments they want to use when creating the instance. But what happens when you want to tell the user that she must call one builder [...]]]></description>
			<content:encoded><![CDATA[<p>The builder pattern is great, isn't it? It lets you create nice immutable classes without the need for multiple constructors and it gives the API users freedom in choosing which arguments they want to use when creating the instance. But what happens when you want to tell the user that she must call one builder method or the other, since it is crucial for the class you're trying to build? The builder pattern simply doesn't have such a feature. This post will try to give an alternative solution to this problem.</p>
<p><span id="more-11940"></span></p>
<p>But lets take it from the beginning.</p>
<h2>Part 1: Why builder pattern?</h2>
<p>Suppose you want to create a class name Address. And suppose you want it to have fields like protocol, url, port, path and description. Now, you want to give your users the freedom to choose which arguments to pass when creating an instance of the class. Also, you want to make your class immutable, so set methods are out of the question. You might start up with something like:</p>
<pre class="brush:java">public class Address {
    private String protocol;
    private String url;
    private int port;
    private String path;
    private String description;

    public Address(String url, int port) {}
    public Address(String protocol, String url, int port) {}
    public Address(String protocol, String url, int port, String path) {}
    public Address(String protocol, String url, int port, String path,
        String description) {}
}</pre>
<p>...but you start realizing there is a problem here. First, maybe you need more combinations, like creating an instance given an url, a port and a path, but - both url and path are Strings, and you already have a constructor which takes two String and an int, and, hey, you know you can't have two constructors with the same signature! Secondly, you realize there's simply too many constructors here, and it reminds you of something you read once in a <a href="http://industriallogic.com/xp/refactoring/">book</a> about code smells. The book suggests solving this by <a href="http://industriallogic.com/xp/refactoring/constructorCreation.html">replacing constructors with creation methods</a>. Using this tip, your class might look like this:</p>
<pre class="brush:java">public class Address {
    private String protocol;
    private String url;
    private int port;
    private String path;
    private String description;

    // no one should use this outside your class
    private Address() {} 

    public Address createAddressWithProtocolUrlAndPort(
        String protocol, String url, int port) {}
    public Address createAddressWithProtocolUrlPortAndPath(
        String protocol, String url, int port, String path) {}
    public Address createAddressWithUrlPortAndPath(
        String url, String path) {}
}</pre>
<p>...but this is also tedious. There's simply too many combinations. And you need to create an endlessly amount of factory methods to allow all of them. It is then that it strikes you! Why didn't you consider using the builder pattern! This way, you don't have to create loads of constructors or creation methods, and still allow the user to create an immutable instance of your class while freely choosing which arguments to use. Your beautiful new class now looks like that:</p>
<pre class="brush:java">public class Address {
    private String protocol;
    private String url;
    private int port;
    private String path;
    private String description;

    // only builder should be able to create an instance
    private Address(Builder builder) {
        this.protocol = builder.protocol;
        this.url = builder.url;
        this.port = builder.port;
        this.path = builder.path;
        this.description = builder.description;
    }

    public static class Builder {
        private String protocol;
        private String url;
        private int port;
        private String path;
        private String description;

        public Builder protocol(String protocol) {
            this.protocol = protocol;
            return this;
        }

        public Builder url(String url) {
            this.url = url;
            return this;
        }

        public Builder port(int port) {
            this.port = port;
            return this;
        }

        public Builder path(String path) {
            this.path = path;
            return this;
        }

        public Builder description(String description) {
            this.description = description;
            return this;
        }

        public Address build() {
            return new Address(this);
        }
    }
    // TODO: add some get methods here...
}</pre>
<p>...and you can create a new instance of Address by calling:</p>
<pre class="brush:java">Address address = new Builder().url("www.google.com").port(80).build();</pre>
<p>Happy? Very. But there's just one tiny problem. What happens if the user of this class tries to create an Address without an url or a port? You simply cant allow that now, can you? So you start thinking. And you realize you simply cannot find a good solution. So you ask a <a href="http://stackoverflow.com/questions/9126276/how-to-mark-a-method-obligatory">question</a> in Stackoverflow and hope someone would give you a good solution. Most of the answers you get there don't help at all, but after a while, someone called <a href="http://stackoverflow.com/users/12719/pgras">pgras</a> gives you this fantastic solution, and, well, you like it so much you decide to write a <a href="http://blog.jayway.com/2012/02/07/builder-pattern-with-a-twist">blog post</a> about it <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>&nbsp;</p>
<h2>Part 2: Mandatory methods in builder pattern</h2>
<p>The solution is to change you builder into a state machine. Each mandatory method in it leads you to the next step, until you get to the last step which includes both non-mandatory methods and the build method itself. It uses interfaces to define the different steps, and, well, it look like that:</p>
<pre class="brush:java">public class Address {
    private String protocol;
    private String url;
    private int port;
    private String path;
    private String description;

    // only builder should be able to create an instance
    private Address(Builder builder) {
        this.protocol = builder.protocol;
        this.url = builder.url;
        this.port = builder.port;
        this.path = builder.path;
        this.description = builder.description;
    }

    public static Url builder() {
        return new Builder();
    }

    public static class Builder implements Url, Port, Build{
        private String protocol;
        private String url;
        private int port;
        private String path;
        private String description;

        /** Mandatory, must be followed by {@link Port#port(int)}  */
        public Port url(String url) {
            this.url = url;
            return this;
        }

        /** Mandatory, must be followed by methods in {@link Build}  */
        public Build port(int port) {
            this.port = port;
            return this;
        }

        /** Non-mandatory, must be followed by methods in {@link Build}  */
        public Build protocol(String protocol) {
            this.protocol = protocol;
            return this;
        }

        /** Non-mandatory, must be followed by methods in {@link Build}  */
        public Build path(String path) {
            this.path = path;
            return this;
        }

        /** Non-mandatory, must be followed by methods in {@link Build}  */
        public Build description(String description) {
            this.description = description;
            return this;
        }

        /** Creates an instance of {@link Address} */
        public Address build() {
            return new Address(this);
        }
    }

    interface Url {
        public Port url(String url);
    }

    interface Port {
        public Build port(int port);
    }

    interface Build {
        public Build protocol(String protocol);
        public Build path(String path);
        public Build description(String description);
        public Address build();
    }

    // TODO: add some get methods here...
}</pre>
<p>Using it is simple:</p>
<pre class="brush:java">Address address = Address.builder().url("www.google.com").port(80).build();</pre>
<p>Try using it without the mandatory methods, and you get a compilation error:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/cannot_resolve1.png" rel="lightbox"><img class="alignnone size-full wp-image-11952" title="cannot_resolve" src="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/cannot_resolve1.png" alt="" width="528" height="53" /></a></p>
<p>Autocomplete is also helpful here, and will only give you the correct options:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/autocomplete.png" rel="lightbox"><img class="wp-image-11953 alignleft" title="autocomplete" src="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/autocomplete.png" alt="" width="800" height="215" /></a></p>
<p>&nbsp;</p>
<p>So there you have it. The API user can now use your friendly API to create a robust and immutable class knowing that she'll get all the help needed along the way, using autocomplete and compilation errors if she did something she wasn't suppose to do. Nothing here can go wrong!</p>
<p>Thanks again, <a href="http://stackoverflow.com/">Stackoverflow</a> and  <a href="http://stackoverflow.com/users/12719/pgras">pgras</a> for this nice solution.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/02/07/builder-pattern-with-a-twist/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Finding with Git</title>
		<link>http://blog.jayway.com/2012/01/25/finding-with-git/</link>
		<comments>http://blog.jayway.com/2012/01/25/finding-with-git/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 16:23:07 +0000</pubDate>
		<dc:creator>Anders Janmyr</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[git]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11903</guid>
		<description><![CDATA[Git is an amazing version control system that never loses anything, but sometimes it can be hard to find out where things are. Most of the time it is going to be git log that is our friend, but not all the time. Where is my file? Sometimes you know that you have a file [...]]]></description>
			<content:encoded><![CDATA[<p>Git is an amazing version control system that never loses anything, but<br />
sometimes it can be hard to find out where things are. Most of the time<br />
it is going to be <code>git log</code> that is our friend, but not all the time.</p>
<h2>Where is my file?</h2>
<p>Sometimes you know that you have a file in your repository but, you<br />
don&#39;t know exactly where it is. <code>git ls-files</code> is the answer.</p>
<p><!-- Generator: GNU source-highlight 3.1.5<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --></p>
<pre><tt><i><font color="#9A1900"># Find all files with the name security in the path.</font></i>
$ git ls-files <font color="#990000">|</font> grep security
lib/dynamo-db/security<font color="#990000">.</font>js
test/security-test<font color="#990000">.</font>js
</tt></pre>
<p>Obviously, you can use any particular <code>grep</code> options you prefer, like <code>-i</code><br />
to ignore case.</p>
<h2>In what files does <em>word</em> exist?</h2>
<p>If you want to find information inside files <code>git grep</code> is your friend.<br />
<code>git grep</code> works similar to a recursive grep <code>grep -r .</code> but it only<br />
searches files that are managed by git.</p>
<p><!-- Generator: GNU source-highlight 3.1.5<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --></p>
<pre><tt><i><font color="#9A1900"># Find all lines matching *crypt* in current version.</font></i>
$ git grep crypt
lib/dynamo-db/security<font color="#990000">.</font>js<font color="#990000">:</font>var crypto <font color="#990000">=</font> require<font color="#990000">(</font><font color="#FF0000">'crypto'</font><font color="#990000">);</font>
lib/dynamo-db/security<font color="#990000">.</font>js<font color="#990000">:</font>   var hmac <font color="#990000">=</font> crypto<font color="#990000">.</font>createHmac<font color="#990000">(</font><font color="#FF0000">'sha256'</font><font color="#990000">,</font> key<font color="#990000">);</font>

<i><font color="#9A1900"># Also give me the line numbers</font></i>
 git grep -n crypt
lib/dynamo-db/security<font color="#990000">.</font>js<font color="#990000">:</font><font color="#993399">2</font><font color="#990000">:</font>var crypto <font color="#990000">=</font> require<font color="#990000">(</font><font color="#FF0000">'crypto'</font><font color="#990000">);</font>
lib/dynamo-db/security<font color="#990000">.</font>js<font color="#990000">:</font><font color="#993399">15</font><font color="#990000">:</font>   var hmac <font color="#990000">=</font> crypto<font color="#990000">.</font>createHmac<font color="#990000">(</font><font color="#FF0000">'sha256'</font><font color="#990000">,</font> key<font color="#990000">);</font>

<i><font color="#9A1900"># List only the file names</font></i>
 git grep -l crypt
lib/dynamo-db/security<font color="#990000">.</font>js

<i><font color="#9A1900"># Also list how many times (count) it matched.</font></i>
$ git grep -c crypt
lib/dynamo-db/security<font color="#990000">.</font>js<font color="#990000">:</font><font color="#993399">2</font>
</tt></pre>
<p>It is also possible to give versions to <code>grep</code> to find out what has<br />
changed between revisions.</p>
<p><!-- Generator: GNU source-highlight 3.1.5<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --></p>
<pre><tt><i><font color="#9A1900"># Find all files with lines matching *type* in revisions `master` and `8f0fb7f`.</font></i>
git grep -l <b><font color="#0000FF">type</font></b>  master 8f0fb7f
master<font color="#990000">:</font>lib/dynamo-db/index<font color="#990000">.</font>js
master<font color="#990000">:</font>lib/dynamo-db/security<font color="#990000">.</font>js
master<font color="#990000">:</font>package<font color="#990000">.</font>json
8f0fb7f<font color="#990000">:</font>lib/dynamo-db/index<font color="#990000">.</font>js
8f0fb7f<font color="#990000">:</font>package<font color="#990000">.</font>json
</tt></pre>
<p>Maybe this is not that impressive. Most of the above can be accomplished<br />
with standard <code>grep</code>, <code>find</code>, <code>ack</code>, and friends. But Git is a version<br />
control system. How do I find out about things that happened in the past?</p>
<h2>Who deleted my file?</h2>
<p>You know how it is, you are working in some project and, your dog gets<br />
sick and you have to stay home from work, when you come back someone has<br />
deleted your file! Where is it and who did it? <code>git log</code> to the rescue.</p>
<p><code>git log</code> shows you the commit logs. It is your eye into the past.</p>
<p><!-- Generator: GNU source-highlight 3.1.5<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --></p>
<pre><tt><i><font color="#9A1900"># When (in what commit) was my file deleted?</font></i>
$ git log --diff-filter<font color="#990000">=</font>D -- test/create-table-test<font color="#990000">.</font>js
commit ba6c4d8bc165b8fb8208979c3e5513bd53477d51
Author<font color="#990000">:</font> Anders Janmyr <font color="#990000">&lt;</font>anders@janmyr<font color="#990000">.</font>com<font color="#990000">&gt;</font>
Date<font color="#990000">:</font>   Wed Jan <font color="#993399">25</font> <font color="#993399">09</font><font color="#990000">:</font><font color="#993399">46</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#993399">2012</font> <font color="#990000">+</font><font color="#993399">0100</font>

    Removed the stupid failing <b><font color="#0000FF">test</font></b><font color="#990000">.</font>
</tt></pre>
<p>Looks like I found the culprit, was I working from home? But is the file<br />
really deleted here. To get some more information about files add the<br />
<code>--summary</code> option.</p>
<p><!-- Generator: GNU source-highlight 3.1.5<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --></p>
<pre><tt><i><font color="#9A1900"># When (in what commit) was my file deleted?</font></i>
$ git log --diff-filter<font color="#990000">=</font>D --summary -- test/create-table-test<font color="#990000">.</font>js
commit ba6c4d8bc165b8fb8208979c3e5513bd53477d51
Author<font color="#990000">:</font> Anders Janmyr <font color="#990000">&lt;</font>anders@janmyr<font color="#990000">.</font>com<font color="#990000">&gt;</font>
Date<font color="#990000">:</font>   Wed Jan <font color="#993399">25</font> <font color="#993399">09</font><font color="#990000">:</font><font color="#993399">46</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#993399">2012</font> <font color="#990000">+</font><font color="#993399">0100</font>

    Removed the stupid failing <b><font color="#0000FF">test</font></b><font color="#990000">.</font>

 delete mode <font color="#993399">100644</font> test/create-table-test<font color="#990000">.</font>js
</tt></pre>
<p>Yes, it looks like the file is really deleted. Stupid bastard! Let me<br />
break this command down starting with the last command.</p>
<ul>
<li><code>test/create-table-test.js</code> - The filename has to be the relative path<br />
to the file (from your current directory).</li>
<li><code>--</code> - The double-dash is used to tell Git that this is not a branch<br />
or an option.</li>
<li><code>--summary</code> - Show me what files were deleted or added.<br />
<code>--name-status</code> is similar.</li>
<li><code>--diff-filter</code> - This is a real beauty, it allows me to limit the log<br />
to show me only the specified kind of change, in this case <code>D</code>, for<br />
Deleted. Other options are: Added (A), Copied (C), Modified (M) and Renamed (R)</li>
</ul>
<h2>When was a file added?</h2>
<p>This uses the same technique as above, but I will vary it since I don&#39;t<br />
want to type the full path of the file.</p>
<p><!-- Generator: GNU source-highlight 3.1.5<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --></p>
<pre><tt><i><font color="#9A1900"># Find out when the integration tests where added.</font></i>
$ git log --diff-filter<font color="#990000">=</font>A --name-status <font color="#990000">|</font>grep -C <font color="#993399">6</font> integ
commit 09420cfea8c7b569cd47f690104750fec358a10a
Author<font color="#990000">:</font> Anders Janmyr <font color="#990000">&lt;</font>anders@janmyr<font color="#990000">.</font>com<font color="#990000">&gt;</font>
Date<font color="#990000">:</font>   Tue Jan <font color="#993399">24</font> <font color="#993399">16</font><font color="#990000">:</font><font color="#993399">23</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#993399">2012</font> <font color="#990000">+</font><font color="#993399">0100</font>

    Extracted integration <b><font color="#0000FF">test</font></b>

A	integration-test/sts-test<font color="#990000">.</font>js

commit 205db3965dec6c2c4c7b2bb75387a591d49e1951
Author<font color="#990000">:</font> Anders Janmyr <font color="#990000">&lt;</font>anders@janmyr<font color="#990000">.</font>com<font color="#990000">&gt;</font>
Date<font color="#990000">:</font>   Sat Jan <font color="#993399">21</font> <font color="#993399">10</font><font color="#990000">:</font><font color="#993399">03</font><font color="#990000">:</font><font color="#993399">59</font> <font color="#993399">2012</font> <font color="#990000">+</font><font color="#993399">0100</font>
</tt></pre>
<p>As you can see here I am using <code>--name-status</code> as a variation on<br />
<code>--summary</code>, it uses the same notation as the <code>--diff-filter</code>.</p>
<p>I am using <code>grep -C 6</code> to get some context around the found element, in<br />
this case six lines before and after the match. Very useful!</p>
<h2>Who changed that line?</h2>
<p>As you probably know it is to see who has done something in a file by<br />
using <code>git blame</code></p>
<p><!-- Generator: GNU source-highlight 3.1.5<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --></p>
<pre><tt>$ git blame test/security-test<font color="#990000">.</font>js
205db396 <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">21</font> <font color="#993399">10</font><font color="#990000">:</font><font color="#993399">03</font><font color="#990000">:</font><font color="#993399">59</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">1</font><font color="#990000">)</font> var vows <font color="#990000">=</font> require<font color="#990000">(</font><font color="#FF0000">'vows'</font><font color="#990000">),</font>
205db396 <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">21</font> <font color="#993399">10</font><font color="#990000">:</font><font color="#993399">03</font><font color="#990000">:</font><font color="#993399">59</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">2</font><font color="#990000">)</font>     assert <font color="#990000">=</font> require<font color="#990000">(</font><font color="#FF0000">'assert'</font><font color="#990000">);</font>
205db396 <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">21</font> <font color="#993399">10</font><font color="#990000">:</font><font color="#993399">03</font><font color="#990000">:</font><font color="#993399">59</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">3</font><font color="#990000">)</font>
09420cfe <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">24</font> <font color="#993399">16</font><font color="#990000">:</font><font color="#993399">23</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">4</font><font color="#990000">)</font> var access <font color="#990000">=</font> <font color="#FF0000">'access'</font><font color="#990000">;</font>
09420cfe <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">24</font> <font color="#993399">16</font><font color="#990000">:</font><font color="#993399">23</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">5</font><font color="#990000">)</font> var secret <font color="#990000">=</font> <font color="#FF0000">'secret'</font><font color="#990000">;</font>
90b65208 <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">21</font> <font color="#993399">11</font><font color="#990000">:</font><font color="#993399">58</font><font color="#990000">:</font><font color="#993399">21</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">6</font><font color="#990000">)</font>
205db396 <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">21</font> <font color="#993399">10</font><font color="#990000">:</font><font color="#993399">03</font><font color="#990000">:</font><font color="#993399">59</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">7</font><font color="#990000">)</font> var security <font color="#990000">=</font> new Security<font color="#990000">(</font>{
90b65208 <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">21</font> <font color="#993399">11</font><font color="#990000">:</font><font color="#993399">58</font><font color="#990000">:</font><font color="#993399">21</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">8</font><font color="#990000">)</font>   access<font color="#990000">:</font> access<font color="#990000">,</font>
90b65208 <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">21</font> <font color="#993399">11</font><font color="#990000">:</font><font color="#993399">58</font><font color="#990000">:</font><font color="#993399">21</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">9</font><font color="#990000">)</font>   secret<font color="#990000">:</font> secret
205db396 <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">21</font> <font color="#993399">10</font><font color="#990000">:</font><font color="#993399">03</font><font color="#990000">:</font><font color="#993399">59</font> <font color="#990000">+</font><font color="#993399">0100</font> <font color="#993399">10</font><font color="#990000">)</font> }<font color="#990000">);</font>
<font color="#990000">...</font>
</tt></pre>
<p>Every line gets annotated with the commit who introduced it and by whom.<br />
Very helpful.</p>
<h2>Who deleted that line?</h2>
<p>Another feature, which is not as well known, is <code>git blame --reverse</code>.<br />
It allows you to see the file as it was before, annotated to show you<br />
where it has been changed.</p>
<p><!-- Generator: GNU source-highlight 3.1.5<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --></p>
<pre><tt><i><font color="#9A1900"># Check the what lines have been changed since the last 6 commits.</font></i>
$ git blame --reverse head<font color="#990000">~</font><font color="#993399">6</font><font color="#990000">..</font>head security-test<font color="#990000">.</font>js
558b8e7f <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">25</font> <font color="#993399">16</font><font color="#990000">:</font><font color="#993399">53</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">1</font><font color="#990000">)</font> var vows <font color="#990000">=</font> require<font color="#990000">(</font><font color="#FF0000">'vows'</font><font color="#990000">),</font>
558b8e7f <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">25</font> <font color="#993399">16</font><font color="#990000">:</font><font color="#993399">53</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">2</font><font color="#990000">)</font>     assert <font color="#990000">=</font> require<font color="#990000">(</font><font color="#FF0000">'assert'</font><font color="#990000">);</font>
558b8e7f <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">25</font> <font color="#993399">16</font><font color="#990000">:</font><font color="#993399">53</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">3</font><font color="#990000">)</font>
093c13e9 <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">24</font> <font color="#993399">17</font><font color="#990000">:</font><font color="#993399">26</font><font color="#990000">:</font><font color="#993399">09</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">4</font><font color="#990000">)</font> var Security <font color="#990000">=</font> require<font color="#990000">(</font><font color="#FF0000">'dynamo-db'</font><font color="#990000">).</font>Security<font color="#990000">;</font>
ba6c4d8b <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">25</font> <font color="#993399">09</font><font color="#990000">:</font><font color="#993399">46</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">5</font><font color="#990000">)</font>
<font color="#990000">^</font>b96c68b <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">21</font> <font color="#993399">12</font><font color="#990000">:</font><font color="#993399">33</font><font color="#990000">:</font><font color="#993399">50</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">6</font><font color="#990000">)</font> var access <font color="#990000">=</font> process<font color="#990000">.</font>env<font color="#990000">[</font><font color="#FF0000">'S3_KEY'</font><font color="#990000">];</font>
<font color="#990000">^</font>b96c68b <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">21</font> <font color="#993399">12</font><font color="#990000">:</font><font color="#993399">33</font><font color="#990000">:</font><font color="#993399">50</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">7</font><font color="#990000">)</font> var secret <font color="#990000">=</font> process<font color="#990000">.</font>env<font color="#990000">[</font><font color="#FF0000">'S3_SECRET'</font><font color="#990000">];</font>
558b8e7f <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">25</font> <font color="#993399">16</font><font color="#990000">:</font><font color="#993399">53</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">8</font><font color="#990000">)</font>
558b8e7f <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">25</font> <font color="#993399">16</font><font color="#990000">:</font><font color="#993399">53</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#990000">+</font><font color="#993399">0100</font>  <font color="#993399">9</font><font color="#990000">)</font> var security <font color="#990000">=</font> new Security<font color="#990000">(</font>{
558b8e7f <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">25</font> <font color="#993399">16</font><font color="#990000">:</font><font color="#993399">53</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#990000">+</font><font color="#993399">0100</font> <font color="#993399">10</font><font color="#990000">)</font>   access<font color="#990000">:</font> access<font color="#990000">,</font>
558b8e7f <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">25</font> <font color="#993399">16</font><font color="#990000">:</font><font color="#993399">53</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#990000">+</font><font color="#993399">0100</font> <font color="#993399">11</font><font color="#990000">)</font>   secret<font color="#990000">:</font> secret
558b8e7f <font color="#990000">(</font>Anders Janmyr <font color="#993399">2012</font>-<font color="#993399">01</font>-<font color="#993399">25</font> <font color="#993399">16</font><font color="#990000">:</font><font color="#993399">53</font><font color="#990000">:</font><font color="#993399">52</font> <font color="#990000">+</font><font color="#993399">0100</font> <font color="#993399">12</font><font color="#990000">)</font> }<font color="#990000">);</font>
</tt></pre>
<p>In the output you can see that most of the lines are still the same at<br />
HEAD (558b8e7f). But the fourth and fifth line <code>093c13e9</code> and <code>ba6c4d8b</code><br />
don&#39;t exist anymore. And the sixth and seventh lines <code>^b96c68b</code> have<br />
been changed after this commit.</p>
<h2>What commits contain the string?</h2>
<p>Another thing I find very useful is to find out when certain words or<br />
sentences are removed or added. For this you can use <code>git log -S&lt;string&gt;</code> or<br />
<code>git log -G&lt;regex&gt;</code></p>
<p><!-- Generator: GNU source-highlight 3.1.5<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --></p>
<pre><tt><i><font color="#9A1900"># Find commits that modified the string aws and display the full diff.</font></i>
$ git log -Saws --diff-filter<font color="#990000">=</font>M --patch
commit b96c68b839f204b310b79570bc3d27dc93cff588
Author<font color="#990000">:</font> Anders Janmyr <font color="#990000">&lt;</font>anders@janmyr<font color="#990000">.</font>com<font color="#990000">&gt;</font>
Date<font color="#990000">:</font>   Sat Jan <font color="#993399">21</font> <font color="#993399">12</font><font color="#990000">:</font><font color="#993399">33</font><font color="#990000">:</font><font color="#993399">50</font> <font color="#993399">2012</font> <font color="#990000">+</font><font color="#993399">0100</font>

    We have a valid request<font color="#990000">,</font> tjohoo

diff --git a/lib/dynamo-db/security<font color="#990000">.</font>js b/lib/dynamo-db/security<font color="#990000">.</font>js
index bee6936<font color="#990000">..</font><font color="#993399">8471527</font> <font color="#993399">100644</font>
--- a/lib/dynamo-db/security<font color="#990000">.</font>js
<font color="#990000">+++</font> b/lib/dynamo-db/security<font color="#990000">.</font>js
@@ -<font color="#993399">2</font><font color="#990000">,</font><font color="#993399">6</font> <font color="#990000">+</font><font color="#993399">2</font><font color="#990000">,</font><font color="#993399">7</font> @@
 var crypto <font color="#990000">=</font> require<font color="#990000">(</font><font color="#FF0000">'crypto'</font><font color="#990000">);</font>
 var _ <font color="#990000">=</font> require<font color="#990000">(</font><font color="#FF0000">'underscore'</font><font color="#990000">);</font>
 var request <font color="#990000">=</font> require<font color="#990000">(</font><font color="#FF0000">"request"</font><font color="#990000">);</font>
<font color="#990000">+</font>var xml2js <font color="#990000">=</font> require<font color="#990000">(</font><font color="#FF0000">'xml2js'</font><font color="#990000">);</font>

 <b><font color="#000000">function Security</font></b><font color="#990000">(</font>options<font color="#990000">)</font> {
   this<font color="#990000">.</font>options <font color="#990000">=</font> options<font color="#990000">;</font>
@@ -<font color="#993399">23</font><font color="#990000">,</font><font color="#993399">7</font> <font color="#990000">+</font><font color="#993399">24</font><font color="#990000">,</font><font color="#993399">7</font> @@ mod<font color="#990000">.</font>timestamp <font color="#990000">=</font> <b><font color="#000000">function()</font></b> {
 mod<font color="#990000">.</font>defaultParams <font color="#990000">=</font> <b><font color="#000000">function()</font></b> {
   <b><font color="#0000FF">return</font></b> {
     AWSAccessKeyId<font color="#990000">:</font> this<font color="#990000">.</font>options<font color="#990000">.</font>access<font color="#990000">,</font>
-    Version<font color="#990000">:</font> <font color="#FF0000">'2010-05-08'</font><font color="#990000">,</font>
<font color="#990000">+</font>    Version<font color="#990000">:</font> <font color="#FF0000">'2011-06-15'</font><font color="#990000">,</font>
     Timestamp<font color="#990000">:</font> this<font color="#990000">.</font><b><font color="#000000">timestamp()</font></b><font color="#990000">,</font>
     SignatureVersion<font color="#990000">:</font> <font color="#993399">2</font><font color="#990000">,</font>
     SignatureMethod<font color="#990000">:</font> <font color="#FF0000">'HmacSHA256'</font>
@@ -<font color="#993399">57</font><font color="#990000">,</font><font color="#993399">9</font> <font color="#990000">+</font><font color="#993399">58</font><font color="#990000">,</font><font color="#993399">10</font> @@ mod<font color="#990000">.</font>url <font color="#990000">=</font> function<font color="#990000">(</font>host<font color="#990000">,</font> path<font color="#990000">,</font> params<font color="#990000">)</font> {

 mod<font color="#990000">.</font>makeRequest <font color="#990000">=</font> function<font color="#990000">(</font>method<font color="#990000">,</font> host<font color="#990000">,</font> path<font color="#990000">,</font> params<font color="#990000">,</font> callback<font color="#990000">)</font> {
   var extParams <font color="#990000">=</font> _<font color="#990000">.</font>extend<font color="#990000">(</font>{}<font color="#990000">,</font> this<font color="#990000">.</font><b><font color="#000000">defaultParams()</font></b><font color="#990000">,</font> params<font color="#990000">);</font>
-  var signedParams <font color="#990000">=</font> this<font color="#990000">.</font>signedParams<font color="#990000">(</font><font color="#FF0000">'GET'</font><font color="#990000">,</font> <font color="#FF0000">'iam.amazonaws.com'</font><font color="#990000">,</font> <font color="#FF0000">'/'</font><font color="#990000">,</font> extParams<font color="#990000">);</font>
-  console<font color="#990000">.</font>log<font color="#990000">(</font>extParams<font color="#990000">,</font>signedParams<font color="#990000">);</font>
-  <b><font color="#0000FF">return</font></b> request<font color="#990000">(</font>{ method<font color="#990000">:</font> method<font color="#990000">,</font> url<font color="#990000">:</font> this<font color="#990000">.</font>url<font color="#990000">(</font>host<font color="#990000">,</font> path<font color="#990000">,</font> signedParams<font color="#990000">)</font> }<font color="#990000">,</font>
<font color="#990000">+</font>  var signedParams <font color="#990000">=</font> this<font color="#990000">.</font>signedParams<font color="#990000">(</font>method<font color="#990000">,</font> host<font color="#990000">,</font> path<font color="#990000">,</font> extParams<font color="#990000">);</font>
<font color="#990000">+</font>  var url <font color="#990000">=</font> this<font color="#990000">.</font>url<font color="#990000">(</font>host<font color="#990000">,</font> path<font color="#990000">,</font> signedParams<font color="#990000">);</font>
<font color="#990000">+</font>  console<font color="#990000">.</font>log<font color="#990000">(</font>url<font color="#990000">,</font>signedParams<font color="#990000">);</font>
<font color="#990000">+</font>  <b><font color="#0000FF">return</font></b> request<font color="#990000">(</font>{ method<font color="#990000">:</font> method<font color="#990000">,</font> url<font color="#990000">:</font> url }<font color="#990000">,</font>
<font color="#990000">...</font>
</tt></pre>
<p>That&#39;s all folks!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/01/25/finding-with-git/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Capistrano and Net:SSH with login shell</title>
		<link>http://blog.jayway.com/2012/01/12/capistrano-and-netssh-with-login-shell/</link>
		<comments>http://blog.jayway.com/2012/01/12/capistrano-and-netssh-with-login-shell/#comments</comments>
		<pubDate>Thu, 12 Jan 2012 15:14:32 +0000</pubDate>
		<dc:creator>Johan Lundahl</dc:creator>
				<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[capistrano]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[shell]]></category>
		<category><![CDATA[ssh]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11751</guid>
		<description><![CDATA[New to Capistrano? Read my previous and more introductory blog post on Capistrano - Remote builds with Capistrano. Are you using Capistrano and are confused why the user environment, the PATH for example, is different from when you log on to your server via SSH? Perhaps you have failed to use RVM or other user [...]]]></description>
			<content:encoded><![CDATA[<p>New to Capistrano? Read my previous and more introductory blog post on Capistrano - <a href="http://blog.jayway.com/2012/01/10/remote-builds-with-capistrano/">Remote builds with Capistrano</a>.</p>
<p>Are you using Capistrano and are confused why the user environment, the PATH for example, is different from when you log on to your server via SSH? Perhaps you have failed to use RVM or other user specific applications when running your Capistrano scripts? This post will explain why this is, and what can be done to solve the problem.</p>
<p>By default Capistrano will execute remote commands by something like so:</p>
<pre class="brush: ruby; ruler: true; gutter: false;">
Net::SSH.start( host, user, password: pass ) do |ssh|
  ssh.open_channel do |channel|
    channel.exec("sh -c '#{command}'")
  end
end
</pre>
<p>There is no interactive shell and only the system's environment is loaded.</p>
<p>With Net:SSH there are at least two ways to execute commands in a login shell. The first is to send the commands after requesting a shell.</p>
<pre class="brush: ruby; ruler: true; gutter: false;">
ssh.open_channel do |channel|
  channel.send_channel_request "shell" do |ch, success|
    if success
      ch.send_data "#{command}\n"
      ch.send_data "exit\n"
    else
      raise "could not start user shell"
    end
  end
end
</pre>
<p>The second way is to make your shell act as if it had been invoked as a login shell.</p>
<pre class="brush: ruby; ruler: true; gutter: false;">
channel = ssh.open_channel do |channel|
  channel.exec("bash -l") do |ch, success|
    ch.send_data "#{command}\n"
    ch.send_data "exit\n"
  end
end
</pre>
<p>Now we know that Capistrano does not give us a user shell. So, what can we do about it? Capistrano actually has an option for changing the default shell. Instead of all remote commands being executed as <code class="typed-text">sh -c '&lt;command&gt;'</code> you can have them executed as <code class="typed-text">&lt;your shell&gt; -c '&lt;command&gt;'</code>. The shell will still not be invoked as a login shell though, and thus no files that sets your user's environment will be loaded. The trick here is to set the default shell to <code class="typed-text">bash -l</code> (or other shell that can be started in interactive mode).</p>
<pre class="brush: ruby; ruler: true; gutter: false;">
set :default_shell, "bash -l"
</pre>
<p>With this line added to your <b>capfile</b> or task, the environment should be exactly the same as when you log on to your server via SSH. For instance, if you are using RVM, the task</p>
<pre class="brush: ruby; ruler: true; gutter: false;">
task :ruby_path, :hosts => "host.example.com" do
  set :default_shell, "bash -l"
  run "which ruby"
end
</pre>
<p>should show that your default RVM ruby is used, rather than the system-global ruby-installation:</p>
<pre>
** [out :: host.example.com] /home/johan/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
</pre>
<p>Hopefully, Capistrano will have proper support for login shell someday soon. Until then, enjoy this little hack.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/01/12/capistrano-and-netssh-with-login-shell/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Graphite with .Net and Ubuntu 11.10</title>
		<link>http://blog.jayway.com/2012/01/04/graphite-with-dotnet-and-ubuntu-11-10/</link>
		<comments>http://blog.jayway.com/2012/01/04/graphite-with-dotnet-and-ubuntu-11-10/#comments</comments>
		<pubDate>Tue, 03 Jan 2012 23:00:57 +0000</pubDate>
		<dc:creator>Henrik Feldt</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[devops]]></category>
		<category><![CDATA[graphing]]></category>
		<category><![CDATA[graphite]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[statsd]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11635</guid>
		<description><![CDATA[This is a quick write-up on how to get started with graphite as a .Net developer. We're going to start using graphite with a virtual machine in VirtualBox, although you could use something else also. Steps: Download/install VirtualBox Download/install Ubuntu Download/install Graphite Expose VM to network Use Graphite from C# Download/install VirtualBox Start by downloading [...]]]></description>
			<content:encoded><![CDATA[<p>This is a quick write-up on how to get started with graphite as a .Net developer. We're going to start using graphite with a virtual machine in VirtualBox, although you could use <span title="VmWare Player, Fusion, Workstation, ESXi, MS Virtual Machine, HyperV or any other virtualisation software you care for">something else also</span>.</p>
<p>Steps:</p>
<ol>
<li><a href="#virtualbox">Download/install VirtualBox</a></li>
<li><a href="#ubuntu">Download/install Ubuntu</a></li>
<li><a href="#graphite">Download/install Graphite</a></li>
<li><a href="#expose">Expose VM to network</a></li>
<li><a href="#csharp">Use Graphite from C#</a></li>
</ol>
<h2 id="virtualbox">Download/install VirtualBox</h2>
<p>Start by downloading and <a href="https://www.virtualbox.org/wiki/Downloads">installing virtualbox.</a></p>
<p>The installer is a "Next - next - next" type of installer, so just click through it.</p>
<h2 id="ubuntu">Download/install Ubuntu</h2>
<p>Once installed, download and <a href="http://www.ubuntu.com/download/ubuntu/download">install ubuntu</a> as a new virtual machine.</p>
<p>Now, what you have to do is to bring up a terminal window. Press <span class="key">Win</span> and type <code class="typed-text">Terminal</code> in the input field and launch the terminal.</p>
<h3>A bit on the terminal and sudo</h3>
<p>When working with a linux, you have to type <code class="typed-text">sudo</code> before any command that makes changes to 'root'-owned directories such as <code class="directory">/etc/</code> and <code class="directory">/opt/</code> where we are going to install graphite, Apache and other dependencies.</p>
<p><code class="typed-text">pushd</code> pushes a folder onto an in-memory stack and changes the current directory to the first argument, while <code class="typed-text">popd</code> pops the stack and moves to the previous directory.</p>
<p>You can paste into the terminal with [CTRL]+[SHIFT]+[V] and copy with [CTRL]+[SHIFT]+[C]. Another tab in the terminal is created with [CTRL]+[SHIFT]+[T] - this can be nice to have if you want to look up data about your VM, such as its ip (with 'ifconfig').</p>
<h2 id="graphite">Installing Graphite</h2>
<p>This gist contains the commands you can use to install graphite.</p>
<p><script src="https://gist.github.com/1555553.js?file=bash"></script></p>
<p>When you have followed the gist, try to navigate to <code class="url">http://127.0.0.1</code> or <code class="url">http://[::1]/</code> from Firefox. You should be able to see the graphite start page.</p>
<h2 id="expose">Expose the VM to the network</h2>
<p>When you have a graphite installation, you likely want to start logging things into it - perhaps you already have a piece of software you want to enable metrics from. In order to reach the virtual machine from other computers on the network.</p>
<p>In order to do this, shut down the virtual machine and change its network interface to be 'bridged' - this is in order to let your <abbr>DHCP</abbr> server give the server and <abbr>IP</abbr> rather than only having access to it through your private computer-LAN-to-VM (<abbr>NAT</abbr>ted). Change the following: Machine Settings > Network > Adapter 1 > Attached to: [Bridged].</p>
<p>Start the virtual machine again.</p>
<p>Now check with <code class="typed-text">ifconfig</code> from the <code class="typed-text">Terminal</code> what IP the machine has, and navigate to that IP from your main development operating system. You should be able to see the graphite install now and the example data you added (from the last line of the gist).</p>
<h2 id="csharp">Use the graphite from C#</h2>
<p>Now it's time to log some data with C# into your brand new graphite install!</p>
<p>Open VS and create a new console application. Using Tools > Library Package Manager > Package Manager Console, type "install-package Graphite.NET", targeting your new console project.</p>
<p>Then type this code in the main method (put a <code>using Graphite;</code> directive on top):</p>
<p><script src="https://gist.github.com/1557425.js?file=gistfile1.cs"></script></p>
<p>Try and run the program!</p>
<p>Now you should have some nice data point in graphite! Zoom in the latest minute so that you can see them.</p>
<h4>References:<br />
<h4>
<ul>
<li>Michael Grace - http://geek.michaelgrace.org/2011/09/how-to-install-graphite-on-ubuntu/</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/01/04/graphite-with-dotnet-and-ubuntu-11-10/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android: The Mysterious NullPointerException</title>
		<link>http://blog.jayway.com/2011/12/15/android-the-mysterious-nullpointerexception/</link>
		<comments>http://blog.jayway.com/2011/12/15/android-the-mysterious-nullpointerexception/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 15:27:19 +0000</pubDate>
		<dc:creator>Darius Katz</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11594</guid>
		<description><![CDATA[The Problem One day it was just there. A mischievous NullPointerException causing, eh, mischief. It was fairly easy to provoke with my application but for some reason my code was not part of the stacktrace. 12-07 14:42:52.722 E/AndroidRuntime(18421): FATAL EXCEPTION: main 12-07 14:42:52.722 E/AndroidRuntime(18421): java.lang.NullPointerException 12-07 14:42:52.722 E/AndroidRuntime(18421): at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1064) 12-07 14:42:52.722 E/AndroidRuntime(18421): at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1081) [...]]]></description>
			<content:encoded><![CDATA[<p><strong>The Problem</strong><br />
One day it was just there. A mischievous <em>NullPointerException</em> causing, eh, mischief. It was fairly easy to provoke with my application but for some reason my code was not part of the stacktrace.</p>
<pre>
12-07 14:42:52.722 E/AndroidRuntime(18421): FATAL EXCEPTION: main
12-07 14:42:52.722 E/AndroidRuntime(18421): java.lang.NullPointerException
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1064)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1081)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.os.Handler.handleCallback(Handler.java:587)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.os.Handler.dispatchMessage(Handler.java:92)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.os.Looper.loop(Looper.java:130)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.app.ActivityThread.main(ActivityThread.java:3701)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at java.lang.reflect.Method.invokeNative(Native Method)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at java.lang.reflect.Method.invoke(Method.java:507)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at dalvik.system.NativeStart.main(Native Method)
</pre>
<p>I fretted. I winced. I even felt a slight irritation coming on.</p>
<p><strong>The Solution</strong><br />
In the end I found out the reason behind the mysterious <em>NullPointerException</em>. My application is binding to a Service and it turns out that the <em>ContextWrapper.bindService()</em>-method can't take a <em>null</em> as its <em>ServiceConnection</em> parameter. </p>
<p><em>ContextWrapper.bindService():</em><br />
<a href="http://developer.android.com/reference/android/content/ContextWrapper.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">public boolean bindService (Intent service, ServiceConnection conn, int flags)</a><br />
<code>Connect to an application service, creating it if needed.</code></p>
<p>Instead of throwing a helpful <em>IllegalArgumentException</em> it forwards the erroneous <em>null</em>-parameter into the innards of The Android Service Beast. That part is then unable to use it and throws a <em>NullPointerException</em> instead together with its own stacktrace which your code is not a part of.</p>
<p><strong>The Summary</strong><br />
In short, make sure you don't pass <em>bindService()</em> a <em>null</em> as the <em>ServiceConnection</em> parameter or you will get an unknown <em>NullPointerException</em> which is hard to track down.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/15/android-the-mysterious-nullpointerexception/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing Web.config Transformations, Part 1</title>
		<link>http://blog.jayway.com/2011/12/08/testing-web-config-transformations/</link>
		<comments>http://blog.jayway.com/2011/12/08/testing-web-config-transformations/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 20:44:45 +0000</pubDate>
		<dc:creator>Mads Troest</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[transformation]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[Web.config]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11089</guid>
		<description><![CDATA[Web.config transformations is a Microsoft-supported technology for adapting a base configuration to a particular deployment environment. In my previous post, I mentioned how AppHarbor provides an online tool for manually testing transformations. Also, the Visual Studio extension SlowCheetah provides support for manually testing and transformation and diffing them against the base configuration from inside Visual Studio. These [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/dd465326.aspx" target="_blank">Web.config transformations</a> is a Microsoft-supported technology for adapting a base configuration to a particular deployment environment.</p>
<p>In my <a href="http://blog.jayway.com/2011/11/14/web-config-transformations-and-xml-namespaces/" target="_blank">previous post</a>, I mentioned how <a href="http://appharbor.com" target="_blank">AppHarbor</a> provides an <a href="http://webconfigtransformationtester.apphb.com/" target="_blank">online tool</a> for manually testing transformations. Also, the Visual Studio extension <a href="http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5" target="_blank">SlowCheetah</a> provides support for manually testing and transformation and <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/SlowCheetahPreviewTransform.png" target="_blank">diffing</a> them against the base configuration from inside Visual Studio. These tools are useful and may be fine for tinkering with getting a transform just right, but being software professionals, we find it highly desirable to reliably automate our transformation testing.</p>
<p>In this article we shall look at one way to exercise our Web.config transformations from our own code, so that we can TDD our transformations and regression test them as part of our continuous integration cycle, like everything else.</p>
<h2>Starting Point</h2>
<p>The actual Web.config transformation process is normally invoked by MSBuild, as described in detail by Elton Stoneman in <a href="http://geekswithblogs.net/EltonStoneman/archive/2010/08/20/using-msbuild-4.0-web.config-transformation-to-generate-any-config-file.aspx" target="_blank">this post</a>. (One approach to testing the transformations could, thus, be to fork off MSBuild processes on custom build targets, but we'd like to take a less cumbersome route.)</p>
<p>Being an MSBuild task means that the transformation is implemented as an <strong>ITask</strong> realization. The concrete implementation is called <strong>TransformXml</strong> and resides in the <strong>Microsoft.Web.Publishing.Tasks.dll</strong> assembly. Note that this assembly is not pre-installed with Windows/.NET but rather installed along with Visual Studio 2010, typically to <em>C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web</em>). Given that its location is not fixed, you'd probably want to add it to your dependencies folder (caveat emptor: check license terms before passing it around).</p>
<p>From Elton's post, we can also see 3 arguments being passed to the TransformXml task:</p>
<ul>
<li>Source (the XML file to transform)</li>
<li>Transform (the transformation XML file itself)</li>
<li>Destination (the target of the transformed XML file)</li>
</ul>
<p>Armed with that background knowledge, let's move on and try to get the transformation to run outside of the MSBuild environment in which it normally executes. For our experiment, we'll be transforming the following source (<em>app.config</em>):</p>
<pre class="brush: xml;">   &lt;configuration&gt;
     &lt;appSettings&gt;
	   &lt;add key="testKey" value="testValue"/&gt;
     &lt;/appSettings&gt;
   &lt;/configuration&gt;</pre>
<p>The transformation we'll be testing (<em>app.Debug.config</em>) should change the "testValue" of the "testKey" to something transformation specific ("debugValue" in this case):</p>
<pre class="brush: xml;">   &lt;configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"&gt;
     &lt;appSettings&gt;
       &lt;add key="testKey"
            value="debugValue"
            xdt:Locator="Match(key)" xdt:Transform="SetAttributes" /&gt;
     &lt;/appSettings&gt;
   &lt;/configuration&gt;</pre>
<h2>Test Approach</h2>
<p>Our initial stab at automatically testing the transformation will be to invoke the XmlTransform through its outermost interface; i.e. the ITask interface. First, we need to add a reference to <strong>Microsoft.Web.Publishing.Tasks.dll</strong> as mentioned above. Additionally, we need to reference <strong>Microsoft.Build.Framework</strong> and <strong>Microsoft.Build.Utilities.v4.0</strong> (these should be available from your usual <em>Project, Add Reference, .NET </em>tab).</p>
<p>Opening up the XmlTransform class in Visual Studio's Object Browser shows us a single method, <strong>Execute()</strong>, plus a handful of properties, most of which we recognize from Stoneman's previously mentioned post. A little experimentation reveals the following details:</p>
<ul>
<li><strong>SourceRootPath</strong></li>
<ul>
<li>The base path to which the XML file specified in <strong>Source</strong> is relative. If not specified, this will  be the current directory (which, when running from a test runner, would typically be your build target directory).</li>
</ul>
<li><strong>Source</strong></li>
<ul>
<li>The name of the XML source file to be transformed. If this is not an absolute path, it will be relative to the <strong>SourceRootPath</strong>.</li>
</ul>
<li><strong>TransformRootPath</strong></li>
<ul>
<li>The base path to which the XML file specified in <strong>Transform</strong> is relative. If not specified, this will be the same as <strong>SourceRootPath</strong>.</li>
</ul>
<li><strong>Transform</strong></li>
<ul>
<li>The name of the XML transformation to be applied to the source. If this is not an absolute path, it will be relative to the <strong>TransformRootPath</strong>.</li>
</ul>
<li><strong>Destination</strong></li>
<ul>
<li>The name of the resulting transformed XML file. If this is not an absolute path, it will be relative to the current directory (typically your build target directory, in a test context).</li>
</ul>
</ul>
<p>So all we need to do is something like the following, right?</p>
<pre class="brush: csharp;">   var transformer = new TransformXml
   {
      SourceRootPath = @"..\..\..\Jayway.WebTransformTesting\",
      Source = @"app.config",
      Transform = @"app.Debug.config",
      Destination = @"app.transformed.config"
   };
   var transformationSucceeded = transformer.Execute();</pre>
<p>Well, as the <strong>System.InvalidOperationException</strong> with the message <em>"Task attempted to log before it was initialized" </em>thrown in our face subtly tells us, this is not quite the case...</p>
<p>Investigating the task implementation with Reflector shows the problem to be due to the fact that a property, <strong>BuildEngine</strong>, of the Task base class has not been set. It is used as a dependency injection mechanism, giving the task access to some environment services (see <a href="http://msdn.microsoft.com/en-us/library/microsoft.build.framework.ibuildengine.aspx" target="_blank">IBuildEngine</a> on MSDN) normally provided by MSBuild.</p>
<p>Well, the whole purpose of this experiment was to run outside of MSBuild, so we'll roll our own "build engine" instead:</p>
<pre class="brush: csharp;">   public class BuildEngineForTest : IBuildEngine
   {
      public void LogErrorEvent(BuildErrorEventArgs e)
      {
         Console.WriteLine(LogFormat, "ERROR", e.Message);
      }

      public void LogWarningEvent(BuildWarningEventArgs e)
      {
         Console.WriteLine(LogFormat, "WARNING", e.Message);
      }

      public void LogMessageEvent(BuildMessageEventArgs e)
      {
         Console.WriteLine(LogFormat, e.Importance, e.Message);
      }

      public void LogCustomEvent(CustomBuildEventArgs e)
      {
         Console.WriteLine(LogFormat, "CUSTOM", e.Message);
      }

      public bool BuildProjectFile(
         string projectFileName, string[] targetNames,
         IDictionary globalProperties, IDictionary targetOutputs)
      {
         return true;
      }

      public bool ContinueOnError
      {
         get { return true; }
      }

      public int LineNumberOfTaskNode
      {
         get { return 0; }
      }

      public int ColumnNumberOfTaskNode
      {
         get { return 0; }
      }

      public string ProjectFileOfTaskNode
      {
         get { return string.Empty; }
      }

      private const string LogFormat = "{0} : {1}";
   }</pre>
<p>This was the piece we were missing to be able to run the transformation outside MSBuild. We are, thus, able to write our coveted test:</p>
<pre class="brush: csharp;">...
   [Test]
   public void ApplyingDebugTransformationToConfigurationSetsExpectedKey()
   {
      const string targetFile = @"app.transformed.config";

      var transformer = new TransformXml
      {
         BuildEngine = new BuildEngineForTest(),
         SourceRootPath = @"..\..\..\Jayway.WebTransformTesting\",
         Source = @"app.config",
         Transform = @"app.Debug.config",
         Destination = targetFile
      };

      // Left as exercise for the reader... ;]
      AssertKeyInTransformedFile(targetFile);
   }
...</pre>
<p>Our transformation runs successfully, yielding the following console output from our "build engine":</p>
<pre>Normal : Transforming Source File: ..\..\..\Jayway.WebTransformTesting\app.config
Normal : Applying Transform File: ..\..\..\Jayway.WebTransformTesting\app.Debug.config
Low : Executing SetAttributes (transform line 6, 35)
Low : on /configuration/appSettings/add[@key='testKey']
Low : Applying to 'add' element (source line 4, 6)
Low : Set 'key' attribute
Low : Set 'value' attribute
Low : Set 2 attributes
Low : Done executing SetAttributes
Normal : Output File: app.transformed.config
Normal : Transformation succeeded</pre>
<p>Yay? Yay.</p>
<h2>Conclusion</h2>
<p>We have shown how Web.config Transformations can be invoked programmatically, outside the MSBuild process by providing a simple custom IBuildEngine realization; a technique that might prove useful for other scenarios as well.</p>
<p>We have applied that knowledge to enable automated testing of our transformations.</p>
<p>In my next post in this series, we'll continue our investigation, aiming to get rid of the whole, nasty detour around the file system.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/08/testing-web-config-transformations/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>WinRM w/ self-signed certificate in 4 steps</title>
		<link>http://blog.jayway.com/2011/11/21/winrm-w-self-signed-certificate-in-4-steps/</link>
		<comments>http://blog.jayway.com/2011/11/21/winrm-w-self-signed-certificate-in-4-steps/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 16:36:07 +0000</pubDate>
		<dc:creator>Henrik Feldt</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[devops]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11003</guid>
		<description><![CDATA[Targeted environment: Windows Server 2008 or Windows Server 2008 R2 You'll be self-signing with makecert from the Windows 7.1 SDK. The certificate tool is a single executable, specifically at %PROGRAMFILES%\Microsoft SDKs\Windows\v7.1\Bin\makecert.exe, per default. You'll need it - copy it to the server unless you already have the SDK installed on it. Secondly, you've got a [...]]]></description>
			<content:encoded><![CDATA[<p><em>Targeted environment: Windows Server 2008 or Windows Server 2008 R2</em></p>
<p>You'll be self-signing with <code>makecert</code> from the <a href="http://www.microsoft.com/download/en/details.aspx?id=8279" title="Download the 7.1 SDK for Windows">Windows 7.1 SDK</a>. The certificate tool is a single executable, specifically at <code>%PROGRAMFILES%\Microsoft SDKs\Windows\v7.1\Bin\makecert.exe</code>, per default.  You'll need it - copy it to the server unless you already have the SDK installed on it.</p>
<p>Secondly, you've got a domain name, <em>mydomain.com</em>. Otherwise, just substitute the IP in the following instructions.</p>
<p>Without further ado; on the <strong>SERVER</strong>:</p>
<ol>
<li>
<p>First, create the self-signed certificate with the regular cmd.exe:</p>
<p><code>makecert -sk "<strong title="This is the FQDN that you are securing">mydomain.com</strong>" -ss My -sr localMachine -r -n "CN=<strong title="This is who is the subject certificate name, the domain to secure">mydomain.com</strong>, O=<strong title="Fill out your company for O (Organisation)">Jayway Stockholm AB</strong>, L=<strong title="This is some real-world address of you, your company or your dog.">Drottninggatan 108 Stockholm</strong>" -a sha1 -eku "1.3.6.1.5.5.7.3.1"</code><br /><a href="http://msdn.microsoft.com/en-us/library/bfsktky3%28VS.80%29.aspx">(flags ref)</a></p>
<p>Substituting your own values.</p>
<p title="You can verify this visually by running mmc, then: CTRL+M &gt; Certificates &gt; Computer Account &gt; Personal &gt; Certificates &gt; mydomain.com in list.">This command will create a certificate for <em>Server Authentication</em> and save it in the certificate store for the local machine.</p>
<p>With powershell, get the thumbprint is for the generated certificate<code></p>
<p>ls cert:\LocalMachine\my</code></p>
<p>It'll look like this: <code>87B1C1818F1828958524A598B4131757EBAF4D35</code></p>
</li>
<li>
<p>Now, configure winrm (PowerShell needs escaping, so use cmd.exe):</p>
<p><code>winrm create winrm/config/listener?Address=IP:<strong title="Btw... don't use that IP, it's google's DNS-server ;)">8.8.8.8</strong>+Transport=HTTPS @{Hostname="<strong>mydomain.com</strong>";CertificateThumbprint="<strong title="The hash from above">87B1C1818F1828958524A598B4131757EBAF4D35</strong>";Port="5986"}</code></p>
<p>Again, substitute your variables.</p>
</li>
<li>
<p>Open port <b title="the previous is for HTTP by default">5986</b>, inbound TCP for all programs (and potentially restricted to your CI-server by IP), by going to Start &gt; Administrative Tools &gt; Windows Firewall with Advanced Security</p>
</li>
<li>Now, from the <strong>CLIENT</strong>, PowerShell:
<pre><code>$so = New-PsSessionOption -SkipCACheck
etsn -cn mydomain.com -Credential MyMachineName\YourUserName -UseSSL -SessionOption $so</code></pre>
<p>Answer the password dialog box, and you're in! Try running "whoami" to see the user name</li>
</ol>
<p>That's it. Congratulations. If you stay at this for a small-scale deployment you have OK security on your communication with WinRM! However, do check out some more details:</p>
<h2>More details</h2>
<p>On <code>makecert</code> and how to switch certificate for one signed by a trusted certificate authority.</p>
<h3><code>makecert</code> switches</h3>
<ol>
<li>
<p><code>-sk</code> says what the <em>Subject Key</em> name should be. This is like the 'user name for keys, i.e. a uniquely identifiable name for your key in the key store.</p>
</li>
<li>
<p><code>-ss</code> is the store's name. It's most often either <code>My</code> or <code>Root</code> depending on what you're using your certificate for.</p>
</li>
<li>
<p><code>-sr</code> is really just if it's a user-local store or the machine store that you are saving the key to. Has either value <em>currentUser</em> or <em>localMachine</em>.</p>
<li>
<p><code>-r</code> is for self-signing which is what we want.</p>
</li>
<li>
<p><code>-sn</code> stands for <em>Subject Name</em> and in this case our subject (what we want to authenticate and encrypt access to) is our domain.</p>
</li>
<li>
<p><code>-a</code> stands for <em>Algorithm</em> - default is md5 which is not much more secure than a 4-digit pin code on a post-it taped to an old man's wallet. <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/Attacking-MD5.pdf'>Ref: Attacking MD5</a>, <a href="https://www.google.com/search?hl=en&q=cuda%20amazon%20hash&aq=f&aqi=">ref 2</a></p>
</li>
</ol>
<h3>Changing Certificates</h3>
<p>Let's discuss what you do when you get a trusted-CA-signed certificate</p>
<h4>Justification</h4>
<p>So this works nicely for a while, until someone captures you laptop because you forgot it on the tube. Suddenly you can't revoke the certificate and you're in a world of pain of managing your keys (to be honest, this has never happened to me and this is already 1000x better than no authentication or basic unencrypted authentication!). Also, you grew a bit and have a few more servers to manage. Fine, let's upgrade WinRM's HTTPS certificate.</p>
<p>First, get the new one. I am personally involved in StartSSL.org, since I like the idea of free, community-driven crypto over the default server-taxation style type of certificates - this will also integrate finely with browser-based X.509 certificates if you're planning on adding an STS to your infrastructure and authenticating users with certificates rather than username/password combos</p>
<p>However, the world is a harsh place and we want <em title="You didn't think you were paying for a real person to do work, did you?">real humans in front of bots</em> to verify our identity for ultra security. We've used geotrust previously and have no real complaints.</p>
<h4>Too long, didn't read</h4>
<p>Use <a href="http://technet.microsoft.com/en-us/library/cc725793%28WS.10%29.aspx">certreq.exe</a> to generate the request, and install it on the server.</p>
<p>Once installed and visible through <code>ls cert://localmachine/my</code> in PowerShell, copy its thumbprint.</p>
<p>Then, you update the listener's binding (<strong>SERVER</strong>):</p>
<p><code>winrm set winrm/config/listener?Address=IP:<strong>8.8.8.8</strong>+Transport=HTTPS @{Hostname="<strong>mydomain.com</strong>";CertificateThumbprint="<strong>CB7434F35E3EA11D49D209F41BB16E96B472D30E</strong>";Port="5986"}</code></p>
<p>The <em>set</em> operation idempotently changes the listener's configuration to the hash presented inside the <code>@{}</code> hash syntax.</p>
<p>Now try it out (<strong>CLIENT</strong>):</p>
<p><code>etsn -cn mydomain.com -Credential MyMachineName\YourUserName -UseSSL</code></p>
<h3>What on earth is <code>etsn</code>?</h3>
<p>See for yourself! <code>Get-Alias etsn</code> in PowerShell</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/21/winrm-w-self-signed-certificate-in-4-steps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Web.config Transformations and XML Namespaces</title>
		<link>http://blog.jayway.com/2011/11/14/web-config-transformations-and-xml-namespaces/</link>
		<comments>http://blog.jayway.com/2011/11/14/web-config-transformations-and-xml-namespaces/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 12:45:15 +0000</pubDate>
		<dc:creator>Mads Troest</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[namespace]]></category>
		<category><![CDATA[NLog]]></category>
		<category><![CDATA[transformation]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[Web.config]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10849</guid>
		<description><![CDATA[In the project I'm currently working on, we use Web.config transformations to adapt a base configuration to a particular deployment environment. I was adding a transformation to adapt our NLog configuration for the various environments, when I ran into a problem. I'd added the following transformation, intended to set the log level to Warning on [...]]]></description>
			<content:encoded><![CDATA[<p>In the project I'm currently working on, we use <a href="http://msdn.microsoft.com/en-us/library/dd465326.aspx" target="_blank">Web.config transformations</a> to adapt a base configuration to a particular deployment environment.</p>
<p>I was adding a transformation to adapt our NLog configuration for the various environments, when I ran into a problem. I'd added the following transformation, intended to set the log level to Warning on the given deloyment:</p>
<pre class="brush: xml;">&lt;nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"&gt;
  &lt;rules&gt;
    &lt;logger name="*" minlevel="Warn"
      xdt:Transform="SetAttributes(minlevel)" xdt:Locator="Match(name)"
    /&gt;
  &lt;/rules&gt;
&lt;/nlog&gt;</pre>
<p>However, the original fragment kept being passed through without modification. I tried various modes of matching (incidentally, the online <a href="http://webconfigtransformationtester.apphb.com/" target="_blank">Web Config Transformation Tester</a> is a good tool for such tinkering with transformations) to no avail, until I decided to try and remove the NLog namespace from the transformation:</p>
<pre class="brush: xml;">&lt;nlog&gt;
  &lt;rules&gt;
    &lt;logger name="*" minlevel="Warn"
      xdt:Transform="SetAttributes(minlevel)" xdt:Locator="Match(name)"
    /&gt;
  &lt;/rules&gt;
&lt;/nlog&gt;</pre>
<p>And lo and behold; it worked.</p>
<p>That could have been the end of it, but I decided to dig a bit deeper, since we have the NLog schema in our solution and properly referencing it allows us to have IntelliSense within the web.config.</p>
<p>Eventually, as an experiment, I tried associating a namespace prefix with the NLog namespace at the top level, and then explicitly qualify the NLog elements with that prefix, rather than relying on specifying a default namespace on the NLog element:</p>
<pre class="brush: xml;">&lt;configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"
  xmlns:nlog="http://www.nlog-project.org/schemas/NLog.xsd"
&gt;

  &lt;nlog:nlog&gt;
    &lt;nlog:rules&gt;
      &lt;nlog:logger name="*" minlevel="Warn"
        xdt:Transform="SetAttributes(minlevel)" xdt:Locator="Match(name)"
      /&gt;
    &lt;/nlog:rules&gt;
  &lt;/nlog:nlog&gt;

&lt;/configuration&gt;</pre>
<p>Success!</p>
<h2>Conclusion</h2>
<p>Explicitly prefixing elements from foreign XML namespaces in config transformations must be described as a workaround, since semantically the first and the third NLog fragments are equivalent.</p>
<p>In spite of this flaw in the web.config transformations implementation, this workaround allows you to get the benefits of IntelliSense and better validation when you have the schema for NLog or any other foreign fragment available.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/14/web-config-transformations-and-xml-namespaces/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WP7 app update and NeutralResourcesLanguage</title>
		<link>http://blog.jayway.com/2011/11/10/wp7-app-update-and-neutralresourceslanguage/</link>
		<comments>http://blog.jayway.com/2011/11/10/wp7-app-update-and-neutralresourceslanguage/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 19:23:24 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[marketplace]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10846</guid>
		<description><![CDATA[The Windows Phone Marketplace was updated with new features in July 2011, one has to do with default language. The previous process to submit an app required you to define the default language when submitting the app, the new version checks the default language in the uploaded xap. The problem An app created before July [...]]]></description>
			<content:encoded><![CDATA[<p>The Windows Phone Marketplace was updated with new features in July 2011, one has to do with default language. The previous process to submit an app required you to define the default language when submitting the app, the new version checks the default language in the uploaded xap.</p>
<h2>The problem</h2>
<p>An app created before July 18th 2011 will not have the AssemblyInfo attribute NeutralResourcesLanguage and submitting an update to this app will give you the error:</p>
<p><font face="Courier New">Error 2003: The [NeutralResourceLanguage] attribute is missing on the entry assembly.</font></p>
<h2>The fix</h2>
<p>So, the fix for this is simple – add the attribute in AssemblyInfo.cs. (can also be done through selecting in a drop down in app properties)</p>
<p><font face="Courier New">[assembly: NeutralResourcesLanguage(&quot;en-us&quot;)]</font></p>
<h2>The quirk</h2>
<p>English it not always English. There is something called location groups. If you’re lucky – you’ll now pass through submission. If you’re not, you’ll end up with:</p>
<p><font face="Courier New">Error 1047: An update cannot support fewer languages than the previous app instance supported.</font></p>
<p>Whoah, what is this? For me, this was because I had stated the language as <strong>English (International)</strong> when submitting the first time. The rules are:</p>
<table border="0" cellspacing="0" cellpadding="5" width="600">
<tbody>
<tr>
<td valign="top" width="300"><strong>Stated on first submit</strong></td>
<td valign="top" width="300"><strong>Needed in AssemblyInfo.cs</strong></td>
</tr>
<tr>
<td valign="top" width="300">English (International)</td>
<td valign="top" width="300">“en”</td>
</tr>
<tr>
<td valign="top" width="300">English</td>
<td valign="top" width="300">“en-us” or “en-ca”</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>I learned this from the MSDN forum page <a href="http://http://forums.create.msdn.com/forums/t/87638.aspx">helpful tips on language processes during app submission</a>. To quote: <em>If the parent instance was marked as “English (International)”, you need to use [NeutralResourcesLanguage(“en”)], if it was “English”, use [NeutralResourcesLanguage(“en-US”)] or [NeutralResourcesLanguage(“en-CA”)], in other cases use two-letter language name.</em></p>
<h2>Summary</h2>
<p>My final statement ended up as:</p>
<p><font face="Courier New">[assembly: NeutralResourcesLanguage(&quot;en-us&quot;)]</font></p>
<p>This bit me when submitting updates – I really hope this helps you avoid or find the problem quickly <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/wlEmoticon-smile.png" /></p>
<p>Bye!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/10/wp7-app-update-and-neutralresourceslanguage/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WP7 Marketplace Beta &#8211; new app downloadable delay</title>
		<link>http://blog.jayway.com/2011/11/03/wp7-marketplace-beta-new-app-downloadable-delay/</link>
		<comments>http://blog.jayway.com/2011/11/03/wp7-marketplace-beta-new-app-downloadable-delay/#comments</comments>
		<pubDate>Thu, 03 Nov 2011 07:06:47 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[marketplace]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10754</guid>
		<description><![CDATA[Have you seen the new (since fall 2011) ways to publish a Windows Phone app to Marketplace? In addition to regular publishing, you can now publish as private beta or targeted. Neither will make the app discoverable in the Marketplace, Beta is time limited and does not include the full certification requirements. MSDN has a [...]]]></description>
			<content:encoded><![CDATA[<p>Have you seen the new (since fall 2011) ways to publish a Windows Phone app to Marketplace? In addition to regular publishing, you can now publish as <em>private beta </em>or <em>targeted</em>. Neither will make the app discoverable in the Marketplace, Beta is time limited and does not include the full certification requirements. MSDN has a really good <a href="http://http://msdn.microsoft.com/en-us/library/hh334586(v=VS.92).aspx">Marketplace submission comparison: Application Distribution Options.</a></p>
<p>Now, onto the topic of the hour: <strong>Beta submission</strong>.</p>
<h2></h2>
<h2>Empirical timing results</h2>
<p>I have during the past months submitted numerous apps to the Marketplace as beta – and come to the conclusion: (this probably will just be true for the near future AND the region I’m in – Sweden)</p>
<p>1) Beta submission takes <strong>4 hours </strong>to complete – the app then becomes “published”</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/image.png" rel="lightbox"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/image_thumb.png" width="575" height="291" /></a></p>
<p>2) It takes another <strong>8 hours</strong> before the app becomes available for download!</p>
<h2>Error when trying to download right after submission completed</h2>
<p>Before the 8 hours, hitting the deep link gives Marketplace error: 805a0194. An explanation of the error can be found in this <a href="http://stackoverflow.com/questions/7777822/marketplace-windows-phone-beta-test-error-code-805a0194/7777955#7777955">StackOverflow response</a>: it’s a 404 – not found.</p>
<p>Why is it like this? I don’t know. Probably propagation of the xap package onto download servers. Annoying – but more bearable once you see the system in it.</p>
<p>Go publish those apps!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/03/wp7-marketplace-beta-new-app-downloadable-delay/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Azure Blob Storage &#8211; a simple example</title>
		<link>http://blog.jayway.com/2011/10/18/azure-blob-storage-a-simple-example/</link>
		<comments>http://blog.jayway.com/2011/10/18/azure-blob-storage-a-simple-example/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 05:22:00 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[azure]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10023</guid>
		<description><![CDATA[This is for all of you that just want a simple, up to date, example/how-to/tutorial of how to use Azure Blob Storage. You won’t see any screen shots or a lengthy guide on how to get started from scratch. Instead I will just focus on writing some code examples for general stuff that you might [...]]]></description>
			<content:encoded><![CDATA[<p>This is for all of you that just want a simple, up to date, example/how-to/tutorial of how to use Azure Blob Storage. You won’t see any screen shots or a lengthy guide on how to get started from scratch. Instead I will just focus on writing some code examples for general stuff that you might like to do. I will keep this simple and avoid getting into more advanced scenarios such as page blobs, VHD and leases. I’ll cover those in posts later on.</p>
<p>All examples below assume that we have already instantiated <a href="http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storageclient.cloudblobclient.aspx"><em>CloudBlobClient</em></a><em> cloudBlobClient</em>. It can be done using the code. </p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">var account = CloudStorageAccount.FromConfigurationSetting(&quot;DataConnectionString&quot;);
var cloudBlobClient = account.CreateCloudBlobClient();</pre>
<h2>Upload a Blob from a string</h2>
<p>First example, upload a string as a text file. We, for example, use this to upload crash logs to blob storage and then mail a link to the support team. </p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public Uri UploadBlob(string path, string fileName, string content)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(path);
    cloudBlobContainer.CreateIfNotExist();

    var blob = cloudBlobContainer.GetBlobReference(fileName);
    blob.UploadText(content);

    return blob.Uri;
}</pre>
<p>So if we would call this method using the following parameters. </p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">var uri = UploadBlob(&quot;folder&quot;, &quot;file.txt&quot;, &quot;text in file&quot;);</pre>
<p>We would get a link pointing at <a href="http://yourstorageaccount.blob.core.windows.net/folder/file.txt">http://yourstorageaccount.blob.core.windows.net/folder/file.txt</a> containing the text – “text in file”. Please note that this call is made synchronously. </p>
<h2>Upload a Blob from a stream</h2>
<p>You will recognize this from the previous example. The difference is that we are using a <a href="http://msdn.microsoft.com/en-us/library/system.io.stream.aspx">stream</a> instead of a string and that the call is made asynchronously. </p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public void UploadBlob(string path, string fileName, Stream stream)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(path);
    cloudBlobContainer.CreateIfNotExist();

    var blob = cloudBlobContainer.GetBlobReference(fileName);
    blob.BeginUploadFromStream(stream, UploadFinished, blob.Uri);
}

private void UploadFinished(IAsyncResult asyncResult)
{
    // do something
}</pre>
<h2>List all Blobs in a container</h2>
<p>This will give a list of links to all blobs stored in a container. </p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public IEnumerable&lt;Uri&gt; ListAllBlobs(string folder)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(folder);
    var listBlobItems = cloudBlobContainer.ListBlobs();

    return listBlobItems.Select(b =&gt; b.Uri);
}</pre>
<p>Simple enough. Once you got the setup right, Azure Blob Storage is actually quite easy to use. If you would like to list blobs in subfolders as well then use the overloaded method for <a href="http://msdn.microsoft.com/en-us/library/ee758385.aspx">ListBlobs</a> and send in BlobRequestOptions { UseFlatBlobListing = true }<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/blob-storage2.png" rel="lightbox">.</a></p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px; padding-top: 0px" title="Azure Blob Storage" border="0" alt="blob storage" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/blob-storage_thumb2.png" width="412" height="354" /></p>
<h2>&#160;</h2>
<h2>Download content from a Blob</h2>
<p>Very similar to uploading data, it works the same way with other data types than string.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public string DownloadBlob(string folder, string fileName)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(folder);
    var blob = cloudBlobContainer.GetBlobReference(fileName);

    return blob.DownloadText();
}</pre>
<p>But, before downloading a blob, you might want to see if it exists…</p>
<h2>See if a Blob exists</h2>
<p>The only way that I have found for doing this (and please correct me if I’m wrong here) is to do a little peek and catch the resulting exception.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">private bool BlobExists(CloudBlob blob)
{
    try
    {
        blob.FetchAttributes();
        return true;
    }
    catch (StorageClientException e)
    {
        if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
        {
            return false;
        }
        throw;
    }
}</pre>
<p>Thanks to <a href="http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob">Steve Marx</a> for the solution. <a href="http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storageclient.cloudblob.fetchattributes.aspx">FetchAttributes()</a> is used simply because it will be a small amount of data transferred or a 404. So even if I call BlobExists() on a 4Mb block blob it won’t be any different from doing the same call on a 2Kb blob.</p>
<h2>Some tips and tricks</h2>
<p>Well, first of all. Azure Blob storage can be used for much more than just file storage. Scalability is built in so if you, for example, have a static html page, you can easily upload it to Azure blob storage and then link to it. It is a good way to take away load from your WebRole.</p>
<p>All methods that I showed you have a Begin/End method as well. So you should be able to do most of the work asynchronously, as I did when I uploaded a blob from a stream.</p>
<p>If an Azure Queue message risk becoming bigger than 8Kb the recommended solution is to upload the message as a blob and then store the URI as the message on the queue. You won’t get charged for the extra data traffic as long as it’s done within the same data center. </p>
<p>Happy blobbing.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/18/azure-blob-storage-a-simple-example/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Getting started with Android NDK</title>
		<link>http://blog.jayway.com/2011/10/13/getting-started-with-android-ndk/</link>
		<comments>http://blog.jayway.com/2011/10/13/getting-started-with-android-ndk/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 20:15:48 +0000</pubDate>
		<dc:creator>Per-Erik Bergman</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[ndk]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10385</guid>
		<description><![CDATA[You want to try out the Android NDK? I have gotten a lot of questions about how to setup and work with the NDK and I decided to write down how I do it. My goal with this entry is to gather all the information you need to get started with the Android NDK. I [...]]]></description>
			<content:encoded><![CDATA[<p>You want to try out the Android NDK? I have gotten a lot of questions about how to setup and work with the NDK and I decided to write down how I do it. My goal with this entry is to gather all the information you need to get started with the Android NDK. I will not get into details about installing the basic components but will focus on setting up the environment. So you will need some knowledge about working with Android.</p>
<p>You will need to download and install a couple of things. </p>
<h2>Eclipse</h2>
<p>I usually go with the Eclipse Classic version. It is available from <a href="http://www.eclipse.org/downloads/" title="eclipse.org" target="_blank">eclipse.org</a>. Installing Eclipse is simply just unpacking the downloaded file.</p>
<h2>Android SDK</h2>
<p>The SDK is located at <a href="http://developer.android.com/sdk/index.html" title="developer.android.com" target="_blank">developer.android.com</a> There is a really good installation guide at <a href="http://developer.android.com/sdk/installing.html" title="developer.android.com" target="_blank">developer.android.com</a></p>
<h2>Android NDK</h2>
<p>The NDK is located at <a href="http://developer.android.com/sdk/ndk/index.html" title="developer.android.com" target="_blank">developer.android.com</a> with an installation guide.</p>
<h2>Eclipse C/C++ Development Tools</h2>
<p>To make it a bit easier we also install the C/C++ Development Tools to get C/C++ support in Eclipse. From the 'Help' menu choose 'Install New Software...'<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_00.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_00-300x233.png" alt="" title="cdt_00" width="300" height="233" class="aligncenter size-medium wp-image-10467" /></a></center></p>
<p>From the drop down select the update site for your eclipse version, in my case Indigo.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_01.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_01-283x300.png" alt="" title="cdt_01" width="283" height="300" class="aligncenter size-medium wp-image-10468" /></a></center></p>
<p>Under 'Programming Languages' you will find 'C/C++ Development Tools'. Select it and click 'next' and follow the install instructions.</p>
<p><center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_02b.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_02b-283x300.png" alt="" title="cdt_02b" width="283" height="300" class="aligncenter size-medium wp-image-10509" /></a></center></p>
<h2>Getting started</h2>
<p>I will show you how to get started by making a small application called NDKSetup.</p>
<p>Create a new android project for this example I will call it NDKSetup.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Screen-shot-2011-10-13-at-4.44.09-PM-copy.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Screen-shot-2011-10-13-at-4.44.09-PM-copy-194x300.png" alt="Project Wizard" title="Project Wizard" width="194" height="300" class="size-medium wp-image-10423" /></a></center></p>
<p>First thing we need to do is to create a new folder called 'jni'<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/jni-folder.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/jni-folder.png" alt="" title="jni-folder" width="258" height="266" class="aligncenter size-full wp-image-10431" /></a></center></p>
<p>The next thing we need to do is to setup Eclipse so we can build the JNI code. Click on the small down arrow on the external tool button and choose the 'External Tools Configuration...'.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_00.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_00-300x161.png" alt="" title="etc_00" width="300" height="161" class="aligncenter size-medium wp-image-10433" /></a></center></p>
<p>Mark the 'Program' and click on the 'new'-icon.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_01.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_01-272x300.png" alt="" title="etc_01" width="272" height="300" class="aligncenter size-medium wp-image-10435" /></a></center></p>
<p>Select a proper name.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_02.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_02-272x300.png" alt="" title="etc_02" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>Location is the location of the external tool you want to run, in our case the ndk-build file. Click on 'Browse file system...' and locate the ndk-build file located under your NDK folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_03.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_03-272x300.png" alt="" title="etc_03" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>The working directory is the jni folder we created in our project. Click on 'Browse Workspace...' ...<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04-272x300.png" alt="" title="etc_04" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>... and choose the jni folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04b1.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04b1-228x300.png" alt="" title="etc_04b" width="228" height="300" class="aligncenter size-medium wp-image-10443" /></a></center></p>
<p>You should now have something looking like this:<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_05.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_05-272x300.png" alt="" title="etc_05" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>Press run and you will get this error:</p>
<pre>/Users/uncle/ndk-setup/android-ndk-r6b/build/core/add-application.mk:118: *** Android NDK: Aborting...    .  Stop.
Android NDK: Your APP_BUILD_SCRIPT points to an unknown file: /Users/uncle/Workspaces/ndk-setup/NDKSetup/jni/Android.mk</pre>
<p>This means two things. Your setup to the ndk-build works and you are missing the Android.mk file.</p>
<p>Create a new file called Android.mk in the jni folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/android-mk.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/android-mk.png" alt="" title="android-mk" width="260" height="268" class="aligncenter size-full wp-image-10451" /></a></center></p>
<p>In the Android.mk file write this:</p>
<pre class="c">LOCAL_PATH := $<span style="color: #66cc66;">&#40;</span>call my-dir<span style="color: #66cc66;">&#41;</span>
&nbsp;
include $<span style="color: #66cc66;">&#40;</span>CLEAR_VARS<span style="color: #66cc66;">&#41;</span>
&nbsp;
LOCAL_LDLIBS := -llog
&nbsp;
LOCAL_MODULE    := ndksetup
LOCAL_SRC_FILES := native.<span style="color: #202020;">c</span>
&nbsp;
include $<span style="color: #66cc66;">&#40;</span>BUILD_SHARED_LIBRARY<span style="color: #66cc66;">&#41;</span></pre>
<p>LOCAL_PATH := $(call my-dir)<br />
An Android.mk file must begin defining the LOCAL_PATH variable, this is where the source files are. The macro 'my-dir' is the path where the Android.mk file is located.</p>
<p>include $(CLEAR_VARS)<br />
Since all the building and parsing is done in the same context the variables called LOCAL_XXX is globals and need to be cleared.</p>
<p>LOCAL_MODULE := ndksetup<br />
This is where you set the name used as the identifier for each module. Later used in java when loading the module. The system will add 'lib' before the module name when compiling into the .so file. So ndksetup will become libndksetup.so. The only exception is if you add 'lib' first in your module name then the system will not add it.</p>
<p>LOCAL_SRC_FILES := native.c<br />
Here you add a list of the files you need to compile your module. You do not need to add headers or include files the system will take care of that for you.</p>
<p>include $(BUILD_SHARED_LIBRARY)<br />
The NDK provides you with two make files that parse and build everything accordingly to your Android.mk file. The two once are BUILD_STATIC_LIBRARY for building static library and BUILD_SHARED_LIBRARY for building shared library. </p>
<p>For the example project here we use the BUILD_SHARED_LIBRARY.</p>
<p>If you run the external tool "NDK Build" we get a new error:</p>
<pre>make: *** No rule to make target `/Users/uncle/Workspaces/ndk-setup/NDKSetup/jni/native.c', needed by `/Users/uncle/Workspaces/ndk-setup/NDKSetup/obj/local/armeabi/objs/ndksetup/native.o'.  Stop.</pre>
<p>So lets att the missing native.c file into the jni folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/native-c.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/native-c-221x300.png" alt="" title="native-c" width="221" height="300" class="aligncenter size-medium wp-image-10486" /></a></center></p>
<p>Before we start adding code to the native.c file I think it is easier to write the API starting from java. We start by adding the loading of the library.</p>
<pre java="java">static {
    System.loadLibrary("ndksetup"); // ndksetup is the LOCAL_MODULE string.
}</pre>
<p>We also need to define the function we are going to implement. By adding the keyword 'native' the system will know it is a function located in the native code.</p>
<pre java="java">private native void printLog(String logThis);</pre>
<p>Putting in all together give us this:</p>
<pre java="java">package com.jayway.ndksetup;

import android.app.Activity;
import android.os.Bundle;

public class NDKSetupActivity extends Activity {

    static {
        System.loadLibrary("ndksetup");
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        printLog("Hello!!!");
    }

    private native void printLog(String logThis);
}</pre>
<p>Back to the native.c file.</p>
<p>The name structure of the function is important. It is build from the java starting with a java identifier followed by the package name, followed by the class name, followed by the function name. This is one way of converting our java function into the native function. I usually do it by right clicking on the function name ( printLog ) and select 'Copy Qualified Name' paste it in the native.c file:</p>
<pre class="c">com.<span style="color: #202020;">jayway</span>.<span style="color: #202020;">ndksetup</span>.<span style="color: #202020;">NDKSetupActivity</span>.<span style="color: #202020;">printLog</span><span style="color: #66cc66;">&#40;</span><span style="color: #993333;">String</span><span style="color: #66cc66;">&#41;</span></pre>
<p>Start by changing all dots (.) to underscores (_).</p>
<pre class="c">com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">String</span><span style="color: #66cc66;">&#41;</span></pre>
<p>Add the return value and a Java_ identifier to the function:</p>
<pre class="c"><span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">String</span><span style="color: #66cc66;">&#41;</span></pre>
<p>The input variable is a String in java so lets make it a java string in native as well.</p>
<pre class="c"><span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span>jstring logString<span style="color: #66cc66;">&#41;</span></pre>
<p>The last thing we need to add is a reference to the JNI enviroment and a reference to java object that this function belongs to.</p>
<pre class="c"><span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span>JNIEnv * env, jobject this, jstring logString<span style="color: #66cc66;">&#41;</span></pre>
<p>Finally our first native function will look like this:</p>
<pre class="c"><span style="color: #339933;">#include &lt;jni.h&gt;</span>
<span style="color: #339933;">#include &lt;string.h&gt;</span>
<span style="color: #339933;">#include &lt;android/log.h&gt;</span>
&nbsp;
<span style="color: #339933;">#define DEBUG_TAG &quot;NDKSetupActivity&quot;</span>
&nbsp;
<span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span>JNIEnv * env, jobject this, jstring logString<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
    jboolean isCopy;
    <span style="color: #993333;">const</span> <span style="color: #993333;">char</span> * szLogString = <span style="color: #66cc66;">&#40;</span>*env<span style="color: #66cc66;">&#41;</span>-&gt;GetStringUTFChars<span style="color: #66cc66;">&#40;</span>env, logString, &amp;isCopy<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    __android_log_print<span style="color: #66cc66;">&#40;</span>ANDROID_LOG_DEBUG, DEBUG_TAG, <span style="color: #ff0000;">&quot;NDK: %s&quot;</span>, szLogString<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #66cc66;">&#40;</span>*env<span style="color: #66cc66;">&#41;</span>-&gt;ReleaseStringUTFChars<span style="color: #66cc66;">&#40;</span>env, logString, szLogString<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>Just for fun we add another function, a fibonacci function.</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">native</span> <span style="color: #993333;">int</span> fibonacci<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> value<span style="color: #66cc66;">&#41;</span>;</pre>
<pre class="c">jint Java_com_jayway_ndksetup_NDKSetupActivity_fibonacci<span style="color: #66cc66;">&#40;</span>JNIEnv * env, jobject this, jint value<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>value &lt;= <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">return</span> value;
	<span style="color: #b1b100;">return</span> Java_com_jayway_ndksetup_NDKSetupActivity_fibonacci<span style="color: #66cc66;">&#40;</span>env, this, value<span style="color: #cc66cc;">-1</span><span style="color: #66cc66;">&#41;</span>
            + Java_com_jayway_ndksetup_NDKSetupActivity_fibonacci<span style="color: #66cc66;">&#40;</span>env, this, value<span style="color: #cc66cc;">-2</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>Now you are up and running with your NDK development for Android.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/13/getting-started-with-android-ndk/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Fixing WP7 app not starting after project rename</title>
		<link>http://blog.jayway.com/2011/10/12/fixing-wp7-app-not-starting-after-project-rename/</link>
		<comments>http://blog.jayway.com/2011/10/12/fixing-wp7-app-not-starting-after-project-rename/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 19:43:04 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tricks]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10396</guid>
		<description><![CDATA[If your Windows Phone 7 project isn’t starting at all – you’re not even hitting App.xaml.cs, you’ve probably renamed the app project. Fix: Set the startup object on the app project’s properties page In the .csproj file, this corresponds to the SilverlightAppEntry element: &#60;SilverlightAppEntry&#62;PhotoDiary.App&#60;/SilverlightAppEntry&#62; I would call it a bug, that you cannot rename a [...]]]></description>
			<content:encoded><![CDATA[<p>If your Windows Phone 7 project isn’t starting at all – you’re not even hitting App.xaml.cs, you’ve probably renamed the app project.</p>
<p><strong>Fix</strong>: Set the <em>startup object</em> on the app project’s properties page</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/startup_object.jpg" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="startup_object" border="0" alt="startup_object" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/startup_object_thumb.jpg" width="484" height="202" /></a></p>
<p>In the .csproj file, this corresponds to the <em>SilverlightAppEntry </em>element:</p>
<pre class="brush: xml; first-line: 1;">

&lt;SilverlightAppEntry&gt;PhotoDiary.App&lt;/SilverlightAppEntry&gt;

</pre>
<p>I would call it a bug, that you cannot rename a project and have the <em>SilverlightAppEntry</em> update accordingly. But luckily, the work-around is simple. </p>
<p>Have a nice day!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/12/fixing-wp7-app-not-starting-after-project-rename/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Open links from Text-elements in QtQuick</title>
		<link>http://blog.jayway.com/2011/10/12/open-links-from-text-elements-in-qtquick/</link>
		<comments>http://blog.jayway.com/2011/10/12/open-links-from-text-elements-in-qtquick/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 08:42:57 +0000</pubDate>
		<dc:creator>Mario Boikov</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[Qt]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10368</guid>
		<description><![CDATA[From day one, QtQuick's Text-element sports opening URL:s in an external application, typically a web page. It's very easy to use this feature and probably most of you have already been close to or have used it. The only thing that is required is that you set the Text.textFormat property to Text.RichText. Default, textFormat is [...]]]></description>
			<content:encoded><![CDATA[<p>From day one, <a href="http://doc.trolltech.com/4.7/qtquick.html">QtQuick's</a> <a href="http://doc.trolltech.com/4.7/qml-text.html"><em>Text</em></a>-element sports opening URL:s in an external application, typically a web page. It's very easy to use this feature and probably most of you have already been close to or have used it.</p>
<p>The only thing that is required is that you set the <em>Text.textFormat</em> property to <em>Text.RichText</em>. Default, <em>textFormat</em> is set to <em>Text.AutoText</em> which means that the element will try to identify if the content is rich text or not. This doesn't always work perfectly so to be sure that the link will actually be clickable, set <em>textFormat</em> to <em>Text.RichText</em>. There's also <em>Text.StyledText</em> which can parse tags but will not make the links clickable.</p>
<p>To 'catch' when someone clicks on a link, you simply connect to the <em>Text.onLinkActivated</em> signal.</p>
<p>The following snippet shows how you can open a URL in an external application:<br />
<code>
<pre>
Text {
    // Make the code more readable by using a property for the url.
    property string blogUrl: "http://pysnippet.blogspot.com" +
        "/2011/06/qtquick-from-bling-bling-to-blink-blink.html"

    property string title: "QtQuick - From Bling Bling To Blink Blink"

    anchors.verticalCenter: parent.verticalCenter
    width: parent.width

    text: "&lt;a href='" + blogUrl + "'&gt;" + title + "&lt;/a&gt;"
    textFormat: Text.RichText
    wrapMode: Text.WrapAnywhere
    horizontalAlignment: Text.AlignHCenter

    font.pixelSize: 26

    onLinkActivated: Qt.openUrlExternally(blogUrl)
}
</pre>
<p></code></p>
<p>The <em>onLinkActivated</em> 'slot' (which is invoked when the link is clicked) simply calls the <a href="http://doc.trolltech.com/4.7/qml-qt.html#openUrlExternally-method"><em>Qt.openUrlExternally()</em></a> function to invoke an external application which can handle the URL, in this case a web browser.</p>
<p>If you are a lucky owner to a <a href="http://swipe.nokia.com/">Nokia N9</a> or a N950 you can for example use the following snippet to start the maps application and show a location (this might also work on Symbian^3 phones):<br />
<code>
<pre>
import QtQuick 1.1
import com.nokia.meego 1.0

Page {

    Button {
        anchors.centerIn: parent

        text: "Click here!"

        onClicked: Qt.openUrlExternally("geo:55.6124,12.9996")
    }

}
</pre>
<p></code></p>
<p>Thanks for reading.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/12/open-links-from-text-elements-in-qtquick/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Parsing of Complex JSON and XML Documents in Java</title>
		<link>http://blog.jayway.com/2011/10/09/simple-parsing-of-complex-json-and-xml-documents-in-java/</link>
		<comments>http://blog.jayway.com/2011/10/09/simple-parsing-of-complex-json-and-xml-documents-in-java/#comments</comments>
		<pubDate>Sun, 09 Oct 2011 15:12:15 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9743</guid>
		<description><![CDATA[In this blog I'm going to demonstrate how to parse and validate more complex JSON and XML documents in Java using the REST Assured framework and the XmlPath and JsonPath components available in this framework. Since REST Assured is implemented in Groovy it can be really beneficial to take advantage of Groovy's collection API. Let's [...]]]></description>
			<content:encoded><![CDATA[<p>In this blog I'm going to demonstrate how to parse and validate more complex JSON and XML documents in Java using the <a href="http://code.google.com/p/rest-assured/">REST Assured</a> framework and the <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/xml/XmlPath.html">XmlPath</a> and <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/json/JsonPath.html">JsonPath</a> components available in this framework. Since REST Assured is implemented in Groovy it can be really beneficial to take advantage of Groovy's <a href="http://groovy.codehaus.org/Collections">collection</a> API. Let's begin by looking at an example in Groovy:</p>
<pre class="groovy">&nbsp;
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> words = <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'ant'</span>, <span style="color: #ff0000;">'buffalo'</span>, <span style="color: #ff0000;">'cat'</span>, <span style="color: #ff0000;">'dinosaur'</span><span style="color: #66cc66;">&#93;</span>
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> wordsWithSizeGreaterThanFour = words.<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20findAll"><span style="color: #663399;">findAll</span></a> <span style="color: #66cc66;">&#123;</span> it.<span style="color: #006600;">length</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> &gt; <span style="color: #cc66cc;">4</span> <span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>At the first line we simply define a list with some words but the second line is more interesting. Here we search the <code>words</code> list for all words that are longer than 4 characters by calling the <code>findAll</code> with a <a href="http://groovy.codehaus.org/Closures">Groovy closure</a>. The closure has an implicit variable called "it" which represents the current item in the list. The result is a new list, <code>wordsWithSizeGreaterThanFour</code>, containing <code>buffalo</code> and <code>dinosaur</code>. Pretty nice and simple! There are other interesting methods that we can use on collections in Groovy as well, e.g.</p>
<ul>
<li>find - finds the first item matching a closure predicate</li>
<li>collect - collect the return value of calling a closure on each item in a collection</li>
<li>sum - Sum all the items in the collection</li>
<li>max/min - returns the max/min values of the collection</li>
</ul>
<p>So how do we take advantage of this when validating our XML or JSON responses with REST Assured?</p>
<h2>XML Example</h2>
<p>Let's say we have a resource at "localhost:8080/shopping" that returns the following XML:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;shopping<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;category</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;groceries&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item<span style="font-weight: bold; color: black;">&gt;</span></span></span>Chocolate<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item<span style="font-weight: bold; color: black;">&gt;</span></span></span>Coffee<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/category<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;category</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;supplies&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item<span style="font-weight: bold; color: black;">&gt;</span></span></span>Paper<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item</span> <span style="color: #000066;">quantity</span>=<span style="color: #ff0000;">&quot;4&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>Pens<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/category<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;category</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;present&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;item</span> <span style="color: #000066;">when</span>=<span style="color: #ff0000;">&quot;Aug 10&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>Kathryn's Birthday<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/item<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/category<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/shopping<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Let's also say we want to write a test that verifies that the category of type <code>groceries</code> has items Chocolate and Coffee. In REST Assured it can look like this:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;shopping.category.find { it.@type == 'groceries' }.item&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;</pre>
</pre>
<p>What's going on here? First of all the XML path "shopping.category" returns a list of all categories. On this list we invoke a function, <code>find</code>, to return the single category that has the XML attribute, <code>type</code>, equal to "groceries". On this category we then continue by getting all the items associated with this category. Since there are more than one item associated with the groceries category a list will be returned and we verify this list against the hasItems <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> matcher. </p>
<p>But what if you want to get the items and not validate them against a Hamcrest matcher? This is also simple using the <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/xml/XmlPath.html">XmlPath</a> class:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as a String</span>
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> response = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// And get the grocieries from the response. &quot;from&quot; is statically imported from the XmlPath class</span>
List&lt;String&gt; groceries = from<span style="color: #66cc66;">&#40;</span>response<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getList</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;shopping.category.find { it.@type == 'groceries' }.item&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>If the list of groceries is the only thing you care about in the response body you can also use a shortcut:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as a String</span>
List&lt;String&gt; groceries = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">path</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;shopping.category.find { it.@type == 'groceries' }.item&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h3>Depth-first search</h3>
<p>It's actually possible to simplify the previous example even further:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == 'groceries' }&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p><code>**</code> is a shortcut for doing depth first searching in the XML document. We search for the first node that has an attribute named <code>type</code> equal to "groceries". Notice also that we don't end the XML path with "item". The reason is that <code>toString()</code> is called automatically on the category node which returns a list of the item values.</p>
<h3>Root path</h3>
<p>Let's expand the example by also validating that the category of type supplies contains Paper and Pens:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == 'groceries' }&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == 'supplies' }&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Paper&quot;</span>, <span style="color: #ff0000;">&quot;Pens&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Even though this works you can probably see that the XML path is almost duplicated for the two body expectations and this is of course something we want to avoid. To address this we can use a root path and path arguments:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">rootPath</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;**.find { it.@type == '%s' }&quot;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;&quot;</span>, withArgs<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;groceries&quot;</span><span style="color: #66cc66;">&#41;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Chocolate&quot;</span>, <span style="color: #ff0000;">&quot;Coffee&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;&quot;</span>, withArgs<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;supplies&quot;</span><span style="color: #66cc66;">&#41;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Paper&quot;</span>, <span style="color: #ff0000;">&quot;Pens&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
         <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/shopping&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>By specifiying a "root path" we don't need to duplicate the entire path just to change the category type.</p>
<h2>JSON Example</h2>
<p>Let's say we have a resource at "/store" that returns the following JSON document:</p>
<pre>&nbsp;
{ &quot;store&quot; : {
  &quot;book&quot; : [
          { &quot;author&quot; : &quot;Nigel Rees&quot;,
            &quot;category&quot; : &quot;reference&quot;,
            &quot;price&quot; : 8.95,
            &quot;title&quot; : &quot;Sayings of the Century&quot;
          },
          { &quot;author&quot; : &quot;Evelyn Waugh&quot;,
            &quot;category&quot; : &quot;fiction&quot;,
            &quot;price&quot; : 12.99,
            &quot;title&quot; : &quot;Sword of Honour&quot;
          },
          { &quot;author&quot; : &quot;Herman Melville&quot;,
            &quot;category&quot; : &quot;fiction&quot;,
            &quot;isbn&quot; : &quot;0-553-21311-3&quot;,
            &quot;price&quot; : 8.99,
            &quot;title&quot; : &quot;Moby Dick&quot;
          },
          { &quot;author&quot; : &quot;J. R. R. Tolkien&quot;,
            &quot;category&quot; : &quot;fiction&quot;,
            &quot;isbn&quot; : &quot;0-395-19395-8&quot;,
            &quot;price&quot; : 22.99,
            &quot;title&quot; : &quot;The Lord of the Rings&quot;
          }
        ]
   }
}
&nbsp;</pre>
<h3>Example 1</h3>
<p>As a first example let's say we want to make the request to "/store" and assert that the titles of the books with a price less than 10 are "Sayings of the Century" and "Moby Dick":</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.findAll { it.price &lt; 10 }.title&quot;</span>, hasItems<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Sayings of the Century&quot;</span>, <span style="color: #ff0000;">&quot;Moby Dick&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Just as in the XML examples above we use a closure to find all books with a price less than 10 and then return the titles of all the books. We then use the <code>hasItems</code> matcher to assert that the titles are the ones we expect. Using <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/json/JsonPath.html">JsonPath</a> we can return the titles instead:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as a String</span>
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> response = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// And get all books with price &lt; 10 from the response. &quot;from&quot; is statically imported from the JsonPath class</span>
List&lt;String&gt; bookTitles = from<span style="color: #66cc66;">&#40;</span>response<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getList</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.findAll { it.price &lt; 10 }.title&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h3>Example 2</h3>
<p>Let's consider instead that we want to assert that the sum of the length of all author names are greater than 50. This is a rather complex question to answer and it really shows the strength of closures and Groovy collections. In REST Assured it looks like this:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.author.collect { it.length() }.sum()&quot;</span>, greaterThan<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">50</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>First we get all the authors ("store.book.author") and invoke the <code>collect</code> method on the resulting list with the closure <code>{ it.length() }</code>. What it does is to call the <code>length()</code> method on each author in the list and returns the result to a new list. On this list we simply call the <code>sum()</code> method to sum all the length's. The end result is <code>53</code> and we assert that it's greater than 50 by using the <code>greaterThan</code> matcher. But it's actually possible to simplify this even further. Consider the <code>words</code> example from the beginning of the article again:</p>
<pre class="groovy">&nbsp;
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> words = <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'ant'</span>, <span style="color: #ff0000;">'buffalo'</span>, <span style="color: #ff0000;">'cat'</span>, <span style="color: #ff0000;">'dinosaur'</span><span style="color: #66cc66;">&#93;</span>
&nbsp;</pre>
<p>Groovy has a very handy way of calling a function for each element in the list by using the <code>*</code> notation, e.g.</p>
<pre class="groovy">&nbsp;
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20def"><span style="color: #000000; font-weight: bold;">def</span></a> words = <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'ant'</span>, <span style="color: #ff0000;">'buffalo'</span>, <span style="color: #ff0000;">'cat'</span>, <span style="color: #ff0000;">'dinosaur'</span><span style="color: #66cc66;">&#93;</span>
<a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20assert"><span style="color: #000000; font-weight: bold;">assert</span></a> <span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">6</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">8</span><span style="color: #66cc66;">&#93;</span> == words*.<span style="color: #006600;">length</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;</pre>
<p>I.e. Groovy returns a new list with the lengths of the items in the words list. We can utilize this for the author list in REST Assured as well:</p>
<pre class="java">&nbsp;
expect<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">body</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.author*.length().sum()&quot;</span>, greaterThan<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">50</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.
<span style="color: #006600;">when</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.
        <span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>And of course we can use <a href="http://rest-assured.googlecode.com/svn/tags/1.4/apidocs/com/jayway/restassured/path/json/JsonPath.html">JsonPath</a> to actually return the result:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">// Get the response body as an input stream</span>
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInputStream+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">InputStream</span></a> response = get<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/store&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">asInputStream</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Get the sum of all author length's as an int. &quot;from&quot; is again statically imported from the JsonPath class</span>
<span style="color: #993333;">int</span> sumOfAllAuthorLengths = from<span style="color: #66cc66;">&#40;</span>response<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getInt</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;store.book.author*.length().sum()&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// We can also assert that the sum is equal to 53 as expected.</span>
assertThat<span style="color: #66cc66;">&#40;</span>sumOfAllAuthorLengths, is<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">53</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Summary</h2>
<p>At a first glance the syntax may seem quite strange and complex but once you get used to it it's extremely powerful and actually quite simple. It's also a good place to start if you work with Java and want to understand the benefit of closures. There are a lot more features that can help you parsing and validating JSON and XML using <a href="http://code.google.com/p/rest-assured/">REST Assured</a> than the ones shown in this article. For further reading refer to the <a href="http://code.google.com/p/rest-assured/">REST Assured web-page</a> and read up on <a href="http://groovy.codehaus.org/Collections">Groovy collections</a>. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/09/simple-parsing-of-complex-json-and-xml-documents-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Finding unread mail in Gmail in your browser</title>
		<link>http://blog.jayway.com/2011/10/08/finding-unread-mail-in-gmail-in-your-browser/</link>
		<comments>http://blog.jayway.com/2011/10/08/finding-unread-mail-in-gmail-in-your-browser/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 09:01:36 +0000</pubDate>
		<dc:creator>Tobias Södergren</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[filtering]]></category>
		<category><![CDATA[gmail]]></category>
		<category><![CDATA[unread]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10057</guid>
		<description><![CDATA[Usually when I have a lot of emails in my inbox, I tend to skim most of them and then mark interesting mails as being unread so that I can read them later on. Sometimes that later on is getting pushed further and further away in the future and suddenly there's a bunch of unread [...]]]></description>
			<content:encoded><![CDATA[<p>Usually when I have a lot of emails in my inbox, I tend to skim most of them and then mark interesting mails as being unread so that I can read them later on. Sometimes that later on is getting pushed further and further away in the future and suddenly there's a bunch of unread mails in my inbox. The<br />
mails are scattered throughout the inbox and trying to find them using by<br />
paginating is quite tedious work. Luckily there's an easier way by using the search box:</p>
<p><code>is:unread label:inbox</code></p>
<p>This will list all unread mails in the inbox. Unfortunately this query is useless when saved<br />
as a filter, as new mail will not be processed by operators such as in:, has: and so on.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/08/finding-unread-mail-in-gmail-in-your-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Backing up a boot camp partition</title>
		<link>http://blog.jayway.com/2011/10/06/backing-up-a-boot-camp-partition/</link>
		<comments>http://blog.jayway.com/2011/10/06/backing-up-a-boot-camp-partition/#comments</comments>
		<pubDate>Thu, 06 Oct 2011 07:44:22 +0000</pubDate>
		<dc:creator>Anders Poulsen</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[Boot Camp]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10050</guid>
		<description><![CDATA[As a .Net developer using a MacBook Pro as my development machine, I plan on using Windows 7 installed on a Boot Camp partition. That way I can either boot into Windows directly for maximum performance or use VMWare Fusion to get the best of both platforms. After a few initial days of work, I've [...]]]></description>
			<content:encoded><![CDATA[<p>As a .Net developer using a MacBook Pro as my development machine, I plan on using Windows 7 installed on a Boot Camp partition. That way I can either boot into Windows directly for maximum performance or use VMWare Fusion to get the best of both platforms.</p>
<p>After a few initial days of work, I've now installed all the tools I need including but far from limited to VS2010, Resharper, SQL Server Express 2008, NUnit, Git Extensions, Tortoise, Beyond Compare and many more. The project that I will be working on is also configured with locally running IIS7 websites, SQL server databases, certificates and, again, much more.</p>
<p>Now is the time, I think, to do a backup/snapshot/whatever of my Windows partition, because I certainly do not want to go through the entire install/configure process again and my Windows installation is still fairly clean.</p>
<p>I considered using Fusions "snapshot" feature, but VMWare recommends that you <a href="http://kb.vmware.com/kb/1014509" target="_blank">don't use snapshots as a backup strategy</a>.</p>
<p>My first move is to use WinClone to create a backup image of the entire boot camp partition, since Time Machine only backs up my OS X files. The otherwise incredible tool Super Duper will not do the trick here, since it only handles OS X partitions. A caveat here is that WinClone is discontinued from the originator and doesn't support Lion. However, an alternative version that does support Lion can be found <a title="Winclone that supports Lion" href="http://roaringapps.com/app:904" target="_blank">here</a>. I'm currently backing up my Boot Camp partition to a USB drive. Next step will be to test if that backup can actually be used for anything.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/06/backing-up-a-boot-camp-partition/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using s3cmd to Backup your WordPress Installation</title>
		<link>http://blog.jayway.com/2011/10/02/using-s3cmd-to-backup-your-wordpress-data/</link>
		<comments>http://blog.jayway.com/2011/10/02/using-s3cmd-to-backup-your-wordpress-data/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 21:05:18 +0000</pubDate>
		<dc:creator>Henrik Bernström</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[backupwordpress]]></category>
		<category><![CDATA[cron]]></category>
		<category><![CDATA[crontab]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[s3]]></category>
		<category><![CDATA[s3cmd]]></category>
		<category><![CDATA[shell scripting]]></category>
		<category><![CDATA[ubuntu]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9849</guid>
		<description><![CDATA[This article will explain, in a few short steps, how to backup your WordPress installation to Amazon S3 service. It will deal with Ubuntu as operating system and Amazon EC2 for hosting but is not limited to such an environment. Prerequisits are an Amazon account for the S3 service, a WordPress installation and knowledge of [...]]]></description>
			<content:encoded><![CDATA[<p>This article will explain, in a few short steps, how to backup your WordPress installation to Amazon S3 service. It will deal with Ubuntu as operating system and Amazon EC2 for hosting but is not limited to such an environment. Prerequisits are an Amazon account for the S3 service, a WordPress installation and knowledge of these products.</p>
<h2>How to backup WordPress</h2>
<p>There are numerous plugins for WordPress when it comes to backup. I have learnt to appreciate the plugin BackUpWordPress as it not only backs up your database but also all the files within the installation. </p>
<p><a href="http://hmn.md/backupwordpress/" title="BackUpWordPress">http://hmn.md/backupwordpress/</a></p>
<p>There are a few number (though quite complete) of configuration options like</p>
<p>- manual or daily scheduled backups<br />
- number of backups to keep<br />
- whether to include files or database or both</p>
<p>The backups are stored on disk on the path of your choice and could also be attempted to be emailed. Having this kind of backup data makes it very comfortable to restore your WordPress installation.</p>
<p>But what if your complete machine/instance is failing? On, for example Amazon EC2 one should take snapshots of instances when the setup of these change but this does not apply to content changes. Restoring from a snapshot does not bring back newly created or updated content from, for example WordPress. That is, moving those WordPress backup files to a safer place becomes vital. So, s3cmd to the rescue.</p>
<h2>What is s3cmd?</h2>
<p>Extracted from its' homepage:</p>
<p><em>"S3cmd is a command line tool for uploading, retrieving and managing data in Amazon S3. It is best suited for power users who don't fear command line. It is also ideal for scripts, automated backups triggered from cron, etc."</em></p>
<p><a href="http://s3tools.org/s3cmd" title="s3cmd">http://s3tools.org/s3cmd</a></p>
<p>At the time of writing s3cmd requires Python 2.4 or newer and some pretty common Python modules. Installing it is merely a matter of running:</p>
<pre class="brush: shell; ruler: true; auto-links: false; smart-tabs: false;">sudo apt-get install s3cmd</pre>
<p>To configure it run</p>
<pre class="brush: shell; ruler: true; auto-links: false; smart-tabs: false;">s3cmd --configure</pre>
<p>You will be asked for the two keys of your Amazon account - copy and paste them from your confirmation email or from your Amazon account page.</p>
<p>To list all your buckets run</p>
<pre class="brush: shell; ruler: true; auto-links: false; smart-tabs: false;">s3cmd ls</pre>
<p>and to list the content of a bucket run</p>
<pre class="brush: shell; ruler: true; auto-links: false; smart-tabs: false;">s3cmd ls s3://[bucket name]</pre>
<p>Now, you could use 's3cmd put' to upload and 's3cmd remove' to remotely remove specific files but then you would have to do some scripting to select these specific files and to keep the bucket contents to an acceptable size. There is another option that simply syncs the content of your local directory to the remote bucket, doing the removal automatically, namely 's3cmd sync'.</p>
<pre class="brush: shell; ruler: true; auto-links: false; smart-tabs: false;">s3cmd sync --delete-removed [source directory] s3://[bucket name]</pre>
<p>The source directory is naturally replaced with the directory of where you put your WordPress backups. </p>
<h2>Scheduling it</h2>
<p>To make it a little easier to schedule via crontab you preferrably put the sync command in a shell script, for example 'sync-wp-backups.sh'</p>
<pre class="brush: bash/shell; ruler: true; auto-links: false; smart-tabs: false;">#!/bin/bash

/usr/bin/s3cmd sync --delete-removed [source directory] s3://[bucket name]</pre>
<p>To schedule this script run</p>
<pre class="brush: bash/shell; ruler: true; auto-links: false; smart-tabs: false;">crontab -e</pre>
<p>which brings you into editing the cron job with the editor of your choice. For example you could edit the crontab file to schedule it to run daily at 23:30 (11:30 PM)</p>
<pre class="brush: bash/shell; ruler: true; auto-links: false; smart-tabs: false;">30 23 * * * /home/ubuntu/sync-wp-backups.sh >> /home/ubuntu/s3-backup.log</pre>
<p>which logs the output to file (s3-backup.log).</p>
<p>That's it! Now I have a number of days of backup automatically synced from the Amazon instance running WordPress to a more fail safe S3 bucket. At least I sleep a lot better with this in place.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/02/using-s3cmd-to-backup-your-wordpress-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IntelliJ IDEA performance improvement</title>
		<link>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/</link>
		<comments>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 17:26:58 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[home directory]]></category>
		<category><![CDATA[idea]]></category>
		<category><![CDATA[intellij]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9443</guid>
		<description><![CDATA[Working as a consultant, it is not unusual that I am referred to customer specific software environment with regard to computers, operating systems, networks and other configurations. However, since I work with Java, most tools are available online and they can easily be downloaded and installed on different platforms. IntelliJ IDEA is no exception, but [...]]]></description>
			<content:encoded><![CDATA[<p>Working as a consultant, it is not unusual that I am referred to customer specific software environment with regard to computers, operating systems, networks and other configurations. However, since I work with Java, most tools are available online and they can easily be downloaded and installed on different platforms. IntelliJ IDEA is no exception, but before you start coding you should make sure you know how the <a href="http://en.wikipedia.org/wiki/Home_directory">home directory</a> of your computer is setup and configure IntelliJ IDEA accordingly. From the <a href="http://devnet.jetbrains.net/docs/DOC-181">documentation</a>:</p>
<blockquote><p>
In some environments user's home directory is located on the mapped network drive which in unacceptable for IntelliJ IDEA. You'll notice the huge performance degradation.
</p></blockquote>
<h2>What is the problem?</h2>
<p>There are some good motives for keeping the home directory mounted to a network folder rather than on the local hard drive. For example, all user settings and user documents can be backed up centrally, and the user could potentially log in to any computer and have the same user environment. However, there are also some drawbacks. Depending on how the home folder is configured, there will either be a remote network call for each file access, or the file changes will be executed as a batch job at scheduled intervals or specific events such as logging off the computer.</p>
<p>The second part of the problem is that IntelliJ IDEA produces quite a lot of data, typically several hundred megabytes, besides the anticipated artifacts. The data consists of IDE plugins, configuration files, log files, but the vast majority is internal cache files. By default, the data is written to a hidden <i>.IntelliJIdea10/</i> folder in your home directory.</p>
<p>If you combine these two factors, the performance will suffer. How much depends on the bandwidth of your network, something that I became painfully aware of when I logged in remotely to the customer's network via a slow VPN connection.</p>
<h2>Solution</h2>
<p>Avoid network overhead by configuring IntelliJ IDEA to cache data on your local computer instead of in your home folder. A recent customer used Windows XP as their working environment, the instructions below are based on that experience.</p>
<ol>
<li>
Create a new directory on a <i>local</i> harddrive that IntelliJ IDEA can use, e.g. <i>C:/.IntelliJIdea10/</i>. Hint, you cannot create a library starting with a "." from Windows Explorer, you have to use the <code>mkdir</code> command from the terminal.
</li>
<li>
Locate the <i>idea.properties</i> file in the <i>bin</i> directory in IntelliJ IDEA's installation directory. The default location is <i>C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 10.5.1\bin</i>.
</li>
<li>
Change the relevant properties to point to the recently created directory:</p>
<pre class="brush:xml">
# path to IDEA config folder. Make sure you're using forward slashes
idea.config.path=C:/.IntelliJIdea10/config

# path to IDEA system folder. Make sure you're using forward slashes
idea.system.path=C:/.IntelliJIdea10/system

# path to user installed plugins folder. Make sure you're using forward slashes
idea.plugins.path=C:/.IntelliJIdea10/config/plugins
</pre>
</li>
</ol>
<h2>Considerations</h2>
<p>Consider <i>not</i> to change the <i>idea.config.path</i> property if you are using several different computers and you would like to have the same configuration on all machines. Additionally, if you are using IntelliJ IDEA Ultimate, i.e. the commercial version of the tool, you should also make a cautious decision about whether or not to keep this property unchanged, because the license file is stored in the denoted directory. On the other hand, if you always use the same computer you might as well change this property together with the other properties, so that all IntelliJ IDEA files are stored in the same location.</p>
<h2>References</h2>
<ul>
<li>IDEA files location: <a href="http://devnet.jetbrains.net/docs/DOC-181">http://devnet.jetbrains.net/docs/DOC-181</a></li>
<li>IDEA license key: <a href="http://devnet.jetbrains.net/docs/DOC-200">http://devnet.jetbrains.net/docs/DOC-200</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Storing double.NaN in a WP7 SQLCE database</title>
		<link>http://blog.jayway.com/2011/09/23/storing-double-nan-in-a-wp7-sqlce-database/</link>
		<comments>http://blog.jayway.com/2011/09/23/storing-double-nan-in-a-wp7-sqlce-database/#comments</comments>
		<pubDate>Fri, 23 Sep 2011 12:02:13 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[sqlce]]></category>
		<category><![CDATA[windows phone 7]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9667</guid>
		<description><![CDATA[Summary double.NaN gives me update issues (ChangeConflictException) in SQL Compact, my fallback was to set the value to zero instead: double.IsNaN(value.Altitude) ? 0 : value.Altitude where ‘Alt’ is the property on my SQLCE entity object. Of course NaN is not the same as zero – but that does not matter to me. Background For a [...]]]></description>
			<content:encoded><![CDATA[<h2>Summary</h2>
<p>double.NaN gives me update issues (ChangeConflictException) in SQL Compact, my fallback was to set the value to zero instead:</p>
<p>double.IsNaN(value.Altitude) ? 0 : value.Altitude</p>
<p>where ‘Alt’ is the property on my SQLCE entity object. Of course NaN is not the same as zero – but that does not matter to me.</p>
<h2>Background</h2>
<p>For a Windows Phone 7 demo app that I’m writing, I’ve been trying to store GPS locations in a SQL Compact database. The GeoCoordinate data type is not supported by SQLCE, so I just took the Latitude, Longitude and Altitude and stored those as doubles in the db. (<a href="http://msdn.microsoft.com/en-us/library/ms172424(SQL.110).aspx">here's a list of SQL Compact supported data types</a>)</p>
<p>And, this was not my first my first version of the app (hence db), so I had to make the properties nullable – otherwise the SQLCE engine cannot add columns for them, <a href="http://msdn.microsoft.com/en-us/library/hh202860(VS.92).aspx">read more about wp7 databases here</a>. I do not think the nullable thing was a part of my problem, but you never know…</p>
<h2>The problem</h2>
<p>So, I happily took data from the GPS in the emulator, got double.NaN as the Altitude and saved that to the DB, all fine so far… Then when updating the database record with other values and trying to save the entry again, I kept getting the error: </p>
<p>ChangeConflictException {&quot;Row not found or changed.&quot;}</p>
<p>Since this problem appeared when I added the Altitude to the database, it was my prime suspect and when I removed it again all was fine.</p>
<p>I’m not sure of the inner workings of this problem, but I suspect it having to do with the fact that when trying to compare a double with double.NaN, VS hints with:</p>
<p><em>A NaN does not compare equal with any floating point number</em></p>
<p>I can perfectly understand that NaN is a special case so I’m fine with sidestepping it like this.</p>
<h2>The fix</h2>
<pre class="brush: csharp;">Alt = double.IsNaN(value.Altitude) ? 0 : value.Altitude;</pre>
<p>The code in the [Table] class:</p>
<pre class="brush: csharp;">private double? _alt;
[Column(CanBeNull = true)]
public double? Alt
{
    get { return _alt; }
    set
    {
        OnPropertyChanging(&quot;Alt&quot;);
        _alt = value;
        OnPropertyChanged(&quot;Alt&quot;);
    }
}

public GeoCoordinate Location
{
    get { return new GeoCoordinate(
        Lat.GetValueOrDefault(),
        Lng.GetValueOrDefault(),
        Alt.GetValueOrDefault()); }
    set
    {
        Lat = value.Latitude;
        Lng = value.Longitude;

        //just setting the double.NaN value, this gave me trouble
        //Alt = value.Altitude;

        //my fix: replacing NaN with zero
        Alt = double.IsNaN(value.Altitude) ? 0 : value.Altitude;

        _location = value;
    }            </pre>
<p>And the code where I update the Item entity from my view model:</p>
<pre class="brush: csharp;">private void SaveEntry()
{
    var item = (from i in db.Items
                where i.Id == ViewModel.Id
                select i).First();

    db.Refresh(RefreshMode.OverwriteCurrentValues, item);

    item.PhotoUrl = ViewModel.PhotoUrl;
    item.Text = ViewModel.LongText;
    item.Title = ViewModel.Title;
    item.Location = ViewModel.Location;
    db.SubmitChanges();
}</pre>
<p>I have of course tried the different RefreshModes, with the same result.</p>
<p>I hope this helped someone out there with weird SQL errors and NaN values.</p>
<p>Bye!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/23/storing-double-nan-in-a-wp7-sqlce-database/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using QtCreator for Arduino development</title>
		<link>http://blog.jayway.com/2011/09/22/using-qtcreator-for-arduino-development/</link>
		<comments>http://blog.jayway.com/2011/09/22/using-qtcreator-for-arduino-development/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 13:16:07 +0000</pubDate>
		<dc:creator>Mario Boikov</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[arduino]]></category>
		<category><![CDATA[Qt]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9617</guid>
		<description><![CDATA[Introduction I've been using QtCreator for some time now, mostly for Qt projects, and I really like the environment. It's fast and have plenty of features for c/c++ development such as code completion, symbol navigation, and git integration. Today I decided to try if I could use QtCreator for Arduino development and it turned out [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>I've been using QtCreator for some time now, mostly for Qt projects, and I really like the environment. It's fast and have plenty of features for c/c++ development such as code completion, symbol navigation, and git integration.</p>
<p>Today I decided to try if I could use QtCreator for Arduino development and it turned out that it wasn't that difficult. The environment isn't perfect but it works and it doesn't take much effort to set up a project.</p>
<p><em>Disclaimer: I'm not doing Arduino development regularly, I just find it amusing to toggle bits on 8-bit hardware now and then. If you find anything in this post that seems totally wrong please let me know.</em></p>
<p><strong>Prerequisites</strong></p>
<p>This tutorial assumes that you're running Ubuntu. It shouldn't be too difficult to adjust for other Linux distributions.</p>
<p>If you haven't already installed the latest QtSDK (1.1.3), please download it from <a title="http://qt.nokia.com/downloads" href="http://qt.nokia.com/downloads" target="_blank">http://qt.nokia.com/downloads</a> and do so.</p>
<p>Install arduino-core package from the Ubuntu repository</p>
<pre>$&gt; sudo apt-get install arduino-core</pre>
<p>This should pull in required dependencies too, such as avr-gcc and avrdude.</p>
<p>Install gtkterm (optional, but recommended)</p>
<pre>$&gt; sudo apt-get install gtkterm</pre>
<p><strong>Creating a simple 'Hello World' project</strong></p>
<p>You can create everything from within QtCreator but I find it easier to do the initial set up from command line.</p>
<pre>$&gt; cd &lt;projects folder&gt;
$&gt; mkdir -p helloworld/src
$&gt; cd helloworld/src</pre>
<p>If you look at the top of the file <em>/usr/share/arduino/Arduino.mk</em> you'll find instructions on how to create a suitable <em>Makefile</em> for your project.</p>
<p>Here's one that I use, just put the content in <em>helloworld/src/Makefile</em></p>
<pre>ARDUINO_DIR  = /usr/share/arduino

TARGET       = main
ARDUINO_LIBS =

MCU          = atmega328p
F_CPU        = 16000000

# Avrdude code
ARDUINO_PORT = /dev/ttyACM0
AVRDUDE_ARD_PROGRAMMER = arduino
AVRDUDE_ARD_BAUDRATE = 115200

include /usr/share/arduino/Arduino.mk</pre>
<p>Finally create <em>helloworld/src/app.cpp</em> with the following content:</p>
<pre><code>
#include &lt;WProgram.h&gt;

void setup()
{
}

void loop()
{
}
</code></pre>
<p><strong>Importing the <em>Hello World</em> project</strong></p>
<p>Start QtCreator and go to <em>'File/New File or Project'</em> (<em>ctrl+n</em>) and then choose <em>'Other Project/Import Existing Project'</em>.</p>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/import_project.png" rel="lightbox"><img class="size-medium wp-image-9620 aligncenter" title="Import project" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/import_project-300x260.png" alt="" width="300" height="260" /></a></p>
<p>Finish the wizard by specifying <em>'HelloWorld'</em> as <em>'Project name'</em> and <em>'&lt;projects folder&gt;/helloworld'</em> as <em>'Location'</em>. You might wonder why I specified <em>'helloworld'</em> as project location instead of <em>'helloworld/src'</em>. This is because I don't want QtCreator's project files to end up in the same folder as my source. Just click on <em>'Next'</em> on the following questions to finish the wizard.</p>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/project_name.png" rel="lightbox"><img class="size-medium wp-image-9621 aligncenter" title="Project name" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/project_name-300x273.png" alt="" width="300" height="273" /></a></p>
<p>QtCreator creates three files:</p>
<ul>
<li>HelloWorld.conf - Add defines</li>
<li>HelloWorld.files - List all files that are part of the project</li>
<li>HelloWorld.includes - List all include paths</li>
</ul>
<p style="text-align: left;">Add '/usr/share/arduino/hardware/arduino/cores/arduino' to 'HelloWorld.includes'. This tells QtCreator where to look for Arduino specific header files.</p>
<p><strong>Configuring 'Clean/Build/Run'</strong><br />
Click 'Projects' (<em>ctrl+5</em>) on the bar to the left to activate the project settings page to change the build and run settings.</p>
<p><strong>Clean and Build settings</strong><br />
Change <em>'Build directory'</em> to <em>'&lt;projects folder&gt;/helloworld/src'</em> and modify the settings to reflect the screen shot below.</p>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/build_settings1.png" rel="lightbox"><img class="size-full wp-image-9624 aligncenter" title="Clean and Build settings" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/build_settings1.png" alt="" width="482" height="426" /></a><strong></strong></p>
<p style="text-align: left;"><strong>Run settings</strong><br />
Choose 'Add Deploy Step' and use the screen shot below to specify the settings.</p>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/run_settings.png" rel="lightbox"><img class="size-full wp-image-9625 aligncenter" title="Run settings" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/run_settings.png" alt="" width="493" height="378" /></a></p>
<p style="text-align: left;">
If you didn't install gtkterm you can specify '<em>echo'</em> or something in the <em>'Run configuration'</em>.</p>
<p style="text-align: left;"><strong>The Hello World app</strong><br />
Finally I'll write the code and upload/run it on the Arduino.</p>
<p style="text-align: left;">Open <em>'app.cpp'</em> and change the code to the following snippet:</p>
<pre><code>
#include &lt;WProgram.h&gt;

void setup()
{
    Serial.begin(115200);
}

void loop()
{
    Serial.println("Hello World");
    delay(1000);
}
</code></pre>
<p>Press <em>ctrl+r</em> and hopefully you'll see 'Hello World' printed each second in the gtkterm console.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/22/using-qtcreator-for-arduino-development/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Infinitest</title>
		<link>http://blog.jayway.com/2011/09/21/infinitest/</link>
		<comments>http://blog.jayway.com/2011/09/21/infinitest/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 20:20:06 +0000</pubDate>
		<dc:creator>Anders Eriksson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[junit]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9572</guid>
		<description><![CDATA[The Infinitest Eclipse plug-in looks for unit tests and have them run as soon as changes are detected. Just as modern IDEs have provided automatic compilation for ages this can now also be provided for unit testing. The test outcome shows up as a green or red bar in the bottom of the Eclipse application [...]]]></description>
			<content:encoded><![CDATA[<p>The <a title="Infinitest" href="http://infinitest.github.com/">Infinitest</a> Eclipse plug-in looks for unit tests and have them run as soon as changes are detected. Just as modern IDEs have provided automatic compilation for ages this can now also be provided for unit testing.</p>
<p>The test outcome shows up as a green or red bar in the bottom of the Eclipse application window. The plugin also gives more feedback. In case of failing test the failing line of code in the unit test shows up with a "problem" icon just as a compilation error would look like. Doing mouse-over on the problem icon you will get the failing assert message. This feature I have noticed in recent versions of Eclipse so try to update to the latest Eclipse if you don't see this happen.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/infinitest12.png" rel="lightbox"><img class="alignnone size-full wp-image-9591" title="infinitest1" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/infinitest12.png" alt="" width="640" height="243" /></a></p>
<p>The problem indicator is quite powerful and allows a higher level of TDD. When doing pure TDD you write a failing test first. This would make Infinitest mark your assert statement as problematic until you save a working implementation of your tested code. This allows a very focused <em>write failing test / write implementation</em>-loop.</p>
<p>Infinitest operates independently from the JUnit view in Eclipse. As Infinitest is activated as soon as source code is saved while JUnit is run when initiated by the developer the state shown by either system is often out of sync. I have also experienced that the Infinitest fails to "re-test" but then a project clean brings it back on track. Even if there are quirks I think Infinitest is useful for my daily work and it really promotes TDD.</p>
<p>The plug-in is available on update site http://infinitest.github.com/ and if you are using SpringSource Tool Suite (STS) the plug-in is also available in STS's  extension list.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/21/infinitest/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Asset management with Sprockets</title>
		<link>http://blog.jayway.com/2011/09/19/asset-management-with-sprockets/</link>
		<comments>http://blog.jayway.com/2011/09/19/asset-management-with-sprockets/#comments</comments>
		<pubDate>Mon, 19 Sep 2011 13:20:38 +0000</pubDate>
		<dc:creator>Andreas Hallberg</dc:creator>
				<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Ruby On Rails]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9317</guid>
		<description><![CDATA[A quick tip in case you're a Ruby person and haven't used the Sprockets gem: Sprockets is a Rack application that serves assets (javascript, css, images etc) over HTTP. It's built in to Rails 3.1 and DHH spent a significant portion of the RailsConf 2011 keynote promoting its benefits (although I'm not sure he ever mentioned its [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;">A quick tip in case you're a Ruby person and haven't used the Sprockets gem: Sprockets is a Rack application that serves assets (javascript, css, images etc) over HTTP. It's built in to Rails 3.1 and DHH spent a significant portion of the <a href="http://www.youtube.com/watch?v=cGdCI2HhfAU" target="_blank">RailsConf 2011 keynote</a> promoting its benefits (although I'm not sure he ever mentioned its name).</p>
<p style="text-align: left;">From the <a href="https://github.com/sstephenson/sprockets">Sprockets github page</a>:</p>
<blockquote><p>Sprockets is a Ruby library for compiling and serving web assets. It features declarative dependency management for JavaScript and CSS assets, as well as a powerful preprocessor pipeline that allows you to write assets in languages like CoffeeScript, Sass, SCSS and LESS.</p></blockquote>
<p style="text-align: left;">Well put! The neat thing is that even if your project might not be on Rails 3.1 yet, you can still enjoy the Sprockets gem. Here's how I set up preprocessing and compilation (as in <em>organizing/concatenating</em>) of some CoffeeScript and JavaScript files in a gem I was working on:</p>
<p style="text-align: left;">1. In config.ru, I mapped up the folders I wanted to server assets from into a single, easy-to-remember path:</p>
<pre style="color: #d1d1d1; background: #000000;"><span style="color: #e66170; font-weight: bold;">require</span> <span style="color: #00c4c4;">'sprockets'</span>

map <span style="color: #00c4c4;">'/'</span> <span style="color: #e66170; font-weight: bold;">do</span>
  run My::Fancy::App
<span style="color: #e66170; font-weight: bold;">end</span>

map <span style="color: #00c4c4;">'/assets'</span> <span style="color: #e66170; font-weight: bold;">do</span>
  environment <span style="color: #d2cd86;">=</span> Sprockets::Environment<span style="color: #d2cd86;">.</span><span style="color: #e66170; font-weight: bold;">new</span>
  environment<span style="color: #d2cd86;">.</span>append_path <span style="color: #00c4c4;">'public/javascripts'</span>
  environment<span style="color: #d2cd86;">.</span>append_path <span style="color: #00c4c4;">'someOtherDirectory/coffeeScripts'</span>
  run environment
<span style="color: #e66170; font-weight: bold;">end</span></pre>
<p>2. I created a main.js file with Sprockets require statements, in the order I needed the files to be concatenated. As I needed erb and CoffeeScript preprocessing on some of them, I gave the file names the appropriate endings, in a right-to-left order of processing:</p>
<pre style="color: #d1d1d1; background: #000000;"><span style="color: #d2cd86;">/</span><span style="color: #d2cd86;">/</span><span style="color: #d2cd86;">=</span> <span style="color: #e66170; font-weight: bold;">require</span> A<span style="color: #d2cd86;">.</span>coffeescript<span style="color: #d2cd86;">.</span>erb
<span style="color: #d2cd86;">/</span><span style="color: #d2cd86;">/</span><span style="color: #d2cd86;">=</span> <span style="color: #e66170; font-weight: bold;">require</span> B<span style="color: #d2cd86;">.</span>js
<span style="color: #d2cd86;">/</span><span style="color: #d2cd86;">/</span><span style="color: #d2cd86;">=</span> <span style="color: #e66170; font-weight: bold;">require</span> C<span style="color: #d2cd86;">.</span>coffeescript<span style="color: #d2cd86;">.</span>erb</pre>
<p style="text-align: left;">So "A.coffeescript.erb" and "C.coffeescript.erb" will first be processed by erb, then by the CoffeeScript compiler. "B.js" will not be preprocessed by anything.</p>
<p style="text-align: left;">3. Good to go! In my HTML page I would load the whole enchilada like so:</p>
<pre style="color: #d1d1d1; background: #000000;">&lt;script type<span style="color: #d2cd86;">=</span><span style="color: #00c4c4;">"text/javascript"</span>  src <span style="color: #d2cd86;">=</span><span style="color: #00c4c4;">"/assets/main.js"</span> <span style="color: #d2cd86;">/</span>&gt;</pre>
<p>... which gives me one file served, preprocessed and concatenated.</p>
<p>It's easy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/19/asset-management-with-sprockets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

