This blog is mainly about Java...

Friday, December 12, 2008

Devoxx 2008 conference comes to an end


I have just attended Devoxx (former JavaPolis) in Belgium Antwerpen, and I must say I am pretty amazed. It was not how I expected it to be.

Although it is much smaller than JavaOne, it is however bigger and better than JavaZone. The conference it self was on a big cinema stadium called Metropolis. It was huge, with 8 different rooms, and all the sessions where video recorded and will be available online on Parleys
early next year.

The conference was very much focused on JavaFX since the 1.0 release came out 4th of December 2008.
I attended many different sessions such as JavaFX, WebBeans, Hibernate tuning, Dojo and DWR and how to hack and secure Java web applications, plus a few others.
I will most certainly try to attend next year again, depending on my schedule. However next time, I will try to live a little closer to the event, and not 10 minute drive or an hour walk.

Saturday, December 6, 2008

Damenes tale ved julebord 2008

Idag skal jeg holde damenes tale ved vårt julebord.
Her er talen i sin helhet:

Kjære alle sammen, men mest av alt, kjære til alle damene her ikveld. Jeg vil først og fremst takke for at jeg fikk lov til å stå her ikveld og gjøre stas på dere.
I år har jeg fått den ærefulle oppgave å holde damenes tale, hvilket er veldig rart, for jeg hadde ingen
anelse hvordan man skulle holde damenes tale.

Jeg er som kjent for mange av dere veldig flink til å forføre damene med mine velvalgte ord, og hypnotiserende kroppspråk. 
Her er jeg på hjemmebane som en løve i serengetti på jakt etter sitt utvalgte bytte.
Men det å stå foran en forsamling av velkledde, flotte og lett berusede damer og forsøke å forføre dem alle samtidig, er ingen enkel sak.
Men ingen utfordring er for stor for en velrenommert sjekker som meg. Her er det bare å begrave seg dypt i materie
og en av de første tingene som står der er at man må ha en god wingman til å hjelpe en ute i feltet.

Derfor, som den geeken jeg er tydde jeg til Google som min trofaste wingman og søkte opp "damenes tale", og det første treffet jeg får opp er følgende:

"Damenes tale er som regel en veldig morsom tale. En ganske kompleks tale som krever mye av deg som skal holde den.
Damenes tale er kanskje den mest omtalte talen man kan holde hvis man ser bort fra den likestilte talen Herrenes tale."


Dette høres veldig utfordrende ut men jeg skal gjøre mitt beste og ta tyren ved hornene. 

Det finnes vesentlig store forskjeller mellom gutter og jenter. Ikke minst utspringer disse forskjellene seg i sjekke scenen.

Her følger en typisk sjekke-prosedyre på en bar en sen lørdagskveld nær stengetid sett fra en gutts perspektiv:

- Gutt ser jente som er sexy.
- Gutt tar en stoor slurk av drinken for å manne seg opp
- Gutt venter ti minutter til jente er alene (før han tør å dra bort)
- Gutt tar en ny stooor slurk
- Gutt drar bort og åpner med et sleskete uttrykk: "Hei sexy, hvordan går det?" (blunker)
- Jente ser stygt på gutt og danser videre
- Gutt står å ser dum ut
- Gutt begynner å danse for seg selv i noen sekunder
- Gutt tar en ny slurk og går tilbake til lattermilde kompiser

Og her følger kvinnenes typiske sjekke-prosedyre.

- Jente ser forførende på gutt (pause)
- Jente blir med gutt hjem
- Så lar jeg dere selv sette inn det sensurerte mellom linjene

Ikke mindre vanskelig er det for dere heller tidligere på lørdagskvelden utenfor inngangen til utestedet.

- Jente ankommer utested og ser mil lang kø.
- Jente går forbi køen, smiler til dørvaktene, viser litt pupper og lår, og slipper gratis inn.

- Gutt ankommer utested
- Gutt plasserer seg helt bak den milelange køen bak andre virile og håpefulle beilere i timesvis
- Gutt fryser
- Gutt fryser enda mer
- Timesvis etterpå står gutt håpefull først køen
- Gutt må stå enda noen minutter
- Gutt fryser
- Dørvakt kommer bort til gutt og påminner gutten om at det er et lukket selskap, eller at joggeskoene og manglende skjorte ikke står helt i stil til stedet, som egentlig direkte oversatt betyr:
"Jeg bruker min steroid forspiste kropp som ikke duger til annet enn å krympe ballene og hjernecellene mine til å vise deg at fordi du garantert er mye smartere enn meg
og tjener mer enn meg, så skal jeg bruke min autoritære mulighet til å overbevise meg selv om at livet mitt ikke stinker, og at jeg kan få noen små ynkelige gleder i livet".
- Gutt må betale ekstra til dørvakta for å slippe inn, i tillegg til inngang.

Men det er ikke så rart at vi gutter går gjennom alt dette for dere skjønne piker. Ja, for hva gjør ikke vi gutter for dere jenter? Vi spiste til og med eplet for dere vi.

For hadde det ikke vært for dere hadde vi fortsatt kost oss i Edens have i perfekt harmoni med alle dyrene.

Istedet har dere tatt til takke med en mink i skapet, en jaguar i garasjen, en tiger i senga og en bjellesau som betaler for alt dere vil ha.

Nei men fra spøk til alvor, vi gutter hadde aldri klart å leve uten dere vakre jenter som fyller hverdagen vår. Vi er kjempe glad i dere og derfor spør jeg dere om dere vennligst kan komme opp her alle sammen.

Jeg vil at alle gutta skal se godt på de kjære og vakre jentene vi har i Redpill Linpro. De sørger for å komplementere hverdagen vår og 

bidrar til at vår testosteron nivå balanseres med deres østrogen til å skape en mer eller mindre perfekt symbiose.

Det er veldig vanlig å gi roser til den bedre halvdelen. Men roser varer kun bare noen uker, og de eksisterer kun for å være vakre, og hvis de står en stund så visner de bare.
Så det er det samme som å si at vår kjærlighet baserer seg kun på utseendet.
Derimot, en potet varer evig, og i poteten er det det indre som teller. Faktisk, har du poteten liggende lenge nok, ikke bare vil den IKKE råtne,
men det vokser faktisk ting ut av poteten, så det er det samme som å si at vår kjærlighet vokser gjennom tiden. Derfor vil jeg på vegne av alle gutta beære de vakre jentene i Redpill Linpro med hver sin potet.

- Da vil jeg at alle guttene skal reise seg opp og skåle for verdens vakreste skapninger. Skål!

Takk for meg...

Wednesday, December 3, 2008

Dynamically generate ODT and PDF documents from Java

I would like to generate a OpenOffice document and a PDF document without having a running OpenOffice service in Java. This was not as easy as it sounds, however I have found a solution.

You can create ODT document fairly easy without having a running instance of OpenOffice. However I have not found an easy way to convert that document to a PDF. However, I found a solution for the latter when running Linux. 

All the following libraries are Open Source .

The easiest way to generate ODT documents from templates is by using a (unmaintaned) library by the name of JOOReport. JOOReport uses Freemarker to create ODT documents based on templates. 

Basically what you need to do is create a template odt document in OpenOffice and whereever you want to insert something, you can insert it with the syntax 
${anythingGoesHere}
ie: My name is ${name}

When you have finished implementing the template, you must then create a properties file defining the values. 

ie. 
name=
age=
birthday=
address=


We can then from the Java program get the Properties file, and fill inn already pre defined variables. We then give the template and the properties file as well as the output odt file in arguments to the program. After the creation is successfull, the easiest way is to call a linux program called 
odt2pdf someFile.odt

which takes the odt file as argument and creates a pdf file with the same name. 

Vouila. As easy as that. You can also style the template as you like and the styling will also be implemented in the generated output file.

This is a standalone program that creates a document from a template and a data file and converts it to the specific format. 


// JOOReports - The Open Source Java/OpenOffice Report Engine 
// Copyright (C) 2004-2006 - Mirko Nasato 
// 
// This library is free software; you can redistribute it and/or 
// modify it under the terms of the GNU Lesser General Public 
// License as published by the Free Software Foundation; either 
// version 2.1 of the License, or (at your option) any later version. 
// 
// This library is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
// Lesser General Public License for more details. 
// http://www.gnu.org/copyleft/lesser.html 
// 
package net.sf.jooreports.tools; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.net.ConnectException; 
import java.util.Properties; 

import org.apache.commons.io.FilenameUtils; 

import net.sf.jooreports.converter.DocumentConverter; 
import net.sf.jooreports.openoffice.connection.OpenOfficeConnection; 
import net.sf.jooreports.openoffice.connection.SocketOpenOfficeConnection; 
import net.sf.jooreports.openoffice.converter.OpenOfficeDocumentConverter; 
import net.sf.jooreports.templates.DocumentTemplate; 
import net.sf.jooreports.templates.UnzippedDocumentTemplate; 
import net.sf.jooreports.templates.ZippedDocumentTemplate; 
import freemarker.ext.dom.NodeModel; 

/** 
 * Command line tool to create a document from a template and a data file 
 * and convert it to the specified format. 
 * 


 * The data file can be in XML format or a simple .properties file. 
 * 


 * Requires an OpenOffice.org service to be running on localhost:8100 
 * (if the output format is other than ODT). 
 */ 
public class CreateAndConvertDocument { 

  public static void main(String[] args) throws Exception { 
  if (args.length < 3) { System.err.println("USAGE: "+ CreateAndConvertDocument.class.getName() +" "); 
  System.exit(0); 
  }  
  File templateFile = new File(args[0]); 
  File dataFile = new File(args[1]); 
  File outputFile = new File(args[2]); 

  DocumentTemplate template = null; 
  if (templateFile.isDirectory()) { 
  template = new UnzippedDocumentTemplate(templateFile); 
  } else { 
  template = new ZippedDocumentTemplate(templateFile); 
  } 
   
  Object model = null; 
  String dataFileExtension = FilenameUtils.getExtension(dataFile.getName()); 
  if (dataFileExtension.equals("xml")) { 
  model = NodeModel.parse(dataFile); 
  } else if (dataFileExtension.equals("properties")) { 
  Properties properties = new Properties(); 
  properties.load(new FileInputStream(dataFile)); 
  model = properties; 
  } else { 
  throw new IllegalArgumentException("data file must be 'xml' or 'properties'; unsupported type: " + dataFileExtension); 
  } 
   
  if ("odt".equals(FilenameUtils.getExtension(outputFile.getName()))) { 
  template.createDocument(model, new FileOutputStream(outputFile)); 
  } else { 
  OpenOfficeConnection connection = new SocketOpenOfficeConnection(); 
  try { 
  connection.connect(); 
  } catch (ConnectException connectException) { 
  System.err.println("ERROR: connection failed. Please make sure OpenOffice.org is running and listening on port "+ SocketOpenOfficeConnection.DEFAULT_PORT +"."); 
  System.exit(1); 
  } 
   
  File temporaryFile = File.createTempFile("document", ".odt"); 
  temporaryFile.deleteOnExit(); 
  template.createDocument(model, new FileOutputStream(temporaryFile)); 
  
  try { 
  DocumentConverter converter = new OpenOfficeDocumentConverter(connection); 
  converter.convert(temporaryFile, outputFile); 
  } finally { 
  connection.disconnect(); 
  } 
  } 
  } 
}




Monday, October 13, 2008

No more Repetitive Strain Injury (RPI)

RPI or (musehånd) in Norwegian is something I have had problems with the last three years.
Read more about RPI here: RPI

Since I work as a developer and using a mouse every day, it has put a strain on my wrist. I have tried many different things throughout the years, like different types of mouse and such.
But I have finally found something that works! And that is the RollerMouse Pro 

This is how it looks like. The roller is used as a mouse. So you dont have to change position so much with your hands. And you use your thumbs to roll the mouse and clicking, instead of your point finger. Remember that when you buy the RollerMouse Pro it doesnt come with a keyboard. You can use your own keyboard with it. The RollerMouse Pro is quite expensive, but it was well worth the 2000kr I paid for it. It also works great on Linux.

I can warmly recommend this product.

Wednesday, October 1, 2008

Richfaces 3.2.x useful tips

Using <a4j:log>
To see this in action, you can use an <a4j:log>, which shows request
data, response data, DOM tree changes on update, and other useful debug
information. When placed on the page, the control doesn’t produce any
visible output, but after hitting Ctrl+Shift+L (the default register hotkey), a
debug window will open. If for some reason a debug log window doesn’t
open, change the hotkey by setting the hotkey attribute to a letter of your
choice, for example, <a4j:log hotkey="D"/>.

</rich:panel>
<a4j:log/>

------------------------------------
<h:inputText value="#{profile.age}">
<a4j:support event="onblur" reRender="userInfo"
ajaxSingle="true">
</h:inputText>

is equivalent to this:

<a4j:region>
<h:inputText value=”#{profile.age}”>
<a4j:support event=”onblur” reRender=”userInfo”>
</h:inputText>
</a4j:region>


*********a4j:support****************
----------------------------------------
JavaScript Interactions
Although RichFaces shields you from writing JavaScript, sometimes you
might want to invoke a custom JavaScript function. Injecting custom
JavaScript is possible by using the following attributes on components that
initiate an Ajax request:
- onsubmit: Just before Ajax request is sent
- onbeforedomupdate: Before any DOM updates are processed
- oncomplete: After DOM updates have been processed

-----------------------
Using bypassUpdates
When just validating form values, set bypassUpdates="true". When set
to true, the Update Model and Invoke Application phases will not be
invoked, improving response time.
-------------------------------------------
Using eventsQueue and requestDelay
Use the eventsQueue attribute when possible. When setting
eventsQueue, the next request will not be set until the previous request
comes back (the response). To further control the sending of requests, use
requestDelay to delay the sending of a request by some number of
milliseconds.
--------------------------------------------------------
Another attribute is data, which allows you to get any additional data from
the server during an Ajax request. The data attribute can simply point to a
bean property via EL, and the data will be serialized in JSON format and
available on the client side. Here’s an example:
<a4j:commandButton value="Submit" reRender="out"
data="#{bean.text}"
oncomplete="alert(data)"/>
where text is as follows:
private String text = "Nice, I can get any data from the server";
*********/a4j:support****************
--------------------------------------------------------------------------
Notice that the event on which an
Ajax request is sent is onblur. The onblur event means the user has to tab
out of the current field or click somewhere else using the mouse.
-------------------------------------------------------------------
To show a modal window with a status "Please wait" and block everything in the background, you can do something like this:
<h:form>
<a4j:commandButton actionListener="#{bean.calculate}"
value="Calculate"/>
</h:form>
<rich:modalPanel id="mp" style="text-align:center">
<h:outputText value="Please wait..."
style="font-weight:bold;font-size:large"/>
</rich:modalPanel>
186 Using RichFaces
<a4j:status id="actionStatus"
onstart="#{rich:component('mp')}.show('',{height:'80',
width:'150'})"
onstop="#{rich:component('mp')}.hide()" />

Saturday, September 27, 2008

How to enable second level caching in Hibernate

To enable second level caching in hibernate you can do it two ways:
One of them is by creating a namedQuery and put it as cacheable and then call the namedQuery.

In your Entity class type
@NamedQueries( { @NamedQuery(name = "findAllDistinctPersons", query = "SELECT DISTINCT p FROM Person p", hints = {
@QueryHint(name = "org.hibernate.cacheable", value = "true"), @QueryHint(name = "org.hibernate.cacheRegion", value = "alkohol_register") }) })

Here I have created a NamedQuery called findAllDistinctPerons, and I put hints to be org.hibernate.cacheable as value true. Then you can if you want put a region.
This is optional. This basically means that you can define a region in your configuration file and define which part of the application should use this region.
You should do this if you want some region to be cacheable and some region not to be, but still want to reuse the object.

The other way is doing it when you are creating the query.
personList = entityManager.createQuery("SELECT DISTINCT p FROM " + Person.class.getName() + " p INNER JOIN p.personAdresseAdressetypes paa " +
"WHERE p.aktiv = " + getSearchAktiv() + " "
+ SearchHelper.getAdresseSearch(getSearchStringAdresse(),true, "paa")).setHint("org.hibernate.cacheable", true).getResultList();
Here you set the Hint directly on the query. Note that we are not defining any region here.

Seam, EJB and Hibernate useful tips

Here are some tips I have gathered during our Seam project.

@Create - Signals that this method should be called upon instantiation of the JavaBean.

@Stateless - Makes an EJB3 object

@Stateful - (SESSION) Caches in memory between server requests

@In - These variables will automatically be set by Seam through injection of the variables labeled by the annotation. i.e
String zipCode; (Behind the curtain: zipCode = request.getParameter("zipCode"); )

@Out - Same as above. This variable is also automatically set by Seam. Behind the curtain this variable is set in the HttpSession object.
( request.setAttribute("bestRestaurant", restaurant); )
What you also must remember is that if you want to use the outjected object, you only call it with its name. Not component name first.
i.e. If you stateful session bean is named @Name("someName") and you have a @Out String test, then when you use it in the view, you must write #{test} and not #{someName.test}
You can also say @Out(required = false) which means that the Object can be null. Otherwize it cannot.

@DataModel annotation exposes an attribute of type java.util.List to the JSF page as an instance of javax.faces.model.DataModel. This allows us to use the list in a JSF with clickable links for each row. The DataModel is made available in a session context variable named the variable name.

@PersistenceContext(type=EXTENDED)
EntityManager em;
This stateful bean has an EJB3 extended persistence context. The messages retrieved in the query remain in the managed state as long as the bean exists, so any subsequent method calls to the stateful bean can update them without needing to make any explicit call to the EntityManager.
Remember, its a good idea to clear the entitymanager once in a while if you do lots of searches

@Factory("messageList")
public void findMessages() {
messageList = em.createQuery("from Message msg order by msg.datetime desc").getResultList();
}
The first time we navigate to the JSP page, there will be no value in the messageList context variable. The @Factory annotation tells Seam to create an instance of MessageManagerBean and invoke the findMessages() method to initialize the value. We call findMessages() a factory method for messages.

@Remove
@Destroy
public void destroy() {}
All stateful session bean Seam components must have a method with no parameters marked @Remove that Seam uses to remove the stateful bean when the Seam context ends, and clean up any server-side state.

@NamedQuery(name="findProeveByAddress",
query = "SELECT p " +
"FROM Proeve p, PersonAdresseAdressetype paa "
+ "WHERE paa.person = p.person "
+ "AND (lower(p.person.fornavn) like :fornavn OR lower(p.person.mellomnavn) like :fornavn) "
+ "AND (lower(p.person.etternavn) like :etternavn) "
+ "AND (lower(p.person.foedselsnummer) like :foedselsnr) "
+ "AND (lower(paa.adresse.adressefelt1) like :adresse) "
+ "AND (lower(p.kommune.navn) like :kommunenavn) "
+ "order by p.person.etternavn, p.avlagt desc"
)

@Lob - Used for storing large string/byte objects. Becomes text or blob.

Join Fetch - Makes the fetch eager. Be careful using join fetch. What I mean with that is that you should only use fetch when you are going to call methods
on the object being fetched. Otherwize it will be a performance issue.

@Enumerated(EnumType.STRING) - Makes the enum as string in the database

@Observer("proeveSearchDirty")
public void clear() {
proeveSokList = null;
}
With the observer annotation you can call on methods by giving it a name from other seam components.
For instance you can raise event which will call the observer method after an persist is made

@RaiseEvent("proeveSearchDirty")
public String persist() {
return super.persist();
}

If you want to override the default "Successfully created/updated/removed" from Seam and your EntityHome objects, then you can either override the methods
in the Home class. i.e
@Override
public String getCreatedMessage() {
return "Saved";
}

@Override
public String getUpdatedMessage() {
return "Updated";
}

@Override
public String getDeletedMessage() {
return "Removed";
}
Or you can put it in the messages.properties file with the notation:
*EntityName*.created. For instance:
Adresse_created=Lagret
Adresse_updated=Oppdatert
Adresse_deleted=Slettet
The messages.properties will be the default even if you have overrided the methods in your Home objects.

Tuesday, September 2, 2008

Deleted entity passed to persist exception

Deleting an entity was seemingly more difficult than I thought.
I thought that I could just loop through a list, find the objects I wanted to delete and just delete them.

Look at this block of code:

List relasjoner = entityManager.createQuery(
"SELECT rel FROM " + Relasjon.class.getName() + " rel " + "WHERE rel.personA.personId = " + personb.getPersonId()
+ " OR rel.personB.personId = " + personb.getPersonId()).getResultList();

for (Relasjon rel : relasjoner) {
if((rel.getPersonB().getPersonId().equals(personb.getPersonId()) || rel.getPersonA().getPersonId().equals(personb.getPersonId()))
// Time to remove
log.debug("Going to remove this relasjon with id: " + rel.getRelasjonId());
entityManager.remove(rel);
}
}

The line entityManager.remove(rel) gave me a "Deleted entity passed to persist" exception with Relasjon<#null>
After some Googling I found out that I had to add these two lines before trying to remove the entity:

rel.getPersonA().getRelasjonsForPersonA().remove(rel);
rel.getPersonB().getRelasjonsForPersonB().remove(rel);


getRelasjonsForPersonA() is a Set of persons.
So I have to remove all the references to a Relasjon first before deleting the entity, and then no more exception.

Thursday, August 28, 2008

Enabled commenting on my blogs

I decided to enable commenting on my blogs.
I dont know why I havent done this earlier, but anyways, never to late. So if you have something to say or a question, please comment the blog and I will answer ASAP.

Ubuntu Hardy for parents

A few months ago I installed Ubuntu Hardy on my newly purchased HP laptop for my mom. My parents have no clue with using computers and I was fed up with frequent calls about viruses, slow computer and stuff like that. Obviously they used Windows XP, so when my mom announced she wanted a new laptop I installed a dual boot for her. She didn't want to only have Ubuntu because she was sceptic, which I can understand. I asked my step dad if he wanted me to do the same for his laptop, but he respectfully declined.

However after a few months of using Ubuntu my mom really loves it. I no more get calls with virus, slow computer, and other miscellaneous windows stuff. They especially love the games that come out of the box on Ubuntu, and now my step dad has asked me to install Ubuntu on his laptop as well :-)

My mom is still using Vista once in a while for stuff that is not working out of the box on Ubuntu, such as copying pictures and videoes from her Nokia to the computer. But when I fix these small issues that come along, then hopefully she will one day convert totally and never use Windows Vista again.

Friday, August 22, 2008

Using Encryption (Jasypt) in Seam 2.0 and how to search on encrypted values

In our project we had to encrypt all fields in the person table that can identify a person.
I found a nice framework that makes encryption quite easy called Jasypt and more specifically, it had very nice and easy configuration for Seam 2, which can be found here: Jasypt with Seam 2.

The problem however is that all our searches that we had created for the person fields that are now encrypted fail. For obvious reasons, you cannot compare (run LIKE) on encrypted fields.
But the user demanded to still be able to filter the search based on the encrypted values.
There are two theories on how I could do this.

The first, was to encrypt the user input and then try to find a match against the encrypted fields. However since Jasypt uses SALT I cannot easily do this because SALT generates x amount of random bytes and makes two equal values different chipertext. So to solve that I would have to remove the SALT and do the comparing. However we have very little time to solve this, so I went with the second option which I really wanted to avoid.

What I do know is create a query based on the values that are not encrypted and return the List. However, it is not certain that the user will enter one of the values that is not encrypted, so the search will then retrieve all Person objects, and then I loop through the List, decrypt the values (which Jasypt automatically does) and compare against what the user has inputted in the search criteria and then return the correct list.
This is a very cumbersome method to retrieve the List. Having all the Person objects in memory is not feasible. I will have to add some sort of caching so that it at least will be better when it is in production, but still this is something I would like to avoid. (Yes I know I have all the objects decrypted in the memory/cache, but I don't see any other solution)

If anyone has other ideas on how could be solved, then please leave a comment or contact me.

Friday, July 4, 2008

How to change the language of your Firefox

I have installed ubuntu on a HP Compaq 6910p for my mom. She is not so fluent in english, so she wanted everything in Norwegian. I thought first that it would be easy to install firefox in norwegian. Boy was I wrong. Yes, I can easily download firefox in the language I wanted, but I wanted to modify the already existing mozilla firefox that was in Ubuntu Hardy Heron. This because all the plugins and whatnot was already installed for me.

Anyways, about two days worth of Googling, and I found a way.
What you need to do is go to this page:

http://releases.mozilla.org/pub/mozilla.org/firefox/releases/
Then you want to find your version of firefox, choose xpi, and then the language you want for firefox, and voilla! Enjoy...

Generating InnoDB engine and UTF-8 for MySQL using hibernate

I found these blogs:

http://blog.tremend.ro/2007/08/14/how-to-set-the-default-charset-to-utf-8-for-create-table-when-using-hibernate-with-java-persistence-annotations


and

http://neoexpedition.wordpress.com/2007/11/01/persisting-japanese-characters-in-db-using-hibernate

They had the same problem as me, on how to generate InnoDB engine and UTF-8 for MySQL through hibernate.

This is the solution for doing it:

In persistence.xml or hibernate.cfg.xml (depending on what you are using), you add this line to get InnoDB as engine.

<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>


or

<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect">


if you are using MySQL 4.x.

To get utf8 as default charset, you have to create the database as default charset utf8 and hibernate will do that automatically for you.

create database foo default charset utf8;

Friday, May 23, 2008

Visiting Iran first time in 21 years (part 2)

Heading back from where I used to live, it was time for dinner. My aunt had made a list of all the food she knew to be good, and wanted me to choose which ones I liked. Mmmm. In hindsight, I shouldn't have eaten that much. I did gain a few kilos in the short period I was there :-D
Oh well....

Food like "Fesenghon", "Ghormesabsi", "Mirza Ghasemi", "Joje kabab", "Cholo kabab" and more are all coming back to me...

Party party party

My cousin Bashir, on the left here, through a party for me and invited some of his friends. Now I don't want to say too much, but it was a pretty cool party, much like the ones we have here in Norway if you know what I mean.
But one thing that can never prepare you was the smoking. The house was filled with smoke. I had to go out and take fresh air every 10 minutes.
Not much more happened that evening. We ended the party quite early and went home singing in the car.
Here is a short video clip from that car...


The days that followed was spent on sightseeing in Tehran. I went to a big museum, which is a park and some castles of the old palace from the Shah time, plus some other cool stuff.
Here is some pictures from inside and outside of the museum.
















These pictures are taken from outside of the museum. You can see the old cars which was used back during the Shah times.















These pictures are from inside of the castle. The rugs are hand made the one on the left was huge!

We also went to another castle where one could see The Marble Throne terrace.
It was a place where the former King used to receive gifts among other things when visitors came. There was also other gifts from Kings, Queens and other royalty as well as countries in one of the museums.

The king used to sit up on the throne and people would come from both sides and give gifts.






Here is right outside of the throne.





to be continued....

Wednesday, May 7, 2008

Seam-gen problems when having MyISAM as engine in MySQL

I tried running seam-gen on an existing MySQL database, where the engine is MyISAM.
Jboss-seam-2.0.1.GA is the version of seam I was running.

The strangest thing happened. When I reversed engineered the database to create entity beans, the foreign keys where not Objects like it is normally, but rather String.
For instance, in our Address entity bean, I have a foreign key that is mapped to the Country entity bean.
Normally the Address.java should look something like this:

@Entity
@Table(name = "address")
public class Address implements java.io.Serializable {

private Integer addressId;
//The ID
private Country country; //The foreign key
....
}


However, the foreign key was generated like this:
private String countryId; //The foreign key

But when I changed the MySQL engine to use InnoDB instead, and I ran a new seam-gen, it was generated correctly.

Just a heads up if someone encounters the same problem. I would guess it is a bug in either seam or hibernate. Probably hibernate, since it is hibernate that does the generation.

Monday, May 5, 2008

Visiting Iran first time in 21 years

I recently went to Iran for the first time in 21 years. Back to the "motherland". It was a great experience, one which I had been looking for, for many years.

I took the flight from Oslo to Amsterdam, and from Amsterdam to Tehran (Emam Khomeni Aiport). Typical my luck, KLM managed to forget my bags, so I was without a suitcase for a couple of days. I forgot to complaint to get some kind of compensation. Oh well....

I was greeted in the airport from my cousins with their better half's. It was a bit strange to meet them for the first time in 21 years, but that feeling was quickly vanished when I said my hellos and the hugs where given. My farsi, from what I believe isn't that good, but they were very astonished that I spoke so well. They imagined that they would have to use sign language or try to translate half of the words in english :-)

In the car driving to my aunts apartment, they put on a cd which they had found for me. The guy was singing "My name is Shervin", and it was pretty fun. They never did managed to find that CD again, because I was imagining myself driving around in Oslo with my new ride pumping the volume with "Esme man Shervin'e", which is translated my name is Shervin. Oh well.... :-)

Before my trip to Iran I had of course heard stories of the infamous traffic. Luck have it seems, I went to Iran during the holidays, so the traffic was non-existent.
Here is a little video from the traffic and other stuff. (Mind the poor quality, it was taking with my camera)







The first day my two cousins Hanieh and Hedieh, took me to the place where I grew up in Tehran. This is the place where I spent my first 5 years of my life. And this is how it looked like:




To be continued...

Monday, April 28, 2008

No JavaOne for me

I was planning to go to JavaOne in San Francisco this year, but my manager gave me the thumbs down the last minute. We have recently won a contract from the Kommuneforlaget, and we are going to work on an electronic application for alcohol serving. They need me on the team ASAP so I can't go :-(

I had ordered the ticket and everything. Anyways, I'm glad to be on the team, it looks like a really cool project where we are going to use JBoss, RHEL, JBoss JBPM, Seam, Mule or JBoss ESB and other cool stuff.

So 1. may is the date I will start working with the Linpro team...

Labels