Total Pageviews

Sunday, December 30, 2012

Friday, December 28, 2012

Pure-FTP Daemon unter Ubuntu Linux installieren und konfigurieren

Und noch eine Perle der Installationsdokumentationen zum Aufsetzen eines FTP Servers (hier Pure FTP unter Ubuntu/Debian). Unter diesem Link findet sich eine schnelle und wie ich finde gut geschriebene, verständliche Anleitung zum Aufsetzen eines FTP Servers.

Mailserver für einen Homeserver unter Linux einrichten

Wer schon immer mal einen Mailserver auf seinem eigenen Server zu Hause betreiben möchte (Stichwort DynDNS), der sollte sich mal diese wirklich gute Anleitung durchlesen.
Die dort beschriebenen Komponenten

  • Postfix
  • Dovecot
  • Fetchmail
  • Sieve

harmonieren sehr gut zusammen.
Generell ist das komplette Wiki dort sehr gut aufgebaut und enthält einige sehr nützliche und tolle Anleitungen.

Wednesday, December 26, 2012

Networking modes in VirtualBox explained

VirtualBox offers different networking modes. Sometimes it's a little bit confusing to understand what each mode is doing exactly and which mode you should choose.
So this posting is a very quick and good overview of the various networking modes.
For those who wants the virtualized guest OS operating as a full member in a network the Bridged Networking mode is the way to go.
With this mode each network member can see and access the guest OS.

Saturday, December 22, 2012

Remove all unused Ubuntu Kernel images, headers and modules

Seeing that my linux box is running low on free space I decided to remove all unused Linux kernel images on my Ubuntu 10.04 system.
For some unknown reason Ubuntu Tweak refused to install properly so I decided to go a different way and used the command from this blog article.

The command mentioned in the blog is

dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs sudo apt-get -y purge  


If you don't understand what this command does I recommend to dig into the topic. I must admit it is a little bit complex, but the command is working well.

Use it at your own risk!

Now my system is cleaned up and still boots the correct and latest kernel. All other kernel images, headers and modules are completely removed.

Thursday, December 20, 2012

Slider widget in Android allowing minimum and maximum (range) values

Can you believe it? There is no standard slider widget in Android available allowing to set a minimum and a maximum value. There is in fact the Seekbar widget that allows to set one value with a thumb.
Either you implement it yourself or you use one of the free available alternatives.

  1. Range Seekbar project on Google Code
  2. Double handled slider for Android referenced on Stackoverflow


In addition you can customize the look and feel of the slider. Take a look at these tutorials:

  1. Custom styled UI Slider
  2. Seekbar your way

Sunday, December 16, 2012

Search box gadget in my Blogger blog does not work

The Search Box Gadget in my Blogger blog does not work reliable. Some search terms show results others not, though the search terms are present in my blog.
Using the Blogger navbar searches the blog as well and produces correct search results.
It seems the Search Box Gadget has a bug.
I found a solution from 2009 that still works around this problem.
So the real question is, is it a bug or a feature? And if it's a bug, why does it take Google so long to fix it?

Thursday, December 13, 2012

SU not working for newly added "root" apps on rooted Nexus 7 and Galaxy Nexus

Recently I installed CatLog on my rooted Nexus 7 device which needed root to work properly. With astonishment I saw that CatLog did not gain root privileges. Superuser refused to do so.
Taken a look into superuser, I saw that already a few apps had root privileges and were doing fine. Just to be sure I started Titanium Backup and the app obtained root privileges without any problems.
Hm, what could be the problem with CatLog?
Seems that newly added apps can not obtain root privileges...

To be sure my device was still rooted properly (I used OTA Rootkeeper in the past when upgrading to new Android versions) I installed Got Root from the Play market and run it on my device.

One of the tests failed saying:

Failed to obtain root privileges through 'su'.

Ok, not sure why, but somehow my device lost its proper root attribute.
It may have something to do with OTA Rootkeeper but I am not sure. I used it when upgrading from 4.1.2 to 4.2 and to 4.2.1.

Anyway, I rerooted it with the Nexus 7 Toolkit. This is an incredible great piece of software and it works on devices running Android 4.2.1.

No surprise that my Galaxy Nexus phone had the same problems. I used to use OTA Rootkeeper there as well ...


Wednesday, December 12, 2012

Numbered Headings in Confluence

Ever wanted to have numbered headings in Confluence? Either on the wiki page or in PDF exports?
The Numbered Headings plugin can do this.
In its simplest form you just go with the default values and get decimal numbers prefixing the headings.


The plugin offers a variety of options and I highly recommend to read the documentation.
Really awesome is that you now have numbered headings in PDF exports, so readers or reviewers of the PDF version can refer to the numbers instead of citing the whole heading.

Tuesday, December 11, 2012

Generating a title page in Confluence PDF export

Well, in a previous posting I already mentioned the possibility to generate a great looking PDF export title page for a wiki page created in Confluence Wiki.
Unfortunately the article mentioned in the posting was written in german. So here is - in short - a manual in english to get great looking PDF exports.
The steps described here are tested and verified in Confluence 4.1.9. I expect it to work with newer Confluence versions but there is no guarantee.

Step 1: Define the user macro in Confluence that defines the dynamic content of the title page



The code in the template textfield:
 
 ## Body processing: Selected body processing option
 ## Output: Selected output option  
 ##  
 ## Developed by:   
 ## Date created:   
 ## Installed by:  
 ## @param Titel:required=true|type=string|desc=Dokumenttitel  
 ## @param Thema:required=true|type=string|desc=Unterthema des Dokuments  
 ## @param Autor:required=true|type=string|desc=Dokument Autor  
 ## @param Datum:required=true|type=string|desc=Dokument Datum  
 ## @param Version:required=true|type=string|desc=Dokument Version  
 <style type="text/css">  
 .KonzeptTitel:before { content: '$paramTitel'; }  
 .KonzeptThema:before { content: '$paramThema'; }  
 .KonzeptAutor:after { content: '$paramAutor'; }  
 .KonzeptDatum:after { content: '$paramDatum'; }  
 .KonzeptVersion:after { content: '$paramVersion'; }  
 </style>  

Step 2: Declare a custom PDF Layout for exporting the title page

You can change the PDF Layout either globally or local for each space. In this example the space version is used.
In Confluence go to

Space - Browse - Space Admin - PDF Layout

and edit the section

PDF space export title page.

Enter the following content:

 <div style="text-align:center; padding:0px; padding-top: 50px;">  
 <img src="/download/attachments/3407974/Logo.jpg" width="70%" height="70%"/>  
 </div>  
 <div style="padding:0px">  
  <div class="KonzeptTitel pdfTitelblattTitel"></div>  
  <div class="KonzeptThema pdfTitelblattThema"></div>  
  <span class="pdfTitelblattText" style="display:inline-block; width:30mm; margin-bottom:2mm; padding-left: 200px;"><b>Autor:</b></span>  
  <span class="KonzeptAutor pdfTitelblattText"></span><br/>  
  <span class="pdfTitelblattText" style="display:inline-block; width:30mm; margin-bottom:2mm; padding-left: 200px"><b>Datum:</b></span>  
  <span class="KonzeptDatum pdfTitelblattText"></span><br/>  
  <span class="pdfTitelblattText" style="display:inline-block; width:30mm; margin-bottom:2mm; padding-left: 200px"><b>Version:</b></span>  
  <span class="KonzeptVersion pdfTitelblattText"></span><br/>  
  <br/>  
 </div>  

The file Logo.jpg is an image attachment somwewhere in the space. This image appears on top of the title page in the PDF export. You can get the url of the attached image when you go to the page where the image is attached and click on Tools - Attachments and then on the image you would like to see on the title page.

Step 3: Declare a custom PDF stylesheet for the PDF layout

The above layout references CSS stylesheets you must declare.
Still in the Space Admin section click on PDF Stylesheet and Edit PDF Export Stylesheet
Enter the following code:
 
@page  
 {  
 @top-right  
   {  
    content: page:title;  
   }  
 @bottom-left  
   {  
     content: element(Datetime);  
     font-family: ConfluenceInstalledFont, Helvetica, Arial, sans-serif;  
     font-size: 8pt;  
   }  
 @bottom-right  
   {  
     content: "Page " counter(page) " of " counter(pages) ;  
     font-family: ConfluenceInstalledFont, Helvetica, Arial, sans-serif;  
     font-size: 8pt;  
   }  
 @bottom-center  
   {  
     content: "Copyright © 2012, My Company LTD";  
     font-family: ConfluenceInstalledFont, Helvetica, Arial, sans-serif;  
     font-size: 8pt;  
     color:#595959;  
   }  
 }  
 .KonzeptTitel {   
 font-size: 36px !important;  
 text-align: center;  
 padding-top: 150px !important;  
 }  
 .KonzeptThema {   
 font-size: 24px !important;  
 text-align: center;  
 padding-top: 100px !important;  
 padding-bottom: 200px !important;  
 }  
 .KonzeptAutor {   
 font-size: 16px !important;  
 text-align: left;  
 }  
 .KonzeptDatum {   
 font-size: 16px !important;  
 text-align: left;  
 }  
 .KonzeptVersion {   
 font-size: 16px !important;  
 text-align: left;  
 }  
 .pdfTitelblattText {   
 font-size: 16px !important;  
 text-align: left;  
 }  
 .noprint  
 {  
 display: none ;  
 }  
 div.pagebreak  
 {  
   page-break-before:always;  
 }  
 .pagetitle h1 { display: none; }  

This stylesheet declares the CSS definition that was already mentioned in step 1 and 2. Furthermore it adds page numbering at the bottom (right) of the page and adds a footer at the bottom (center).
Customizing PDF exports is described in detail on this official Confluence documentation.

Step 4: Use the macro in a wiki page

The last thing to do is to insert the macro in a confluence page. Choose the macro with name konzept from the macro browser and fill in the required fields.
The following screenshot shows an example:

That's it.
One important thing to mention: You will not get the title page in your export using the PDF export from the page tools. It only works when using the PDF export method of the space.
Click on Advanced - PDF Export and select the page you would like to export. The resulting export should look something like this:



Tuesday, November 27, 2012

OTA Rootkeeper still works when updating to Android 4.2.1

Note (2013-02-18):
There is a newer blog entry available which says that OTA Rootkeeper did not properly reroot the device after upgrading to Android 4.2.1.
The observations I made when I wrote this post seem to be false.

Original blog posting:
And surprise, surprise OTA Rootkeeper has helped me once again to keep root on my Nexus 7 device.
BTW, Google rolled out Android 4.2.1 today and I already received the OTA update :-)

Sunday, November 25, 2012

Remove the page title in Confluence PDF export


Confluence always adds a page title when you export a page to PDF format.
If you want to get rid off the title do the following:

Go to

 Browse -> Space Admin -> Look and Feel -> PDF Stylesheet -> PDF Export Stylesheet -> Edit  

and add the following line:

 .pagetitle h1 { display: none; }  

Now PDF exports don't show the title anymore.

Thursday, November 22, 2012

Pagebreaks in Confluence PDF Export

It is often necessary to export a wiki page to PDF so managers, customers or other people who can't (or don't want to) access the wiki can read documents.
One thing that embarrasses me the most is that you don't have control over page breaks in Confluence PDF exports. There is - at least to my knowledge - no predefined macro available.
But there is a community macro which solves the problem. Take a look at the pagebreak user macro and try it.
With this macro you are in full control over page breaks in PDF exports.

Making Screenshots with Greenshot under Windows

I don't think I have high requirements for a good screenshot tool but Greenshot is by far the best one I have ever used.
It even has plugins for Jira and Confluence. Moreover it is free to use even in commercial environment. Cool :-)

Thursday, November 15, 2012

Keeping root on Nexus 7 when updating Android from 4.1.2 to 4.2

Yesterday Google rolled out Android 4.2 for the Nexus 7 devices. I hesitated to do an instant update because I was not sure if OTA Rootkeeper was capable of rooting my device (using Android 4.1.2) again after the update.
Searching through the usually suspects boards (xda-developers, android-hilfe, etc ...) didn't yield a result. Seems that no one has tried it so far or no one has found the time to post his experiences :(
At least I found out that the Nexus 7 Root Toolkit was updated and therefore able to root a Nexus 7 device with Android 4.2 (afaik your device will be wiped after rooting - please check board posting on xda-developers).
That was the starting signal for me to do the update and try rooting again with rootkeeper. If rootkeeper does not work I still can reroot my device again using the toolkit.
Well it turns out my fear was baseless.
Rootkeeper was able to root my device again so I still have a rooted Nexus 7 using Android 4.2.
Great tool :-)

Tuesday, November 13, 2012

Multiple Virtual Desktops in Windows 7

Most Linux desktops / window managers support it out of the box: Multiple virtual desktops. I really miss this feature on Windows 7.
A great tool for managing virtual desktops under Windows is Dexpot.
It's a great alternative to VirtuaWin and free of charge for private use.

Tuesday, October 23, 2012

Samsung Galaxy Nexus OTA Update from Android 4.1.1 to 4.1.2 and keeping root

A few days ago my carrier rolled out the OTA Android Update 4.1.2.
I didn't want to lose root on my Samsung Galaxy Nexus after updating from 4.1.1 to the new 4.1.2 release and I installed OTA RootKeeper from Google Play.
The important step is to install and run RootKeeper before you do the update. Instructions on how to use RootKeeper can be found here.
This should work at least for the Samsung Galaxy Nexus running Android 4.1.2 without a custom recovery image.
After updating to the new Android version and rebooting your phone you have to start RootKeeper again to reactivate root. All you have to do is to select Restore Root and your phone is rooted again.

Tuesday, October 09, 2012

Grub error 17 and a possible solution


Give this a try if you are getting grub rescue:
  1. At grub>. enter these commands
    find /boot/grub/stage1
    
    This will return a location. If you have more than one, select the installation that you want to provide the grub files.
  2. This is important: what was returned for the find command use it in the next line for the "?" -
    root (hd?,?)
    
    Again use the value from the find command i.e. if find returned (hd0,1) then you would enter root (hd0,1)
  3. Next enter the command to install grub to the mbr
    setup (hd0)
    
  4. Finally exit the grub shell
    quit
    
Now you are done. Reboot the machine.

Another option is to run this command:
grub-install /dev/hda

If you don't have grub rescue:

  1. Try booting from a live CD
  2. In case Live CD doesn't have package "grub" install it first (eg. sudo apt-get install grub)
  3. Take a look at your partition table: sudo fdisk -l
    /dev/sda5            1276        1397      979902   82  Linux swap / Solaris
    /dev/sda6            1398        2550     9261441   83  Linux
  4. In this case grub should be installed on /dev/sda6 (in grub this is hd0,5).
    NOTE: Every device in grub starts with "hd", even if it's a SATA device.
  5. Type in the following in a shell:
  6.  sudo grub  
     grub > root (hd0,5)  
     grub > setup (hd0)  
     grub > quit  
    
  7. More infos can be found in this article.

In Virtualbox einen bootbaren USB Stick starten

Virtualbox unterstützt das Booten von Gastsystemen von einem USB Stick nicht out-of-the-box.
Mit dem hier beschriebenen Trick geht es aber doch.

Zusammengefasst:

Schritt 1:

In Windows die Datenträgerverwaltung starten und den USB Stick identifizieren:

Im Bild ist das Laufwerk I.

Laufwerk I hat die laufende Nummer 3 (Datenträger 3 im obigen Bild)

Schritt 2:

Jetzt in einer Kommandozeile in das Installationsverzeichnis von VirtualBox wechseln und folgenden Befehl eingeben:

 VBoxManage.exe internalcommands createrawvmdk -filename "G:\VirtualBox\usb-stick.vmdk" -rawdisk \\.\PhysicalDrive3  

Entscheidend ist hier der letzte Parameter "rawdisk". Hier wird das physikalische Laufwerk mit der Nummer angegeben, die in der Datenträgerverwaltung (siehe Schritt 1) identifiziert wurde.
In diesem Beispiel ist das die Nummer 3.
Der Parameter "filename" gibt an, wo die vmdk Datei auf dem Dateisystem abgelegt werden soll.

Schritt 3:

Jetzt kann VirtualBox als Admin gestartet werden und in der Konfiguratoin der Massenspeicher die gerade erzeugte Datei usb-stick.vmdk hinzugefügt werden.
Idealerweise als erstes Gerät damit auch direkt davon gebootet wird.

Tuesday, September 25, 2012

Root your Galaxy Nexus without unlocking bootloader

Since I bought a Samsung Galaxy Nexus a few weeks ago I was looking for the possibility to root it without unlocking the bootloader or wiping anything.
I don't want to use a custom ROM nor a custom recovery. I just want to get rid of the ads.
Finally someone has found a working solution and posted the instructions in the XDA forum.
I have tried it and now my Nexus is rooted :-)

Thursday, September 20, 2012

m2e and generating classes using jaxws-maven-plugin solved

Since m2e 1.0 (Maven integration for Eclipse) developers are complaining about issues with the jaxws-maven-plugin.

See here and here.

The m2e wiki offers documentation describing the issue and proposing solutions. For me, none of those suggestions worked.
The classes were not generated and I had to generate the classes using Maven from the command line and refresh the Eclipse workspace. Since upgrading m2e in my Eclipse 3.7 even that doesn't work anymore.

Googling around I found this project hosted on github solving all problems. After downloading and extracting the projects zip file to my computer I installed the connector plugin in Eclipse using the local directory on my computer as update site.
After restarting Eclipse, updating the Maven project configuration and doing a clean rebuild of the project all sources from the WSDL were generated and the project compiled without errors.

Thursday, September 06, 2012

Import von Excel Trainingsaufzeichnungen nach Trainingstagebuch.org

Falls jemand gerätselt haben sollte, wie er seine in Excel (oder OpenOffice) dokumentierten Trainingseinheiten halbwegs automatisiert nach http://trainingstagebuch.org importiert bekommt, sollte sich mal diesen Eintrag in der FAQ von Trainingstagebuch.org durchlesen und das dort hinterlegte Excel Dokument ausprobieren.
Mit OpenOffice oder LibreOffice funktionieren die Makros nicht. Ich hab es dann mit einer bei mir noch vorhandenen Office 2007 Installation geschafft meine alten Daten zu importieren.
Mit ein wenig Handarbeit waren dann in ungefähr 90 Minuten über 400 Einheiten importiert.
Und ich wollte mir schon ein eigenes Import Tool schreiben ...

Copy your Firefox passwords to another Firefox on a different machine

Just in case you are in process of setting up a new machine and installing Firefox you might want to save a little bit of time.
There is a stackoverflow question concerning where Firefox saves its passwords. This information becomes very valuable in case you don't want to enter (and maybe can't remember) each and every password of websites which require authentification.
In my case it works copying the files:
  • key3.db
  • signons.sqlite
from a Firefox 13 installation under Windows XP to a new Firefox 14 installation under Windows 7 (64 Bit).
I don't say it will work always but this situation is working well.
The above mentioned files are located in your Firefox profile folder.

Friday, August 17, 2012

Go and check out the Eclipse Memory Analyzer in case of OutOfMemory exceptions

I have to mention this great tool once again: The Eclipse Memory Analyzer is an awesome tool to analyze heap dumps and to find problems very fast. Especially the "Leak Suspects" feature is very useful for determining memory leaks in your application.

Thursday, August 16, 2012

Confluence Wiki PDF Export and generating a title page

Sometimes you have the requirement to export docs written in Confluence as PDF so customers who don't get access to your wiki can read it.
Often your company has guidelines for publishing documents to the outside (or for customers).
Confluence doesn't generate a title page as default when you do a single page export or a space export as PDF.
This article (sorry, only in german) describes how to achieve this in a few steps.
It only works using the space export to PDF not the single page export.
The author has forgotten to include the CSS styles for the title page so I will publish mine as a starting point.


 .KonzeptTitel {   
 font-size: 36px !important;  
 text-align: center;  
 padding-top: 150px !important;  
 }  
 .KonzeptThema {   
 font-size: 24px !important;  
 text-align: center;  
 padding-top: 100px !important;  
 padding-bottom: 200px !important;  
 }  
 .KonzeptAutor {   
 font-size: 16px !important;  
 text-align: left;  
 }  
 .KonzeptDatum {   
 font-size: 16px !important;  
 text-align: left;  
 }  
 .KonzeptVersion {   
 font-size: 16px !important;  
 text-align: left;  
 }  
 .pdfTitelblattText {   
 font-size: 16px !important;  
 text-align: left;  
 }  
Hope this helps somebody.

Thursday, August 02, 2012

SMTP Appender with logback and reducing log messages in email

Logback has some pretty cool features which makes developer life so much easier. Among them is configuring the buffer size of the log messages. Especially in conjunction with error messages delivered by the email appender adjusting the buffer size is very useful.
This blog entry shows you how to configure email alerts with logback and how to reduce the quantity of log messages in the error mail.
The default buffer size for log messages is set to 256 which might scatter your email with too much infos. The example given in the blog reduces the lines to 5 so you will receive only the latest 4 log messages (if logged) previously issued by your application including the error log message.

Wednesday, July 18, 2012

Using Preferences in Android

I am currently working on an Android app which can be configured by the user through preferences. Everybody who is somehow familiar with configuration dialogs in desktop applications or mobile phone apps knows that those configuration dialogs uses UI controls like checkboxes, radio buttons, list views, etc ...
On my trail through the official Android tutorial I didn't find any docs saying there is an Android preferences API which frees the developer from writing much code to display, read and store those preferences. Maybe I am to blind to find those docs ...
However, I found a few online tutorials which helped me a lot:

And of course the Android Preference API is always a good friend :-)

Friday, July 13, 2012

Stevie Ray Vaughan in action with number one

I just love this guy ... unfortunately I never saw him live on stage.


How to flush DNS cache

Sometimes it's good to know how to flush the DNS cache on your Linux or Windows box. Here is how to do it:

Linux

Restart the nscd daemon. In case it is not installed install it first

 apt-get install nscd  

then type the command

 sudo /etc/init.d/nscd restart  

or

 sudo service nscd restart  

There are a few alternatives to flush the DNS cache under Linux. See this blog posting to get a more complete overview.

Windows

Open a command shell and type

 ipconfig /flushdns  



Thursday, July 12, 2012

Solving "Too many open files" under Linux

Every now and then I got this error and everytime I start googling around how to fix this. So now I have decided to write it down and publish it to avoid using Google or any other search engines.

On any Linux most if not everything "is a file".
This is also the case for network connections. Thus, the error message "Too many open files" is more likely the problem of "Too many open connections".

The message comes from the operating system to tell you that the application opened a large number of connections. The Linux kernel has several securities to prevent an application from slowing the system by opening too many file handles.

In Linux there are two limits:
  • A global limit specifying the total amount of open file descriptors by the whole system
  • A per-process limit specifying the total amount of open files that can be opened by an application

Specifying the global limit

Determine the global limit with the command

 cat /proc/sys/fs/file-nr  

The result is a set of 3 numbers:

 1408  0    380226  

  1. The amount of currently opened file handles
  2. The number of free allocated file handles
  3. The maximum number of allowed file handles for the whole system
The maximum number on Ubuntu systems is somewhere around 300000. This should suffice in most of the cases. However, if you want to increase the size edit the file /etc/sysctl.conf as root and add/edit this:

 fs.file-max = 380180  

After editing you have to reconnect or restart your system for changed to be taken into account.

Specifying the per-process limit

To get the maximum value of file handles an application can open run this command

 ulimit -n  

Be aware, that this limit depends on the user running the application. You might get different results depending on the user running ulimit -n

On Ubuntu systems the value is set to 1024 which is in certain situations too low.
To permanently increase the value edit file /etc/security/limits.conf as root and add the following lines

 *      hard  nofile   65536  
 *      soft  nofile   65536  
 root   hard  nofile   65536  
 root   soft  nofile   65536  

With these settings any application running under any user can open a maximum amount of 65536 files. That should be enough in most cases.

The meaning of the four columns are:
  1. The name of the user the setting applies to. A "*" means every user except for user "root"
  2. Either "hard" or "soft" are possible values. A hard limit is fixed and can not be modified by a non-root user. A soft limit may be modified to the value up to the hard limit
  3. The type of resource to be limited. "nofile" means number of open files.
  4. The number of the limit to be set. In the case above the limit is always set to 65536
You have to reboot your system to apply the changes.

There is also a temporary method to set the per-process limit.

 ulimit -n 65536  

This limit of 65536 open files only applies for the life of the session or shell and is lost if you reconnect or restart your system. The value cannot be higher than those specified in /etc/security/limits.conf except if you are acting as user root.

How to measure the number of open files used?


To get the number of open files used by your application type:

 ps -aux | grep $APPLICATION_NAME  

$APPLICATION_NAME is the name of the process you want to get the process id for. This can be "java" for a running Java virtual machine or "tomcat" for a running tomcat container or XXX for any other application.

Copy the process id and enter:

 lsof -p $PROCESS_ID | wc -l  

where $PROCESS_ID is the process id you received from the ps command. The command returns the number of open files used by the process you specified.

Tuesday, July 10, 2012

Good examples of asynchronous method calls in EJB 3.1

Doing parallel processing in EJB containers before EJB 3.1 was a pain in the ass. You have to fiddle around with JMS and Message Driven Beans.
EJB 3.1 introduces asynchronous method calls and simplified the management of concurrently running tasks a lot. I found two pretty good examples how to use asynchronous method calls:

http://satishgopal.wordpress.com/2011/04/24/ejb-3-1-asynchronous-methods/
http://docs.oracle.com/javaee/6/tutorial/doc/gkkqg.html

Sunday, July 08, 2012

Speed up the Android Device Emulator under Windows

Everyone who is frustrated about the poor performance of the Android Device Emulator under Windows should follow the acceleration instructions from the official Google Android documentation site - section "Using the Android Emulator".
In particular when you are developing under Windows you should use the Intel Hardware Accelerated Execution Manager (HAXM). Unfortunately HAXM is not available for all Intel CPUs. So check the docs if your CPU is supported. 
After I installed it on my Windows 7 (64 Bit) system the emulator starts within 10 seconds.

Thursday, June 28, 2012

Alternatives to Spring JMX exporter in JSE/JEE without using Spring framework


Question:
Is there anything similar to the Spring JMX exporter out there WITHOUT using the Spring framework? SimpleJMX (http://256.com/sources/simplejmx/) seems to be reasonable but seems also to be a very young framework pushed only by a single person.

I'm in need of exposing a whole bunch of attributes, methods and classes as JMX but don't want to fiddle with the JMX API and writing tons of JMX interfaces. And there is no way to introduce Spring in the project (just in case you ask). Any hints or ideas are greatly appreciated :-)

Answer:
Ok, I have quickly evaluated SimpleJMX and JMXUtils. Both work as expected and are very similar to the Spring JMX exporter. However, I find JMXUtils to be more usable in my case.

With JMXUtils it is very easy to register/unregister MBeans to an already started platform mbean server. In my case I was using GlassFish V3 as application server and I didn't want to start another MBean Server just for my own mbeans.

As far as I can see the API of SimpleJMX does not allow this and you are either forced to start another MBeanServer using the SimpleJMX API and register the created mbeans (very easy with the API) or you start fiddling around with trying to register the mbeans into the platform mbean server. The later is a little bit more complicated and therefore I decided to use JMXUtils.

The downside of JMXUtils is the manipulation of the bean name. SimpleJMX uses attributes in annotations (domainName, beanName) which is very useful but with JMXUtils you have to know the syntax for naming mbeans when using mbean domains. All in all not a big deal but for my taste SimpleJMX has the better solution for this.

The bottom line is, that both libraries are great and do their job. I decided to use JMXUtils.

This question was also posted in this stackoverflow topic.

Monday, June 25, 2012

Great Android tutorial

If you are planning to develop Android apps check out Lars Vogel's great Android Tutorial. It's one of the best tutorials out there if you are starting Android development from scratch.

Monday, May 14, 2012

Ein hoch interessanter Artikel über außerirdisches Leben in unserer Milchstraße

Wer sich mit der Wahrscheinlichkeit außerirdischen Lebens in unserer Galaxie beschäftigt sollte sich mal diesen Artikel durchlesen.
Bemerkenswerte und wie ich finde sehr interessante Annahmen und Berechnungen.
Unter Umständen muss man die Formeln aber korrigieren, da ja in letzter Zeit immer mehr Exoplaneten entdeckt werden und einige Forscher bereits der Meinung sind, dass es deutlich mehr Planeten gibt, auf denen Leben möglich wäre.
Hierzu gibt es sicherlich aber auch noch eine Menge anderer Meinungen und Berechnungsgrundlagen. Das ganze Thema ist halt sehr stark abhängig vom gegenwärtigen Kenntnisstand und der eingesetzten Technologie und Analyseverfahren.

Thursday, May 10, 2012

SSD unter Windows 7 richtig einrichten

Da ich seit kurzem einen neuen Windows 7 Laptop mit einer SSD mein Eigen nennen darf habe ich mir die Tips aus diesem Artikel zu Herzen genommen um die Lebensdauer der SSD zu verlängern.
An und für sich geht Windows 7 schon recht gut mit SSDs um. Seit dem SP1 sogar noch etwas schonender. Dennoch sind einige Einstellungen immer noch nicht akkurat und sollten entsprechend den Tips aus dem Artikel angepasst werden.

Thursday, April 19, 2012

Logging in Java: Switching to logback and slf4j

log4j was and maybe still is the de facto standard when it comes to logging in Java applications.
Sun's solution with the internal JDK logging could not be enforced across the board. The reasons for this are certainly the lack of configurability and flexibility. For simple projects the JDK logging is certainly a solution, but not for enterprise applications.

Now, in addition to log4j a new implementation that is more powerful, faster and more flexible than log4j has entered the market: logback. Ok, in fact logback was started in 2006, but version 1.0 was released in Nov. 2011.

logback has been created as a successor to log4j by the same developer and is now available after many years of testing and development in a version 1.0 (current version is 1.0.1). To avoid misunderstandings due to the small version number it should be said that logback is already in use for years in business and the version number does not reflect in any case a statement about the stability or functionality.

logback provides several advantages over log4j. Among other things:
  •      Much faster implementation
  •      Automatic reloading of logging configuration
  •      Better filter
  •      Automatic compression of archived log files
  •      Stack traces with information about the manufacturing Java Package (jar file)
  •      Automatic removal of old log archives

For the developer a switch from log4j to logback is very easy. Just switch a dependency in your Maven POM and you are ready to go:

 <dependency>  
   <groupId>ch.qos.logback</groupId>  
   <artifactId>logback-classic</artifactId>  
   <version>1.0.0</version>  
 </dependency>  

Thanks to the transitive dependencies you now also have the logging facade slf4j added to your project.
A "Hello World" example using slf4j looks like this:

 package demo;  
 import org.slf4j.Logger;  
 import org.slf4j.LoggerFactory;  
 public class HelloWorld {  
   public static void main(String[] args) {  
    Logger log = LoggerFactory.getLogger(HelloWorld.class);  
    log.info("Hello World");  
   }  
 }  

All that remains is a configuration file to control log output. 

With log4j it is usually called log4j.xml. With logback it is called logback.xml or logback-test.xml for testing environment.

In Maven projects the file logback.xml must be placed into $PROJECT_HOME/src/main/resources. The file logback-test.xml must be placed into $PROJECT_HOME/src/test/resources. A simple configuration looks like this:

 <configuration>  
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">  
   <!-- encoders are assigned the type  
      ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->  
   <encoder>  
    <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>  
   </encoder>  
  </appender>  
  <root level="debug">  
   <appender-ref ref="STDOUT" />  
  </root>  
 </configuration>  

The complete manual for logback is very detailed and available here.

Wednesday, April 18, 2012

Moving default progress indicator and make it modal in Vaadin

The default progress indicator in Vaadin is displayed at the upper right corner of your web application. Sometimes this is not the best location, especially if you want your users not to miss this little image. So just place the progress indicator into the centre of the screen.
The progress indicator is by default not modal, so users can still interact with the web application. Maybe this is not what you want and you would like to make the progress indicator modal so users can't interact with the web application during a long running process.
To summarize the goals:
  1. Move default progress indicator from upper right corner to centre
  2. Make indicator modal, so users can't interact during a long running process
The easiest thing to accomplish this is to edit the styles.css file of your Vaadin theme. If you use the standard theme you may want to extend it by creating your own styles.css for your theme.
I use the reindeermods theme so the styles.css example provided below extends exactly that theme.
The minimal styles.css solution to solve the requirements:

 
 @CHARSET "ISO-8859-1";
 @import url(../reindeermods/styles.css);

 .v-loading-indicator,  
 .v-loading-indicator-delay,  
 .v-loading-indicator-wait {  
   width: 100%;  
   height: 100%;  
   margin: 0;  
   background-position: 50%;  
   background-color: gray;  
   background-repeat: no-repeat;  
   background-attachment: fixed;   
   opacity: .8;  
   -ms-filter: alpha(opacity=80);  
   filter: alpha(opacity=80);  
 }  

This solution was taken from this Vaadin forum post.

Friday, April 13, 2012

How to edit UTF-8 resource properties in Eclipse

Editing resource properties files in Eclipse is easy - as long as you don't need characters beyond the ISO-8859-1 encoding.
Characters that cannot be directly represented in this encoding can be written using Unicode escapes.
I really don't know all Unicode escapes for german umlauts and I don't want to waste my time with those things when editing properties files.

The first solution I tried was to create my properties file with an UTF-8 encoding using Notepad++. This works pretty well as far as you don't touch this file ever again with Eclipse :-(
Any change of the file using Eclipse converts this file back to ISO-8859-1 encoding and native umlauts like "ä" and "ü" will display strangely in your application.

Note: In Eclipse Preferences every encoding setting (Workspace, CSS, HTML, JSP, XML) was set to UTF-8. In this Stackoverflow question someone tried even the option of specifying -Dfile.encoding=UTF-8 in eclipse.ini. Still not working.

BTW, if you prefer creating and maintaining UTF-8 properties files (maybe you don't work with Eclipse or use another IDE/Editor which is capable of editing UTF-8 property files) you have to check out this stackoverflow posting. Both code examples of reading resource bundles in UTF-8 format work like a charm.

For me, this is not an option because I want to stick to Eclipse and I don't want to edit the properties files with a different tool.

What finally really did the trick was the Resource Bundle Plugin for Eclipse mentioned in this stackoverflow answer. The plugin converts native non ISO-8859-1 characters on the fly to Unicode escapes and frees you from typing the Unicode escapes manually.
All in all a pretty good solution and a very handy plugin.




Thursday, April 12, 2012

Adding Vaadin Add-Ons to your Maven managed application

One of the things I really like about Vaadin is the simplicity and the speed when developing the UI with Vaadin. Another great benefit of Vaadin is its Add-On directory where lots of useful add-ons are maintained and provided.

Add-Ons which implement client side UI must be recompiled by the GWT compiler to include them into your app.
To me it was not clear how to do that precisely despite the docs provided here and here.

I found this great blog article describing the necessary steps to use Add-ons with Maven. This is especially useful and described in detail for using Add-Ons which implement client side (JavaScript) code.

To minimize compile time I recommend to use a maven profile as described in the article. This prevents a GWT compilation of the widgetset each time the project is built.

In my case I used version 2.3.0 for GWT and for the gwt-maven-plugin.

Sunday, April 08, 2012

Using Eclipse 3.7 and GlassFish 3.1.2 server runtime plugin under Windows to control GlassFish servers

I installed GlassFish 3.1.2 Open Source Edition on my Windows 7 box and wanted to manage the GlassFish instance from Eclipse 3.7 using the GlassFish server runtime plugin.
I installed the plugin via the eclipse marketplace and found out that the version from the marketplace doesn't support GlassFish 3.1.2.
So I googled around and found out about this blog post describing how to install the GlassFish server runtime plugin properly on Eclipse 3.7. There is also a great stackoverflow question describing the problems with multiple "internal GlassFish servers" each time you start Eclipse after you have installed the server runtime plugin for GlassFish 3.1.2.
The later problem only occurs on Windows machines!

Tuesday, March 20, 2012

Voodoo Lab Pedal Power 2+ in Pedaltrain PT Pro einbauen - Auf die richtige Bohrlochgröße kommt es an

So, es ist vollbracht :-)
Ich habe meine zwei Voodoo Lab Pedal Power 2+ Netzteile unterhalb meines Pedaltrain PT Pro Boards angebracht.
Durch meinen Bodentreter-Wahn reichte ein Pedal Power Netzteil leider nicht mehr aus. Aber das schöne ist ja, dass das Pedaltrain Board großzügigen Platz bietet und man locker zwei oder sogar drei Voodoo Labs darunter schrauben kann.
Ich hatte allerdings mit ein paar Schwierigkeiten zu kämpfen.
  1. Das Pedaltrain PT Pro Board besitzt nur einen Satz an Befestigungshalterungen und Schrauben für eben genau ein Voodoo Lab. Diese Befestigungshalterungen mal eben so zu besorgen ist nicht ganz einfach. Selbst mein "Local Dealer" um die Ecke hat mehrere Wochen gebraucht. Da ich solange nicht warten wollte hab ich mir dann welche bei einem ebay Händler aus den USA gekauft die preislich mit Versandkosten genauso teuer waren wie beim Kauf in einem Geschäft vor Ort. Die Lieferzeit betrug knapp 2 Wochen und war damit sogar noch etwas schneller als in meinem Gitarrenladen. Im Endeffekt scheint es aber ziemlich egal zu sein, ob man die Halterungen vor Ort in dem Laden seiner Wahl bestellt (vorrätig sind die meiner Erfahrung nach so gut wie nie) oder aus den USA importiert.
  2. Das Befestigen der Halterungen ist prinzipiell ein Klacks. Es gibt im Internet massenweise Anleitungen dafür. Zum Beispiel diese hier mit einer guten Bebilderung (nicht für ein PT Pro, aber das Prinzip ist das gleiche) oder diese hier als Video bei youtube.
    Das einzige Problem das ich hatte war, dass alle Anleitungen auf englisch sind. Nicht, dass ich des englischen nicht mächtig wäre - ganz im Gegenteil - aber die Maßeinheiten und die Umrechungen vom englischen ins metrische System waren eine kleine Herausforderung. Warum das?
    In allen Anleitungen war die Rede davon, dass man die Löcher mit einem 1/8 drill bit Metallbohrer in das Pedaltrain bohren muss. Also ganz einfach dachte ich mir: Umrechnungstabelle von inch nach Millimetern im Netz suchen und einfach die passenden Bohrer besorgen. Ich hab dann diese Umrechnungstabelle gefunden und war etwas überrascht: Da stehen tatsächlich 2(!) metrische Bohrergrößen für den Wert 1/8 inch drin.
    3.1750 und 3.5000. Äh ja und nu?
    Tja, ich bin dann in den Baumarkt und hab nachgeschaut bzw. auch nochmal Google konsultiert: Es gibt entweder 3mm oder 3,5mm Bohrer. Ok, hab ich dann einen Set gekauft, der beide Bohrergrößen enthält. War auch nicht teuer und kann man sicherlich immer mal wieder gebrauchen.
  3. Jetzt zum bohren: Welche Bohrergröße nimmt man denn dann? Erfahrung meinerseits: Nimm den 3,5mm Bohrer. Ich habe zuerst den 3mm Bohrer benutzt und da ist mir beim Eindrehen einer Schraube der Schraubenkopf tatsächlich abgebrochen. Das gebohrte Loch war zu schmal. Und nein - ich habe die Schraube nicht mit einem Akkubohrer eingeschraubt sondern ganz old-school per Hand.
    Mit den 3,5mm Löchern hat dann aber alles perfekt geklappt.

Ein Foto des fertigen Boards wird es sicherlich auch nochmal geben. Aber es sind noch nicht alle Effekte drauf und das Kabelwirrwarr muss erst noch "schön gemacht" werden.

Übrigens hab ich jetzt ein Rockcase 80x40 Board über. Sehr guter Zustand und wenig benutzt ...

Solution for "Sniffers with type [connector] and type [ejb] should not claim the archive at the same time"

In case you are using GlassFish it may happen you run into this error

"java.lang.IllegalArgumentException: Sniffers with type [connector] and type [ejb] should not claim the archive at the same time. Please check the packaging of your archive" 

In my case it happens when I deployed a web archive out of Eclipse directly into a running GlassFish instance on my machine using the GlassFish plugin. 
I tried a Google search for this error and found a blog posting by Adam Bien describing this error and a solution. Well, indeed my packaging was wrong. I accidentally bundled the artifact glassfish-embedded-all into my WAR archive and this was causing the trouble.
The solution is very simple: Either change the scope in your pom.xml to "provided" or - in case you don't need the dependency - remove it from the dependency section of your pom.
In my case it turns out that the dependency was not necessary anymore and I deleted it.

Monday, March 05, 2012

Stopping Tomcat with remote JMX enabled through script

Tomcat comes with handy start and stop scripts in the bin folder. Those scripts are working very well.
With this script it's pretty simple to start/stop Tomcat on linux systems.

But if you decide to add jmxremote properties to your start script using $JAVA_OPTS variable, stopping of Tomcat (and mostly any other AppServer started with these options) will not succeed.

There will be an error message stating that the address is already in use (BindException) and you have to kill the process manually.

The solution is very simple. Make sure the stop command does not contain the jmxremote properties definition. So you might declare a $JAVA_OPTS for the start command as usual:

 JAVA_OPTS="-Xmx256m -XX:MaxPermSize=128m 
-Dcom.sun.management.jmxremote.port=3336 
-Dcom.sun.management.jmxremote.ssl=false 
-Dcom.sun.management.jmxremote.authenticate=false 
-Djava.rmi.server.hostname=192.168.1.5"  


but for the stop command you must omit those jmx definitions and declare it for example like this:

 JAVA_OPTS_STOP="-Xmx256m -XX:MaxPermSize=128m"  
.
The stop command then forks a JVM with the $JAVA_OPTS_STOP definition NOT trying to open another listening socket on an already bound port.


Thursday, March 01, 2012

Setting up an Apache cluster under RedHat Enterprise Linux

If it ever happens that you have to set up an Apache Linux cluster, I highly recommend the step-by-step manual from clusterlabs.org.
The docs are really easy to read and are very helpful.
I only have two negative points:

  1. Sometimes the commands you have to enter into the console are not clearly separated from the parameters or text you have to pass. Example:
    cat <<-END >>/etc/corosync/service.d/pcmkservice {
            # Load the Pacemaker Cluster Resource Manager
            name: pacemaker
            ver:  1
    }
    END
    The file to create is called /etc/corosync/service.d/pcmk (NOT pcmkservice) and the content of the file starts with "service {
    # Load the Pacemaker ..."
    I assume this has something to do with the formatting of the docs.
  2. The docs almost never tell you what to do in case things go wrong or you did a typo or your environment differs from the one used in the docs.
    In that case you have to use google and cross your fingers or use other resources like this one.
After all I only had to consult google once during the complete setup.
My failover tests succeeded after a few hours of setup including writing a howto for my specific setup.
Now the cluster works using corosync and pacemaker as services.

Wednesday, February 15, 2012

Howto dynamically change webservice endpoint URL with Metro

A really cool feature of Metro (and maybe other webservice stacks) is the possibility to change the webservice endpoint URL at runtime.
In general, you typically generate the code via JAX-WS maven plugin (or ant task), specifying the endpoint URL in the generation properties. This is a fast and reliable way to generate webservices. The downside is, that it seems you can't change the endpoint URL at runtime ...
Well, you can. And it is pretty simple.
The example in this posting is taken from the Metro FAQ.

You can use BindingProvider.ENDPOINT_ADDRESS_PROPERTY to set the endpoint address in your client application code.

Sample:

 //Create service and proxy from the generated Service class.   
  HelloService service = new HelloService();   
  HelloPort proxy = service.getHelloPort();   
  ((BindingProvider)proxy).getRequestContext().  
       put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://new/endpointaddress");   
     
  proxy.sayHello("Hello World!");   

With the property key

BindingProvider.ENDPOINT_ADDRESS_PROPERTY
you can also get the currently used endpoint url at runtime. This may be helpful for debugging purposes.
Sample:

 LOG.info("Using endpoint URL: "  
        + ((BindingProvider)proxy).getRequestContext().get(  
            BindingProvider.ENDPOINT_ADDRESS_PROPERTY));  

Friday, February 10, 2012

Updating GlassFish 3.1 under RHEL 6 on a 64 Bit machine

Don't be surprised when you have problems updating GlassFish 3.1 on a RedHat Enterprise Linux 6 64 Bit machine. This will not work out of the box (officially Oracle only supports GlassFish on RedHat 4 and 5 not on version 6). But there is a way to get it to work.
You will get this error when executing the pkg command:

 [glassfish@MYMACHINE glassfish3]$ pkg list -u  
 Traceback (most recent call last):  
  File "/opt/glassfish/glassfish3/pkg/bin/client.py", line 61, in ?  
   import pkg.actions as actions  
  File "/opt/glassfish/glassfish3/pkg/vendor-packages/pkg/actions/__init__.py", line 59, in ?  
   globals(), locals(), [modname])  
  File "/opt/glassfish/glassfish3/pkg/vendor-packages/pkg/actions/link.py", line 36, in ?  
   import generic  
  File "/opt/glassfish/glassfish3/pkg/vendor-packages/pkg/actions/generic.py", line 45, in ?  
   import pkg.variant as variant  
  File "/opt/glassfish/glassfish3/pkg/vendor-packages/pkg/variant.py", line 28, in ?  
   from pkg.misc import EmptyI  
  File "/opt/glassfish/glassfish3/pkg/vendor-packages/pkg/misc.py", line 49, in ?  
   import zlib  
 ImportError: libz.so.1: cannot open shared object file: No such file or directory  
 ---------------------------------------------------------------  
 There was an error running  
   
 /opt/glassfish/glassfish3/pkg/bin/../python2.4-minimal/bin/python  
   
 You are running on a 64 bit Linux distribution and the 32 bit Linux  
 compatibility libraries do not appear to be installed. In order to use  
 the Update Center tools you must install the 32 bit compatibility libraries.  
   
 On Ubuntu (and possibly other Debian based systems) please install the  
 ia32-libs package. On RedHat 4 (and other RPM based systems), you may  
 need to add multiple 'compat' runtime library packages. Please see the  
 Update Center Release Notes for more information.  
   
   

The solution is to install the following packages using yum

yum install compat-db.i686 zlib.i686 libidn.i686 krb5-libs.i686

The trick is to find out about the correct names of the packages. It's easy on Debian based systems but quiet difficult on RPM based systems.
If you are using CentOS take a closer look at this blog post.

Monday, February 06, 2012

Deep cloning of java objects

I was in need of deep cloning a map with all its keys and values.
All the map implementations in standard Java only do shallow cloning of the map. They don't clone the keys and values. But that was exactly what I want to realize.
I found out about the cloning library which does the job very easy and extremely fast. This library can clone nearly any java object.
A cloning expression is just a two-liner.
Very useful!
On this stackoverflow question you can find more deep cloning libraries.

Thursday, February 02, 2012

Don't use commons lang < 2.4 with HtmlUnit

In case you have a project which has a dependency to Apache commons-lang and you plan to use the latest HtmlUnit (as of writing this post this is HtmlUnit 2.9) you should take care of the version of commons-lang.

HtmlUnit is using a method (startsWithIgnoreCase) from commons-lang that was introduced in commons-lang 2.4.
So any commons-lang version below 2.4 will produce runtime exceptions when using HtmlUnit. The stacktrace may be similar to this one:

 java.lang.NoClassDefFoundError: Could not initialize class  
 com.gargoylesoftware.htmlunit.WebClient  
     at net.sourceforge.jwebunit.htmlunit.HtmlUnitTestingEngineImpl.createWebClient(HtmlUnitTestingEngineImpl.java:804)  
     at net.sourceforge.jwebunit.htmlunit.HtmlUnitTestingEngineImpl.initWebClient(HtmlUnitTestingEngineImpl.java:813)  
   
 also :  
   
 java.lang.NoSuchMethodError:  
 org.apache.commons.lang.StringUtils.startsWithIgnoreCase(Ljava/lang/String;Ljava/lang/String;)Z  
     at com.gargoylesoftware.htmlunit.util.URLCreator$URLCreatorStandard.toUrlUnsafeClassic(URLCreator.java:66)  
     at com.gargoylesoftware.htmlunit.util.UrlUtils.toUrlUnsafe(UrlUtils.java:193)  
     at com.gargoylesoftware.htmlunit.util.UrlUtils.toUrlSafe(UrlUtils.java:171)  
     at com.gargoylesoftware.htmlunit.WebClient.<clinit>(WebClient.java:162)  
     at net.sourceforge.jwebunit.htmlunit.HtmlUnitTestingEngineImpl.createWebClient(HtmlUnitTestingEngineImpl.java:804)  
     at net.sourceforge.jwebunit.htmlunit.HtmlUnitTestingEngineImpl.initWebClient(HtmlUnitTestingEngineImpl.java:813)  
   
   
   

In case you use Maven as your build tool you can check the dependencies using the command:

mvn dependency:tree

To avoid this error you can declare version 2.6 of commons-lang in your project.

Friday, January 20, 2012

Iterating over result list from a JPA query

Sometimes when using EJB 3.x, it is necessary to use JPA QL or SQL native queries to fetch objects from the database. It might be used to achieve better performance or to just fetch a particular set of attributes of the object but not the complete object with all its dependencies.

There's one thing you have to keep in mind when doing this: The result list containing the object will be an array of objects!

"The SELECT clause queries more than one column or entity, the results are aggregated in an object array (Object[]) in the java.util.List returned by getResultList( )"

Working example:
 Query query = manager.createQuery("SELECT v1.bitbit, v1.numnum, v1.someTime, t1.username, t1.anotherNum FROM MasatosanTest t1 JOIN MasatoView v1 ON v1.username = t1.username;");  
   
   List results = query.getResultList( ); // Fetches list containing arrays of object  
   
   Iterator it = results.iterator( );  
   
   while (it.hasNext( )) {  
   
     Object[] result = (Object[])it.next(); // Iterating through array object   
   
     Boolean first = (Boolean) result[0]; // Fetching the field from array  
   
     /* Likewise for all the fields, casting accordingly to the sequence in SELECT query*/  
   
   }  
   
   

There's is even the possibility to avoid casting completely by using a constructor expression with the appropriate arguments in the SELECT section:
 SELECT new org.somepackage.XEntity(x.a, x.b) FROM XEntity x  

Remember to declare the appropriate constructor.
The code fragments and the solution in this blog post was taken from this question on stackoverflow.