Τετάρτη 16 Ιουλίου 2008

Collections.copy

Well, it looks like this method contains a "bug"?!?!?

Simply do this test:

public void testCollectionsCopy () {
ArrayList list1 = new ArrayList(3);
list1.add("one");
list1.add("two");
list1.add("three");
ArrayList list2 = new ArrayList(3);
Collections.copy(list2, list1); // throws IndexOutOfBoundsException!!!!!
}
Well, the solution? Pass the collection to be copied as a parameter to the constructor.
ArrayList list1 = new ArrayList(list1);


Σάββατο 28 Ιουνίου 2008

JavaOne Afterglow 2008

On Friday, 27th of June 2008, I attended the JavaOne Afterglow 2008 in De Montil, Affligem, a few km outside Brussels. It was a well organised day event, that gave us useful information about the things to come, a summary of what was presented in JavaOne conference. Here is the agenda:

Agenda:
09:15 - 09:45 Registration
09:45 - 10:45 "JavaOne Afterglow keynote"
David Delabassée - Sun Microsystems Belgium
10:45 - 11:30 "Modularity in Java : OSGi and/or JSR 277 ?"
Stijn Van Den Enden - ACA IT-Solutions
11:30 - 12:30 "Project Fuji, an Integration Profile"
Andreas Egloff - Sun Microsystems Inc.
12:30 - 13:30 Lunch
13:30 - 14:30 "Java EE 6"
Alexis Moussine - Pouchkine - Sun Microsystems Inc.
14:30 - 15:30 "Boldly Go Where the Java Programming Language Has Never Gone Before"
Geert Bevin - Terracotta
15:30 - 15:45 Coffee break
15:45 - 16:15 "JavaFX overview"
Jo Voordeckers - RealDolmen
16:15 - 17:00 "Parleys.com: A Flex/AIR, JavaFX and GWT Case Study"
Stephan Janssen - RealDolmen
17:00 - 17:15 Wrap-up and prize raffle


The conference started with David Delabasée, the Java ambassador in Belgium-Luxembourgh, who gave an overview of the new things we are to expect regarding Java 7 as well as other Java technologies such as Java Card. A Java Card is a smart card that contains an application server in it! Hence, you can upload a servlet to itconnect it to various devices and call it from various programs and devices as David demonstrated. David also shown a roadmap of Java through expected version 7, mentioning OpenJDK/IcedTea project, the new Nimbus look & feel in JDK 6 update 10 (consumer JRE). The "Java Virutal Machine" becomes simply "Virtual Machine", as it now hosts not only Java but a large number of other languages such as Ruby, Groovy, Grails, Pascal etc. Characteristics of the new JDK 7 are:
  • hosting of many languages, as already mentioned
  • Profiles
  • JMX 2.0
  • Visual JVM (a nice tool that will graphically displays the internal of the VM); and
  • closures
Next, Stijn Van Den Enden, spoke about modularity and compared the current two frameworks, OSGi and JSR 277. As you already know, currently modularity in Java is addressed by packages and interfaces and there is no versioning or access control. If a class in one package needs to access a class in another package, the only way is to declare the class in the other package public, hoping that no one will find out that an internal class is exposed as public.
OSGi solves these problems with bundles. A bundle is a package with some useful metadata about the package in MANIFEST.MF. It separates private from public resources; determines package resolution; and allows versioning.
JSR 277, or Java Module System, is a new specification that addresses the same problem. The equivalent to OSGi bundle is called Java Module and it is packaged as a special kind of JAR, called JAM (JAva Module). Metadata is not in the manifest file, but as annotations.

Andreas Engloff gave a presentation about project Fuji, an integration profile project or standard plugin model for modules. It has three layers, Modularity, Service Orientation and application interface. It is based on OSGi, Open ESB and provides for Enterprise Integration. Andreas presented a demo of the simple workflow language one can use to easily get RSS feeds, filter them by JRuby and feed them to an XMPP (instant messaging) application. He wrote less than 10 lines of simple commands to accomplish this!

The session continued after the lunch break with Geert Bevin from Terracotta who presented 4 hot Java technologies:
  • Terracotta, an open source clustering framework which allows you to run your code to multiple JVMs seamlessly
  • RIFE, a full-stack component framework for web applications, which with the principle of continuation, allows you to stop, save and reload a web app state like one does with computer games
  • Google Web Toolkit; and
  • Google Android
Alexis Moussine-Pouchkine gave a presentation about upcoming Glassfish v.3 application server as well as about the new features of Java EE 6:
  • Extensibility
  • Profiles
  • Pruning; and
  • ease of development
After the coffee break, Jo Voordeckers gave a short presentation about JavaFX, or the return of the applet. JavaFX is the new scripting language provided by SUN, that hopes to boost and simplify both desktop and web development. The new "Java 6 update N" is less than 3 Mb, compared to ~12 Mb of current JRE 6, which can be quickly downloaded by clients' machines. However, JavaFX has a number of competitors, like Adobe Flex, MS Silverlight but also JRuby and others.

The conference ended with Stephan Janssens' presentation of parleys.com, and a comparison of 3 hot competitors in the RIA arena, namely, Adobe Flex, JavaFX and GWT.
Adobe provides AIR for desktop and Flex for Web applications; JavaFX is for both the desktop and the web; while GWT is only for developing Web applications. A thing to note is that Flex is only compatible with Flash version 9 or later, so he is developing a version of parleys.com with GWT which is compatible with Flash version 8 for clients that run this version of Flash.

The conference finished with some draws, and the winners won books and a playstation 3.

A well organised conference as I said, but in the middle of nowhere, with no public transport available, and difficult to go there if you don't have a car! :-)

Τρίτη 24 Ιουνίου 2008

Hashtable vs. HashMap

HashMaps accept null values, while Hashtables don't.

import java.util.HashMap;
import java.util.Hashtable;

import junit.framework.TestCase;

public class HashMapTest extends TestCase {
private HashMap map = new HashMap();
private Hashtable hashtable = new Hashtable();

public void testHashMap() {
map.put("name", null);
assertNotNull(map);
assertEquals(1,map.size());
}

public void testHashtable() {
hashtable.put("name", null);
assertNotNull(hashtable);
assertEquals(1,hashtable.size());
}
}

The 2nd test simply throws a NullPointerException.

Hashtable is historical, according to JavaPractices.

Παρασκευή 1 Φεβρουαρίου 2008

How to debug your web application in JBoss with Eclipse

For many developers, debugging a web application simply means looking at the logs and trying to figure out what went wrong. Fortunately, there is an easier way. You can debug a web/JEE application the same way you debug a JSE or JME application.
With today's IDEs you can also debug web/jee applications step by step, while the application is deployed to an application server like JBoss. The following trick works with JBoss application server, please contribute for other application servers.
OK, here is the trick. Open %JBOSS_HOME%/bin/run.bat (Windows) or $JBOSS_HOME/bin/run.sh (Linux) and uncomment the line that contains the port 8787, i.e. this line (by simply deleting the rem word in front):

rem set JAVA_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y %JAVA_OPTS%

If you cannot find the line in run.sh, try $JBOSS_HOME/bin/run.conf.

In your eclipse environment, click on the arrow next to the Debug button and select Debug... Select Remote Java Application and press the New button to create a new configuration of this type.
In the Connect tab, browse your web / jee eclipse project, leave the connection type to Standard (Socket Attach) and enter the host name (localhost if it is local) but modify the port to 8787 (this is JBoss' debugging port). In the Source tab you may wish to add any dependent projects. Click on Apply. That's it.

Now all you need to do is start your JBoss application server, deploy before or after your war or ear file. The application server stops waiting for someone to listen to port 8787. Click on Debug or select the above configuration in the Debug window, and voila, JBoss continues starting up.

Set your breakpoints etc. enjoy!

P.S. Netbeans has very good debugging integration with most of the application servers. If your application server is not listed in its list of available application servers, simply define it under Tools --> Server.

References
  1. Monitoring a remote JBoss Server from Eclipse

Δευτέρα 17 Δεκεμβρίου 2007

Javapolis 2007

This was my first time in a Javapolis event. Javapolis, like JavaOne, is a fiest of Java. It is not only the new knowledge that one acquires from the various presentations, which are going to be available from parleys.com anyway, but also the exhibition, exchanging ideas with other Java developers, meeting famous authors etc.

This event was even more special because the legend, James Gosling himself, was there! 3000+ participants watched his speech live! Javapolis takes place in Antwerp, Belgium, every year since 2004. It is equal, or even better as some say, from JavaOne, in the US. I really had very good time all these five days, from 10th to 14th of December.

Here is my point of view of the event, the program of which you can find here. Unfortunately, there had been 5 parallel sessions so if you wished to attend more than one of them at the same time, then you had a problem.

Day 1 (University day)

I chose to start my day with Maurice Naftalin's “Java Generics and Collections” speech. Maurice is the author with an excellent book with the same title. He presented a deep understanding on Generics issues, what to do and what to avoid, e.g. problems like casts and instanceof, parametric exceptions and problems with arrays. “Never ignore unchecked warnings” he said. Generics may have not had the great acceptance in the Java community yet, but I believe it is one of the positive additions of the language, and if you learn how to use them correctly, you can get great benefits from them.

After the break, I didn't watch the 2nd part on Collections, as I also wanted to watch Sang Shin's “Introduction to Ajax”. Another excellent speaker, Sang maintains the Javapassion web site where he gives lessons in Java for free! If you check his site you 'll see a lot of information in almost every aspect of the language, and all this for free! Sang gave an overview of the main Ajax toolkits like Dojo, GWT, jMaki, JSF 2.0 with Ajax support etc. Amazing to watch this guy on stage.

After the lunch break, I attended “Seam in Action”. Seam is an extention to JSF, and as the speakers said, Seam is the new Struts. E.g. apart from Event, Session and Application, Seam also introduces the notions of Page, Conversation and Business Process. It seems to be a good extension and improvement upon JSF.

In the afternoon, I attended "BPM in action" using SoftwareAG's webMethods software, another tool for Business Process Modelling development. Unfortunately, the demo didn't work and so wasn't demonstrated by the good though speaker, Hilde Janssen.

Finally, I attended JetBrains' "Teamcity" tool. It seems to be an excellent tool for teamworking. Mike Aizatsky, an excellent speaker, demonstrated, using simple and to the point slides, the benefits of using the tool, which is now in version 3 and you can download it for free. E.g. one use of the tool is before the Version Control system, where it checks whether your code compiles before submitting it to version control. This way, you can be sure that only compiled versions are submitted to version control.

Day 2 (University day)

In day 2, the exhibition kiosks were set in place. The conference sponsors, like SUN, Adobe, Jboss, Intellij, Oracle, IBM and others, provided information about their products, and gave gifts to the participants. The participants could also participate in many video games and competitions. For example, the faster driver of a BMW emulator, brought by Cegeka, gained a PSP each day. JavaBlackBelt also had daily competitions; you had to answer 5 tricky multiple choice questions in a limited time. Those who had the best score and finished earlier participated in the finals for a PSP 3. And of course, Adobe, gave away O' Reilly books on Flex 2 and ActionScript. And there were many more gifts from other sponsors. This is the best part of Javapolis I think!

I began my second day with Bruce Eckel's presentation “Thinking in Flex”. Bruce moved to Adobe for those who didn't know. It was great to watch the author of one of the best Java books “Thinking in Java” live on the stage. Along with the help of Christophe Rooms, they presented Adobe Flex. It was a very good presentation and Flex 2 is a very impressive tool that now works with Java as the back end. I wish Java had the same impressive GUI components as Adobe Flex does. I avoided developing in Flash all these years because, however impressive the result of a Flash application is, the code is difficult to maintain. But with Flex and ActionScript you can create impressive Flash applications with a powerful scripting language that is easy to maintain. Even though a proprietary product, I 'll definitely give it a try. The new version of parleys.com is going to be built with this tool!

“JavaFX in Action” by Jim Weaver was my next attendance. I don't know if you have noticed, but there is a plethora or scripting languages nowadays and many more are developed. See e.g. Perl, PHP, Ruby, JavaScript, ActionScript, Wicket just to name a few. And many developers prefer to develop faster using a scripting languages. For many, scripting languages are the future of programming. Java's answer is JavaFX, a scripting language based in Java that allows you to develop quickly from swing applications for desktops, to mobile, or even web applications. SUN seems to have put a lot of effort in this new language, so I 'll give it a try and I suggest you do too.

In the afternoon I watched “Developing software like a band plays Jazz” presented by another legend, Erich Gamma, one of Gang of Four guys. Now employed by IBM, he presented Jazz, a collaboration product for enterprises. Erich addressed one of the main problems in companies today, lack of collaboration, which this tool addresses. Even though I didn't like the presentation, this tool seems to be of great help to software teams. And, it is an IBM product.

Day 3 (Conference day)

The day started with the speech of the father of Java, James Gosling, after a welcome by the event's responsible, Stephan Janssen, president of BeJUG, and an uncoference kick-off by Bruce Eckel. Three conference rooms where full just to watch the legend. The father of Java shared impressive statistics with the audience: 5 million Java enabled devices worldwide, 6 million Java developers, 12 million JRE downloads per week, 4 million Netbeans and 2.5 million Glassfish downloads. “If you are still using Emacs, then go shoot yourself”, said James, announcing Netbeans version 6.0. This new version has support for not only Java but also for Ruby, C++, Javascript and PHP. And as I say to my friends who use Visual Studio, just go and download Netbeans to see how Visual Studio 2012 is going to be like! James, also showed some impressive statistics regarding the speed of Java 6.0 which is now equal in speed or even outperforms C++! Far behind is C#, which is still very slow in all benchmarks. Finally, the father of Java asked the community to download and try JavaFX, where SUN puts a lot of effort in. We watched a couple of applications on Java, such as a very impressive demo of navigating two robots!

After this impressive beginning, the rest of the day continued with a presentation of “SoapUI”, a very good commercial product to test SOA applications, something that was actually missing from SOA apps.

“Google Web Toolkit” gave a nice overview of GWT also through the presentation of OpenSocial, an application developed by GWT.

The afternoon sessions were far more interesting. Instead of “Scrum in practice for non-believers”, Sander Hoogendoom gave a presentation on Anti-management practices or how to make your project fail! An excellent presentation that shows the reality in most software projects, and what to avoid to make your project succeed, or rather fail, in the speaker's words. He successfully presented common syndromes encountered today in project managers, architects, developers etc. The presentaiton is live on parleys.

The last presentation of the day was actually a Q&A with James Gosling, Joshua Bloch, Neal Gafter and Martin Odersky were the speakers answered questions posed by the audience. Not very successful in my opinion though.

Day 4 (Conference day)

The 2nd conference day also started dynamically with a presentation of Adobe Flex by Bruce Eckel, followed by a speech of the Javapolis' creator, Stephan Janssen, who presented parleys.com version 2, built on Adobe Flex, and a keynote on JavaFX by Tim Cramer. We had the chance to see the possibilities of Netbeans 6 in developing mobile applications. Did you know that JME now comes with a games engine for mobile game applications?

After the break, I watched JPA 2.0 by Linda Demichiel, the chief architect of JPA at SUN Microsystems. With 20 years experience in IT, she gave an overview of JPA's new features and future work on it.

After the lunch break, the day was devoted to Joshua Bloch, an excellent speaker and author! The author of the most popular Java book “Effective Java”, changed his initial presentation and gave a presentation on Closures, a feature to be added to Java 7. Closures will allow to pass whole piece of code from one method to another. The speaker presented his skeptisism about this new feature and said that the language has already become too complicated to add yet another such complicated feature. And I wouldn't agree more with him. How many developers actually use most of Java 5's new features? Many still have problems to even understand Generics. Personally, I don't find Closures to be a useful addition to the language. We developers need the language to help us in solving our business or scientific problems in a simple and easy way, and I cannot see how Closures can help us in that. I don't see why to add a feature that will be used rarely or not at all by most of us. I would prefer to see improvements in the existing language syntax, like simplification or best practices of use of the features of the language, properties, even better performance etc.

Emmanuel Bernard gave next a presentation on “Hibernate search” or how to use Hibernate with Lucene to do efficient and effective full text searching.

Mark Janssen, author of “SOA using Java Web Services” book, gave a technical overview of how to develop web services with Java.

The day had the best ending ever with “The Java puzzlers” show by Joshua Bloch and Neal Gafter. Dressed with uniforms from Star Wars, they started their show by “fencing” with their “light pointers”! Each one of them posed alternatively 4 Java puzzlers to the other, and the audience had to answer which one of the 4 multiple answers was correct. These were new puzzlers to be added to “Java Puzzlers” version 2 book. If you haven't got this excellent book yet, what are you waiting for? Many participants bought it with 20% discount from the kiosk in the exhibition hall after this presentation!

This was the best day of the conference, ended with many more gifts, and competitions by the sponsor companies, as this was the last day of the exhibition. The day finshed by watching the movie “BeoWulf”.

Day 5 (Conference day)

The last day of the conference lasted only half a day and was not as good as the previous ones. “Wicket2”, presented by Martjin Dashorst, seems to be another very cool framework for building web applications using simply Wicket scripting language inside HTML for the presentation layer and Java for the business logic. No complicated things like JEE and EJB. Very promising framework which I 'll give it a try.

The rest presentations of the day were not that interesting. I started with OSGi, but I found the presentation rather boring and then left to watch “Innovating with Java” which I didn't find interesting either.

“Testing Driven Development” by the author Lasse Koskela of the book with the same name as the presentation, didn't say many new things to what I already know.

Thus, the conference finished.

A few final comments. The food was awful. An event, or something could also have been organised the last day of the conference to give us a better feeling of the last day and keep up our interest. Free drinks, like coke, sprite, water, even beer, were offered all five days. The exhibition was great!

You can watch all presentations from parleys.com when they become available. But of course, the value is to attend the conference, to live the excitement of these five days, to meet new people with same interests, to participate in the competitions and games, to get all these gifts, T-shirts, Cds, coffee cups, pens, bags etc. This is the spirit of Javapolis. See you there next year.

Πέμπτη 11 Οκτωβρίου 2007

Greek and Java

Under this subject I publish any issues that a Java programmer may encounter with Greek letters while writing Java programs. This information might be useful to programmers of other native languages too.

Issue 1: Apache Tomcat doesn't display Greek

Instead ???? are displayed.

Solution
You have to perform the following steps:
  1. Edit conf/server.xml like so:

    connector port="8080" maxhttpheader="8192" maxthreads="150" minsparethreads="25" maxsparethreads="75" enablelookups="false" redirectport="8443" acceptcount="100" connectiontimeout="20000" disableuploadtimeout="true" URIEncoding="ISO-8859-7" or URIEncoding="UTF-8" depending on your application.

  2. If you are using a servlet, then you have to add the following lines of code to your doGet() method:

    request.setCharacterEncoding("ISO-8859-7"); // or UTF-8
    response.setCharacterEncoding("ISO-8859-7"); // or UTF-8


  3. If you are using a JSP, then you must include the following header on the beginning of the jsp page:

    <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> // or ISO-8859-7
  4. You may need to add this line too
    // or ISO-8859-7
  5. In case the encoding of the GET command is different than the one in URIEncoding (e.g. ISO-8859-7 and URIEncoding="UTF-8"), then use the command request.getQueryString() to get the original query string, before this is changed by Tomcat's URIEncoding, manually parse the string to a variable, e.g. myVar, and then use e.g. URLDecoder.decode(myvar, "ISO-8859-7").

Note: This info applies to JBoss too, as it is based on Tomcat.

References:
  1. JHUG forum link
  2. Apache Tomcat wiki
  3. The absolute minimum about Unicode and Character Sets

Issue 2: Greek support in Eclipse IDE

Right click an eclipse project and select Properties. In the info property, under Text file encoding box, select one of the following encodings:
  • ISO-8859-7
  • Cp1253
  • UTF-8
Issue 3: Greek support in Netbeans IDE

Right click on a project and select Properties. In the Encoding property, select one of the following encodings:
  • ISO-8859-7
  • Windows-1253
  • UTF-8
Issue 4: Greek support in MySQL

Use one of the following collations: utf8_unicode_ci or utf8_general_ci. Charset should be UTF-8.
If you are using phpmyadmin, you can do this while creating the database. If you have already created the database, you can change its collation by clicking on Operations tab.
If you can still not see Greek, edit my.conf and under [mysqld] tag add the string
character-set-server = utf8.

To use together with Tomcat:

url="jdbc:mysql://localhost/timesheet?useUnicode=true;characterEncoding=utf8" // or ISO-8859-7

Issue 5: Define encoding

Whenever you open/save a text file, specify the character encoding and don't rely on the OS default encoding:

Reader r = new InputStreamReader(new FileInputStream(file), "UTF-8"); // ISO-8859-7
Reader r = new InputStreamWriter(new FileInputStream(file), Charset.forName("ISO-8859-7"));
Writer w = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-7"); // UTF-8
Writer w = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8"));
String s = new String(byteArray, "UTF-8");
byte[] a = string.getBytes("UTF-8"); // Cp1253

Issue 6: Greek locale
private static final Locale GREEK_LOCALE = new Locale("el", "GR");

Issue 7: Greek and JEditorPane
Unfortunately, JEditorPane supports HTML 3.2 (to some arguable extend), while named Greek entities were added in HTML 4.0. This means, that

jEditorPane.setContentType("text/html");
jEditorPane.setText("αβγδ");
System.out.println(jEditorPane.getText());

will not return the Greek characters but something like

#965;#966;#967;#968

You can try

jEditorPane.setContentType("text/html;charset=utf-8");
jEditorPane.setText(new String("αβγδ".getBytes("utf-8"),"utf-8");

but it still doesn't work.

A solution is simply to use

jEditorPane.setContentType("text/plain");

In any case, it is better to handle the text from the variable it is stored than getting it from jEditorPane.getText().

References:
  1. Java Anti-Patterns


Τετάρτη 26 Σεπτεμβρίου 2007

Simple suggestions for 'team' programming

Most programmers think that they are unique, that the way they program is the best, and they program only for themselves. This selfish attitude, however, does more bad than good. Working as a team has more advantages, less individual work, better cooperation to achieve deadlines, just to name a few, so why don't we (developers) learn how to cooperate?
Here I put four suggestions, which are so obvious to me, but I don't know why most programmers don't wish to follow:
  1. Use and apply design patterns; they help better communication between the team as the provide for a common language; not to mention all the other advantages they provide, like extensible code, program to an interface etc.;
  2. Don't hesitate to write javadoc and comments; they save another developer that looks at your methods and classes much time to know what it does than having to go through the code to realise what an uncommented method does;
  3. Write test cases; they are mainly for documentation; they show another developer what is the input to a method and what to expect as an output than having to guess each time, especially when there is no javadoc;
  4. Use this *bloody* CVS/SVN of yours correctly; add a comment each time you do a modification letting others know what you did and why. E.g. another guy just erased (or moved to another eclipse project) some classes in the team I work, and he never writes anything in CVS, letting me in nowhere of knowing why he did that and he 's too busy to ask.
If you have never heard of design patterns, then here are some references you may find useful:
Write javadoc comments even to package or private methods explaining the algorithm that you use, any reference to a web site or book, and of course reference back to the use case or requirement that forced you to write this method. In eclipse it is also very easy to produce the html API by clicking on the project in package explorer and then to menu Project --> Generate Javadoc.

Creating junit test cases is also very easy with eclipse, just right click on the class you wish to test and choose New --> JUnit Test Case. Eclipse will ask you of the methods that you wish to test and will create the skeleton for you.

Next time you write a piece of code, think that you don't write it for yourself, but also for others who might review it or continue from where you left or need to modify it. Stop thinking selfishly; it doesn't help.

Heinz Kabutz also gave an interview on becoming a Better Programmer in SUN's website.