<?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>Smartkey - Java Software Consultancy</title>
	<atom:link href="http://blog.smartkey.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smartkey.co.uk</link>
	<description></description>
	<lastBuildDate>Tue, 09 Mar 2010 15:43:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Open Session in View Pattern for Spring and JPA</title>
		<link>http://blog.smartkey.co.uk/2010/03/open-session-in-view-pattern-spring-jpa/</link>
		<comments>http://blog.smartkey.co.uk/2010/03/open-session-in-view-pattern-spring-jpa/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 18:13:24 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[Open]]></category>
		<category><![CDATA[Session]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Transaction]]></category>
		<category><![CDATA[View]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=676</guid>
		<description><![CDATA[The Open Session in View Pattern is well publicised in Hibernate circles as the best practice approach to presenting data in the Web tier of an application. In this article I'll demonstrate how simple it is to configure a Spring application to do the same thing with the Java Persistence API (JPA).]]></description>
			<content:encoded><![CDATA[<p>The Open Session in View Pattern is a well publicised <a href="https://www.hibernate.org/43.html" target="_blank">design pattern</a> for Hibernate applications and is considered the best practice approach to presenting data within the Web tier of an application. In this article I&#8217;ll demonstrate how simple it is to configure a Spring application to work the same way when JPA is used for the persistence technology. The exact same principles apply for a plain Spring/Hibernate application that does not use JPA.</p>
<h3>What is Open Session in View?</h3>
<p>The Java Persistence API (JPA) allows an object oriented model to be mapped to a relational database. JPA is a standard specification for Java based Object Relational Mapping frameworks &#8211; in order to use JPA an underlying implementation must be available; the most common choice being Hibernate.</p>
<p>Both JPA an Hibernate support lazy loading of data to restrict the number of queries fired off to the database. In general this means that data will be loaded on demand when methods are called, on a loaded object, that require more data to be loaded. In order for this to work, the object that the method is called on must have been loaded by JPA and be part of the current running transaction.</p>
<p>In a Spring application, calls to demarcate transactions are generally handled by the Spring interceptors.Transactions are normally started when a method call is made on a Spring managed object and committed once that method call ends. This means that if a JSP page requests data by calling a transactional method on a Spring managed bean, then it can only access the data in that bean that has already been loaded within that call. Any calls for data that might be loaded lazily will fail because the object is no longer attached to a JPA transaction after that method call has returned.</p>
<p>Hibernate developers solved this problem using the Open Session in View design, which associates the active session (and hence it&#8217;s transaction) with the thread that makes the call. In this design, the transaction will be committed when the thread completed processing the request, rather than when a method call completes. This allows lazily loaded data to be loaded within the JSP page not just within Spring managed objects.</p>
<h3>Providing Request Scoped Transactions</h3>
<p>A standard way to intercept requests in any Java Web application is to use a web filter. Spring provide an out-of-the-box Web filters that implement the Open Session in View design for both Hibernate and JPA. We will see the JPA version here, but the Hibernate one works in just the same way; just change the class name in the configuration file.</p>
<p>In web.xml:</p>
<pre class="brush: xml">
&lt;filter&gt;
    &lt;filter-name&gt;oemInViewFilter&lt;/filter-name&gt;
    &lt;filter-class&gt;
        org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
    &lt;/filter-class&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;entityManagerFactoryBeanName&lt;/param-name&gt;
        &lt;param-value&gt;reportsEntityManagerFactory&lt;/param-value&gt;
    &lt;/init-param&gt;
&lt;/filter&gt;

&lt;filter-mapping&gt;
    &lt;filter-name&gt;oemInViewFilter&lt;/filter-name&gt;
    &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;
</pre>
<p>The filter class is from the Spring framework libraries. The filter mapping, in this example, applies this filter to all URLs ending with &#8216;.jsp&#8217;; this means that all JSPs that retrieve a lazily loaded object form the service tier of the application are now free to read any data members from it &#8211; any unloaded data will be loaded from the database when calls are made to access it. </p>
<p>Be aware that the filter turns off the auto-flush behaviour of the standard entity manager. This means that any changes that are made to the data in the JSP will not be persisted. The filter can be configured to flush these if requested.</p>
<p>Finally, the init-param that&#8217;s provided to the filter is optional and can be used to explicitly name the entity manager factory that will be used. The example shows how to use an entity manager named &#8216;reportsEntityManagerFactory&#8217; in the Spring configuration files; the default value for this is &#8216;entityManagerFactory&#8217;.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/03/open-session-in-view-pattern-spring-jpa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Mockito to Unit Test Java Applications</title>
		<link>http://blog.smartkey.co.uk/2010/02/mockito-unit-test-java/</link>
		<comments>http://blog.smartkey.co.uk/2010/02/mockito-unit-test-java/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 18:39:26 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Tool support]]></category>
		<category><![CDATA[Google Code]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mockito]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=604</guid>
		<description><![CDATA[If you&#8217;ve spent any time writing unit tests then you&#8217;ll know that it&#8217;s not always straight-forward. Certain things are inherently hard to test. In this post I&#8217;ll show you the basic principles of creating mock objects with a little help from the Mockito mocking tool.
One common problem faced when unit testing is how to test [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve spent any time writing unit tests then you&#8217;ll know that it&#8217;s not always straight-forward. Certain things are inherently hard to test. In this post I&#8217;ll show you the basic principles of creating mock objects with a little help from the <a href="http://www.mockito.org">Mockito</a> mocking tool.</p>
<p>One common problem faced when unit testing is how to test one object when it is dependant on another object. You could create instances of both the object under test and the dependent object and test them both together, however testing aggregated objects is not what unit testing is about &#8211; unit tests should test individual objects for their correct behaviour, not aggregations of objects! Moreover, this approach just won&#8217;t work if the dependent object hasn&#8217;t even been implemented yet.</p>
<p>A common technique for handling dependencies in unit tests is to provide a surrogate, or &#8220;mock&#8221; object, for the dependent object instead of a real one. The mock object will implement a simplified version of the real objects methods that return predictable results and can be used for testing purposes. </p>
<p>The drawback of this approach is that in a complex application, you could find yourself creating a lot of mock objects. This is where frameworks like Mockito can save you a lot of time and effort.</p>
<h3>A Test Scenario</h3>
<p>To demonstrate what you can do with Mockito, we&#8217;ll examine how we might test an Account object that is dependant on a data access object (AccountDAO).  The account object can calculate the charges applicable in the current month by using the DAO to count the number of days overdrawn and then performing a simple calculation on the value obtained from that call. The method names on the classes we&#8217;ll use are self-explanatory:</p>
<p><img src="http://blog.smartkey.co.uk/wp-content/uploads/2010/02/AccountAndDAO1.png" alt="AccountAndDAO" title="AccountAndDAO" width="376" height="55" class="aligncenter size-full wp-image-648" /><br />
To test this thoroughly, we should test two things:</p>
<ol>
<li>that the account obtains the number of overdrawn days by calling the correct method on the DAO,</li>
<li>that the account calculates the correct fees based upon the value it gets back from the call.</li>
</ol>
<h3>Testing that the account calls the correct method on the DAO</h3>
<p>Using JUnit to run the test case, we could write something like this:</p>
<pre class="brush: java">
import static org.mockito.Mockito.*;

public class TestAccount {
    @Test
    public void checkAccountCallsDaoMethods() {
        //create the object under test
        Account account = new Account();

        //create a mock DAO
        AccountDAO mockedDao = mock(AccountDAO.class);	

        //associate the mocked DAO with the object under test
        account.setDAO(dao);

        //call the method under test
        long charge = account.calculateCharges();

        //verify that the &#039;countOverdrawnDaysThisMonth&#039; was called
        verify(mockedDao).countOverdrawnDaysThisMonth();
    }
}
</pre>
<p>Taking centre stage in all this is the Mockito class which has a bunch of static methods that are used within the unit test (note the static import on line 1). </p>
<p>The call to the &#8216;mock&#8217; method (line 10) creates a mock object that can be used in place of a real AccountDAO. The call to &#8216;verify&#8217; (line 19), will throw an exception if the &#8216;countOverdrawnDaysThisMonth&#8217; method was not called on the mock object. </p>
<p>It is worth noting here that this is a simple example which just demonstrates the basic principle of verification, it is also possible to use the verify method to check for parameter values and ranges in the method call too.</p>
<h3>Testing that the account performs its calculations correctly</h3>
<p>In the above example, we mocked the DAO but didn&#8217;t specify what any of the mocked methods should do. In this case, all methods will return sensible default values of: null, zero or false. More commonly we need to specify something other than these defaults when writing our tests:</p>
<pre class="brush: java">
import static org.mockito.Mockito.*;
import static junit.framework.Assert.*;
import org.junit.*;

public class TestAccount {
    private Account account;

    @Before
    public void setup() {
        AccountDAO mockedDao = mock(AccountDAO.class);

    	//specify that this method on the mock object should return 8
        when(mockedDao.countOverdrawnDaysThisMonth()).thenReturn(8);

        account = new Account();
        account.setDAO(dao);
    }

    @Test
    public void checkChargesWhenOverdrawn() {
        //call the method under test
        long charge = account.calculateCharges();

        //assert that the charge was £2 per day overdrawn
        assertEquals(charge, 16);
    }
}
</pre>
<p>The statement on line 18 specifies that whenever the &#8216;countOverdrawnDaysThisMonth&#8217; is called it should return a value of 8; overriding the default of zero.</p>
<p>Given that the correct charge is two pounds (or dollars) per day overdrawn, then the assertion on line 25 will pass if the account performed the correct calculation (8 x 2 = 16 right).</p>
<h3>Comments</h3>
<p>There&#8217;s loads more to Mockito than we&#8217;ve looked at here. It&#8217;s a neat testing tool that works great with JUnit or TestNG. I&#8217;ve found that it&#8217;s small enough to learn quickly and capable enough to be really useful. Give it a go and write a comment below to let me know what you think of it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/02/mockito-unit-test-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Configuring MySQL on Mac OS X</title>
		<link>http://blog.smartkey.co.uk/2010/02/configuring-mysql-on-mac-os-x/</link>
		<comments>http://blog.smartkey.co.uk/2010/02/configuring-mysql-on-mac-os-x/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 14:41:03 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Tool support]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=624</guid>
		<description><![CDATA[I found the documentation for MySQL a little rough around the edges recently when I needed to change a configuration setting for it &#8211; everything seemed spread around their comprehensive PDF documentation and it took me a little while to fathom my way through it. 
It&#8217;s not often that changes to MySQL configuration need to [...]]]></description>
			<content:encoded><![CDATA[<p>I found the documentation for MySQL a little rough around the edges recently when I needed to change a configuration setting for it &#8211; everything seemed spread around their comprehensive PDF documentation and it took me a little while to fathom my way through it. </p>
<p>It&#8217;s not often that changes to MySQL configuration need to be made. This post is, therefore, more a reminder to myself than anything else.</p>
<p>First locate the configuration file. On my Mac I found this empty configuration file had been created as part of the installation process:</p>
<p><code>/etc/my.cnf</code> </p>
<p>You&#8217;ll need super-user privileges to update it. I used:</p>
<p><code>sudo vi /etc/my.cnf</code></p>
<p>Enter the configuration settings you require. I wanted to update the maximum packet size so I entered:</p>
<p><code>[mysqld]<br />
max_allowed_packet=16000000<br />
</code></p>
<p>Then you should be able to stop MySql with:</p>
<p><code>mysqladmin -u root -p shutdown<br />
</code></p>
<p>Restart it using whatever start script you prefer. To make sure that your changes have taken effect you can print the server variables to the console with:</p>
<p><code>mysqladmin -u root -p variables<br />
</code></p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/02/configuring-mysql-on-mac-os-x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Assertions in Java</title>
		<link>http://blog.smartkey.co.uk/2010/02/java-assertions/</link>
		<comments>http://blog.smartkey.co.uk/2010/02/java-assertions/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 14:47:25 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=607</guid>
		<description><![CDATA[I&#8217;ve been working on a project this week and have been delighted to see that the original team of programmers who developed it have made the effort to use assertions in their code. 
The assert keyword was introduced in Java 1.4 and has since been a sadly under-used language feature. Assertions offer developers a neat [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working on a project this week and have been delighted to see that the original team of programmers who developed it have made the effort to use assertions in their code. </p>
<p>The assert keyword was introduced in Java 1.4 and has since been a sadly under-used language feature. Assertions offer developers a neat way to implement error detecting statements that are only active during development and can be turned off in production environments. </p>
<p>For example you might want to check that appropriate values are passed to a method during development to ensure that it is being called correctly:</p>
<pre class="brush: java">
private void onlyPositiveNumbersPlease(int i) {
    assert i &gt; 0;

    //rest of method implementation...

}
</pre>
<p>If the assertion fails, then an AssertionError is thrown. If you have a lot of assertions in your code, then its useful to be able to specify a value that will be used in the error message:</p>
<pre class="brush: java">
private void onlyPositiveNumbersPlease(int i) {
    assert i &gt; 0 : &quot;only positive numbers are allowed&quot;;

    //rest of method implementation...

}
</pre>
<p>The value that is specified can also be any primitive type, for example:</p>
<pre class="brush: java">
File f = loadFile();
assert f != null : 404;
</pre>
<p>In all cases, the value is converted to a String and set as the detail message of the AssertionException.</p>
<p>When the Java source is compiled, assertions instructions are included in the bytecode that is generated. However, by default, the assertions are not executed at runtime.</p>
<p>In order to activate all of the assertions, a command line flag must be passed to the JVM:<code></p>
<p>$ java <b>-ea</b> co.uk.smartkey.ui.MainClass<br />
</code></p>
<p>it is also possible to specify that assertions should only be activated for classes within a certain package. For example to run the same application as before, but only activate assertions for classes in the util package of our application, you could use something like:<code></p>
<p>$ java <b>-ea:co.uk.smartkey.util</b> co.uk.smartkey.ui.MainClass<br />
</code></p>
<p>if you just wanted to turn on assertions for a single class, you can specify the class name instead of the package name. Finally, if you really feel the need to, you can turn on assertions in the Java system classes with this:<code></p>
<p>$ java <b>-esa</b> co.uk.smartkey.ui.MainClass<br />
</code></p>
<p>Personally, I like using assertions as they can help to iron out problems during development that are unlikely to need checking for in production. Language level support for them means that the statements are only used if the JVM is launched with them activated; this ensures that there is no performance overhead associated with them when they are not in use.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/02/java-assertions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Counting the Days Between Two Java Dates using a Gregorian Calendar</title>
		<link>http://blog.smartkey.co.uk/2009/12/counting-the-days-between-two-java-dates-using-a-gregorian-calendar/</link>
		<comments>http://blog.smartkey.co.uk/2009/12/counting-the-days-between-two-java-dates-using-a-gregorian-calendar/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 15:03:37 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Calendar]]></category>
		<category><![CDATA[Date]]></category>
		<category><![CDATA[Gregorian]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=588</guid>
		<description><![CDATA[Today I needed to figure out a way to count the number of days between two dates in Java. There are no API methods that will do this for you so a little work is required to achieve this. This post illustrates the solution I came up with.
]]></description>
			<content:encoded><![CDATA[<p>Today I needed to figure out a way to count the number of days passed between two dates and this is the solution I came up with.</p>
<p>Some things in Java seem to be a whole lot trickier than they need be, and working with dates is a good example of this. The Date class&#8217; primary purpose is storing date values. For date oriented calculations the Calendar class should be used. The calendars will handle tricky problems like leap years but the methods for doing this operate at a low level and in many cases you still need to do some of the calculations for yourself. In addition to the standard classes, there&#8217;s some great support for working with dates provided in the Apache commons libraries; these libraries don&#8217;t provide a method for counting days between two dates though.</p>
<p>Anyway, to cut to the chase, here&#8217;s the solution I came up with:</p>
<pre class="brush: java">
public class DateTools {
    private static final int MILLISECONDS_IN_DAY = 1000 * 60 * 60 * 24;

    /**
     * Calculates the number of days between start and end dates, taking
     * into consideration leap years, year boundaries etc.
     *
     * @param start the start date
     * @param end the end date, must be later than the start date
     * @return the number of days between the start and end dates
     */
    public static long countDaysBetween(Date start, Date end) {
        if (end.before(start)) {
            throw new IllegalArgumentException(&quot;The end date must be later than the start date&quot;);
        }

        //reset all hours mins and secs to zero on start date
        Calendar startCal = GregorianCalendar.getInstance();
        startCal.setTime(start);
        startCal.set(Calendar.HOUR_OF_DAY, 0);
        startCal.set(Calendar.MINUTE, 0);
        startCal.set(Calendar.SECOND, 0);
        long startTime = startCal.getTimeInMillis();

        //reset all hours mins and secs to zero on end date
        Calendar endCal = GregorianCalendar.getInstance();
        endCal.setTime(end);
        endCal.set(Calendar.HOUR_OF_DAY, 0);
        endCal.set(Calendar.MINUTE, 0);
        endCal.set(Calendar.SECOND, 0);
        long endTime = endCal.getTimeInMillis();

        return (endTime - startTime) / MILLISECONDS_IN_DAY;
    }
}
</pre>
<p>As you can see each of the dates passed to this method are converted into milliseconds and the number of days between them is calculated based upon the number of days this equates to.</p>
<p>In order to ensure that the times are not relevant in the dates, these are set to zero. This means that if the start date is at 11:00 PM, and the end date is at 1:00 AM the next day, you&#8217;ll still get one day returned from this method call, rather than zero.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2009/12/counting-the-days-between-two-java-dates-using-a-gregorian-calendar/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Ignoring Files and Directories in a Subversion Project</title>
		<link>http://blog.smartkey.co.uk/2009/12/ignoring-files-and-directories-subversion/</link>
		<comments>http://blog.smartkey.co.uk/2009/12/ignoring-files-and-directories-subversion/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 11:58:07 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Tool support]]></category>
		<category><![CDATA[Ignore]]></category>
		<category><![CDATA[Subversion]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=566</guid>
		<description><![CDATA[Configuring Subversion to ignore files can sometimes cause confusion. Like most things though, if you understand the basic principles, then its not tricky at all. In this post I'll demonstrate just how you should go about ignoring files in a subversion project. ]]></description>
			<content:encoded><![CDATA[<p>Configuring Subversion to ignore files can sometimes cause confusion. Like most things though, if you understand the basic principles, then its not tricky at all. In this post I&#8217;ll demonstrate just how you should go about ignoring files in a subversion project.</p>
<p>There are two ways to ignore files in svn: global settings and local. Global settings configure the users environment with some rules for ignoring files, but generally the local ignores are more useful and will be discussed here.</p>
<p>Most projects have files that should be ignored and not included in the version repository. For example, in Java projects, the compiler output shouldn&#8217;t be included as these can be regenerated from the source anyway. You might also have temporary cache files being generated, or output from running unit tests that you don&#8217;t want to share too.</p>
<h3>Ignoring files and directories</h3>
<p>Each directory in a svn managed project has a sub-directory called .svn which contains configuration information that svn uses when working in that directory. To make svn ignore certain content within a directory you need to configure an <strong>svn:ignore</strong> property for it.</p>
<p>To demonstrate this let&#8217;s work with the following project directory structure:</p>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">myproject/build/classes</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">myproject/log.txt</div>
<pre style="font: normal normal normal 12px/18px Consolas, Monaco, 'Courier New', Courier, monospace;">myproject/log-2009-12-01.txt
myproject/log-2009-12-02.txt
myproject/build/classes</pre>
<p>First let&#8217;s tell svn to ignore the log files that have been created. I&#8217;m using SVN 1.5.4 on a Mac so I&#8217;ll demonstrate this using a command line but you could do much the same using a GUI tool like Tortoise:</p>
<pre>$ svn propset svn:ignore 'log-*.txt' myproject</pre>
<p>The above command has used the <strong>propset</strong> command to set the <strong>svn:ignore</strong> property value to <strong>log-*.txt</strong> for the <strong>myproject</strong> directory.</p>
<p>Note that it is possible to use a wild-card &#8216;*&#8217; as part of the file name. You can also use the &#8216;?&#8217; symbol to match a single character in a file name but svn does not currently support any more powerful matching features.</p>
<p><em>Importantly note also that the file name must be quoted in order that the literal value is passed to the svn command; without this the shell will process the wild-card and pass all matching file names instead.</em></p>
<p>You can inspect the value of this property using the propget command like this:</p>
<pre>$ svn propget svn:ignore myproject
log-*.txt</pre>
<p>An ignore property can also be applied to directories, causing all files and sub-directories within it to be ignored. To make svn ignore the classes directory and its contents we could use the command:</p>
<pre style="font: normal normal normal 12px/18px Consolas, Monaco, 'Courier New', Courier, monospace;">$ svn propset svn:ignore 'classes' myproject/build</pre>
<h3>Setting multiple ignore rules within a directory</h3>
<p>So far we&#8217;ve looked at how we can set an individual ignore rule within a directory using the <strong>propset</strong> command. Although both of the rules we&#8217;ve demonstrated have resulted in multiple files being ignored, either by using a wild card syntax or by specifying a directory whose content will also be ignored, we&#8217;ve not yet discussed is how these rules can be combined within a directory; for example: to ignore all log files and also a sub-directory:</p>
<pre>/myproject/log-2009-12-01.txt
/myproject/log-2009-12-02.txt
/myproject/classes</pre>
<p>The <strong>svn:ignore</strong> property is actually a list of file name patterns that svn must ignore. The propset command simply overwrites that list with a single line that includes the pattern you specify when you issue the command.</p>
<p>To create a list of file names that will be matched, use the <strong>propedit</strong> command instead:</p>
<pre>$ svn propedit svn:ignore myproject</pre>
<p>Your svn editor will then be started and you can edit the list of filenames that must be ignored. For our example it would need to look like this:</p>
<pre>log-*.txt
classes</pre>
<p>Note that each file name pattern must be on a separate line.</p>
<h3>Ignoring versioned files and directories</h3>
<p>You must be aware that the <strong>svn:ignore</strong> properties only apply to any files that are <em>not</em> under version control.</p>
<p>In practical terms this means if you accidentally add a file or directory to your version control, you will need to explicitly issue a svn delete command (rm) in order that svn will ignore the files.</p>
<p>Commands like <strong>add</strong> and <strong>import</strong> work recursively in svn, so it&#8217;s easy to accidentally add files like those mentioned above to a versioned project. For example if our log files were accidentally added we could issue this command to delete them from svn:</p>
<pre>svn rm log*.txt</pre>
<p>Note this time that the filename is not quoted as we want the shell to pass all log files to be deleted.</p>
<p>After committing the changes to the project, the files will no longer be managed by svn and the ignore properties will once again work.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2009/12/ignoring-files-and-directories-subversion/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A Unix Command to Recursively Delete all .svn Folders</title>
		<link>http://blog.smartkey.co.uk/2009/11/recursively-delete-svn-folders/</link>
		<comments>http://blog.smartkey.co.uk/2009/11/recursively-delete-svn-folders/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 11:26:39 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Tool support]]></category>
		<category><![CDATA[Subversion]]></category>
		<category><![CDATA[Unix / Linux]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=554</guid>
		<description><![CDATA[I recently needed to check out a project from Subversion and then delete all of the .svn files from the project directories. Google found me a few different ways to do this, but none of them seemed to deal with a case where some of the directory and file names had spaces or quotes in them – as mine did. After a little experimenting, I figured out how some simple Unix commands that could be combined using pipes to do this.]]></description>
			<content:encoded><![CDATA[<p>I recently needed to check out a project from Subversion and then delete all of the .svn files from the project directories. Google found me a few different ways to do this, but none of them seemed to deal with a case where some of the directory and file names had spaces or quotes in them &#8211; as mine did.</p>
<p>After a little experimenting, I figured out the following commands could be combined as illustrated below:</p>
<p>From within the project root folder this command can be used to list all of the .svn directories:</p>
<pre>$ find . -type d -name .svn</pre>
<p>If your directory names don&#8217;t have spaces or quotes in them, then you could just pipe the find command directly into xargs and rm to delete them all:</p>
<pre>$ find . -type d -name .svn | xargs rm -rf</pre>
<p>If you do have spaces or quotes in your directory names, then you need to change the newlines returned from find into null characters (notice the -print0 flag), and make xargs use this to split the input into individual file names (see the -0 flag) rather than the newlines, spaces and quotes that it normally looks for:</p>
<pre>$ find . -type d -name .svn -print0 | xargs -0 rm -fr</pre>
<p>The above command will delete all directories named &#8216;.svn&#8217;, regardless of whether they have spaces, or quote characters in their names.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2009/11/recursively-delete-svn-folders/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>The Details of Member Level Inner Class Syntax</title>
		<link>http://blog.smartkey.co.uk/2009/11/details-of-inner-class-syntax/</link>
		<comments>http://blog.smartkey.co.uk/2009/11/details-of-inner-class-syntax/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 15:52:46 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Inner classes]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=511</guid>
		<description><![CDATA[Inner classes offer are a powerful extension to Java's object model. However, the syntax for some of the more advanced features of member inner classes is quite tricky to get to grips with. In this article I'll explain the full details of this syntax.]]></description>
			<content:encoded><![CDATA[<p>Inner classes offer are a powerful extension to Java&#8217;s object model. However, the syntax for some of the more advanced features of member inner classes is quite tricky to get to grips with. In a <a href="/2009/11/programming-with-inner-classes-in-java/">previous article</a>, I discussed the different types of inner classes along with a demonstration of how they are most commonly used. In this article I&#8217;ll explain the full details of the inner class syntax in Java.</p>
<h3>The basics</h3>
<p>To define an inner class, just define one class within another:</p>
<pre class="brush: java">
public class Outer {
    public class Inner {

    }
}
</pre>
<p>Generally, the outer class will be responsible for creating instances of the inner classes and this could be done in the methods of the outer class, for example here where the outerClassesMethod creates an inner class instance and calls its method (lines 7-8) :</p>
<pre class="brush: java">
public class Outer {

    private String message = &quot;foo&quot;;

    public void outerClassesMethod() {
        //create an inner object to do the work
        Inner ii = new Inner();
        ii.innerClassesMethod();
    }

    private class Inner {
        private void innerClassesMethod() {
            System.out.println(message);
        }
    }
}
</pre>
<p>Note above that the inner classes method (line 12), although private, can still be called by the outer class. Also note that the private message field on the outer class (line 3) can be accessed from the inner class. A call to the outerClassesMethod will cause the innerClassesMethod to be called and the message &#8216;<strong>foo</strong>&#8216; to be printed to std out. </p>
<h3>What about &#8216;this&#8217; ?</h3>
<p>Each object in a Java application can refer to itself using the &#8216;this&#8217; reference. When an instance of an inner class is created, it is created within the instance that created it; so what effect does this have on &#8216;this&#8217; reference?</p>
<p>In fact, inner class instances have more than one &#8216;this&#8217; reference: one that refers to the instance of the inner instance, and one that refers to the outer instance. Consider this simple change to the example:</p>
<pre class="brush: java">
public class Outer {

    private String message = &quot;foo&quot;;

    public void outerClassesMethod() {
        //create an inner object to do the work
        Inner ii = new Inner();
        ii.innerClassesMethod();
    }

    private class Inner {
        private String message = &quot;bar&quot;;

        private void innerClassesMethod() {
            System.out.println(message);
        }
    }
}
</pre>
<p>Now that the inner class also has a field named message, the text &#8216;<strong>bar</strong>&#8216; will be printed out instead of &#8216;foo&#8217;.</p>
<p>The reason for this is that the inner classes message field has shadowed the outer classes one. The inner classes println call (line 15) would have the exact same behaviour if it were written as:</p>
<pre class="brush: java">
System.out.println(this.message);
</pre>
<p>if we want to access the message field on the outer class, then we need to use a &#8216;this&#8217; reference for the outer instance; we do this by pre-pending the class name to &#8216;this&#8217; as follows:</p>
<pre class="brush: java">
System.out.println(Outer.this.message);
</pre>
<p>substituting the println statement with the one shown above, will access the message field on the Outer class and cause &#8216;<strong>foo</strong>&#8216; to be printed out once again.</p>
<h3>Creating inner instances from outside the outer class</h3>
<p>As noted above, the inner instances will generally be created within the outer class. However, it is possible for inner instances to be created in other places too; for example, a factory class could be used to create the outer objects and also the inner objects that they will contain. </p>
<p>To demonstrate this scenario, we&#8217;ll use a slightly revised example where the inner class, and its method, have been made publicly visible. Note also that the outer class now has a constructor (lines 4-6) that will allow us to initialise its private message field (line 3) :</p>
<pre class="brush: java">
public class Outer {

    private String message;

    public Outer(String message) {
        this.message = message;
    }

    public class Inner {
        public void innerClassesMethod() {
            System.out.println(message);
        }
    }
}
</pre>
<p>If our factory class is to create the inner class instances, then it must associate them with an outer instance. In order to do this the new keyword must be scoped to a particular outer instance using this somewhat cumbersome syntax:</p>
<pre class="brush: java">
Outer o = new Outer(&quot;foo&quot;);
Outer.Inner i = o.new Inner();
i.innerClassesMethod();
</pre>
<p>Note the use of the new keyword (line 2) is prepended with the outer object reference (i.e. <strong>o.new</strong>). It is this outer reference that will be accessible within the inner object&#8217;s methods using the &#8216;this&#8217; syntax explained above.</p>
<p>So, when the call to the inner classes method is made (on line 3), the private message field of the outer instance will be printed out &#8211; i.e. we&#8217;ll see &#8216;<strong>foo</strong>&#8216; appear in std out.</p>
<h3>Static inner classes</h3>
<p>The static modifier can be applied to member level classes in much the same was as it can with the fields and methods of that class. As with fields and methods, use of the static modifier pretty much turns off OO. </p>
<pre class="brush: java">
public class Outer {

    private String message;

    static class Inner {
        private String message;

        public void innerClassesMethod() {
            //can access the message field defined on this class:
            System.out.println(this.message);

            //can&#039;t access the one from the outer class though:
            System.out.println(Outer.this.message);
        }
    }
}
</pre>
<p>In much the same way as a static method is not associated with an object instance, objects created from static inner class definitions are not associated with an outer object instance either.</p>
<p>Static inner classes therefore do not have a second this reference, and cannot access the non-static fields of the outer class (line 13 in the above example would produce a compiler error). Effectively, inner classes are just regular classes defined within an outer classes name-space. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2009/11/details-of-inner-class-syntax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Explanation of &#8216;this&#8217; in Java</title>
		<link>http://blog.smartkey.co.uk/2009/11/what-is-this/</link>
		<comments>http://blog.smartkey.co.uk/2009/11/what-is-this/#comments</comments>
		<pubDate>Sun, 08 Nov 2009 19:03:42 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=478</guid>
		<description><![CDATA[As every Java programmer should know, code within any non-static method can access the current object via a special reference called 'this'. Just how this works may not be immediately obvious so I've taken a moment to explain it here.
]]></description>
			<content:encoded><![CDATA[<p>As every Java programmer should know, code within any non-static method can access the current object via a special reference called &#8216;this&#8217;. Just how this works may not be immediately obvious so I&#8217;ve taken a moment to explain it here.</p>
<p>The best way I know to explain &#8216;this&#8217; properly is by taking a look at how object oriented languages actually work and comparing them to their older siblings: structured programming languages. </p>
<p>In a structured programming language (like C or Pascal for example) you store data in a struct or a record and reuse code by creating functions. Moreover, when you call a function you may pass them records to work with.</p>
<p>So before we start looking at Java, let&#8217;s consider some pseudo-code in an imaginary structured programming language. First we&#8217;ll define an account record structure in this language, and then a simple function that can be used to update them:</p>
<pre class="brush: php">
//define an account record structure with two fields (balance and overdraft)
record account {
    int balance;
    int overdraft;
}

//now define a function for updating the account&#039;s balance
void deposit(account a, int amount) {
    a.balance += amount;
}
</pre>
<p>So, given an account record &#8216;a&#8217;, we could use our imaginary language to deposit £100 by calling the above function as follows:</p>
<pre class="brush: php">
//create a new account record
a = new account();

//update the account&#039;s balance using the function
deposit(a, 100);
</pre>
<p>In an Object Oriented language like Java we would more likely define an account class with a deposit method:</p>
<pre class="brush: java">
public class Account {
    private int balance;

    public void deposit(int amount) {
        balance += amount;
    }
}
</pre>
<p>and use it like this:</p>
<pre class="brush: java">
Account a = new Account();
a.deposit(100);
</pre>
<p>As we know, Object Orientation is just a higher level programming abstraction. Therefore, the code that you&#8217;d write in Java is just another way of expressing what you&#8217;d write in a procedural language.</p>
<p>In fact, the Java compiler actually produces bytecode that looks more like procedural code. For example, a method call like this:</p>
<pre class="brush: java">
a.deposit(100)
</pre>
<p>would actually be compiled as though it were a function call:</p>
<pre class="brush: java">
deposit(a, 100);
</pre>
<p>and our deposit method would be treated likewise and compiled as though it were:</p>
<pre class="brush: java">
void deposit(Account this, int amount) {
    this.balance += amount;
}
</pre>
<p>Note that the compiler has restructured the statement as a function and introduced an initial parameter called &#8216;this&#8217; that will be a reference to the object that the method is being invoked on. As you can see then, it is this &#8216;this&#8217; variable that allows you to refer explicitly to the current object.</p>
<p>The one gotcha here is if you define a method with the static modifier. Static methods don&#8217;t require that an object is created before they are called; they are generally just called via the class name, like Math.min(&#8230;) for example. In this sense they really are just like a procedural language function so the compiler does not introduce a &#8216;this&#8217; parameter. Clearly then, this is why you cannot access &#8216;this&#8217; from within static methods.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2009/11/what-is-this/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming with Inner Classes in Java</title>
		<link>http://blog.smartkey.co.uk/2009/11/programming-with-inner-classes-in-java/</link>
		<comments>http://blog.smartkey.co.uk/2009/11/programming-with-inner-classes-in-java/#comments</comments>
		<pubDate>Sun, 08 Nov 2009 17:12:40 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Inner classes]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Swing]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=400</guid>
		<description><![CDATA[Inner classes are an advanced programming feature in Java. They add another dimension to the concept of Object Oriented programming by allowing objects to not only reside alongside one another, but also within one another too. In this post I'll explain how inner classes work with the help of an example that illustrates their most common use: Swing GUI programming.
]]></description>
			<content:encoded><![CDATA[<p>Inner classes are an advanced programming feature in Java. They add another dimension to the concept of Object Oriented programming by allowing objects to not only reside alongside one another, but also within one another too. In this post I&#8217;ll explain how inner classes work with the help of an example that illustrates their most common use: Swing GUI programming.</p>
<h3>Extending the Object Oriented Programming Model</h3>
<p>Encapsulation can be regarded as a barrier that an object puts up to protect itself from other objects. Within an object we generally expect there to be fields (that each object will have it&#8217;s own instance of) and methods (that can be called to affect that object). Inner classes extend Java&#8217;s OO model by also allowing objects to be created within an object, thus making the code within an object truly object oriented.</p>
<p>To demonstrate this, lets start by looking at some less-than-ideal Swing GUI code. The DemoUI class is a simple application frame that uses a WindowCloser object as a listener for its window events. The code for both of these classes is shown here:</p>
<pre class="brush: java">
public class DemoUI extends JFrame {
    public DemoUI() {
        //add the window closing event listener
        this.addWindowListener(new WindowCloser(this));
    }

    public void shutdown() {
        int answer = JOptionPane.showConfirmDialog(this, &quot;Are you sure?&quot;);
        if (answer == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }
}

class WindowCloser extends WindowAdapter {
    private DemoUI demoUI;

    public WindowCloser(DemoUI demoUI) {
        this.demoUI = demoUI;
    }

    public void windowClosing(WindowEvent windowEvent) {
        demoUI.shutdown();
    }
}
</pre>
<p>When the user clicks application frame&#8217;s close button (i.e. the cross button on the frame&#8217;s title bar), the windowClosing method will be called on the event listener which will, in turn, call the shutdown method of the frame. The shutdown method prompts the user to make sure that they want to quit before calling System.exit(&#8230;) to exit the application.</p>
<p>Although a fairly simple example, this code is more complex than it need be. The reason for this complexity stems from the fact that the objects created from these classes are completely separate from one another, we could picture these objects as follows:</p>
<p><img class="aligncenter size-full wp-image-442" title="outer" src="http://blog.smartkey.co.uk/wp-content/uploads/2009/11/outer1.png" alt="outer" width="310" height="84" /></p>
<p>Because these objects would otherwise have no association with one another, we must provide a reference from the listener to the frame in order that the frame&#8217;s shutdown method may be called by the listener. It also means that the frame&#8217;s shutdown method cannot be declared private, thus weakening its encapsulation.</p>
<h3>Applying Inner Classes</h3>
<p>If we make the listener an inner class of the frame, then it will have access to all members of the frame (even private ones). We do this simply by moving the listener class definition inside the frame class:</p>
<pre class="brush: java">
public class DemoUI extends JFrame {
    public DemoUI() {
        //add the window closing event listener
        this.addWindowListener(new WindowCloser());
    }

    private void shutdown() {
        int answer = JOptionPane.showConfirmDialog(this, &quot;Are you sure?&quot;);
        if (answer == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }

    private class WindowCloser extends WindowAdapter {
        public void windowClosing(WindowEvent windowEvent) {
            shutdown();
        }
    }
}
</pre>
<p>Now that the listener is declared as an inner class of the frame, instances of the listener will be created inside the enclosing frame instance. In contrast to the above example, this can now be pictured as follows:</p>
<p><img class="aligncenter size-full wp-image-433" title="inner" src="http://blog.smartkey.co.uk/wp-content/uploads/2009/11/inner1.png" alt="inner" width="232" height="84" /></p>
<p>Note that there is now no need to keep a reference to the frame instance from the listener as the listener object is implicitly associated with it. This means that the shutdown method, although declared as private on the frame, is still available to the listener. Finally, and for good measure, because the listener is only ever used by the frame, we can make its class definition private and prevent any other classes from accessing it.</p>
<h3>Method Level Inner Classes</h3>
<p>The example above shows an inner class being defined at the same level of scope as the methods and fields (aka the members) of the outer class. This type of inner class is therefore commonly referred to as a member level inner class.</p>
<p>In Java it is common to declare variables where they are first used. It is possible to do this with inner classes too. In this example the inner class has been declared just before it is used; i.e. within the constructor method of the frame:</p>
<pre class="brush: java">
public class DemoUI extends JFrame {
    public DemoUI() {
        //add the window closing event listener
        class WindowCloser extends WindowAdapter {
            public void windowClosing(WindowEvent windowEvent) {
                shutdown();
            }
        }
        this.addWindowListener(new WindowCloser());
    }

    private void shutdown() {
        int answer = JOptionPane.showConfirmDialog(this, &quot;Are you sure?&quot;);
        if (answer == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }
}
</pre>
<p>A method level inner class can only be used in the method it is declared in and it is inherently private to that method. Classes defined at method level also have the additional advantage of being able to access local variables in that method, just so long as they are declared as final.</p>
<h3>Anonymous Inner Classes</h3>
<p>The next progression from a method level inner class is an anonymous inner class. In the previous example, the class was defined just before it was created and used. The name for the class was therefore only ever used in the definition and then in the subsequent call to create an instance of it. In cases such as this, it is possible to create and define the inner class in a single statement, rendering its name irrelevant:</p>
<pre class="brush: java">
public class DemoUI extends JFrame {
    public DemoUI() {
        //add the window closing event listener
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent) {
                shutdown();
            }
        });
    }

    private void shutdown() {
        int answer = JOptionPane.showConfirmDialog(this, &quot;Are you sure?&quot;);
        if (answer == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }
}
</pre>
<p>You can see from this code that the inner class has now been created using the Java &#8216;new&#8217; operator but that the name WindowCloser is no longer used; just the supertype WindowAdapter is used instead and the implementation of the windowClosing method is simply specified in the curly braces following the normal constructor call.</p>
<p>This example demonstrates how to create an anonymous subclass of the WindowAdapter class which is an abstract class defined within the Swing APIs. You can create an anonymous subclass of any class though using this syntax; just place the code for the subclass within the curly braces and you&#8217;re done.</p>
<p>It is also possible to implement an interface using this syntax. So for example if there were a Quit button in our GUI, then we could implement the ActionListener interface for the event listener that reuses the shutdown method like so:</p>
<pre class="brush: java">
JButton quitButton = new JButton(&quot;Quit&quot;);
quitButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        shutdown();
    }
});
</pre>
<h3>Summary</h3>
<p>The discussion I&#8217;ve presented above illustrates the most common use of inner classes but there are dozens of other uses; for example, the Spring data abstraction layer uses them to great effect, as does the Wicket web framework. </p>
<p>Fundamentally, inner classes in Java enable objects to be created within objects. This simple principle opens up a whole array of design choices for object aggregation. With careful consideration, inner classes allow your code to be more concise and maintainable than it might otherwise be. A good understanding of inner classes is therefore a key skill for any serious Java developer.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2009/11/programming-with-inner-classes-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
