<?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>Java crumbs &#187; Articles in English</title>
	<atom:link href="http://blog.krecan.net/category/articles-in-english/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.krecan.net</link>
	<description>Short remarks from Java world</description>
	<lastBuildDate>Sun, 21 Feb 2010 10:20:02 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Different programming worlds</title>
		<link>http://blog.krecan.net/2009/04/11/different-programming-worlds/</link>
		<comments>http://blog.krecan.net/2009/04/11/different-programming-worlds/#comments</comments>
		<pubDate>Sat, 11 Apr 2009 12:35:41 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=353</guid>
		<description><![CDATA[I have had this article in my head for almost a year but reading Practical API design book have forced me to finally write it. The idea is not new or revolutionary, on the contrary it's quite obvious: There are different programming worlds. We can use metaphor of workshops. 
Jaroslav Tulach, author of Practical API [...]]]></description>
			<content:encoded><![CDATA[<p>I have had this article in my head for almost a year but reading <a href="http://wiki.apidesign.org/wiki/Main_Page">Practical API design</a> book have forced me to finally write it. The idea is not new or revolutionary, on the contrary it's quite obvious: There are different programming worlds. We can use metaphor of workshops. </p>
<p>Jaroslav Tulach, author of Practical API design book works in one workshop. He is creating components for other programmers. Lets imagine that he is making nuts and bolts. Of course, his nuts and bolts are more sophisticated, but for sake of argument lets imagine this simple nuts and bolts scenario. </p>
<p>Apparently, his customers are other craftsman and their main requirement is compatibility. They want to use his parts in existing machines, they want to use the same tools they currently have. He just can't decide, that hexagonal head is not modern any more. All his customers have tools for them. Therefore, he has too maintain compatibility. Of course, in some cases he can enhance quality by using better materials, he can introduce better types of components, but once a component is sold to a customer he can't change its dimensions or other important properties. For him backward compatibility and well defined API are crucial. I think that definition for API should be: “Something that is not allowed to change”.</p>
<p>I am on the other hand server-side Java programmer. I write software mainly for end-users. Lets say that I am building custom-made bicycles. You know, some people have  so special requirements that they can't go to a shop and just buy a bike. They need special, super-duper tailor made bike. </p>
<p>Usually they do not care what parts I use. They want me to meet their requirements and do it as fast as possible. In this case, I don't care about API at all. I just take existing components and put them together. Of course, I want this components to be well supported, developed in backward compatible way. But me personally, I do not care about creating APIs. I am just using them. Sure, I create my own components, but I do it only because I have to. Sometimes I have to connect two incompatible parts, sometimes there is no-one who makes the part I need. But I always prefer to use already existing parts. I do not know how in bike workshop, but in software there usually is no need to write your own library or new API. Of course, sometimes you are doing something really revolutionary, sometimes your customer requirements are really special, but in my experience, usually customers want something that has already been done hundred times before and there is already someone who makes corresponding parts.</p>
<p>There are only two cases when we have to define an API. The first one is, when we want to reuse custom made components in different projects. It looks like a plausible argument, but I think that in 99% of cases there already is an existing library that already does almost exactly what you need. And I think it is always better to use existing solution then reinvent a wheel. </p>
<p>The other situation where you have to define an API is when you interface with other supplier. For example if your customer wants to mount a rocket launcher on the bike. Then you usually have to agree on some interface between you and the rocket launcher manufacturer. I would bet that there is already a standard for this, but if there is no standard you have to define an API. In my workshop it is usually done using WebServices or other XML based format just because it is easier to change such API in almost compatible way. I usually do not use Java based API just because all the versioning and other issues it brings.</p>
<p>Well, it looks like I do not do anything useful. Hell, I have to defend myself. My added value is that I put those parts together. Customers do not pay me for making bicycle components they pay me for delivering a <a hef="http://www.freepatentsonline.com/4458908.html">tandem-tricycles</a> for elephants. That's my job. To build such thing as fast as possible and as cheep as possible. They do not want me to loose their money by reinventing a wheel. </p>
<p>So in my case creating an API is not useful. Sometimes it is even harmful. I'd like to be flexible, I want to be able to fix my mistakes as fast as possible, I'd like to change my design quite often, I do not want to maintain backward compatibility. I do not have to. The only people who will be influenced by my changes are my colleagues. It is quite easy to fix their components accordingly to my changes. At least in software world.</p>
<p>Of course that I try to create well encapsulated and reusable classes. Of course I try to create some kind of communication interface to all my modules. Even for internal usage, I like to have some level of <a href="http://wiki.apidesign.org/wiki/Cluelessness">cluelessness</a>. But I would not call it API. It is something one level under API. For me it is just an implementation trick I use to make my life easier. I am not publishing it outside the team, I know that it is not stable at all. It's not an API it's just PI. Of course the distinction is not clear, but I still feel that there is a difference between a stable API and volatile internal PI. Both of them hide implementation details but only API has to be stable.</p>
<p>There are other types of workshops as well. There are for example mass producers. They sell bikes or software in boxes. These people live somewhere in between. They try to use existing parts as much as possible, but they have to differ somehow from their competitors. So they have to provide something special. In this case, there might be a reason to create a special component and make it standard, so they can share this component between teems working on different products. But again, I do not think that they need stable well defined API so much.</p>
<p>There are of course other types of workshops, but my metaphor is slowly reaching its limits so I will abandon it.  What I want to say is, that there is no one size fits all approach or advice. What a surprise!</p>
<p>For example, you can read that you should not optimize your code because JVM will do it for you. That's true unless you work for mobile devices. I recommend you to read <a href=" http://developer.android.com/guide/practices/design/performance.html">this</a>, it goes against everything I believe in, yet in their use case it's valid.   </p>
<p>There are other examples, I am sure you will come up with your own. The important thing to realize is that there are different worlds for which different approaches apply. So if you do not agree with someone, maybe the reason is that he is from completely different world.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2009/04/11/different-programming-worlds/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Hibernate SQL logging</title>
		<link>http://blog.krecan.net/2009/04/05/hibernate-sql-logging/</link>
		<comments>http://blog.krecan.net/2009/04/05/hibernate-sql-logging/#comments</comments>
		<pubDate>Sun, 05 Apr 2009 14:00:35 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[SQl]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=345</guid>
		<description><![CDATA[If you need to log SQL queries generated by Hibernate together with parameter values you do not need P6Spy. It is enough to set-up log4j or your favorite logging framework like this

log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE

Then you will see everything in your log. For example:

7820 DEBUG [org.hibernate.SQL] {main} - insert into Client (name, personalNumber, id) values (?, ?, ?)
7821 [...]]]></description>
			<content:encoded><![CDATA[<p>If you need to log SQL queries generated by Hibernate together with parameter values you do not need <a href="http://www.p6spy.com/">P6Spy</a>. It is enough to set-up log4j or your favorite logging framework like this</p>
<p><code><br />
log4j.logger.org.hibernate.SQL=DEBUG<br />
log4j.logger.org.hibernate.type=TRACE<br />
</code></p>
<p>Then you will see everything in your log. For example:</p>
<p><code><br />
7820 DEBUG [org.hibernate.SQL] {main} - insert into Client (name, personalNumber, id) values (?, ?, ?)<br />
7821 TRACE [org.hibernate.type.StringType] {main} - binding 'John Doe' to parameter: 1<br />
7821 TRACE [org.hibernate.type.StringType] {main} - binding '123X' to parameter: 2<br />
7821 TRACE [org.hibernate.type.LongType] {main} - binding '10' to parameter: 3<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2009/04/05/hibernate-sql-logging/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Streaming a stream</title>
		<link>http://blog.krecan.net/2009/02/27/streaming-a-stream/</link>
		<comments>http://blog.krecan.net/2009/02/27/streaming-a-stream/#comments</comments>
		<pubDate>Fri, 27 Feb 2009 10:53:01 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[HttpInvoker]]></category>
		<category><![CDATA[InputStream]]></category>
		<category><![CDATA[RMIIO]]></category>
		<category><![CDATA[Serializable]]></category>
		<category><![CDATA[serialization]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=286</guid>
		<description><![CDATA[I have another dirty trick for you. Let's imagine that you have a document server with following sophisticated interface.

public interface DocumentServer {
	/**
	 * Stores a document.
	 * @return document id
	 */
	public String storeDocument(InputStream in);

	/**
	 * Loads document with given id.
	 * @param id
	 * @return
	 */
	public InputStream loadDocument(String id);
}

It works well, until you realize, that [...]]]></description>
			<content:encoded><![CDATA[<p>I have another dirty trick for you. Let's imagine that you have a document server with following sophisticated interface.</p>
<pre name="code" class="java">
public interface DocumentServer {
	/**
	 * Stores a document.
	 * @return document id
	 */
	public String storeDocument(InputStream in);

	/**
	 * Loads document with given id.
	 * @param id
	 * @return
	 */
	public InputStream loadDocument(String id);
}
</pre>
<p>It works well, until you realize, that you want to call the DocumentServer remotely, for example using Spring <a href="http://static.springframework.org/spring/docs/2.0.x/reference/remoting.html#remoting-httpinvoker">HttpInvoker</a>. </p>
<p>HttpInvoker is a nice small tool, that lets you make remote method invocations over HTTP without much pain. It creates dynamic proxy, serializes all attributes using Java serialization, calls remote proxy, which deserializes arguments, calls the implementation and sends the result back in the same way. It is nice, simple and it works without any problem. You can configure it in five minutes. The downside is, that you have to have Spring Java application on both ends of the wire and all arguments that you send over the wire have to be Serializable.</p>
<p>And that's exactly the trouble we have with our DocumentServer. There is no standard InputStream implementation that implements serializable. Lets think about it. We need to have a stream that is able to stream itself into an <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectOutputStream.html">ObjectOutputStream</a>. Sounds strange, but it is quite easy. We can simply write a wrapper, that implements <a href="http://java.sun.com/developer/technicalArticles/Programming/serialization/">writeObject(ObjectOutputStream)</a> method and that takes all the bytes from the underlying stream and writes them to the ObjectOutputStream. It is simple and it does not consume much memory.</p>
<p>Deserialization is much harder. We have to implement readObject(ObjectInputStream in) method, load the data and store them somewhere for later use. We can store them in the memory or in a temporary file. If the streams are larger, temporary file is better choice but we have to delete them after use and the implementation gets messy. </p>
<p>The good news is, that we do not have to implement it, it's already done by <a href="http://openhms.sourceforge.net/rmiio/">RMIIO</a> library. They provide <a href="http://openhms.sourceforge.net/rmiio/apidocs/com/healthmarketscience/rmiio/SerializableInputStream.html">SerializableInputStream</a> class that does exactly what we need. You just have to ignore Javadoc comment saying:</p>
<blockquote><p>An additional layer around a RemoteInputStream which makes it Serializable and an InputStream. In general, this extra layer is not necessary and I do not recommend using this class. However, in the odd case where the callee really wants to get something which is already an InputStream, this class can be useful. </p></blockquote>
<p>The only thing we have to do is to wrap all the streams into SerializableInputStream like this</p>
<pre name="code" class="java">
new SerializableInputStream(new DirectRemoteInputStream(inputStream));
</pre>
<p>It can be done by hand written proxy, by dynamically generated proxy or by AOP.</p>
<p>Of course there are other alternatives. The easiest one is to create something like ByteArayInputStream that implements Serializable. If the streams are small enough, it's the best solution. </p>
<p>We can also try to use <a href="http://static.springframework.org/spring/docs/2.0.x/reference/remoting.html#remoting-caucho-protocols-hessian">Hessian</a>, but I had some troubles when method signatures were more complicated. And of course there is still a possibility to implement own remoting mechanism. After all, HTTP is meant to transport streams. But it would require lot of boilerplate code and I do not like boilerplate code. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2009/02/27/streaming-a-stream/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring managed Hibernate interceptor in JPA</title>
		<link>http://blog.krecan.net/2009/01/24/spring-managed-hibernate-interceptor-in-jpa/</link>
		<comments>http://blog.krecan.net/2009/01/24/spring-managed-hibernate-interceptor-in-jpa/#comments</comments>
		<pubDate>Sat, 24 Jan 2009 16:29:27 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[injection]]></category>
		<category><![CDATA[interceptor]]></category>
		<category><![CDATA[JPA]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=261</guid>
		<description><![CDATA[I have been trying to teach Hibernate injecting dependencies into Entities (I know, there is magic @Configurable annotation, I wanted to try it without magic). It is quite easy to do it using Hibernate interceptor (for example like this). But there is one drawback. It is not straightforward to inject interceptor into Hibernate when JPA [...]]]></description>
			<content:encoded><![CDATA[<p>I have been trying to teach Hibernate injecting dependencies into Entities (I know, there is magic <a href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-atconfigurable">@Configurable</a> annotation, I wanted to try it without magic). It is quite easy to do it using Hibernate interceptor (for example like <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/jpa-test/tags/jpa-test-3.0/jpa-test/src/main/java/net/krecan/javacrumbs/jpa/interceptor/SpringInjectingInterceptor.java">this</a>). But there is one drawback. It is not straightforward to inject interceptor into Hibernate when JPA abstraction is in the way. </p>
<p>It is simple to define interceptor in <code>persistence.xml</code> using <a href="http://www.hibernate.org/hib_docs/entitymanager/reference/en/html/configuration.html#setup-configuration-bootstrapping">hibernate.ejb.interceptor</a> property. But it is only possible to specify class name, you can not inject Spring bean. If you read documentation to Spring <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.html">LocalContainerEntityManagerFactoryBean</a> there is no possibility to specify the interceptor bean there neither. But there is a way how to achieve it. First of all, you have to redefine Hibernate PersistenceProvider. </p>
<pre name="code" class="java">
public class ConfigurableHibernatePersistence extends HibernatePersistence {
	private Interceptor interceptor;
	public Interceptor getInterceptor() {
		return interceptor;
	}

	public void setInterceptor(Interceptor interceptor) {
		this.interceptor = interceptor;
	}

	@SuppressWarnings("unchecked")
	@Override
	public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) {
		Ejb3Configuration cfg = new Ejb3Configuration();
		Ejb3Configuration configured = cfg.configure( info, map );
		postprocessConfiguration(info, map, configured);
		return configured != null ? configured.buildEntityManagerFactory() : null;
	}

	@SuppressWarnings("unchecked")
	protected void postprocessConfiguration(PersistenceUnitInfo info, Map map, Ejb3Configuration configured) {
		if (this.interceptor != null)
		{
			if (configured.getInterceptor()==null || EmptyInterceptor.class.equals(configured.getInterceptor().getClass()))
			{
				configured.setInterceptor(this.interceptor);
			}
			else
			{
				throw new IllegalStateException("Hibernate interceptor already set in persistence.xml ("+configured.getInterceptor()+")");
			}
		}
	}
}
</pre>
<p>(<a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/jpa-test/tags/jpa-test-3.0/jpa-test/src/main/java/net/krecan/javacrumbs/jpa/interceptor/ConfigurableHibernatePersistence.java">source</a>)</p>
<p>Here we override method <code>createContainerEntityManagerFactory</code> in order to add <code>postprocessConfiguration</code> method call. In this method, it is possible to change Hibernate configuration as needed. Now the only thing to be done is configuring Spring to use our new PersistenceProvider. It is quite simple.</p>
<pre name="code" class="xml">
	&lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt;
		&lt;property name="persistenceUnitName" value="testPU" /&gt;
		&lt;property name="dataSource" ref="dataSource" /&gt;
		&lt;property name="persistenceProvider"&gt;
			&lt;bean class="net.krecan.javacrumbs.jpa.interceptor.ConfigurableHibernatePersistence"&gt;
				&lt;property name="interceptor"&gt;
					&lt;bean class="net.krecan.javacrumbs.jpa.interceptor.SpringInjectingInterceptor"/&gt;
				&lt;/property&gt;
			&lt;/bean&gt;
		&lt;/property&gt;
	&lt;/bean&gt;
</pre>
<p>And that all folks, we have Spring configured interceptor even when using JPA abstraction. It would be better if similar classes were in Spring or Hibernate, but it's just few lines of code so feel free to copy them if you need to. If you know easier way how to do it, please mention it in the comments below.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2009/01/24/spring-managed-hibernate-interceptor-in-jpa/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaFX security</title>
		<link>http://blog.krecan.net/2008/12/16/javafx-security/</link>
		<comments>http://blog.krecan.net/2008/12/16/javafx-security/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 09:47:16 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javafx]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=198</guid>
		<description><![CDATA[I had some concerns regarding JavaFX security. You know, if you go to JavaFX samples page, most of them are self-signed and you have to give them all permissions to be able to run them. I didn't like it at all. On Devoxx I asked few guys from Sun about it and their responses were [...]]]></description>
			<content:encoded><![CDATA[<p>I had some concerns regarding JavaFX security. You know, if you go to JavaFX samples page, most of them are self-signed and you have to give them all permissions to be able to run them. I didn't like it at all. On Devoxx I asked few guys from Sun about it and their responses were not clear. So I have decided to do few experiments to find out how it works. It's nothing new, it's similar to the way applets have worked all the time. But who remembers how applet security works?</p>
<p>I took <a href="http://javafx.com/samples/InterestingPhotos/index.html">InterestingPhotos</a> sample application from JavaFX pages and added following code to onNext function (behold, my very first JavaFX code).</p>
<pre name="code" class="java">
try {
	var writer = new FileWriter(new File(System.getProperty("user.home"),"javafx_infection.txt"));
	writer.append("I have escaped the browser. {new Date()}");
	writer.close();
} catch (e:Exception) {
	e.printStackTrace();
}
</pre>
<p>Now every time user clicks on the “next” button, the applet attempts to write to a file in user home directory. It can be both a malicious code or a legitimate action. There is no way to tell them apart. That's the reason why we need some security mechanism.</p>
<p><strong>Unsigned application</strong><br />
<a href="http://blog.krecan.net/files/javafx/unsigned/InterestingPhotos.html">Example</a><br />
You can choose not to sign the application at all. Usually it is the best choice. This way the application will run in a sandbox and will not be able to execute any potentially dangerous code. On the other hand it will be safe for user to run it and he will not be troubled by any security alert. If the application attempts to execute dangerous code, the JRE will throw a security exception. In our case it will throw<br />
<code><br />
java.security.AccessControlException: access denied (java.util.PropertyPermission user.home read)<br />
	at java.security.AccessControlContext.checkPermission(Unknown Source)<br />
	at java.security.AccessController.checkPermission(Unknown Source)<br />
	at java.lang.SecurityManager.checkPermission(Unknown Source)<br />
	at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)<br />
	at java.lang.System.getProperty(Unknown Source)<br />
	at interesting.Main.hackIt(Main.fx:406)<br />
	at interesting.Main.onNext(Main.fx:133)<br />
</code></p>
<p>So if you don't need to do anything dangerous and you are happy to play in the sandbox, unsigned application is the best choice.</p>
<p><strong>Selfsigned application</strong><br />
<a href="http://blog.krecan.net/files/javafx/selfsigned/InterestingPhotos.html">Example</a><br />
Most of the samples on JavaFX page are self-signed. It means that the JAR is signed by a certificate that is not verified by any certification authority. In my opinion, that's the worst option you can choose. You force the user to answer following security dialog.</p>
<p><img src="/files/javafx/alert.png" alt="Security Warning" /></p>
<p>Basically it's the same as executing EXE (or binary) file only more dangerous. Some users already know that they should not execute EXE files from unknown sources, but they don't know that they shouldn't execute Java applications from unknown sources. I am afraid that we will hear about this issue more in the future. </p>
<p>If the user clicks on Run, the application can do whatever it want, if the user clicks on Cancel, the application will not run at all. </p>
<p><strong>Signed application</strong><br />
<a href="http://blog.krecan.net/files/javafx/signed/InterestingPhotos.html">Example</a><br />
We can sign the application by a certificate that is validated by a CA. I have used Thawte Freemail Certificate. Sounds trustworthy, doesn't it? If you open the example, you will see following security warning. </p>
<p><img src="/files/javafx/signed.png" alt="Security Warning" /></p>
<p>It looks less threatening than with the selfsigned certificate. It looks less dangerous. The “Always trust” check-box is even checked by default. But in fact, it's not much safer. It is more complicated to generate  such certificate but anyone (even me) can do it. It might be even more dangerous. Everyone who is able to generate a certificate that is validated by the same CA will be allowed to execute the code (if you leave the check box checked). And again, it is all or nothing choice. User can either give the application all permissions or do not run it at all.</p>
<p><strong>Unsigned application with signed JAR</strong><br />
<a href="http://blog.krecan.net/files/javafx/signed_jar/InterestingPhotos.html">Example</a><br />
In case you really need to do something potentially dangerous and you do not want to scare the user at the start of the application, you can use signed JAR in an unsigned application. Basically you can put all the dangerous stuff into a jar and sign only this jar. Most of the code can live in the main application which is unsigned. This way the application will start as unsigned and when you attempt to execute the dangerous parts the signed jar will be loaded and the security warning will be shown. In our example the application will start and the security warning will be shown when user clicks on the “next” button. At least that's how it works on my machine. And I like it. This way user can use my application and is notified only when the application needs to do something insecure. And even if he decides that he doesn't trust me, he can still use the application. (This idea came from a guy from Sun, unfortunately I don't remember his name, thanks anyway)</p>
<p>To reiterate, the most secure choice is to write a JavaFX application that does not need any security permissions. If you do not sign it, it runs in the sandbox and everything is fine. If you need to execute some dangerous code, you have to ask user for a permission. Which is good, but users should be   instructed that they shouldn't execute any Java(FX) code if they are not sure what it does. So there is a possibility that they will not execute your applications because they will be afraid to do so. I can imagine that in the next versions of JavaFX there will be a signed library provided by Sun that will contain operations that are potentially dangerous but that are in fact safe. Like opening a file using “Open File dialog” etc.</p>
<p><em>Disclaimer: I am server-side developer, I know nothing about client-side Java, so do not be surprised if something I have written here turns up being wrong. Just correct it in the comments. Thanks.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2008/12/16/javafx-security/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Date puzzle</title>
		<link>http://blog.krecan.net/2008/11/26/date-puzzle/</link>
		<comments>http://blog.krecan.net/2008/11/26/date-puzzle/#comments</comments>
		<pubDate>Wed, 26 Nov 2008 19:06:08 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=171</guid>
		<description><![CDATA[I like surprises, I like puzzles, therefore I like Java Date and Calendar library. I already thought that there is nothing it could surprise me with. And I was wrong. Today it got me again. Consider the following code snippet.

		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, 1970);
		calendar.set(Calendar.MONTH, 0);//month is zero based
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		Date date = calendar.getTime();
		System.out.println(date);
		System.out.println(date.getTime());

The command on the [...]]]></description>
			<content:encoded><![CDATA[<p>I like surprises, I like puzzles, therefore I like Java Date and Calendar library. I already thought that there is nothing it could surprise me with. And I was wrong. Today it got me again. Consider the following code snippet.</p>
<pre name="code" class="java">
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, 1970);
		calendar.set(Calendar.MONTH, 0);//month is zero based
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		Date date = calendar.getTime();
		System.out.println(date);
		System.out.println(date.getTime());
</pre>
<p>The command on the line 07 prints out "<code>Thu Jan 01 00:00:00 GMT 1970</code>", the question is what does the command on the line 08 prints? If you are such looser and you do not remember the JavaDoc of java.util.Date class, here is the description of  <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Date.html#getTime()">getTime()</a> method.</p>
<blockquote><p>Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.</p></blockquote>
<p>So to reformulate the question, what is the number of milliseconds between January 1, 1970, 00:00:00 GMT and Thu Jan 01 00:00:00 GMT 1970?</p>
<p>What are your guesses?  Make yourself famous by adding a comment with correct explanation. And do not worry, if you do not find the solution until tomorrow evening, I will post it here. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2008/11/26/date-puzzle/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Specific environment setting with Spring</title>
		<link>http://blog.krecan.net/2008/11/14/specific-environment-setting-with-spring/</link>
		<comments>http://blog.krecan.net/2008/11/14/specific-environment-setting-with-spring/#comments</comments>
		<pubDate>Fri, 14 Nov 2008 19:11:40 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=140</guid>
		<description><![CDATA[There is one issue that people usually have with J2EE deployment. I call it specific environment setting. Imagine that you have several environments that you want to deploy your J2EE application to. For example development, test, stress test, staging or production. For all those environments you need specific settings like JDBC URL, JDBC user name [...]]]></description>
			<content:encoded><![CDATA[<p>There is one issue that people usually have with J2EE deployment. I call it specific environment setting. Imagine that you have several environments that you want to deploy your J2EE application to. For example development, test, stress test, staging or production. For all those environments you need specific settings like JDBC URL, JDBC user name and password, path to a directory for data export etc. The question is where to put such setting. If you store it in the WAR (JAR, EAR, SAR or other AR) you have to create specific archive for every environment.<br />
	It is not a big problem, provided you have an automated build. Nevertheless I do not like this solution. I like to have the same archive for all environments. This way I am sure that the application on production is exactly the same as the one I have tested on the test environment.  Moreover, there is a problem with passwords. You have to make them part of the build process and effectively publish them by doing so.<br />
	One possible solution is to use JNDI. It is probably the best solution if you can use it. But what if you don't use big and heavy J2EE server.  What if you use a servlet container like Tomcat or Jetty instead. In this case I have one of my favorite tricks for you. I use Spring configuration similar to the following one:</p>
<pre name="code" class="xml">
 &lt;bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;
	&lt;property name="locations"&gt;
		&lt;list&gt;
			&lt;value&gt;
			  classpath:main-config.properties
			&lt;/value&gt;
			&lt;value&gt;
			  file:///${user.home}/spring-test.properties
			&lt;/value&gt;
		&lt;/list&gt;
	&lt;/property&gt;
	&lt;property name="ignoreResourceNotFound" value="true"/&gt;
	&lt;property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/&gt;
 &lt;/bean&gt;

&lt;bean class="net.krecan.spring.TstBean"&gt;
	&lt;property name="property1" value="${property1}"/&gt;
	&lt;property name="property2" value="${property2}"/&gt;
	&lt;property name="property3" value="${property3}"/&gt;
&lt;/bean&gt;
</pre>
<p>Spring tries to load a configuration file from user home directory. If the file is found, properties from the main-config file are overwritten by those found in the spring-test file. And you can even overwrite those by defining a system property with the same name.<br />
	I like it. This way every developer can have his own configuration. There is no danger of accidentally committing passwords to a source control system. You can use exactly the same WAR on every environment. It is relatively safe, although some system administrators do not like it. This way you can distribute an application over the internet without forcing users to unpack it, edit a config file and pack it again afterwards.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2008/11/14/specific-environment-setting-with-spring/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Spring field injection</title>
		<link>http://blog.krecan.net/2008/06/17/spring-field-injection/</link>
		<comments>http://blog.krecan.net/2008/06/17/spring-field-injection/#comments</comments>
		<pubDate>Tue, 17 Jun 2008 10:41:14 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=78</guid>
		<description><![CDATA[Few weeks ago, I worked on an interesting task. I had to find out how to migrate my customer's proprietary framework to Spring. The framework was quite similar to Spring, although there were some differences. They used combination of XML and annotation configuration. Every property had special annotation saying that it is a property. XML [...]]]></description>
			<content:encoded><![CDATA[<p>Few weeks ago, I worked on an interesting task. I had to find out how to migrate my customer's proprietary framework to Spring. The framework was quite similar to Spring, although there were some differences. They used combination of XML and annotation configuration. Every property had special annotation saying that it is a property. XML schema for configuration was generated based on this annotation. So basically you had XML configuration that said what to inject to the annotated fields. The problem was that they did not have set methods for the fields.</p>
<p>And of course, the customer did not want to change all their classes just to migrate to Spring. It meant that they needed configure all the beans using Spring, but inject the dependencies directly, not through set methods. </p>
<p>I know that it is ugly and not recommended but in this case I think I have good excuse. It is a customer's requirement. The question of course is how to  do it.</p>
<p>You can try to use Spring post-processor. If you register instance of <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/InstantiationAwareBeanPostProcessor.html">InstantiationAwareBeanPostProcessor </a>you can use method <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/InstantiationAwareBeanPostProcessor.html#postProcessPropertyValues(org.springframework.beans.PropertyValues,%20java.beans.PropertyDescriptor[],%20java.lang.Object,%20java.lang.String)">postProcessPropertyValues</a> to manipulate with property values just before Spring attempts to inject them. So you can inject the values into fields by yourself. And it works. The trouble is that you have to do property instantiation and conversion by yourself too. I almost  managed to do it when I encountered a big problem - inner beans. In Spring, you can define a bean inside another bean. In order to inject the inner bean to the outer bean, the inner bean has to be already instantiated. But  <code>postProcessPropertyValues</code> method is called before inner bean instantiation. So that is a blind alley. </p>
<p>OK, post-processor can not be used, let's do it more hard-core. Spring has something called <code><a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/BeanWrapper.html">BeanWrapper</a></code>. It is used by Spring for setting bean properties. Great, that is the point where I can force Spring to inject into the fields. The only thing I need to do, is to inject my  BeanWrapper implementation into Spring. There is only one small trouble. It is not possible to do it. Unsurprisingly, dependency injection does not work inside the dependency injection code. I tried hard, but did not find any simple and safe way how to replace default BeanWrapper implementation.  (If you know how to do it, please let me know)</p>
<p>So, if it is not possible to force Spring to inject without set method, let's give him what he is asking for. The final solution is simple. When instantiating beans, I do not instantiate the original class but a  subclass that is generated in the runtime and has all needed set methods.  For the class generation I use <a href="http://www.csg.is.titech.ac.jp/~chiba/javassist/">Javassist</a>, it is simple and powerful. To make the integration with Spring as simple as possible, I use factory bean. So the Spring XML config file looks like this</p>
<pre name="code" class="xml">
	&lt;bean id="beanFactory" class="net.krecan.beanfactory.SetMethodGeneratingBeanFactory"/&gt;
	&lt;bean id="sampleClass"
		      factory-bean="beanFactory"
		      factory-method="createBean"&gt;
		&lt;constructor-arg value="net.krecan.beanfactory.Sample"/&gt;
		&lt;property name="textProperty" value="test.txt"/&gt;
		&lt;property name="intProperty" value="123"/&gt;
		&lt;property name="simpleSample"&gt;
			&lt;bean factory-bean="beanFactory"
			   factory-method="createBean"&gt;
				&lt;constructor-arg value="net.krecan.beanfactory.SimpleSample"/&gt;
				&lt;property name="textProperty" value="hallo"/&gt;

			&lt;/bean&gt;

		&lt;/property&gt;
	&lt;/bean&gt;
</pre>
<p>Instead of providing class name in the bean definition, factory-bean attribute is used. Spring than calls method createBean on the factory bean with parameter taken from the constructor-arg element. It contains the class name of the bean. The result of the method call is used as a bean instance and all the properties are set by Spring. </p>
<p>Of course, you do not have to write it this way every time you want to instantiate this kind of bean. Simple custom namespace can be created in order to simplify the syntax.</p>
<p>In the future, when my customer realize that setters are a good thing, the factory can be easily replaced by a dummy implementation. </p>
<p>To reiterate, direct injection of dependencies from XML to the fields without using set methods is not supported by Spring. You can choose between XML based configuration using set methods or annotation based configuration. It is extremely hard to change default Spring behavior. And maybe it is a good thing. So if you need to do ugly XML based field injection, your only choice is to generate set methods in the runtime. Or maybe something else, but I have no idea what.</p>
<p><span id="more-78"></span></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2008/06/17/spring-field-injection/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Let&#8217;s play with OSGi, Spring and Maven, part 2</title>
		<link>http://blog.krecan.net/2008/06/01/lets-play-with-osgi-spring-and-maven-part-2/</link>
		<comments>http://blog.krecan.net/2008/06/01/lets-play-with-osgi-spring-and-maven-part-2/#comments</comments>
		<pubDate>Sun, 01 Jun 2008 16:29:49 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[OSGi]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=75</guid>
		<description><![CDATA[In the first part of this article, we have finished and tested DAO part of the application. Today we are going to create the UI and connect all the parts using  Service bundle.
If you think about it, you realize that UI bundle is exactly the same as the DAO bundle. It only exports a [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://http://blog.krecan.net/2008/05/29/lets-play-with-osgi-spring-and-maven-part-1/">first part</a> of this article, we have finished and tested DAO part of the application. Today we are going to create the UI and connect all the parts using  Service bundle.</p>
<p>If you think about it, you realize that UI bundle is exactly the same as the DAO bundle. It only exports a service. In this case it implements DataReceiver interface from the Common bundle. Therefore, pom.xml, generated MANIFEST.MF file and Spring configuration file will be similar to that we have seen in part 1. So I will skip this bundle and jump directly to the Service layer.</p>
<p>In the Service bundle we want to use both DAO and UI. We want to periodically pull the data from the DataLoader and push them to the DataReceiver service. </p>
<p>Let's start with bundle metadata. </p>
<pre name="code" class="xml">
	&lt;plugin&gt;
	    &lt;groupId&gt;org.apache.felix&lt;/groupId&gt;
	    &lt;artifactId&gt;maven-bundle-plugin&lt;/artifactId&gt;
	    &lt;extensions&gt;true&lt;/extensions&gt;
	    &lt;configuration&gt;
	    	&lt;instructions&gt;
	    	 &lt;Private-Package&gt;
	    	    net.krecan.spring.osgi.service.*
	    	 &lt;/Private-Package&gt;
	    	&lt;/instructions&gt;
	    &lt;/configuration&gt;
	  &lt;/plugin&gt;
</pre>
<p>This configuration of the Maven  OSGi plugin is going to generate following MANIFEST.MF file.</p>
<p><code><br />
Manifest-Version: 1.0<br />
Bundle-Name: demo-spring-osgi-service<br />
Build-Jdk: 1.5.0_15<br />
Built-By: lukas<br />
Created-By: Apache Maven Bundle Plugin<br />
Private-Package: net.krecan.spring.osgi.service<br />
Import-Package: net.krecan.spring.osgi,org.apache.commons.logging<br />
Bundle-ManifestVersion: 2<br />
Bundle-SymbolicName: net.krecan.spring-osgi.demo-spring-osgi-service<br />
Tool: Bnd-0.0.255<br />
Bnd-LastModified: 1212320410936<br />
Bundle-Version: 1.0.0.SNAPSHOT<br />
</code><br />
You can see that we do not export any package. It is not needed. Service bundle only coordinates DAO and UI, it does not need to expose anything. </p>
<p>Import-Package directive is more interesting. Maven plugin analyzed Java classes and figured out that import  of net.krecan.spring.osgi and org.apache.commons.logging package is needed. The first one is exported by our Common bundle, the other one is provided by the commons-logging package. Great, I do not have to specify dependencies by hand, Maven plugin does it automatically. </p>
<p>OK, OSGi is configured, we can try to use our services. Again, I will use Spring OSGi integration. I will create following Spring XML configuration in the META-INF/spring directory of the Service bundle</p>
<pre name="code" class="xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans ...&gt;

	&lt;osgi:reference id="dataLoader" interface="net.krecan.spring.osgi.DataLoader"/&gt;

	&lt;osgi:list id="receivers"  interface="net.krecan.spring.osgi.DataReceiver"/&gt;

	&lt;bean id="dataDistributor" class="net.krecan.spring.osgi.service.DataDistributor"&gt;
		&lt;property name="dataLoader" ref="dataLoader"/&gt;
		&lt;property name="receivers" ref="receivers"/&gt;
	&lt;/bean&gt;

	&lt;!-- Timer config --&gt;
	...	

&lt;/beans&gt;
</pre>
<p><small>(Full version can be downloade <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/spring-osgi-demo/tags/part1/demo-spring-osgi-service/src/main/resources/META-INF/spring/applicationContext.xml">here</a>)</small></p>
<p>By <code>osgi:reference</code> element we say, that we want to find a service that implements <code>DataLoader</code> service. If such service is running in the OSGi engine, we can use the reference as a Spring bean with ID “dataLoader”. So we can inject it to the <code><a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/spring-osgi-demo/tags/part1/demo-spring-osgi-service/src/main/java/net/krecan/spring/osgi/service/DataDistributor.java">dataDistributor</a></code> bean like any other Spring bean. That is great. The source code is not bound to OSGi at all. If you wish, you can switch form OSGi to a simple deployment, to remote invocation, web service or whatever you want. The source code will remain unchanged. The only thing we need to change is the configuration.</p>
<p>Do you wonder what happens, if there is no DataLoader service running? The answer is simple. Service bundle will wait for it. When DataLoader became available, the Service bundle will start to pull data from it. (This behavior can be changed by the cardinality attribute)</p>
<p><code>osgi:list</code> element is similar to <code>osgi:reference</code>. It supports multiple references. It implements normal <code>java.util.List</code>. Again, we can inject it to an ordinary Spring bean. Moreover, the list is magic. If new service with given interface appears in the OSGi container, it is automagically added to the list. So I do not have to care about it. </p>
<p>The rest of the Spring config is not connected with OSGi. It just starts timer job that calls <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/spring-osgi-demo/tags/part1/demo-spring-osgi-service/src/main/java/net/krecan/spring/osgi/service/DataDistributor.java">dataDistributor.loadAndSend</a> method every 100ms.</p>
<p>And now we can test it. We will again use Spring OSGi support for integration tests. First of all, we have to say which bundles we are going to use. </p>
<pre name="code" class="java">
	protected String[] getTestBundlesNames() {
		return new String[] {
			"net.krecan.spring-osgi, demo-spring-osgi-dao, "+DEMO_VERSION,
			"net.krecan.spring-osgi, demo-spring-osgi-ui, "+DEMO_VERSION,
			"net.krecan.spring-osgi, demo-spring-osgi-service, "+DEMO_VERSION,
		};
	}
</pre>
<p>And now we can run the test. </p>
<pre name="code" class="java">
	public void testAddUi() throws InterruptedException, BundleException, IOException
	{
		Thread.sleep(500);
		LOG.info("Starting alternative UI");
		Resource bundleResource = locateBundle("net.krecan.spring-osgi, demo-spring-osgi-ui-alternative, "+DEMO_VERSION);
		Bundle bundle = bundleContext.installBundle(bundleResource.getURL().toString());
		bundle.start();
		LOG.info("Alternative UI started");
		Thread.sleep(500);
		LOG.info("Stopping alternative UI");
		bundle.stop();
		LOG.info("Alternative UI stopped");
		Thread.sleep(500);

	}
</pre>
<p>To make it more interesting, we will run the test for 500ms and then we will add and start alternative UI bundle. After another 500ms we will stop the alternative UI bundle again. It will result into following log output.</p>
<div class="code">
2008-06-01 14:33:55,818 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:55 CEST 2008     )<br />
2008-06-01 14:33:55,908 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:55 CEST 2008     )<br />
2008-06-01 14:33:56,009 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,108 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,209 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,308 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,317 INFO [net.krecan.spring.osgi.dao.ServiceOsgiTest] {main} - Starting alternative UI<br />
2008-06-01 14:33:56,384 INFO [net.krecan.spring.osgi.dao.ServiceOsgiTest] {main} - Alternative UI started<br />
2008-06-01 14:33:56,408 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,508 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,508 INFO [net.krecan.spring.osgi.ui.alternative.AlternativeDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,609 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,609 INFO [net.krecan.spring.osgi.ui.alternative.AlternativeDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,708 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,708 INFO [net.krecan.spring.osgi.ui.alternative.AlternativeDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,809 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,809 INFO [net.krecan.spring.osgi.ui.alternative.AlternativeDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,884 INFO [net.krecan.spring.osgi.dao.ServiceOsgiTest] {main} - Stopping alternative UI<br />
2008-06-01 14:33:56,909 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:56,909 INFO [net.krecan.spring.osgi.ui.alternative.AlternativeDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:56 CEST 2008     )<br />
2008-06-01 14:33:57,009 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:57 CEST 2008     )<br />
2008-06-01 14:33:57,009 INFO [net.krecan.spring.osgi.ui.alternative.AlternativeDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:57 CEST 2008     )<br />
2008-06-01 14:33:57,101 INFO [net.krecan.spring.osgi.dao.ServiceOsgiTest] {main} - Alternative UI stopped<br />
2008-06-01 14:33:57,108 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:57 CEST 2008     )<br />
2008-06-01 14:33:57,209 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:57 CEST 2008     )<br />
2008-06-01 14:33:57,311 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:57 CEST 2008     )<br />
2008-06-01 14:33:57,409 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:57 CEST 2008     )<br />
2008-06-01 14:33:57,509 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:57 CEST 2008     )<br />
2008-06-01 14:33:57,614 INFO [net.krecan.spring.osgi.ui.DefaultDataReceiver] {timerFactory} - ***** Received data: Data ( text = Hallo Sun Jun 01 14:33:57 CEST 2008     )
</div>
<p>It looks exactly how it should. Messages from the alternative UI appear and then disappear together with corresponding bundle. That's what OSGi is all about. It enables dynamic binding of components. We can replace or plug-in services dynamically in the runtime. </p>
<p>To reiterate. Today we have seen OSGi in action. We have connected several services using Spring  support and we have seen dynamic nature of OSGi. And what's the best, our source code is not aware of OSGi. What a nice example of dependency injection.</p>
<p>Next time, we will try to play a bit with the example. I want to run it standalone, without Spring integration testing support and I'd like to test how it is resistant to class loader leaks. </p>
<p>Source code is accessible in <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/spring-osgi-demo/tags/part1/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2008/06/01/lets-play-with-osgi-spring-and-maven-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Let&#8217;s play with OSGi, Spring and Maven, part 1</title>
		<link>http://blog.krecan.net/2008/05/29/lets-play-with-osgi-spring-and-maven-part-1/</link>
		<comments>http://blog.krecan.net/2008/05/29/lets-play-with-osgi-spring-and-maven-part-1/#comments</comments>
		<pubDate>Thu, 29 May 2008 20:42:02 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=74</guid>
		<description><![CDATA[In programming every problem can be solved by adding another layer of abstraction 
Today, I am going to write about my experiments with OSGi. Please, be aware that I do not know OSGi. Moreover, I am too lazy to learn it. But I know Spring and Maven quite well, so I will use them quite [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>In programming every problem can be solved by adding another layer of abstraction </p></blockquote>
<p>Today, I am going to write about my experiments with <a href="http://www.osgi.org/Main/HomePage">OSGi</a>. Please, be aware that I do not know OSGi. Moreover, I am too lazy to learn it. But I know Spring and Maven quite well, so I will use them quite extensively.</p>
<p>I will try to implement following sample application</p>
<p><img src="/files/osgi.png" alt="Sample application" /></p>
<p>We will have 5 bundles in total. Bundle is basic building block when working with OSGi applications. Please, read the OSGi documentation for more details. </p>
<p>We will have the <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/spring-osgi-demo/tags/part1/demo-spring-osgi-common/src/main/java/net/krecan/spring/osgi/">Common bundle</a>, which is quite simple passive bundle. It contains DataLoader and DataReceiver interfaces and Data object. This bundle does not provide any service, but every other bundle has compile-time dependency on it. </p>
<p>DAO bundle provides DataLoader service implementation. Please, imagine that there is some really cool data access logic. </p>
<p>UI bundle provides DataReciver service implementation. Again, we will pretend that there is something more sophisticated than printing to the console. To make the example more interesting, we will have two different implementations of the UI.</p>
<p>And in the middle of the application sits Service bundle that loads data from the DAO layer and propagates them to the UI layer.</p>
<p>Before diving into the code, I want to point out one interesting thing. If you look at the picture, you will see red and black arrows. Black arrows represent compile-time dependencies. Basically it means, that when I want to compile UI, Service and DAO, I have to have Common jar in the classpath. But I do not need to have there any other bundle. It means, that the bundles are really decoupled. They just do not need to know about each other. They are independent. Do you understand? That's the modularity we are looking for. The only thing the bundle needs to know is the interface of the service. Did I already mention that the bundles are independent? If not, I am saying it right know. They are independent.</p>
<p>The red arrows are run-time dependencies. That's what OSGi framework is for. It will find for us the implementations of the interfaces (services) and will connect them together.</p>
<p><strong>DAO service</strong></p>
<p>So lets dive to the code. We will start with the DAO service. OSGi uses MANIFEST.MF file for defining its meta-data. Since I am to lazy to write it, I will use Maven plugin to generate it for me.</p>
<pre name="code" class="xml">
&lt;plugin&gt;
	&lt;groupId&gt;org.apache.felix&lt;/groupId&gt;
	&lt;artifactId&gt;maven-bundle-plugin&lt;/artifactId&gt;
	&lt;extensions&gt;true&lt;/extensions&gt;
	&lt;configuration&gt;
		&lt;instructions&gt;
		 &lt;Export-Package&gt;
		 	net.krecan.spring.osgi
		 &lt;/Export-Package&gt;
		 &lt;Private-Package&gt;
		 	net.krecan.spring.osgi.*
		 &lt;/Private-Package&gt;
		&lt;/instructions&gt;
	&lt;/configuration&gt;
&lt;/plugin&gt;
</pre>
<p>As you can see, I am using <a href="http://felix.apache.org/site/maven-bundle-plugin-bnd.html">Apache Felix plugin for Maven</a>. It generates following MANIFEST.MF file for me.</p>
<p><code><br />
Manifest-Version: 1.0<br />
Export-Package: net.krecan.spring.osgi<br />
Private-Package: net.krecan.spring.osgi.dao<br />
Built-By: krel<br />
Tool: Bnd-0.0.255<br />
Bundle-Name: demo-spring-osgi-dao<br />
Created-By: Apache Maven Bundle Plugin<br />
Bundle-Version: 1.0.0.SNAPSHOT<br />
Build-Jdk: 1.6.0_03<br />
Bnd-LastModified: 1211919191482<br />
Bundle-ManifestVersion: 2<br />
Import-Package: net.krecan.spring.osgi<br />
Bundle-SymbolicName: net.krecan.spring-osgi.demo-spring-osgi-dao<br />
</code></p>
<p>It says that I am importing package <code>net.krecan.spring.osgi</code>. That's the package where the interfaces are defined in. And I am exporting this package again, since I am publishing implementation of  one of the interfaces. (Well, I am not sure if its true, but it did not work, when this package was not exported.) All other packages are private. It means, that they can not be used be other bundles. Wow, it is something like <a href="http://blogs.sun.com/andreas/entry/superpackages_in_jsr_294">Java 7 superpackages</a>. </p>
<p>Ok, OSGi is almost configured, the only think we need to do is to define the service. But again, I am to lazy to learn OSGi. What to do? What about Spring?. Spring provides <a href="http://www.springframework.org/osgi">support for OSGi</a>. So I can export whatever Spring bean I want as an OSGi service. The only think I have to do, is to put following XML file into META-INF/spring directory. </p>
<pre name="code" class="xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans ...&gt;

	&lt;osgi:service ref="dataLoader"
		interface="net.krecan.spring.osgi.DataLoader" /&gt;

	&lt;bean id="dataLoader"
		class="net.krecan.spring.osgi.dao.DefaultDataLoader" /&gt;
&lt;/beans&gt;
</pre>
<p><small>(Full version can be downloade <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/spring-osgi-demo/tags/part1/demo-spring-osgi-dao/src/main/resources/META-INF/spring/applicationContext.xml">here</a>)</small></p>
<p>I am publishing dataLoader bean as an implementation of DataLoader interface. Later on, when some other bundle will look for the service, it will just say, that it wants implementation of this interface and OSGi will find it.<br />
And that's it. I have created my first OSGi bundle. What? You do not believe that it works? Ok, I will test it using Spring OSGi testing support. We will write simple integration test. </p>
<pre name="code" class="java">
package net.krecan.spring.osgi.dao;

import net.krecan.spring.osgi.DataLoader;

import org.osgi.framework.ServiceReference;
import org.springframework.osgi.test.AbstractConfigurableBundleCreatorTests;
import org.springframework.osgi.test.platform.Platforms;

/**
 * Tests the DAO bundle.
 * @author Lukas Krecan
 *
 */
public class DaoOsgiTest extends AbstractConfigurableBundleCreatorTests {

private static final String DEMO_VERSION = "1.0-SNAPSHOT";

	protected String getPlatformName() {
		   return Platforms.FELIX;
	}

	protected String[] getTestBundlesNames() {
		return new String[] {
			"net.krecan.spring-osgi, demo-spring-osgi-dao, "+DEMO_VERSION,
		};
	}

	/**
	 * The superclass provides us access to the root bundle
	 * context via the 'getBundleContext' operation
	 */
	public void testOSGiStartedOk() {
		assertNotNull(bundleContext);
	}

	public void testGetDataLoader() throws Exception {
		ServiceReference ref = bundleContext.getServiceReference(DataLoader.class.getName());
        assertNotNull("Service Reference is null", ref);
        try {
        	DataLoader dataLoader = (DataLoader) bundleContext.getService(ref);
            assertNotNull("Cannot find the service", dataLoader);
            assertNotNull("Data are null", dataLoader.loadData());
        } finally {
            bundleContext.ungetService(ref);
        }
	}
}
</pre>
<p>The test extends <a href="http://static.springframework.org/osgi/docs/1.0-m3/api/org/springframework/osgi/test/AbstractConfigurableBundleCreatorTests.html">AbstractConfigurableBundleCreatorTests </a>which takes care of starting OSGi engine (Apache Felix in this case) and loading all necessary bundles. The only think we have to specify is the name of the bundle under test. (The test loads the bundles from the local Maven repository by default.) We can than test whether the bundle is started and the service is running.</p>
<p>That's all for today, in the next part we will discuss UI bundle and the service bundle. I will be glad for any feedback, so if you will spot any mistake in the text, please let me know. Of course I accept the compliments as well.</p>
<p>Source code is accessible in <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/spring-osgi-demo/tags/part1/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2008/05/29/lets-play-with-osgi-spring-and-maven-part-1/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
