<?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>Databases and Life &#187; Java</title>
	<atom:link href="http://www.databasesandlife.com/category/coding/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.databasesandlife.com</link>
	<description>Adrian Smith's blog</description>
	<lastBuildDate>Mon, 14 Jun 2010 09:41:07 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>The special variable &#8220;_&#8221;</title>
		<link>http://www.databasesandlife.com/the-underscore-variable/</link>
		<comments>http://www.databasesandlife.com/the-underscore-variable/#comments</comments>
		<pubDate>Fri, 30 Apr 2010 14:05:39 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Perl]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=479</guid>
		<description><![CDATA[Reading this blog post, Destructuring binds in Ruby just now reminded me of a feature I love about Prolog which I wish would make it into other languages.
Firstly, I love assigning a list to a list of lvalues i.e. variables; this is possible in both PHP and Perl which I use regularly; and no doubt [...]]]></description>
			<content:encoded><![CDATA[<p>Reading this blog post, <a href="http://citizen428.net/archives/427-Destructuring-binds-in-Ruby.html">Destructuring binds in Ruby</a> just now reminded me of a feature I love about Prolog which I wish would make it into other languages.</p>
<p>Firstly, I love assigning a list to a list of <a href="http://cplus.about.com/od/glossar1/g/lvalue.htm">lvalues</a> i.e. variables; this is possible in both PHP and Perl which I use regularly; and no doubt many other languages. (But not Java: why not!?)</p>
<pre>
    ($a, $b) =      ($b, $a);  // Perl
list($a, $b) = array($b, $a);  // PHP
</pre>
<p>PHP, as always, wins in inelegance, having the left side syntactically different to the right side. While it&#8217;s obviously the case that a list of values and a list of lvalues are technically different, I don&#8217;t think this difference should be expressed in the syntax.</p>
<p>I mean, in most languages you write e.g. $foo=4 and $bar=$foo; in both those cases you write $foo but yet they do something different (lvalue and rvalue); given that you write them the same there i think the same should apply to lists.</p>
<p>But I digress &#8211; What I want to mention is using &#8220;underscore&#8221; to mean &#8220;any variable&#8221;. I first saw this in Prolog.</p>
<p>For example, imagine you have to implement an interface (e.g. in Java), it requires you to write a function taking two parameters, but one of the parameters you don&#8217;t care about. Wouldn&#8217;t it be nice to write</p>
<pre>
interface ExistingApi {
   public void createObject(String name, Object otherInformation);
}

class MyInstanceOfTheApi {
   public void createObject(String name, _) {
      ...
   }
}
</pre>
<p>i.e. this shows clearly you do not care about the second parameter. </p>
<p>In current Java (and all languages I program including Perl, PHP) you have to give all variables a name even if you don’t use them, either in function definitions or in “assign to a list” scenarios mentioned above. It is then left as an exercise to the reader to determine if these variables are used or not, and indeed an exercise to the writer to name the variable they are never going to use.</p>
<p>I mean yes, technically you can actually just call variables “_” (or “$_” (except in Perl where “$_” already means something)) but that would then be a coding convention as opposed to a language feature, and who knows if the coding convention is actually used correctly by a programmer. (If “_” is a variable there’s nothing stopping someone from using its value.)</p>
<p>And then you have the problem if you have two variables you don&#8217;t care about, you can&#8217;t call them both &#8220;_&#8221;.</p>
<p>By the way, <a href="http://books.google.com/books?id=VjHk2Cjrti8C&#038;printsec=frontcover&#038;dq=Programming+in+Prolog&#038;source=bl&#038;ots=IHQtLmvJqC&#038;sig=RFhnlEzs_Nu_GkwTQD_Z3som5Ds#v=onepage&#038;q&#038;f=false">Programming in Prolog</a> is an excellent book.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/the-underscore-variable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java is lacking a String &#8220;join&#8221; function</title>
		<link>http://www.databasesandlife.com/java-is-lacking-a-string-join-function/</link>
		<comments>http://www.databasesandlife.com/java-is-lacking-a-string-join-function/#comments</comments>
		<pubDate>Fri, 16 Apr 2010 10:49:49 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Broken]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=465</guid>
		<description><![CDATA[Between Java 1.0 and Java 1.3 (1996-2002 according to Wikipedia) there was no way to split strings into an array or a list.
In Java 1.4 the authors of Java saw it fit to introduce a method to split strings,
String csvData = "field1,field2,field3";
String[] fields = csvData.split(",");

However they did not introduce a method to &#8220;join&#8221; strings! Even [...]]]></description>
			<content:encoded><![CDATA[<p>Between Java 1.0 and Java 1.3 (1996-2002 according to Wikipedia) there was no way to split strings into an array or a list.</p>
<p>In Java 1.4 the authors of Java saw it fit to introduce a method to split strings,</p>
<pre>String csvData = "field1,field2,field3";
String[] fields = csvData.split(",");
</pre>
<p>However they did not introduce a method to &#8220;join&#8221; strings! Even in Java 7 there is no way to do this, e.g. via a static String.join method (2002-now).</p>
<p>OK I realize this is not &#8220;rocket science&#8221;, and I appreciate it exists in various versions in various third-party libraries, but still, it&#8217;s something every program needs to do at some point, it&#8217;s annoying to have to re-define it or think about it for each application.</p>
<p>For example, in one project I was working on in the last 6 months, such a function was created, and then had a bug! (OK but to be fair, that was not the only bug in the application!)</p>
<p>Come on, I mean this is a totally trivial function, totally necessary, available in all scripting lanuags why is it still not in Java?!</p>
<p>(P.S. Want to see an &#8220;enterprise java&#8221; solution to this problem? Check out the <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/base/Joiner.html#method_summary">number of methods on this class</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/java-is-lacking-a-string-join-function/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Java varargs: inconsistent behaviour if you pass an array</title>
		<link>http://www.databasesandlife.com/java-varargs-inconsistent-behaviour-if-you-pass-an-array/</link>
		<comments>http://www.databasesandlife.com/java-varargs-inconsistent-behaviour-if-you-pass-an-array/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 10:39:07 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Broken]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=461</guid>
		<description><![CDATA[In Java 1.4 there was the function Arrays.asList. You could pass it an array and it would make a list out of it.
String[] myArray = new String[] { "foo", "bar" };
List myList = Arrays.asList(myArray);

In Java 1.5 this was retrofitted for varargs; you could simply pass elements to the function
List&#60;String&#62; myList = Arrays.asList("foo", "bar");

I never really [...]]]></description>
			<content:encoded><![CDATA[<p>In Java 1.4 there was the function Arrays.asList. You could pass it an array and it would make a list out of it.</p>
<pre>String[] myArray = new String[] { "foo", "bar" };
List myList = Arrays.asList(myArray);
</pre>
<p>In Java 1.5 this was retrofitted for varargs; you could simply pass elements to the function</p>
<pre>List&lt;String&gt; myList = Arrays.asList("foo", "bar");
</pre>
<p>I never really understood how that worked in a backwards-compatible way; I mean either the function takes an array of stuff, or it takes individual elements, surely?</p>
<p>It turns out, that with the varargs syntax, the caller is not forced to pass individual elements, the caller can instead pass an array of elements.</p>
<pre>List&lt;String&gt; myList = Arrays.asList("foo", "bar");
List&lt;String&gt; myList = Arrays.asList(new String[] { "foo", "bar" });
</pre>
<p>The above two calls are identical, both return a List&lt;String&gt;.</p>
<p>But surely this is really dangerous? I mean Arrays.asList does not make any assumptions about what types of arguments it accepts; the list can be composed of any object.</p>
<p>How can it be certain that you want to have an List of Strings, and not a List containing a single element which is a String array? (An array is an object.)</p>
<p>To demonstrate this inconsistency:</p>
<pre>String[] arr = new String[] { "foo", "bar" };
Arrays.asList(arr);            // returns List&lt;String&gt;
Arrays.asList(arr, arr);       // returns List&lt;String[]&gt;
Arrays.asList(arr, arr, arr);  // returns List&lt;String[]&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/java-varargs-inconsistent-behaviour-if-you-pass-an-array/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Code generation? Don&#8217;t generate to Java</title>
		<link>http://www.databasesandlife.com/java-method-64k-limit/</link>
		<comments>http://www.databasesandlife.com/java-method-64k-limit/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 16:40:13 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=407</guid>
		<description><![CDATA[I tried to write a program using Java; it all seemed to be going well but then I hit a ridiculous limit. Java cannot be used for this type of problem. I have now completely re-written it in a different programming language, and that works fine.
Be aware of this limit. I was unaware of it [...]]]></description>
			<content:encoded><![CDATA[<p><strong>I tried to write a program using Java; it all seemed to be going well but then I hit a ridiculous limit. Java cannot be used for this type of problem. I have now completely re-written it in a different programming language, and that works fine.</strong></p>
<p>Be aware of this limit. I was unaware of it when I started this project. But it makes Java completely unsuitable for a whole class of problem.</p>
<p>My customer supplies me with a config file from time to time, this specifies a certain algorithm. When the user enters data, this algorithm must be applied. The algorithm is complex, so performance is an issue.</p>
<p>The solution I chose was to <strong>generate code</strong> to execute the algorithm, based on the information in the config file. This is a valid computer-science approach, and is used for similar problems. For example, language parsers are often expressed as a grammar, and code to parse documents in the grammar are generated. JSPs are turned into Java classes which are then compiled and executed. WebTek <a href="http://github.com/prozessor13/webtek/blob/master/lib/WebTek/Compiler.pm">pre-compiles</a> HTML templates containing macros into code which produces the resulting HTML when executed.</p>
<p>However, <strong>don&#8217;t try this in Java</strong>, unless you are only working with small problems. A single method in Java can only be 64KB in size, once compiled.<br />
<a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4262078"> http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4262078</a></p>
<p>This means, JSPs can only be of a certain length, parsers can only parse languages of a certain complexity, if WebTek were written in Java then templates could only be of a certain length and complexity, and so on. Do you want to place such restrictions on the software you produce?</p>
<p>My specific problem involves simulating one million variations to a particular solution. How can I fit that into 64K?</p>
<ul>
<li>That is 0.06 bytes per solution variation; yet the simulation of a single variation involves many lines of code (i.e. in total compiling to more than 0.06 bytes!).</li>
<li>I could put each variation into its own method, and have a big method which calls them all&#8212;but a method call takes more than 0.06 bytes!</li>
<li>I could have a hierarchy of methods: one main method which calls, say, 100 sub-methods, each of those call 100 sub-sub-methods, and finally those methods call the methods for the individual variations.</li>
</ul>
<p>It&#8217;s not even possible to know how many bytes a method will generate to! So, as the complexity of the simulation of a variation is expressed in the config file, I would have to essentially have to do a &#8220;trial and error&#8221; approach: generate a method, compile it, if I get the error concerning the 64KB limit, split the problem up into slightly smaller methods, try the compilation again, repeat, etc. (And the Java compiler is not even very fast.)</p>
<p><strong>This is all so wrong! </strong>This is complexity, which isn&#8217;t solving the customer&#8217;s problem. This complexity costs me time (and thus my customer money), complexity leads to bugs and difficulty of maintenance, etc.</p>
<p>So I have changed the language. <strong>Rather than generate Java, I generate C</strong> and compile it using the GNU gcc compiler. <a href="http://www.gnu.org/prep/standards/standards.html#Semantics">From the GNU coding standards</a>:</p>
<blockquote><p>
Avoid arbitrary limits on the length or number of any data structure, including file names, lines, files, and symbols, by allocating all data structures dynamically.
</p></blockquote>
<p>This is a good standard! I like it. All programs should be written with this in mind. Your program may well be online in 10 or 20 years, and the hardware may well have changed: a 64KB limit may seem reasonable one year but is a real limitation 10 or 20 years later in software which would otherwise still be useful.</p>
<p>So, if you are solving this type of problem, don&#8217;t use Java.</p>
<p>P.S. On a separate project I used a similar approach using Perl, and that worked out fine too.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/java-method-64k-limit/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java: Always explicitly specify which XML parser to use</title>
		<link>http://www.databasesandlife.com/java-always-explicitly-specify-which-xml-parser-to-use/</link>
		<comments>http://www.databasesandlife.com/java-always-explicitly-specify-which-xml-parser-to-use/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 12:42:26 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Broken]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=351</guid>
		<description><![CDATA[There is the following design error in Java (at least in Servlets):

A server may serve multiple applications; each application may use different libraries or even different versions of the same library, &#8220;side by side&#8221;.
XML parsers, transformers (XSLT), etc., have a standard interface, and there may be different implementations of this interface from different vendors, open-source [...]]]></description>
			<content:encoded><![CDATA[<p>There is the following design error in Java (at least in Servlets):</p>
<ol>
<li>A server may serve multiple applications; each application may use different libraries or even different versions of the same library, &#8220;side by side&#8221;.</li>
<li>XML parsers, transformers (XSLT), etc., have a standard interface, and there may be different implementations of this interface from different vendors, open-source projects, etc.</li>
<li>Which XML parser, transformed etc. is actually used depends on a <strong>global system variable</strong>.</li>
</ol>
<p>And it&#8217;s point 3 that&#8217;s the problem really. Points 1 and 2 are debatable: they certainly bring advantages, but they certainly bring complexity too.</p>
<p>I just had the problem that one of my web applications stopped working, but only intermittently. Restarting the server led to everything being OK, but later things would not be OK. I do hate environments where everything appears to work, yet in fact doesn&#8217;t. I mean how do you know when you&#8217;re &#8220;done&#8221; in such an environment? (Or how do you even know you are in such an environment?)</p>
<p>The bug was caused by:</p>
<ol>
<li>Application one used the default XML parser, and didn&#8217;t have any extra JARs (libraries) for reading XML</li>
<li>Application two required a special XML parser, set the global variable so it would be used, and included the JARs necessary for the special XML parser</li>
</ol>
<p>So when a request came to application 1, <em>after </em>a request had come to application 2, then the system would try to instantiate the special XML parser within application 1 (specified in the global variable set by application 2), but wouldn&#8217;t find it, as it wasn&#8217;t deployed in application 1 (and applications can&#8217;t use one another&#8217;s libraries, due to feature #1).</p>
<p>This seems obvious when one describes it, but looking at the logs, on a live server, with the system down and the clock ticking? &#8211; Far from obvious.</p>
<p>So now, I assert, every time you want to create an XML parser, do the following:</p>
<h3>If you require a special XML library, use:</h3>
<pre>
System.<strong>setProperty</strong>("javax.xml.parsers.DocumentBuilderFactory",
    "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
...
</pre>
<h3>If you require the standard XML library, use:</h3>
<pre>
Properties systemProperties = System.getProperties();
systemProperties.<strong>remove</strong>("javax.xml.parsers.DocumentBuilderFactory");
System.setProperties(systemProperties);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
...
</pre>
<p>There is also the possibility to pass a parameter to DocumentBuilderFactory to specify which XML parser technology to use. That&#8217;s a good option too, as it wouldn&#8217;t &#8220;corrupt&#8221; this global variable (&#8220;system property&#8221;). However I think one should be defensive, and always delete the global variable if one wishes to use the standard XML parser, and therefore it doesn&#8217;t matter if this global variable gets corrupted or not.</p>
<h3>Never do the following:</h3>
<pre>
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
</pre>
<p>This simply relies on whichever XML parser is currently set in the global variable. You have no way to guarantee that some other application running on the same server won&#8217;t set the global variable to use an XML parser you don&#8217;t have installed in your application. Even if you have control of the server and all applications, you don&#8217;t know what software you&#8217;ll be writing in the future. (In this case I installed a new application to a server which&#8217;d been running fine for 1 year, but due to setting the global variable, the old application broke..)</p>
<p>The same applies for all those other &#8220;factory&#8221; situations such as TransformerFactory.newInstance() etc.</p>
<p>This feels all quite inelegant to me, and has just cost me a lot of time, and it&#8217;s not as if I&#8217;m so new to programming Java. I am wondering if there is a better way to approach it? Or is Java just broken in this particular respect?</p>
<p>P.S. This is not the only thing that went wrong with the old application today. I upgraded from Java 5 to Java 6 and suddenly some XML was not compliant against a schema according to Java &#8211; I had hit <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6529766">this error</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/java-always-explicitly-specify-which-xml-parser-to-use/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Starting Jetty: FAILED</title>
		<link>http://www.databasesandlife.com/starting-jetty-failed/</link>
		<comments>http://www.databasesandlife.com/starting-jetty-failed/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 21:28:45 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=346</guid>
		<description><![CDATA[It is literally 23:19 on a Sunday and I&#8217;ve been working through the weekend to get a release out of some software I&#8217;m working on.
The Java application webserver (Jetty) was taking a long time to restart each time I did a change, so for some reason I thought I&#8217;d experiment with some new command-line options. [...]]]></description>
			<content:encoded><![CDATA[<p>It is literally 23:19 on a Sunday and I&#8217;ve been working through the weekend to get a release out of some software I&#8217;m working on.</p>
<p>The Java application webserver (Jetty) was taking a long time to restart each time I did a change, so for some reason I thought I&#8217;d experiment with some new command-line options. Probably not the right time to do that.</p>
<p>Normally I would type</p>
<pre>
$ sudo  /etc/init.d/jetty6 restart
Stopping Jetty: OK
Starting Jetty: OK
</pre>
<p>and everything would be good. I tried typing</p>
<pre>
$ sudo /etc/init.d/jetty6 supervise
</pre>
<p>Then some stuff happened that I didn&#8217;t really understand. Rather than try and work out what it did I tried to restart it again using the old restart mechanism</p>
<pre>
$ sudo  /etc/init.d/jetty6 restart
...
<b>Starting Jetty: FAILED</b>
</pre>
<p>OK I mean that was basically what was going on, it just wrote FAILED. How helpful! There was no info in the logfile. I searched Google but didn&#8217;t come up with anything.</p>
<p>A reboot later, and about half an hour of looking into /etc/init.d/jetty6 with vi and randomly making changes and printing more stuff out yielded the fact that the &#8220;supervise&#8221; command had evidently run Jetty &#8220;as me&#8221; and not as the &#8220;jetty&#8221; user. So when the normal &#8220;restart&#8221; command came along and tried to run the program as &#8220;jetty&#8221; then there were files it couldn&#8217;t write to.</p>
<p>Solution:</p>
<pre>
$ sudo chown jetty /var/log/jetty6/2009_07_12.stderrout.log
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/starting-jetty-failed/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>My favourite Hibernate error</title>
		<link>http://www.databasesandlife.com/my-favourite-hibernate-error/</link>
		<comments>http://www.databasesandlife.com/my-favourite-hibernate-error/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 13:35:41 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Broken]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=345</guid>
		<description><![CDATA[&#8230; is this one. I&#8217;ve wasted many an hour searching for the cause of this. And it&#8217;s one you&#8217;re likely to run into pretty quickly when you try to write your first Hibernate configuration file.
The XML
&#60;one-to-many type=&#8221;OtherClass&#8221;/&#62;
delivers the error
Error parsing XML: Attribute &#8220;type&#8221; must be declared for element type &#8220;one-to-many&#8221;.
This looks like a perfectly self-explanatory [...]]]></description>
			<content:encoded><![CDATA[<p>&#8230; is this one. I&#8217;ve wasted many an hour searching for the cause of this. And it&#8217;s one you&#8217;re likely to run into pretty quickly when you try to write your first Hibernate configuration file.</p>
<p>The XML</p>
<blockquote><p>&lt;one-to-many type=&#8221;OtherClass&#8221;/&gt;</p></blockquote>
<p>delivers the error</p>
<blockquote><p>Error parsing XML: Attribute &#8220;type&#8221; must be declared for element type &#8220;one-to-many&#8221;.</p></blockquote>
<p>This looks like a perfectly self-explanatory error, however looking at the file, the element <em>does </em>have a &#8220;type&#8221; attribute. What should one do?</p>
<p>Thinking about it, I only just introduced the &#8220;type&#8221; attribute to the &lt;one-to-many&gt; element in my config. What happens if I change the attribute name to &#8220;fsdjkfdk&#8221;?</p>
<blockquote><p>&lt;one-to-many fsdjkfdk=&#8221;OtherClass&#8221;/&gt;</p></blockquote>
<p>The error is now:</p>
<blockquote><p>Error parsing XML: Attribute &#8220;fsdjkfdk&#8221; must be declared for element type &#8220;one-to-many&#8221;.</p></blockquote>
<p>What the error means is that the attribute <strong>must not </strong>be declared, as opposed to <strong>must</strong>.</p>
<p>It&#8217;s amusing to read even people on the Hibernate team get <a href="https://forum.hibernate.org/viewtopic.php?f=1&#038;t=946756&#038;start=0">confused</a> by this error, and can&#8217;t find a solution.</p>
<p><em>(Hibernate 3.3.1 &#8211; the most current version &#8211; although I encountered this error within the first hour of ever using Hibernate in Q1/2006.)</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/my-favourite-hibernate-error/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java really delivers &#8220;write once, run anywhere&#8221;</title>
		<link>http://www.databasesandlife.com/java-really-delivers-write-once-run-anywhere/</link>
		<comments>http://www.databasesandlife.com/java-really-delivers-write-once-run-anywhere/#comments</comments>
		<pubDate>Wed, 06 May 2009 08:25:18 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=337</guid>
		<description><![CDATA[Java&#8217;s slogan was &#8220;write once, run anywhere&#8221;. They received a certain amount of criticism but I have to say that compared to other programming languages it&#8217;s really true. You can use it for:

Background jobs (without user-interface)
Server-side web applications (many web servers &#038; web frameworks available)
In the web browser (applets)
In the web browser (translation from Java to Javascript [...]]]></description>
			<content:encoded><![CDATA[<p>Java&#8217;s slogan was &#8220;write once, run anywhere&#8221;. They received a certain amount of criticism but I have to say that compared to other programming languages it&#8217;s really true. You can use it for:</p>
<ul class=tight>
<li>Background jobs (without user-interface)</li>
<li>Server-side web applications (many web servers &#038; web frameworks available)</li>
<li>In the web browser (applets)</li>
<li>In the web browser (translation from Java to Javascript by <a href="http://code.google.com/webtoolkit/">GWT</a>)</li>
<li>On the desktop (using platform-independent Swing, or with native Apple UI using Cocoa)</li>
<li>On some mobile phones (J2ME, Google Android) &#8211; although I haven&#8217;t tested how good that really works?</li>
</ul>
<p>Writing the previous version of a certain application website in Perl, there was no easy way to give the customer a &#8220;tool&#8221; to test out new versions of the configuration file. These files would normally be installed on the server, were multiple megabytes in size, and the Perl would parse and use them. For testing, it was not ideal to have to upload potential new files to the test server, due to their size.</p>
<p>The new version is in Java and also takes a configuration file, but I have written a Swing (desktop) tool which simply allows the tester to select a new potential configuration file from their local hard disk, and the desktop tool reuses all the processing logic 1:1 that the web server in production would use.</p>
<p>That wouldn&#8217;t have been possible with the old version of the logic written in Perl. (I know there are windowing libraries for languages like Perl but they are hardly as easy to deploy &#8211; i.e. install on a Windows workstation &#8211; as a Java application &#8211; simply double-click the .jar file once Java is installed)</p>
<p>I am writing the web front-end for the new version in GWT so I can reuse certain (mainly user validation) code between the web browser (giving the user instant feedback in case of errors) and the web server (necessary for security in case someone bypasses the client and sends HTTP requests directly.) And simply pass Java objects between the web server and the web client, without having to worry about how that transfer works (JSON, XML, etc.)</p>
<p>Other mainstream candidates for languages which run on multiple places:</p>
<ul>
<li>Objective-C is not too bad, running on Apple desktops, Apple iPhones, and on the web server via <a href="http://developer.apple.com/tools/webobjects/">WebObjects</a> (does the current version of WO still use Objective-C or is it Java-only these days?) &#8211; but not in the browser</li>
<li>Javascript runs on the web browser and server, and no doubt mobile browsers (but not desktops as far as I know)</li>
<li>Perhaps C#? Certainly good desktop, web server integration, no doubt IE/Windows integration via ActiveX</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/java-really-delivers-write-once-run-anywhere/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jetty &#8220;null127.0.0.1&#8243; error</title>
		<link>http://www.databasesandlife.com/jetty-null127001-error/</link>
		<comments>http://www.databasesandlife.com/jetty-null127001-error/#comments</comments>
		<pubDate>Thu, 20 Nov 2008 11:31:12 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=316</guid>
		<description><![CDATA[I have just spent an hour debugging the following problem. Suddenly my Jetty Java web server didn&#8217;t work any more. Starting it claimed:

Starting Jetty: OK

Yet connecting to the port (telnet localhost 8080) showed that the port was not open. Looking in the logfile (/var/log/jetty6) showed the following error:

2008-11-20 12:08:47.477::WARN:
  failed SelectChannelConnector@null127.0.0.1:8080
...
Caused by: java.nio.channels.UnresolvedAddressException

That meant [...]]]></description>
			<content:encoded><![CDATA[<p>I have just spent an hour debugging the following problem. Suddenly my Jetty Java web server didn&#8217;t work any more. Starting it claimed:</p>
<pre>
Starting Jetty: OK
</pre>
<p>Yet connecting to the port (telnet localhost 8080) showed that the port was not open. Looking in the logfile (/var/log/jetty6) showed the following error:</p>
<pre>
2008-11-20 12:08:47.477::WARN:
  failed SelectChannelConnector@null127.0.0.1:8080
...
Caused by: java.nio.channels.UnresolvedAddressException
</pre>
<p>That meant that the web server was unable to open the socket on port 8080.</p>
<p>Googling for this error showed only 1 result which lead to a 404. Javadocs and Jetty docs did not mention any problem like that.</p>
<p>Thankfully I had a working system to compare it with. The working system wrote in its logfile:</p>
<pre>
2008-11-03 13:34:41.283::INFO:
  Started SelectChannelConnector@0.0.0.0:8080
</pre>
<p>Notice the difference between <strong>0.0.0.0</strong> (works) and <strong>null127.0.0.1</strong> (doesn&#8217;t work). It turned out that on the good system, the config file /etc/jetty6/jetty.xml had the line</p>
<pre>
&lt;Set name="host"&gt;&lt;SystemProperty name="jetty.host" /&gt;&lt;/Set&gt;
</pre>
<p>and the non-working system had:</p>
<pre>
&lt;Set name="host"&gt;&lt;SystemProperty name="jetty.host" /&gt;127.0.0.1&lt;/Set&gt;
</pre>
<p>I have absolutely no idea how this non-working line came into the config. I didn&#8217;t change it, and the operations department surely didn&#8217;t change it either. I have absolutely no idea.</p>
<p>Why is Java so difficult !?</p>
<p><em>Jetty 6.1.11, Debian Etch, Linux 2.6.24, Sun Java 1.5</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/jetty-null127001-error/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automatic reconnect from Hibernate to MySQL</title>
		<link>http://www.databasesandlife.com/automatic-reconnect-from-hibernate-to-mysql/</link>
		<comments>http://www.databasesandlife.com/automatic-reconnect-from-hibernate-to-mysql/#comments</comments>
		<pubDate>Fri, 24 Oct 2008 11:44:34 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Broken]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=315</guid>
		<description><![CDATA[Yesterday I spent the entire day getting the following amazing state-of-the-art not-ever-done-before feature to work:

Executing a SQL statement from my program

Because, as everyone knows, I don&#8217;t suffer from NIHS, I used standard object-relational mapping software Hibernate, with a standard programming language Java, using the standard web-application server Tomcat, and now I am using the standard &#8220;connection pooling&#8221; software C3P0 (which [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I spent the entire day getting the following amazing state-of-the-art not-ever-done-before feature to work:</p>
<ul>
<li>Executing a SQL statement from my program</li>
</ul>
<p>Because, as everyone knows, I don&#8217;t suffer from <a href="http://www.databasesandlife.com/not-invented-here-syndrome/">NIHS</a>, I used standard object-relational mapping software <a href="http://www.hibernate.org/">Hibernate</a>, with a standard programming language Java, using the standard web-application server Tomcat, and now I am using the standard &#8220;connection pooling&#8221; software <a href="http://www.mchange.com/projects/c3p0/index.html">C3P0</a> (which I didn&#8217;t know I needed to execute a SQL statement, see below..)</p>
<p>The program is, in fact, already completed, and is nearly deployed. On the test server it works fine and even on the (future) live server it worked fine. But the customer noticed that if one installed it one day, the next day it didn&#8217;t work. I&#8217;ve had such symptoms many times before, so I know immediately what was going on:</p>
<ul class=tight>
<li>MySQL drops a connection after 8 hours (configurable)</li>
<li>The software is used during the day, but isn&#8217;t used during the night, therefore the connection times out in the night</li>
<li>Therefore in the morning, the program one installed the day before no longer works</li>
</ul>
<p>Perhaps I exaggerated the simplicity above of what I was really trying to achieve. It should really be expressed as the following:</p>
<ul>
<li>Executing a SQL statement from my program, even if a long time has passed since the last one was executed</li>
</ul>
<p>But that amounts to the same thing in my opinion! It isn&#8217;t rocket science! (But in fact is, see below..)</p>
<p>A obvious non-solution is to increase the &#8220;connection drop after&#8221; time on the MySQL server from 8 hours to e.g. &#8220;2 weeks&#8221; (&#8220;wait_timeout&#8221; in &#8220;mysql.cnf&#8221;). But software has got to be capable of reconnecting after a connection drops. The database server may need to be reset, it may crash, it may suffer hardware failure, etc. If, every time one restarts one particular service, one has to restart a thousand dependent services (maybe some Java, some Perl, some PHP, some robots, ..) and then maybe restart services which are dependent on them &#8211; that&#8217;s a maintenance nightmare. So the software has to be altered to be able to handle connection drops automatically, by reconnecting. Once the software has been so altered, one no longer needs to alter the &#8220;wait_timeout&#8221; on the server.</p>
<p>The error was:</p>
<blockquote><p>
org.hibernate.util.JDBCExceptionReporter: The last packet successfully received from the server was 56697 seconds ago. The last packet sent successfully to the server was 56697 seconds ago, which  is longer than the server configured value of &#8216;wait_timeout&#8217;. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property &#8216;autoReconnect=true&#8217; to avoid this problem.
</p></blockquote>
<p>Quite a helpful error message, don&#8217;t you think? But</p>
<ul class=tight>
<li>I&#8217;m not going to increase &#8220;wait_timeout&#8221; as discussed above,</li>
<li>&#8220;testing validity&#8221; in the application &#8211; well I was using standard software Hibernate which should take care of this sort of thing automatically, but evidently wasn&#8217;t</li>
<li>and we were already using ?autoReconnect=true in the JDBC URL (this evidently wasn&#8217;t working).</li>
</ul>
<p>I figured I really needed to get to the bottom of this. Googling just showed (many) people with the same problem, but no solutions. The only way to get to the bottom of software is to read the source. (It has been the way to resolve issues of simple things simply not working in MySQL <a href="http://www.databasesandlife.com/reading-row-by-row-into-java-from-mysql/">before</a>.)</p>
<p>I stopped looking in the MySQL source for why &#8220;autoReconnect=true&#8221; didn&#8217;t work when I saw the following text in the source describing the autoReconnect parameter:</p>
<blockquote><p>The use of this feature is not recommended, because it has side effects related to session state and data consistency
</p></blockquote>
<p>I have no idea what particular side-effects are meant here? I guess that&#8217;s left as an exercise for the reader, to test their imagination.</p>
<p>And anyway, I figure that a reconnect-facility belongs in the &#8220;application&#8221; (Hibernate in my case) as opposed to in database-vendor specific code. I mean the exactly the same logic would be necessary if one were connecting to PostgreSQL or Oracle, so it doesn&#8217;t make sense to build it in to the database driver.</p>
<p>So then I looked in the Hibernate code. To cut a long story short, the basic connection mechanism of Hibernate (as specified in all the introductory books and websites, which is probably how most people learn Hibernate) doesn&#8217;t support reconnecting, one has to use H3C0 connection pool (which itself <a href="http://forum.hibernate.org/viewtopic.php?t=934779">didn&#8217;t always support reconnecting</a>)</p>
<p>(I don&#8217;t want to use container/Tomcat-managed connections, as I have some command-line robots which do some work, and I don&#8217;t want to use different code for the robots as the web application. Although another company defined Servlets which did &#8220;robot work&#8221;, and the robot was just a &#8220;wget&#8221; entered into Tomcat &#8211; to get the user of container-managed connections &#8211; but this seems a too-complex solution to my taste..</p>
<p>But once one&#8217;s used H3C0, the default behavior seems to be that to process a request, if the connection is dead then the user sees and error &#8211; but at least it reconnects for the next request. I suppose one error is better than infinite errors, but still not as good as zero errors. It turns out one needs the option <a href="http://www.mchange.com/projects/c3p0/index.html#testConnectionOnCheckout">testConnectionOnCheckout</a> - which the documentation doesn&#8217;t recommend because testing the connection before a request might lead to lower performance. Surely the software firstly has to work, only secondly does it have to work fast.</p>
<p>So, to summarize, to get a connection to &#8220;work&#8221; (which I define as including handling dropped connections by reconnecting without error): In &#8220;hibernate.cfg.xml&#8221;:</p>
<pre>
&lt;!-- hibernate.cfg.xml --&gt;
&lt;property name="c3p0.min_size"&gt;5&lt;/property&gt;
&lt;property name="c3p0.max_size"&gt;20&lt;/property&gt;
&lt;property name="c3p0.timeout"&gt;1800&lt;/property&gt;
&lt;property name="c3p0.max_statements"&gt;50&lt;/property&gt;
&lt;property name="connection.provider_class"&gt;
   org.hibernate.connection.C3P0ConnectionProvider&lt;/property&gt;
&lt;!-- no "connection.pool_size" entry! --&gt;
</pre>
<p>Then create a file &#8220;c3p0.properties&#8221; which must be in the root of the classpath (i.e. no way to override it for particular parts of the application):</p>
<pre>
# c3p0.properties
c3p0.testConnectionOnCheckout=true
</pre>
<p>Amazing, that that stuff doesn&#8217;t just work out of the box. Programming the solution myself in Uboot took, I think, 1 line, and I&#8217;m sure it&#8217;s not more in <a href="http://max.xaok.org/webtek">WebTek</a> either.</p>
<p>That was an amazing amount of effort and research to get the simplest thing to work. Now if only this project had been paid by the hour&#8230;..</p>
<p><strong>[Update 28 May 2009] </strong>More Java hate today. Starting a new application, deployed it, and it didn&#8217;t work. In the morning, the application was down. Reason: The new project used Hibernate 3.3, and upgrade from 3.2 to 3.3 requires the &#8220;connection.provider_class&#8221; property to be set. Previously the presence of &#8220;c3p0.max_size&#8221; was enough.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/automatic-reconnect-from-hibernate-to-mysql/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
	</channel>
</rss>
