<?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; java</title>
	<atom:link href="http://blog.krecan.net/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.krecan.net</link>
	<description>Short remarks from Java world</description>
	<lastBuildDate>Tue, 31 Jan 2012 20:13:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>JsonUnit</title>
		<link>http://blog.krecan.net/2012/01/31/jsonunit/</link>
		<comments>http://blog.krecan.net/2012/01/31/jsonunit/#comments</comments>
		<pubDate>Tue, 31 Jan 2012 20:13:55 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=1082</guid>
		<description><![CDATA[Let me introduce you another of my pet projects. It's called JsonUnit and it's something like XmlUnit only for JSON (well it's much, much more simple). Basically it's able to compare two JSON documents and if they do not match, it prints out the differences. For example the following test import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; ... assertJsonEquals("{\n" [...]]]></description>
			<content:encoded><![CDATA[<p>Let me introduce you another of my pet projects. It's called <a href="https://github.com/lukas-krecan/JsonUnit">JsonUnit</a> and it's something like <a href="http://xmlunit.sourceforge.net/">XmlUnit</a> only for JSON (well it's much, much more simple). Basically it's able to compare two JSON documents and if they do not match, it prints out the differences. For example the following test </p>
<pre name="code" class="java">
import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;

...

assertJsonEquals("{\n" +
			"   \"test\":[\n" +
			"      1,\n" +
			"      2,\n" +
			"      {\n" +
			"         \"child\":{\n" +
			"            \"value1\":1,\n" +
			"            \"value2\":true,\n" +
			"            \"value3\":\"test\",\n" +
			"            \"value4\":{\n" +
			"               \"leaf\":5\n" +
			"            }\n" +
			"         }\n" +
			"      }\n" +
			"   ],\n" +
			"   \"root2\":false,\n" +
			"   \"root3\":1\n" +
			"}",
			"{\n" +
			"   \"test\":[\n" +
			"      5,\n" +
			"      false,\n" +
			"      {\n" +
			"         \"child\":{\n" +
			"            \"value1\":5,\n" +
			"            \"value2\":\"true\",\n" +
			"            \"value3\":\"test\",\n" +
			"            \"value4\":{\n" +
			"               \"leaf2\":5\n" +
			"            }\n" +
			"         },\n" +
			"         \"child2\":{\n" +
			"\n" +
			"         }\n" +
			"      }\n" +
			"   ],\n" +
			"   \"root4\":\"bar\"\n" +
			"}");
</pre>
<p>will result in </p>
<pre name="code">
java.lang.AssertionError: JSON documents are different:
Different keys found in node "". Expected [root2, root3, test], got [root4, test].
Different value found in node "test[0]". Expected 1, got 5.
Different types found in node "test[1]". Expected NUMBER, got BOOLEAN.
Different keys found in node "test[2]". Expected [child], got [child, child2].
Different value found in node "test[2].child.value1". Expected 1, got 5.
Different types found in node "test[2].child.value2". Expected BOOLEAN, got STRING.
Different keys found in node "test[2].child.value4". Expected [leaf], got [leaf2].
</pre>
<p>Neat, isn't it?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2012/01/31/jsonunit/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Mock socket</title>
		<link>http://blog.krecan.net/2011/08/27/mock-socket/</link>
		<comments>http://blog.krecan.net/2011/08/27/mock-socket/#comments</comments>
		<pubDate>Sat, 27 Aug 2011 12:56:47 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Tests]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Mock]]></category>
		<category><![CDATA[Socket]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=948</guid>
		<description><![CDATA[Few months ago I have written a small tool that mocks network sockets in Java. Now I have some time to describe it, so here you are. Let's imagine you want to test network communication in Java. It's not easy, you have to start some server on the other side, configure its responses and somehow [...]]]></description>
			<content:encoded><![CDATA[<p>Few months ago I have written a <a href="https://github.com/lukas-krecan/mock-socket/">small tool that mocks network sockets in Java</a>. Now I have some time to describe it, so here you are. </p>
<p>Let's imagine you want to test network communication in Java. It's not easy, you have to start some server on the other side, configure its responses and somehow verify that the data you send are correct.</p>
<p>With mock-socket it's incredibly easy.</p>
<pre name="code" class="java">
import static net.javacrumbs.mocksocket.MockSocket.*;
...

//prepare mock
byte[] dataToWrite = new byte[]{5,4,3,2};
expectCall().andReturn(emptyResponse());

//do test
Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234);
IOUtils.write(dataToWrite, socket.getOutputStream());
socket.close();

//verify data sent
assertThat(recordedConnections().get(0), data(is(dataToWrite)));
assertThat(recordedConnections().get(0), address(is("example.org:1234")));
</pre>
<p>You see, just statically import MockSocket class, prepare the mock, execute the test and verify the data. The library just removes the default Java socket implementation and place a mock implementation in its stead. </p>
<p>Of course, this example does not have much sense. It just tests that Java socket implementation works. But imagine that you implement some non-trivial network library. A test library can be handy.</p>
<p>Moreover, there is a HTTP extension which can be used if you want to test some HTTP client. Let's say a JSON REST client. In such case, you can write this.</p>
<pre name="code" class="java">
import static net.javacrumbs.mocksocket.http.HttpMockSocket.*;

...

//prepare mock
expectCall()
  .andWhenRequest(uri(is("/test/something.do")))
     .thenReturn(response().withStatus(404))
  .andWhenRequest(uri(is("/test/other.do")))
    .thenReturn(response().withContent("Text")).thenReturn(response().withContent("Text"));

//do your test
...

//verify
assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain"))));
</pre>
<p>Ain't great? You can do much more, please take a look at the <a href="https://github.com/lukas-krecan/mock-socket/">project page</a> if you are interested.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2011/08/27/mock-socket/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Where does this class came from?</title>
		<link>http://blog.krecan.net/2010/11/01/where-this-class-came-from/</link>
		<comments>http://blog.krecan.net/2010/11/01/where-this-class-came-from/#comments</comments>
		<pubDate>Mon, 01 Nov 2010 21:18:09 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[classloader]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=770</guid>
		<description><![CDATA[Today I have been debugging some nasty problem on Weblogic. The application worked on one version but did not work on an older one. Apparently some classes were not compatible. But it's quite difficult to debug such problem. You need to find out from which JAR given class was taken from. It's not trivial in [...]]]></description>
			<content:encoded><![CDATA[<p>Today I have been debugging some nasty problem on Weblogic. The application worked on one version but did not work on an older one. Apparently some classes were not compatible. But it's quite difficult to debug such problem. You need to find out from which JAR given class was taken from. It's not trivial in enterprise environment. The class can be part of J2SE, application server and your EAR at the same time. Especially if the class has something to do with XML or web services. End if you have such class, you need some trick to determine which version was actually used.</p>
<p>The trick is simple yet not widely known. In fact I have encountered it in a <a href="http://speaking-my-language.blogspot.com/2009/11/embedded-scala-interpreter.html"> Scala related article</a>. You just call this code from JSP or some other suitable place.</p>
<pre name="code" class="java">
YourClass.class.getProtectionDomain().getCodeSource().getLocation()
</pre>
<p>And that's all, this command will return path to your mystery class JAR.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2010/11/01/where-this-class-came-from/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>
	</channel>
</rss>

