<?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>Five Minutes</title>
	<atom:link href="http://www.fiveminutes.eu/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.fiveminutes.eu</link>
	<description>Technology and Marketing Solutions</description>
	<lastBuildDate>Mon, 20 Feb 2012 08:39:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using mock objects for Stripes-Spring testing</title>
		<link>http://www.fiveminutes.eu/using-mock-objects-for-stripes-spring-testing/</link>
		<comments>http://www.fiveminutes.eu/using-mock-objects-for-stripes-spring-testing/#comments</comments>
		<pubDate>Thu, 16 Feb 2012 13:15:32 +0000</pubDate>
		<dc:creator>ante.brkic</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Five Minutes]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Software testing]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://www.fiveminutes.eu/?p=3255</guid>
		<description><![CDATA[Usage of mocked container stripes junit testing which uses mocked spring objects for fast and precise testing. <a href="http://www.fiveminutes.eu/using-mock-objects-for-stripes-spring-testing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a rel="attachment wp-att-3256" href="http://www.fiveminutes.eu/using-mock-objects-for-stripes-spring-testing/test/"><img class="alignright size-full wp-image-3256" src="http://www.fiveminutes.eu/wp-content/uploads/2012/02/test.jpg" alt="" width="177" height="203" /></a></p>
<p>It is very easy to create a mock objects of your <a href="http://www.springsource.org/">Spring</a> layer, and not only does it allow you to create a consistent junit tests, but in the process you will end up with a mocked spring layer which you can use for fast front-end development!<br />
Let&#8217;s see how.</p>
<p><span id="more-3255"></span></p>
<p>First of all, <em>junit</em> testing of <a href="http://www.stripesframework.org/display/stripes/Home">Stripes</a> comes in a two flavors, first one invoking your action beans directly and as expected is a simple approach but with a big disadvantage (among others) &#8211; you can not test spring beans as injection is not started. Second approach, which really looks much more convenient and is introduced into Stripes with version 1.1.1 (wow, that was 6 years ago!) is so called &#8220;Mock Container Usage Approach&#8221;, so it requires a little bit more work.</p>
<p>For the later, we need to create a <em>MockServlerContext</em> which we will use for each test, so we want to do it with a singleton class (it takes a while to initialize <em>MockServletContext</em> as it actually boots the simulator container). After that, in each test we create <em>MockRoundtrip</em> (based on mocked context), which is a simulation of a request. So, for <em>MockRoundtrip</em>, we set parameters which would &#8220;in real life&#8221; be set from the JSP (or other presentation layer, Stripes authors mention that <strong><a href="http://freemarker.sourceforge.net/">FreeMarker</a></strong> can also be used with Stripes), call &#8220;execute&#8221; and then assert results. But i have skipped the important part and that is configuring of <em>MockServlerContext</em>. This is done java-style, in our singleton, and simulates <em>web.xml</em> configuration. Here i will just say that this is the place where we define which spring configuration file we want to use. But let me first just say a few words about spring mock object and i will return here really fast.</p>
<p>So in our project we connect to the remote server using the <a href="http://en.wikipedia.org/wiki/Representational_state_transfer">REST</a> paradigm, while communicating using JSON objects. This is slow when looking from the perspective that for <em>junit</em> tests you do not really depend on over-the-wire communication, and you know how it goes, test servers are shared among many people and so on, and also, you do not want your <em>junit</em> tests to really on the data that everybody can edit, right? So one layer of <em>junit</em> tests is definitely this, connecting to mock objects that do include spring beans, but not the real ones that use REST calls, but fake ones, that just return some fixed data.</p>
<p>And i promised to return to <em>MockServletContext</em> configuration, so now is the good time because there the developer specifies that the configuration that will be used is the one that points to the mocked spring layer. That way, our <em>junit</em> tests are fast and consistent.</p>
<p><code><br />
filterParams.put("ActionResolver.Packages", "your.package.with.actions");<br />
filterParams.put("Interceptor.Classes", "net.sourceforge.stripes.integration.spring.SpringInterceptor");<br />
filterParams.put("ActionBeanContext.Class", "your.subclass.of.ActionBeanContext");<br />
filterParams.put("LocalePicker.Locales", "en_US:UTF-8");<br />
mockServletContext.addFilter(StripesFilter.class, "StripesFilter", filterParams);</code></p>
<p><code> </code></p>
<p><code> // spring configuration file<br />
mockServletContext.addInitParameter("contextConfigLocation", "classpath:applicationContext.mock.xml");<br />
</code><br />
Once you have established two versions of spring configuration, it is extremely easy to switch between those two: it is a matter of commenting/uncommenting a line in your <em>web.xml</em>.</p>
<p>For more details on this subject see <a href="http://www.stripesframework.org/display/stripes/Unit+Testing">this</a>, or just ask :)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiveminutes.eu/using-mock-objects-for-stripes-spring-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing Spring Integration</title>
		<link>http://www.fiveminutes.eu/introducing-spring-integration/</link>
		<comments>http://www.fiveminutes.eu/introducing-spring-integration/#comments</comments>
		<pubDate>Wed, 15 Feb 2012 12:14:45 +0000</pubDate>
		<dc:creator>Samir Čauš</dc:creator>
				<category><![CDATA[Blog]]></category>

		<guid isPermaLink="false">http://www.fiveminutes.eu/?p=3197</guid>
		<description><![CDATA[Introducing spring Integration trough polling database example. <a href="http://www.fiveminutes.eu/introducing-spring-integration/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.fiveminutes.eu/introducing-spring-integration/placeholder_video_spring_projects/" rel="attachment wp-att-3246"><img src="http://www.fiveminutes.eu/wp-content/uploads/2012/02/placeholder_video_spring_projects-150x150.png" alt="Spring Integration" width="150" height="150" class="alignleft size-thumbnail wp-image-3246" /></a>
<p>Recently, we worked on a project that required frequent polling of database table, processing each row, and writing output to different database table(s). The data tables are incoming and outgoing sms messages, and load would get quite high sometimes. We also had to support load balancing. Since our services are already done with spring &#8211; the choice was to try <a href="http://www.springsource.org/spring-integration">Spring Integration</a>.</p>
<p><span id="more-3197"></span></p>
<p>So what is Spring Integration? &#8220;Spring Integration provides an extension of the Spring programming model to support <a href="http://www.eaipatterns.com/">Enterprise Integration Patterns</a>. It enables lightweight messaging within Spring-based applications and supports integration with external systems via declarative adapters.&#8221;</p>
<p>Basic concepts when designing Spring Integration applications are Messages (java objects with metadata), Channels (pipes that messages go trough) and Message Endpoints.<br />
Message endpoints can be various &#8211; like Transformer (transforms data), Router(route data), Filter (filters data), Splitter (splits messages), Aggregator (inverse of Splitter), Service Activator (connecting messages to Services) and most important Channel Adapters.</p>
<p>Channel Adapters connects Message Channels to &#8220;external&#8221; world. They can be inbound (create new messages) and outbound (consumes messages). The choice of connection type is pretty big &#8211; like AMQP, JDBC, Web Services, FTP, File, HTTP, TCP, UDP, JMS, Mail, MongoDb, RMI, XML, XMPP, Stream and even <a href="http://static.springsource.org/spring-integration/reference/htmlsingle/#twitter">Twitter</a>.</p>
<div id="attachment_3202" class="wp-caption alignleft" style="width: 590px"><a href="http://static.springsource.org/spring-integration/reference/htmlsingle/#samples-cafe"><img src="http://www.fiveminutes.eu/wp-content/uploads/2012/02/cafe-eip-580x290.png" alt="Spring Integration Sample" width="580" height="290" class="size-medium wp-image-3202" /></a><p class="wp-caption-text">Spring Integration Sample</p></div>
<p>Back to our application. Its very easy to add polling of database table. Just add <a href="http://static.springsource.org/spring-integration/reference/htmlsingle/#jdbc-inbound-channel-adapter">Jdbc Inbound Channel Adapter</a> that will poll database table with query that you specify (load balancing is working as we are using oracles &#8220;select for update nowait skip locked&#8221; syntax which skips rows with read lock). Specify properties like channel (name of channel where will message go), data-source, row-mapper (converts table row to java objects), update (query that is executed after table is read &#8211; you want to delete row once it is processed or put some flag) and fixed-rate (polling interval). There is also possibility to add <a href="http://static.springsource.org/spring-integration/reference/htmlsingle/#transactions">transaction </a>support , or define cron expression instead of fixed rate polling, but we didn&#8217;t need that. What we needed is to add Thread pool with Spring <a href="http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/scheduling.html">Task Executor</a>, and combine this with Spring Integration by  setting message channel as <a href="http://static.springsource.org/spring-integration/reference/htmlsingle/#channel-implementations">ExecutorChannel</a></p>
<pre><code>
	&lt;int-jdbc:inbound-channel-adapter query="${db.select.userrequest.query}"
		channel="smsInboundChannel" data-source="dataSource" row-mapper="userRequestMapper"
		update="${db.delete.userrequest.query}"  max-rows-per-poll="${db.poller.maxrowsperpoll}" &gt;
			&lt;int:poller fixed-rate="${db.poller.fixedrate}"  &gt;
			&lt;/int:poller&gt;
	&lt;/int-jdbc:inbound-channel-adapter&gt;
</pre>
<p></code><br />
That's it. Now we just needed to make a Spring Integration <a href="http://static.springsource.org/spring-integration/reference/htmlsingle/#chain">chain</a>. Add splitter to separate messages per row. Add Service Activator to process message. Finally add <a href="http://static.springsource.org/spring-integration/reference/htmlsingle/#jdbc-outbound-channel-adapter">Jdbc Outbound Channel Adapter</a> to write to database.The possibilities are numerous. And since everything is done using Spring concepts, the code is easily maintainable and testable.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiveminutes.eu/introducing-spring-integration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Check user permission using aspect-oriented programming</title>
		<link>http://www.fiveminutes.eu/check-user-permission-using-aspect-oriented-programming/</link>
		<comments>http://www.fiveminutes.eu/check-user-permission-using-aspect-oriented-programming/#comments</comments>
		<pubDate>Tue, 07 Feb 2012 09:24:50 +0000</pubDate>
		<dc:creator>Kristijan Rebernišak</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Five Minutes]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://www.fiveminutes.eu/?p=3147</guid>
		<description><![CDATA[In this post we will show a example of simple and clean way to check your users permissions across your application using aspect-oriented programming (AOP). In computing, AOP is a programming paradigm which aims to increase modularity by allowing the &#8230; <a href="http://www.fiveminutes.eu/check-user-permission-using-aspect-oriented-programming/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this post we will show a example of simple and clean way to check your users permissions across your application using aspect-oriented programming (AOP).<br />
<span id="more-3147"></span><br />
In computing, AOP is a programming paradigm which aims to increase modularity by allowing the separation of cross-cutting concerns. AOP forms a basis for aspect-oriented software development. Read more about it <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">here</a>.</p>
<p>This example is extracted from a web aplication project build on dependency injection framework <a href="http://code.google.com/p/google-guice/">Google Guice</a>. To compliment dependency injection, Guice supports method interception that divides a problem into aspects rather than objects. This feature enables you to write code that is executed each time a matching method is invoked. It&#8217;s suited for cross cutting concerns (&#8220;aspects&#8221;), such as transactions, security and logging.</p>
<p>Now lets define our simple user base with this three types:</p>
<pre class="brush: java; gutter: true">public enum UserType {
     ADMIN,
     CUSTOMER,
     GUEST;
 }</pre>
<p>To mark select methods that need user validation, we define an annotation:</p>
<pre class="brush: java; gutter: true">import com.google.inject.BindingAnnotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@BindingAnnotation
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresUserType {
    UserType value();
}</pre>
<p>&#8230;and apply it to the methods that need to be intercepted:</p>
<pre class="brush: java; gutter: true">public class ProductService implements IProductService {

    @RequiresUserType(CUSTOMER)
    public Product view(Key key) {
        ...
    }

    @RequiresUserType(ADMIN)
    public void delete(Key key) {
        ...
    }
}</pre>
<p>Next, we define the interceptor by implementing the <em>org.aopalliance.intercept.MethodInterceptor</em> interface. When we need to call through to the underlying method, we do so by calling <em>invocation.proceed()</em>:</p>
<pre class="brush: java; gutter: true">public class UserValidationInterceptor implements MethodInterceptor {

    public Object invoke(MethodInvocation invocation) throws Throwable {
        final UserType requiredType = invocation.getMethod().getAnnotation(RequiresUserType.class).value();
        //cross check current user type and throw an exception if validation fails
        ...
        //if everything checks out proceed to method execution
        return invocation.proceed();
    }
}</pre>
<p>Finally, we configure everything. This is where we create matchers for the classes and methods to be intercepted. In this case we match any class, but only the methods with our <em>@RequiresUserType</em> annotation:</p>
<pre class="brush: java; gutter: true">import com.google.inject.AbstractModule;
import com.google.inject.matcher.Matchers;

public class SecurityModule extends AbstractModule {
    protected void configure() {
        bindInterceptor(Matchers.any(), Matchers.annotatedWith(RequiresUserType.class), new UserValidationInterceptor());
    }
}</pre>
<p>The method interceptor API implemented by Guice is a part of a public specification called <a href="http://aopalliance.sourceforge.net/">AOP Alliance</a>. This makes it possible to use the same interceptors across a variety of frameworks.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiveminutes.eu/check-user-permission-using-aspect-oriented-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tracing Zombie objects in Objective C</title>
		<link>http://www.fiveminutes.eu/tracing-zombie-objects-in-objective-c/</link>
		<comments>http://www.fiveminutes.eu/tracing-zombie-objects-in-objective-c/#comments</comments>
		<pubDate>Mon, 23 Jan 2012 08:55:56 +0000</pubDate>
		<dc:creator>Drago Ružman</dc:creator>
				<category><![CDATA[Blog]]></category>

		<guid isPermaLink="false">http://www.fiveminutes.eu/?p=3134</guid>
		<description><![CDATA[Tracing Zombie objects can be challenging from time to time. This post shows a simple way to trace memory management calls to an object and discover why did it become a Zombie. <a href="http://www.fiveminutes.eu/tracing-zombie-objects-in-objective-c/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If an object gets deallocated too early, other objects still might have references to it and accessing it will lead to crash. Enabling Zombie objects will prevent crashes because objects are never actually deallocated and we&#8217;ll get an exception if we try to access such an object. But figuring out which object is causing trouble is just smaller part of the job. We need to find out where is the extra release (or missing retain) that is causing troubles. <span id="more-3134"></span></p>
<p>In smaller projects or when objects in question are localized to a smaller number of classes, we can find the bug by static code investigation. But if the object is used in a larger scope and often conditionally, we might want to take a look at what is going on in runtime.</p>
<p>To trace memory management related calls to our class, we will need to expand retain, release and autorelease methods. Simplest variant will just call super method, so we can put a breakpoint and see where is it called from. This can be useful, but usually there are lots of instances of the same class and lots of calls to those methods, so this isn&#8217;t really practical. It would be much more practical to log all calls to retain/release/autorelease and then dump the data when we need it. We can save three types of information to our log &#8211; current event (is it release, retain or autorelease), current time and what is most important, call stack trace so we know how exactly did we end up here. All this information can be stored into a simple array which will we add to the class we want to trace (of course, we want to allocate and release this array where appropriate).</p>
<p><code> </code></p>
<pre><code>NSMutableArray* _memTrace;</code></pre>
<p><code> </code></p>
<p>We can fill the _memTrace array with a call to the following method:</p>
<p><code> </code></p>
<pre><code>-(void) addMemTraceEvent:(NSString*)event
{
    [_memTrace addObject:[NSString stringWithFormat:@"%@ %@ at %@",
                          [NSDate date],
                          event,
                          [NSThread callStackSymbols]
                          ]];
}</code></pre>
<p><code> </code></p>
<p>We are using [NSDate date] to get current date and time and [NSThread callStackSymbols] to fetch current call stack trace.</p>
<p>To dump _memTrace, we can use following code:</p>
<p><code> </code></p>
<pre><code>-(void) dumpMemTrace
{
    NSLog(@"%@", _memTrace);
}</code></pre>
<p><code> </code></p>
<p>We can now update our memory management methods, so they log all calls to them:</p>
<p><code> </code></p>
<pre><code>-(void)release
{
    [self addMemTraceEvent:@"release"];

    [super release];
}

-(id)retain
{
    [self addMemTraceEvent:@"retain"];

    return [super retain];
}

-(id)autorelease
{
    [self addMemTraceEvent:@"autorelease"];

    return [super autorelease];
}</code></pre>
<p><code> </code></p>
<p>Now, when such updated object makes a Zombie access exception, we can simply call -dumpMemTrace from gdb&#8217;s command window, examine the log and find the extra release.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiveminutes.eu/tracing-zombie-objects-in-objective-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Drag&amp;Drop on tree structure with SmartGwt</title>
		<link>http://www.fiveminutes.eu/using-dragdrop-on-tree-structure-with-smartgwt/</link>
		<comments>http://www.fiveminutes.eu/using-dragdrop-on-tree-structure-with-smartgwt/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 13:41:51 +0000</pubDate>
		<dc:creator>ante.brkic</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://www.fiveminutes.eu/?p=3044</guid>
		<description><![CDATA[Today i'm going to show how easy it is implement drag&#38;drop functionality on a visually represented tree structure using SmartGwt. <a href="http://www.fiveminutes.eu/using-dragdrop-on-tree-structure-with-smartgwt/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: left"><a rel="attachment wp-att-3045" href="http://www.fiveminutes.eu/using-dragdrop-on-tree-structure-with-smartgwt/tree1/"><img class="size-medium wp-image-3045  aligncenter" src="http://www.fiveminutes.eu/wp-content/uploads/2011/11/tree1-382x380.jpg" alt="The Tree" width="382" height="380" /></a>It has never been as easy to create a thin client web application as it is with the tools such as GWT and it&#8217;s third party library SmartGwt. This is a deadly combination which has out-of-the-box support for drag&amp;drop, asynchronous remote procedure calls, localization, history management and much more inherited from GWT (Google Web Toolkit) and accompanied with numerous customizable widgets (lists, trees, buttons, layout support widgets, HTML5 support&#8230;). In this text, a simple drag&amp;drop implementation will be demonstrated.</p>
<p><span id="more-3044"></span><br />
<span style="font-family: Arial">After setting up the required environment (see links below), we need a class that will implement EntryPoint interface, which will force it to implement onModuleLoad() method, with self-explanatory name.<br />
</span></p>
<p>Now, let&#8217;s create our tree structures:</p>
<p><code>Tree leftTree = new Tree();</code></p>
<p><code>leftTree.setModelType(TreeModelType.CHILDREN);</code></p>
<p><code> </code></p>
<p><code>leftTree.setRoot ...</code></p>
<p><code> </code></p>
<p>Setting model type to CHILDREN means that we will specify children nodes for each node. Other way would be to use PARENT type and then we would be specifying parent ids for each node that has a parent.</p>
<p>We set the actual data using setRoot method. I omitted the details for readability here. Numerous other method for filling up the tree could be used also, like variants of simple add, addList or even connecting our structure to some data source like XML Schema, relational database or EJB.</p>
<p>Note that this is only a data structure and we still need some &#8220;physical&#8221; representation:</p>
<p><code>final PartsTreeGrid leftGrid = new PartsTreeGrid();</code></p>
<p><code>leftGrid.setDragDataAction(DragDataAction.MOVE);</code></p>
<p><code> </code></p>
<p><code>leftGrid.setData(leftTree);</code></p>
<p><code>grid1.getData().openAll();</code></p>
<p><code> </code></p>
<p>DragDataAction.MOVE means that the dragged item will not stay in the originating tree (in contrast to DragDataAction.COPY).</p>
<p>setData is used to bind earlier created data-set to this graphical representation.</p>
<p>PartsTreeGrid is actually a custom extension of TreeGrid adding some face-lifting instructions, and i will emphasize only these lines here:</p>
<p><code>setCanReorderRecords(true);</code></p>
<p><code>setCanAcceptDroppedRecords(true);</code></p>
<p><code> </code></p>
<p><code>setCanDragRecordsOut(true);</code></p>
<p><code> </code></p>
<p>Yes, this is all you have to do to enable drag&amp;drop in your application!</p>
<p>Analogously we add the gird to the right and also the arrow buttons to demonstrate transfer of the selected nodes with mouse click.</p>
<p>And to demonstrate the layout capabilities let&#8217;s see how we construct our parts together:</p>
<p><code>HStack grids = new HStack(10);</code></p>
<p><code>grids.setHeight(160);</code></p>
<p><code> </code></p>
<p><code>grids.addMember(leftGrid);</code></p>
<p><code>grids.addMember(moveControls);</code></p>
<p><code>grids.addMember(rightGrid);</code></p>
<p><code>grids.draw();</code></p>
<p><code> </code></p>
<p>Those familiar with Java Swing will see the similarities. Basically we create appropriate layout and fill it with elements. Layouts can be nested, so combining horizontal and vertical layouts (or some more complex layouts) we can create whatever we want to.</p>
<p>Ah i almost forgot! Our program is finishe<a rel="attachment wp-att-3048" href="http://www.fiveminutes.eu/using-dragdrop-on-tree-structure-with-smartgwt/capture/"><img class="alignright size-full wp-image-3048" src="http://www.fiveminutes.eu/wp-content/uploads/2011/11/Capture.png" alt="" width="466" height="215" /></a>d.</p>
<p>OK, almost completely, this example is using demonstration framework, but what we would additionally need to do would be to create a simple html page referencing generated JavaScript code (GWT is compiled into JavaScript) and add our grid to the rootPanel using</p>
<p><code>RootLayoutPanel.get().add(...</code></p>
<p><code> </code></p>
<p>If we were not connected to some data source, then now we need to manually handle the data changes. We could subscribe the gird for changes, update the data on exit event or else, whatever suits our needs.</p>
<p>For info about GWT please see: <a href="http://code.google.com/intl/hr-HR/webtoolkit/">http://code.google.com/intl/hr-HR/webtoolkit/</a></p>
<p>For info about SmartGwt, see: <a href="http://code.google.com/p/smartgwt/">http://code.google.com/p/smartgwt/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiveminutes.eu/using-dragdrop-on-tree-structure-with-smartgwt/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cross-platform javascript touch scrolling</title>
		<link>http://www.fiveminutes.eu/cross-platform-javascript-touch-scrolling/</link>
		<comments>http://www.fiveminutes.eu/cross-platform-javascript-touch-scrolling/#comments</comments>
		<pubDate>Thu, 17 Nov 2011 23:59:48 +0000</pubDate>
		<dc:creator>Matija Šmalcelj</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://www.fiveminutes.eu/?p=3024</guid>
		<description><![CDATA[Currently CSS position:fixed property is only partially supported on mobile devices. iOS below version 5 doesn&#8217;t support it at all and Android is plagued by fragmentation hell. To solve these problems developers created libraries for JavaScript scrolling powered by CSS3 &#8230; <a href="http://www.fiveminutes.eu/cross-platform-javascript-touch-scrolling/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.fiveminutes.eu/wp-content/uploads/2011/11/touchscreen1.jpg" alt="" width="250" height="167" class="alignleft size-full wp-image-3037" />Currently CSS position:fixed property is only partially supported on mobile devices. iOS below version 5 doesn&#8217;t support it at all and Android is plagued by fragmentation hell. To solve these problems developers created libraries for JavaScript scrolling powered by CSS3 transitions. We recently wrote from scratch cross-platform mobile web site which uses a combination of native scroll and multiple touch scroll libraries depending on device. In this post I&#8217;d like to share our experiences..</p>
<p><span id="more-3024"></span></p>
<p>Only recently in version 5 iOS began to support CSS position:fixed and before that fixed positioned elements behaved like they&#8217;re absolute positioned relative to document body. On Android it is officially supported since version 2.2 but actual behavior of scroll greatly depends on device and manufacturer with end result ranging from great user experience on some Androids v2.2 to horrible glitchy animation on latest versions. Thumbs up to HTC which did a good job on improving stock browsers with their HTC Sense framework and because of that fixed positioning mostly works fine.</p>
<p>JavaScript touch scroll libraries offer a way out of this mess by trying to provide stable cross platform scroll emulation. Basically the idea is to attach JavaScript handlers to document&#8217;s touch events, detect swipe gestures on scrollable element, and emulate scroll behavior with CSS3 transitions. At first these JavaScript libraries enabled only basic scrolling, but today there are features like pinch zoom, fancy fading scrollbars, pull to refresh, etc. </p>
<h2>iOS devices</h2>
<p>On iOS there no support for position fixed until version 5 that only recently came out. By far the best library to use is <a href="http://cubiq.org/iscroll-4">Matteo Spinelli&#8217;s iScroll</a> because of both features it offers and overall smoothness that almost resembles native scroll. Current version is 4 which is a complete rewrite of older iScroll 3 and offers much more than just scrolling. It comes in two flavors, full version with all features and support for desktop browsers, and lite version which offers only touch scrolling in mobile Webkit. It&#8217;s written in pure JavaScript and doesn&#8217;t require any third party library to function (e.g. jQuery). Unlike version 3, iScroll v4 no longer supports automatic refresh when content updates so you&#8217;ll have to call refresh method manually. Although performance is very good, you might want to use native scroll in iOS5 which can be detected through browser&#8217;s user agent.<br />
<code><br />
if ((navigator.userAgent.match(/iPhone/i)<br />
&nbsp;&nbsp;|| navigator.userAgent.match(/iPod/i)<br />
&nbsp;&nbsp;|| navigator.userAgent.match(/iPad/i))<br />
&nbsp;&nbsp;&amp;&amp; navigator.userAgent.match(/ OS 5_/i)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// do not use iScroll<br />
}<br />
</code></p>
<h2>Android</h2>
<p>To get usable and consistent scroll experience on Android proved to be a real challenge. Although position fixed is officially supported since version 2.2 this was only partially true and in most cases did not work. We tested a lot of libraries and best one is <a href="https://github.com/neave/touch-scroll">touchScroll jQuery plugin by Paul Neave</a>. Under the hood it uses the same scrolling logic as iScroll but works much better and refreshes automatically when content updates. Few things to keep in mind is that there&#8217;s a bug causing content flicker when elastic bounce is turned off so it&#8217;s best to leave it active. Also there&#8217;s no way of destroying touchScroll once it&#8217;s been activated.<br />
<br />
One other bug we noticed is present only on vanilla Androids (e.g. Nexus S) where scroll freezes after returning to page using back button. To fix this rewrite touch event bindings to use addEventListener instead of jQuery bind() method and fix bug in getTouches(e) method:</p>
<p><code><br />
function getTouches(e) {<br />
&nbsp;&nbsp;if (e.originalEvent) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;if (e.originalEvent.touches &amp;&amp; e.originalEvent.touches.length) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return e.originalEvent.touches;<br />
&nbsp;&nbsp;&nbsp;&nbsp;} else if (e.originalEvent.changedTouches &amp;&amp; e.originalEvent.changedTouches.length) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return e.originalEvent.changedTouches;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;} else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;if (e.touches.length) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return e.touches;<br />
&nbsp;&nbsp;&nbsp;&nbsp;} else if (e.changedTouches.length) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return e.changedTouches;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;return null;<br />
}<br />
</code><br />
Like I said before HTCs handle position fixed much better so you might want to use native scroll. This will also prevent problems with input fields being offset that sometimes occur on HTC devices. For detection you can once again use user agent string but it&#8217;s not 100% reliable because Android browser allows user to change it.<br />
<code><br />
if (navigator.userAgent.match(/ HTC/i)<br />
&nbsp;&nbsp;// other Androids that don't have HTC in user agent<br />
&nbsp;&nbsp;|| navigator.userAgent.match(/ Desire_A8181/i)<br />
&nbsp;&nbsp;|| navigator.userAgent.match(/ myTouch4G/i)<br />
&nbsp;&nbsp;|| navigator.userAgent.match(/ ADR6200/i)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// do not use touchScroll<br />
}<br />
</code></p>
<h2>Tips for better performance</h2>
<ul>
<li>1. do not use CSS gradients</li>
<li>2. keep content simple and reduce number of html elements</li>
<li><b>3. if possible avoid JavaScript scroll entirely. From user experience point of view mobile web sites shouldn&#8217;t try to emulate mobile application with fixed header and footer</b></li>
</ul>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiveminutes.eu/cross-platform-javascript-touch-scrolling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Git merge and rebase &#8211; the simple explanation</title>
		<link>http://www.fiveminutes.eu/git-merge-and-rebase-the-simple-explanation/</link>
		<comments>http://www.fiveminutes.eu/git-merge-and-rebase-the-simple-explanation/#comments</comments>
		<pubDate>Thu, 03 Nov 2011 12:06:40 +0000</pubDate>
		<dc:creator>Merlin Rebrović</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[merge]]></category>
		<category><![CDATA[rebase]]></category>

		<guid isPermaLink="false">http://www.fiveminutes.eu/?p=3005</guid>
		<description><![CDATA[Git merge and rebase have the same purpose &#8211; to converge multiple branches of development. Although the final goal is the same, those two methods get to it walking different paths. Here is a sample repository that has two diverging &#8230; <a href="http://www.fiveminutes.eu/git-merge-and-rebase-the-simple-explanation/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img class="aligncenter size-full wp-image-3012" src="http://www.fiveminutes.eu/wp-content/uploads/2011/11/branches.jpg" alt="" width="450" height="210" /></p>
<p>Git <strong>merge</strong> and <strong>rebase</strong> have the same purpose &#8211; to converge multiple branches of development. Although the final goal is the same, those two methods get to it walking different paths.<span id="more-3005"></span></p>
<p><!-- more --></p>
<p><!-- more --></p>
<p>Here is a sample repository that has two diverging branches: <code>master</code> and <code>feature</code>. Commit hashes will be represented with integers to help comprehension. They are also representing timestamps &#8211; smaller number means earlier commit.</p>
<pre><code>      +--3--5   master
      |
1--2--+
      |
      +--4--6   feature
</code></pre>
<h2>Merge</h2>
<p>Merge is a <strong>new</strong> commit. That is very important thing to remember and one that is elusive to the newcomers. It is a simple commit with one difference &#8211; it has <strong>two parents</strong>. All other regular commits have only one. How do you check that? Fire up terminal and type <code>git status</code>. See that first two lines for merge?</p>
<pre><code>commit 7777777777777777777777777777777777777777
Merge: 5555555 6666666
Author: Merlin &lt;no.spam@for.me&gt;
Date:   Thu Nov 3 10:11:27 2011 +0100

    Merge branch 'feature' into master.
</code></pre>
<p>Merge in ASCII art.</p>
<pre><code>      +--3--5--+
      |        |
1--2--+        +--7
      |        |
      +--4--6--+
</code></pre>
<p>If you type <code>git log</code> on master branch, you&#8217;ll get a linear output: <strong>7 6 5 4 3 2 1</strong>, sorted by date. But be mindful that is just eye-candy. The history is not linear under the hood. If you checkout at the commit 5, and type <code>git log</code> you&#8217;ll get: <strong>5 3 2 1</strong>. Commit 4 is not a child of 5 or a parent of 3, so it&#8217;s not in the output.</p>
<h2>Fast-forward merge</h2>
<p>The only time a merge creates no new commits is the fast-forward merge. It happens in a situation when there are no commits in an another branch. Than it just updates the branch pointer to the last commit (number 4 in the graph).</p>
<pre><code>Before

1--2--+         master
      |
      +--3--4   feature

After

1--2--3--4   master/feature
</code></pre>
<h2>Rebase</h2>
<p>Rebase is <strong>recreating your work of one branch onto another</strong>. For every commit that you have on the <code>feature</code> branch and not in <code>master</code>, new commit will be created on top of the <code>master</code>. Read this again, slowly: <strong>new commit for every old one, with the same changes</strong>.</p>
<p>When you checkout to <code>feature</code> branch and then rebase onto <code>master</code>, you will get this:</p>
<pre><code>      +--3--5   master
      |
1--2--+
      |
      +--3--5--7--8   feature
              (4)(6)
</code></pre>
<p>Rebase has removed changes 4 and 6, synced with<code> master</code> changes 3 and 5, and then &#8211; remember the above statement &#8211; created new commits for old ones. It added commit 7 with the changes of commit 4 and commit 8 with the changes of commit 6. That way the <code>feature</code> branch has all changes from the <code>master</code> plus its own.</p>
<p>After you do fast-forward merge, you will have:</p>
<pre><code>1--2--3--5--7--8   master/feature
</code></pre>
<p><code>git log</code> will output: <strong>8 7 5 3 2 1</strong>. And it&#8217;s important to notice that the history is linear under the hood too.</p>
<h2>Conclusion</h2>
<p>So, when to use merge and when rebase? As you may have guessed, the answer is &#8220;it depends&#8221;. And it depends mostly on the agreed workflow. But there are a few good guidelines.</p>
<p><!-- Weird codes and markup ahead is because of the limitations of the global blog style, it should be updated. But for now ... --></p>
<p>Use <strong>rebase</strong> when:<br />
● You have a need to merge local changes and don&#8217;t need an exact history. Why litter it with merge commits?<br />
● You prefer a linear history and use <a href="/cut-your-way-through-problems-with-git-bisect/">git bisect</a> very often (it can get confused with a non-linear history).</p>
<p>Use <strong>merge</strong> when:<br />
● You have shared some of the changes with others and it&#8217;s important not to break their repositories. <code>git rebase</code> changes a lot of history so a normal merge is much safer and cleaner for others.<br />
● You care about history and development tracks.</p>
<p><a href="http://www.flickr.com/photos/drb62/4115627864/">Picture credits</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiveminutes.eu/git-merge-and-rebase-the-simple-explanation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Riding the Bézier wave</title>
		<link>http://www.fiveminutes.eu/riding-the-bezier-wave/</link>
		<comments>http://www.fiveminutes.eu/riding-the-bezier-wave/#comments</comments>
		<pubDate>Tue, 25 Oct 2011 13:08:33 +0000</pubDate>
		<dc:creator>Matej Salković</dc:creator>
				<category><![CDATA[Blog]]></category>

		<guid isPermaLink="false">http://www.fiveminutes.eu/?p=2987</guid>
		<description><![CDATA[When working on 2D/3D graphic applications, moving objects along curves is very often a requirement. Solution to this problem - the Bézier curve - has been known for decades. This article is not intended to be a comprehensive analysis of Bézier curves; rather, it should give a beginner just enough knowledge to get her/him started. <a href="http://www.fiveminutes.eu/riding-the-bezier-wave/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img alt="" src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/Bezier_curve.svg/300px-Bezier_curve.svg.png" class="alignleft" width="300" height="188" />When working on 2D/3D graphic applications, animating various objects and moving them across the screen is very often a requirement. As a programmer or designer, sometimes you would like to have the freedom to move objects not only along straight, but also along curved lines. Solution to this problem &#8211; the Bézier curve &#8211; has been known for decades. Still, people unfamiliar with curves may find them a bit confusing at first. This article is not intended to be a comprehensive analysis of Bézier curves; rather, it should give a beginner just enough knowledge to get her/him started.<br />
<span id="more-2987"></span><br />
For now, we&#8217;ll focus on cubic Béziers &#8211; they provide enough control over the curve and are simple to calculate at the same time. Every cubic curve is defined by four control points: <em>P<sub>0</sub>(x<sub>0</sub>, y<sub>0</sub>)</em>, <em>P(x<sub>1</sub>, y<sub>1</sub>)</em>, <em>P<sub>2</sub>(x<sub>2</sub>, y<sub>2</sub>)</em> and <em>P<sub>3</sub>(x<sub>3</sub>, y<sub>3</sub>)</em>. <em>P<sub>0</sub></em> is the start point, <em>P<sub>3</sub></em> is the end point. The curve passes through <em>P<sub>0</sub></em> and <em>P<sub>3</sub></em>, but not through <em>P<sub>1</sub></em> and <em>P<sub>2</sub></em>. All points on the curve are defined with:</p>
<pre><code>C(p) = ∑ P<sub>i</sub> B<sub>i,n</sub>(p)		i∈[0,n]</code></pre>
<p>Note that this expands to two equations &#8211; one for <em>x</em>, and one for <em>y</em> coordinate. Since the curve is cubic, <em>n</em> = 3:</p>
<pre><code>C<sub>x</sub>(p) = ∑ P<sub>xi</sub> B<sub>i,3</sub>(p)
C<sub>y</sub>(p) = ∑ P<sub>yi</sub> B<sub>i,3</sub>(p)</code></pre>
<p>In each equation, <em>B<sub>i,3</sub></em> is one Bernstein polynomial. <a href="http://en.wikipedia.org/wiki/Bernstein_polynomial">Bernstein polynomials</a> have all kinds of nice properties &#8211; but we&#8217;re currently not interested in them, so we&#8217;ll just write down all four polynomials of third degree:</p>
<pre><code>b<sub>0,3</sub>(p) = (1 - p)<sup>3</sup>
b<sub>1,3</sub>(p) = 3p (1 - p)<sup>2</sup>
b<sub>2,3</sub>(p) = 3p<sup>2</sup> (1 - p)
b<sub>3,3</sub>(p) = p<sup>3</sup></code></pre>
<p>So, what exactly is going on? Parameter <em>p</em> gradually changes from 0 to 1. For each value of <em>p</em>, we evaluate the polynomials, then multiply each polynomial with the coordinate of its corresponding control point. Finally, we add all these values to obtain the <em>x</em> coordinate of curve point at <em>p</em>:</p>
<pre><code>C<sub>x</sub>(p) = ∑ P<sub>xi</sub> B<sub>i,n</sub>(p)
      = x<sub>0</sub> b<sub>0,3</sub>(p) + x<sub>1</sub> b<sub>1,3</sub>(p) + x<sub>2</sub> b<sub>2,3</sub>(p) + x<sub>3</sub> b<sub>3,3</sub>(p)</code></pre>
<p>Calculating the <em>y</em> coordinate is the same, except that <em>y</em> coordinates of control points are used instead of <em>x</em>. To speed things up, previous equation can be expanded, and the terms rearranged:</p>
<pre><code>C<sub>x</sub>(p) = a<sub>x </sub>p<sup>3</sup> + b<sub>x</sub> p<sup>2</sup> + c<sub>x</sub> p + d<sub>x</sub>        (*)</code></pre>
<p>where:</p>
<pre><code>a<sub>x</sub> = x<sub>3</sub> - 3x<sub>2</sub> + 3x<sub>1</sub> - x<sub>0</sub>
b<sub>x</sub> = 3x<sub>2</sub> - 6x<sub>1</sub> + 3x<sub>0</sub>
c<sub>x</sub> = 3x<sub>1</sub> - 3x<sub>0</sub>
d<sub>x</sub> = x<sub>0</sub></code></pre>
<p>Now, as soon as you are given four control points, you can calculate <em>a<sub>x</sub></em>, <em>b<sub>x</sub></em>, <em>c<sub>x</sub></em> and <em>d<sub>x</sub></em>. After that, all you have to do is vary the value of <em>p</em> from 0 to 1, and use it to evaluate (*). Then, repeat the procedure for <em>y</em> coordinates. Smaller changes of <em>p</em> will result in more calculations, but the curve will appear smoother. And that&#8217;s all there is to it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiveminutes.eu/riding-the-bezier-wave/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Battle of the Android screens</title>
		<link>http://www.fiveminutes.eu/battle-of-the-screens/</link>
		<comments>http://www.fiveminutes.eu/battle-of-the-screens/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 13:57:41 +0000</pubDate>
		<dc:creator>Ivan Ferdelja</dc:creator>
				<category><![CDATA[Blog]]></category>

		<guid isPermaLink="false">http://www.fiveminutes.eu/?p=2886</guid>
		<description><![CDATA[We recently developed a simple Android app that needed to run on smartphones and tablets, meaning 3-4″ phones, 7″ phonetabs with identity issues and 10″ tablets. It's all made simple enough by the framework but some things always need a bit of tweaking. <a href="http://www.fiveminutes.eu/battle-of-the-screens/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a rel="attachment wp-att-2913" href="http://www.fiveminutes.eu/battle-of-the-screens/android_transformer_desire/"><img class="alignleft size-full wp-image-2913" src="http://www.fiveminutes.eu/wp-content/uploads/2011/10/android_transformer_desire-e1318943265147.png" alt="" width="220" height="116" /></a>We recently developed a simple Android app that needed to run on smartphones and tablets, meaning 3-4″ phones, 7″ phonetabs with identity issues and 10″ tablets. It&#8217;s all made simple enough by the framework but some things always need a bit of tweaking.</p>
<p><span id="more-2886"></span></p>
<p>For simplicity sake, we&#8217;ll ignore the 7″ phonetabs which (mostly) fall into the hdpi/large group anyway.</p>
<p>In our case we had a HTC Hero, HTC Desire and an ASUS Transformer tablet. Hero has a HVGA screen with density of ~180dpi. Desire has a WVGA screen with density of ~250dpi. Transformer has a much larger WXGA screen but a lower density of ~160dpi.</p>
<p><a rel="attachment wp-att-2885" href="http://www.fiveminutes.eu/battle-of-the-screens/android_resolution_graph/"><img class="aligncenter size-full wp-image-2885" src="http://www.fiveminutes.eu/wp-content/uploads/2011/10/android_resolution_graph-e1318942299451.png" alt="" width="400" height="176" /></a></p>
<p>In Android terms, Desire occupies the <em>hdpi</em> group.</p>
<p>Strange as it may seem, Transformer and Hero fall into the <em>mdpi</em> density group. This makes perfect sense from density point of view. But still, Hero has a screen couple of times smaller then the Transformer. So naturally, not all resources will apply to both devices.</p>
<p>Android documentation suggests to use density qualifiers (ldpi, mdpi, hdpi) for images and size qualifiers (normal, large, xlarge) for layouts.</p>
<p>Purpose of this post is to outline that other combinations are also possible. You are free to have a resource folder <strong>drawable-xlarge</strong>. This also applies to other resources such as values. Even though this setup makes sense, it&#8217;s not as straightforward in the official docs so it takes some playing around to see what works and how.</p>
<p>This is exactly what we need for our device set. We don&#8217;t want the Transformer to use the exact same image and value set as the Hero just because they fall into the same density group. Playing with the <strong>xlarge</strong> qualifier we are able to provide a set of resources specific to the tablet.</p>
<p>Note that if you&#8217;re developing a 3.2+ app then you can specify the exact minimum screen size you app needs to work properly. This simplifies things further for the developer.</p>
<p><a href="http://developer.android.com/intl/zh-TW/guide/practices/screens_support.html">Check out the official docs on multiple screen support!</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiveminutes.eu/battle-of-the-screens/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Logging custom parameters with log4j</title>
		<link>http://www.fiveminutes.eu/logging-custom-parameters-with-log4j/</link>
		<comments>http://www.fiveminutes.eu/logging-custom-parameters-with-log4j/#comments</comments>
		<pubDate>Thu, 06 Oct 2011 13:13:44 +0000</pubDate>
		<dc:creator>Samir Čauš</dc:creator>
				<category><![CDATA[Blog]]></category>

		<guid isPermaLink="false">http://www.fiveminutes.eu/?p=2839</guid>
		<description><![CDATA[Tips on how to add custom parameters to log lines using popular log4j. <a href="http://www.fiveminutes.eu/logging-custom-parameters-with-log4j/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.fiveminutes.eu/logging-custom-parameters-with-log4j/log4j-2/" rel="attachment wp-att-2850"><img src="http://www.fiveminutes.eu/wp-content/uploads/2011/10/log4j1.jpg" alt="" width="167" height="139" class="alignleft size-full wp-image-2850" /></a>One important thing that needs to be setup early in every development process is logging. If you are using <a href="http://logging.apache.org/log4j/1.2/">log4j </a>, you have to set up properties file(s) and define Loggers, Appenders  and Layouts. According to documentations <em>“These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported”</em>.<br />
<span id="more-2839"></span>One important property of every log4j configuration file is layout parameter ConversionPattern, which defines data (and data format) of log lines. Usually, your ConversionPattern will consist of information such as Log message, Timestamp, Thread,  Class or Location of log line. You have to be aware that some of these properties consume more <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html">resources</a> than others.<br />
But what if you want to add custom parameter to your log lines? For example things like username, ip address, user agent or some kind of relevant data that is meaningful when you (or someone else) reads log files and tries to understand what happened.<br />
This can be easily achieved with log4j Mapped Diagnostic Context or <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/MDC.html">MDC</a>. According to documentation <em>“MDC in short, is an instrument for distinguishing interleaved log output from different sources”</em> and is <em>“managed on a per thread basis”</em>. MDC is essentially a Map in which you can store/read/remove values and use them later in PatternLayout property to write them in log lines.<br />
Say for example you want to put User-Agent header in all your log lines.<br />
You want to fill your MDC before you wrote any log line. Good place for this is perhaps <a href="http://download.oracle.com/javaee/6/api/javax/servlet/Filter.html">Filter</a>, which you can setup to be executed before other code. In filter you just need to read request header, and put it in log4j MDC, before any other logging is executed.</p>
<pre><code>
String userAgent = request.getHeader(“User-Agent”);
MDC.put(“user-agent”, userAgent );
</pre>
<p></code><br />
Now there is only one more thing left to do - add ConversionPattern property “%X{user-agent}” in your log4j configuration file, like in an example below:</p>
<pre><code>
&lt;appender name="console" class="org.apache.log4j.ConsoleAppender"&gt;
	&lt;param name="Target" value="System.out" /&gt;
	&lt;layout class="org.apache.log4j.PatternLayout"&gt;
		&lt;param name="ConversionPattern" value="[%X{user-agent}] %d %-5p %l - %m%n" /&gt;
	&lt;/layout&gt;
&lt;/appender&gt;
</pre>
<p></code><br />
Similar to Log4j MDC, there is also a <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/NDC.html">NDC </a> (Nested Diagonostic Context), which is basically stack implementations onto which context information can be pushed and popped.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiveminutes.eu/logging-custom-parameters-with-log4j/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

