Monday, January 25, 2010

JNDI InitialContext reminder

When building J2EE apps which require JNDI lookup, make sure what type of clients are instantiating the InitialContext object: should it be a container-managed class (i.e. servlet, JSF bean,etc), all you need to do is write:
try {
            Context ctx = new InitialContext();
            IHelloRemote hello = (IHelloRemote) ctx.lookup("AnotherOne/HelloBean/remote");
            hello.sayHello();
        } catch (NamingException e) {
            e.printStackTrace();
        }

But should it be just a regular POJO (btw, you CAN'T use dependency injection in EJB3 POJOs) you have to set some properties which otherwise are set by default by the J2EE app server (at least when I tried it with JBoss it worked just fine):

try{
Properties properties = new Properties(); 
                 properties.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); 
                 properties.put("java.naming.provider.url","jnp://localhost:1099"); 
                 properties.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); 
                  
         Context context = new InitialContext(properties);
         IHelloRemote hello = (IHelloRemote) ctx.lookup("AnotherOne/HelloBean/remote");
            hello.sayHello();
        } catch (NamingException e) {
            e.printStackTrace();
        }



Go Spring-Framework yourself...


Sunday, January 24, 2010

Configuring JMS destinations in Jboss 5

http://javabeanz.wordpress.com/2009/06/05/configuring-jms-in-jboss-5/

Saturday, January 23, 2010

Dealing with transactions ( from EJB3 in Action, Chapter 12 - Effectively integrating EJB3 across your application tiers, Manning publications, 2007)

Remember from our discussion in chapter 6 that in your EJB applications you
can use either container-managed transactions (CMT) or bean-managed transac-
tions, in which you programmatically manage transactions using the User-
Transaction API. While CMT is not available in the web container, if your
application uses session beans they allow you to use CMTs and avoid User-
Transaction. We highly recommend you take advantage of CMT. For example,
if you want to make multiple EJB method calls from the same transaction, then
you may be tempted to do the following:
    public class ActionBazaarRegistrationControllerServlet
      extends HttpServlet {
    ...
    //--- Do NOT do this!!! This is NOT recommended!!!
    @EJB ItemManager itemManager;
    @EJB categoryManager categoryManager;
    @Resource private UserTransaction ut;
    ...
    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
                 throws ServletException, IOException {
    ...
    ut.begin();
    ...
    categoryManager.addCategory(category);
    itemManager.addItem();
    itemManager.setCategory(category);
    ...
    ut.commit();
    }
    ...
    }
In this example we are injecting the instances ItemManager and CategoryManager
and then invoking several methods on injected session beans. The first issue here
is that you have to write error-prone code to demarcate the transaction. Second,
because your EJBs are fine-grained, the business logic gets scattered between the
EJBs and the web module. Finally, if the EJBs are remote, these translate to three
RMI calls, which can be expensive from a performance perspective. We suggest
you avoid this practice. If your application includes such a requirement, we rec-
ommend you create a session façade and use that to perform all operations, and
then invoke that EJB from the web tier.


Friday, January 22, 2010

Horrors of the past (IE)

Someone I trust recently told me that the only reason she's not switching to ubuntu linux is that it doesn't have internet explorer on it on which she can test her web applications - with IE being (surprisingly) the most widely-used internet browser in the world, all web apps have as starting requirement "MUST work on internet explorer and other browsers", so if it works on Mozilla and Opera and not on IE, your web application is close to worthless. So here's a little solution to have both the liberty of Ubuntu and the dying shade of IE integrated with it - kind of like a benign form of cancer if you will.

1. Go to Administration/synaptic package manager and install the playonlinux package (which will also install wine as a prerequisite)
2. go to Games/Playonlinux
3. click on the install button in the upper menu
4. search for "Internet explorer" in the search bar
5. install it and despair

NOTE: for the sake of easy accessing, don't forget to tick the option at the end of the installation which will add an icon of IE to your main menu

P.S. When searching for Internet explorer you will find that Playonlinux supports a huge variety of windows software from development tools all the way to the pc games. Windows has had great longevity but its days are numbered to say the least


Monday, January 18, 2010

Polymorphic queries in JPQL ?!

You may be surprised to find out that JPA supports polymorphism, and that JPQL
queries are polymorphic. This means a JPQL query to retrieve a parent entity in an
entity hierarchy is not just limited to the entity, but retrieves all subclasses as well.
For example, in ActionBazaar any query to retrieve User entities will retrieve its
subclasses, such as Seller, Bidder, and Admin.
Suppose we have a query like this:
   SELECT u
   FROM User u
   WHERE u.firstName LIKE :firstName
The query will retrieve all instances of Seller, Bidder, Admin, and so forth that
match this query condition. How do you handle a polymorphic query in your client
code? Consider the following:
       query = em.createNamedQuery("findUserByName");
       query.setParameter("firstName", firstName);
       List<User> users = query.getResultList();
       Iterator i = users.iterator();
       while (i.hasNext()) {
             User user = (User) i.next();
             System.out.print("User:"+emp.getUserId());
             if (user instanceof Seller) {
                     Seller seller = (Seller) user;
                     System.out.println("Seller:" +
                            seller.getCommissionRate());
             }
             else if (user instanceof Bidder) {
                     Bidder bidder = (Bidder) bidder;
                     System.out.println("Bidder:" +
                            bidder.getDiscountRate());
             }
       }
This code snippet uses the instanceof keyword to test user. Some Java gurus
recommend you avoid using instanceof, but we use it here as a last resort.
You have to ensure that your operations are just as polymorphic as your que-
ries! In our example, you can easily convert the operations to be polymorphic by
adding a getRate method in all entities. The getRate method will return the
commissionRate for the Seller entity, whereas it will return the discount-
Rate for the Bidder entity. The resulting code should look like this:
Iterator i = users.iterator();
while (i.hasNext()) {
  User user = (User)i.next();
  System.out.print("User:" + emp.getUserId());
  System.out.println(user.getRate());

Source: Enterprise Java Beans 3 in Action,chapter 10, Manning publications, 2007
}


Sunday, January 17, 2010

Ubuntu wrong resolution fixer

great fix:

http://ubuntuforums.org/showthread.php?p=8302145

Friday, January 15, 2010

J2EE EAP reminder

After properly configuring jboss with respect to the last 2 posts, don't forget to add jbossall-client.jar to the EJB module's classpath

configure mysql data source in jboss [part 2]

This and previous post work hand in hand to make jpa work in mysql

http://community.jboss.org/thread/130668

how to setup a mysql data source in Jboss

Download the driver

 

  • First, http://www.mysql.com/products/connector/j/ appropriate for your edition of mySQL. 

  • Next, untar/unzip it and extract the jar file.

  • Copy the jar file into $JBOSS_HOME/server/xxx/lib, where xxx is your config name (such as "default") NOTE: For JBoss 4.0.2, use the jar file mysql-connector-java-3.1.8-bin.jar, not mysql-connector-java-3.1.8-bin-g.jar.

  • Copy the $JBOSS_HOME/docs/examples/jca/mysql-ds.xml file to $JBOSS_HOME/server/xxx/deploy

 

Configure the datasource

 

  • Edit the mysql-ds.xml file.

  • Replace <jndi-name>MySqlDS</jndi-name> with your datasource name.  If you choose to make mySQL your default database (DefaultDS), then call this DefaultDS and be sure to delete the example $JBOSS_HOME/server/all/deploy/hsqldb-ds.xml which is also configured to be DefaultDS.

  • Replace <connection-url>jdbc:mysql://mysql-hostname:3306/jbossdb</connection-url> with your connection string.  Generally you just need to replace mysql-hostname with your host.  Be sure that your user has permission to connect to that hostname.

  • Set the user-name and hostname elements to your database username and hostname

 

Advanced options for the MySQL Driver can be set with <connection-property name="property">value</connection-property>.

Refer to MySQL Connector/J Manual Chapter 2 for more Information.



Source: http://community.jboss.org/wiki/SetUpAMysqlDatasource

simple EJB3 JPA mappings+code example

Consider the following DB schema:


Now let's create the following entities: Movie, User and Screening. Figure out the mappings from the upper diagram


package com.cinema.entities;

import java.io.Serializable;
import java.util.Set;

import javax.persistence.*;

@Entity
@Table(name="Movie")
public class Movie implements Serializable{

@Id
@Column(name="ID")
private int id;

@Column(name="title")
private String title;

@Column(name="genre")
private String genre;

@Column(name="duration")
private int duration;

@Column(name="director")
private String director;

@OneToMany(mappedBy="movie")
private Set screenings;

public Movie() {}



public Movie(String title, String genre, int duration, String director) {
super();
this.title = title;
this.genre = genre;
this.duration = duration;
this.director = director;
}



public Set getScreenings() {
return screenings;
}



public void setScreenings(Set screenings) {
this.screenings = screenings;
}



public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getGenre() {
return genre;
}

public void setGenre(String genre) {
this.genre = genre;
}

public int getDuration() {
return duration;
}

public void setDuration(int duration) {
this.duration = duration;
}

public String getDirector() {
return director;
}

public void setDirector(String director) {
this.director = director;
}



}




package com.cinema.entities;

import javax.persistence.*;

import java.io.Serializable;
import java.util.*;

@Entity
@Table(name="Screening")
public class Screening implements Serializable{

@Id
@Column(name="ID")
private int id;

@ManyToOne
@JoinColumn(name="Movie_ID", referencedColumnName="ID")
private Movie movie;

@Temporal(TemporalType.TIMESTAMP)
private Date time;

@ManyToMany(mappedBy="screenings")
private Set users;

public Screening(){}

public Screening(Movie movie, Date time) {
super();
this.movie = movie;
this.time = time;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public Movie getMovie() {
return movie;
}

public void setMovie(Movie movie) {
this.movie = movie;
}

public Date getTime() {
return time;
}

public void setTime(Date time) {
this.time = time;
}

public Set getUsers() {
return users;
}

public void setUsers(Set users) {
this.users = users;
}



}



package com.cinema.entities;

import java.io.Serializable;
import java.util.Set;

import javax.persistence.*;



@Entity
@Table(name="User")
public class User implements Serializable{


@Id
@Column(name="username")
private String username;

@Column(name="password")
private String password;

@Column(name="role")
private String role;


@ManyToMany
@JoinTable(name="Bookings",
joinColumns=
@JoinColumn(name="username", referencedColumnName="username"),
inverseJoinColumns=
@JoinColumn(name="Screening_ID", referencedColumnName="ID"))
private Set screenings;


public String getUsername() {
return username;
}

public User() {}



public User(String username, String password, String role) {
super();
this.username = username;
this.password = password;
this.role = role;
}

public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}



public Set getScreenings() {
return screenings;
}

public void setScreenings(Set screenings) {
this.screenings = screenings;
}




}


There you go.... now edit persistence.xml and you're pretty much done:



xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">


org.hibernate.ejb.HibernatePersistence












Peace, out



setup ftp server on ubuntu karmic

  1. 1
    Install a program called vsftpd. In order to do this, open up a command line and type sudo apt-get install vsftpd. You will be required to type in the root password and after that, just follow the instructions vsftpd gives you in order to install it.
  2. 2
    Change the configuration file. Get to the file browser and type /etc. Next scroll down and double click on a file called vsftpd.conf. Remember that lines that start with a '#' are commented out:  
    1. Disable anonymous access: Change the "anonymous_enable" setting to NO
    2. Change the "local_enable" setting to YES.
  3. 3
    Restart the FTP server to enable your changes: in a shell window, type: sudo /etc/init.d/vsftpd restart
  4. 4
    Place the files you want to serve in the FTP Home Directory (~ftp).
Source: http://www.wikihow.com/Set-up-an-FTP-Server-in-Ubuntu-Linux

Wednesday, January 13, 2010

my karmic koala's /etc/apt/sources.list with the best repositories around

# Ubuntu Karmic Koala 9.10 Repositories, from the_guv @ http://guvnr.com
#

#
# Ubuntu Karmic
#

deb http://archive.ubuntu.com/ubuntu karmic main restricted multiverse universe
deb-src http://archive.ubuntu.com/ubuntu karmic main restricted multiverse universe
deb http://archive.ubuntu.com/ubuntu karmic-backports main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu karmic-backports main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu karmic-updates main restricted multiverse universe
deb-src http://archive.ubuntu.com/ubuntu karmic-updates main restricted multiverse universe
deb http://security.ubuntu.com/ubuntu karmic-security main restricted universe multiverse
deb-src http://security.ubuntu.com/ubuntu karmic-security main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu karmic-proposed main restricted universe multiverse
deb-src http://security.ubuntu.com/ubuntu karmic-proposed main restricted universe multiverse

#
# Canonical Commercial
#

deb http://archive.canonical.com/ubuntu karmic partner
deb-src http://archive.canonical.com/ubuntu karmic partner
deb http://archive.canonical.com/ubuntu karmic-backports partner
deb-src http://archive.canonical.com/ubuntu karmic-backports partner
deb http://archive.canonical.com/ubuntu karmic-updates partner
deb-src http://archive.canonical.com/ubuntu karmic-updates partner
deb http://archive.canonical.com/ubuntu karmic-security partner
deb-src http://archive.canonical.com/ubuntu karmic-security partner
deb http://archive.canonical.com/ubuntu karmic-proposed partner
deb-src http://archive.canonical.com/ubuntu karmic-proposed partner

#
# System Tools
#

# Ubuntu Tweak
# Must-have Ubuntu configuration tool .. http://ubuntu-tweak.com/about
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 6AF0E1940624A220
deb http://ppa.launchpad.net/tualatrix/ubuntu karmic main
deb-src http://ppa.launchpad.net/tualatrix/ubuntu karmic main

#
# Productivity
#

# Gnome-do
# Mac-like desktop apps dock for improved productivity .. http://do.davebsd.com/
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 28A8205077558DD0
deb http://ppa.launchpad.net/do-core/ppa/ubuntu karmic main

# Gnome-Globalmenu
# OS X-style global menu  .. http://code.google.com/p/gnome2-globalmenu/
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 7889D725DA6DEEAA
deb http://ppa.launchpad.net/globalmenu-team/ubuntu karmic main

# Nautilus-dropbox
# File syncing online & across machines, with 2Gb space for free .. http://www.getdropbox.com/
deb http://linux.getdropbox.com/ubuntu karmic main

#
# Computer Graphics & Themes
#

# Compiz-Fusion
# Improved usability with jazzed up graphics .. http://www.compiz-fusion.org/
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 2ED6BB6042C24D89
deb http://ppa.launchpad.net/compiz/ubuntu karmic main

# Gnome Icon Theme
# Nice desktop graphics .. http://www.gnome-look.org/content/show.php/GNOME-colors?content=82562
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 2D79F61BE8D31A30
deb http://ppa.launchpad.net/gnome-colors-packagers/ppa/ubuntu karmic main
deb-src http://ppa.launchpad.net/gnome-colors-packagers/ppa/ubuntu karmic main

# Project Bisigi Themes
# Strikingly beautiful Gnome themes .. http://www.bisigi-project.org/?lang=en
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 6E871C4A881574DE
deb http://ppa.launchpad.net/bisigi/ppa/ubuntu karmic main
deb-src http://ppa.launchpad.net/bisigi/ppa/ubuntu karmic main

#
# Web browsers
#

# Chromium Browser
# Open-source Webkit browser, for testing Safari and Chrome .. http://dev.chromium.org/
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 5A9BF3BB4E5E17B5
deb http://ppa.launchpad.net/chromium-daily/ppa/ubuntu karmic main

# Epihany
# Another Webkit browser, for testing Safari and Chrome .. http://projects.gnome.org/epiphany/
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 2D9A3C5B
deb http://ppa.launchpad.net/webkit-team/epiphany/ubuntu karmic main
deb-src http://ppa.launchpad.net/webkit-team/epiphany/ubuntu karmic main

# Firefox
# Gecko browser
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 632D16BB0C713DA6
# deb http://ppa.launchpad.net/fta/ppa/ubuntu karmic main
# This gets latest beta .. for addon conpatability, add bolean to about:config: extensions.checkCompatibility
# sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 247510BE
# deb http://ppa.launchpad.net/ubuntu-mozilla-daily/ppa/ubuntu karmic main
# deb http://dl.google.com/linux/deb/ stable non-free

# Opera
# Presto browser
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 033431536A423791
deb http://deb.opera.com/opera/ stable non-free

#
# Communication
#

# Pidgin
# Multi-client instant messenger .. http://www.pidgin.im/
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 7FB8BEE0A1F196A8
deb http://ppa.launchpad.net/pidgin-developers/ppa/ubuntu karmic main

#
# Media
#

# Medibuntu
# Multimedia, entertainment and other distractions .. http://www.medibuntu.org/
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 2EBC26B60C5A2783
deb http://packages.medibuntu.org/ karmic free non-free
deb-src http://packages.medibuntu.org/ karmic free non-free

# VLC Player
# Media player, well decked with codecs .. http://www.videolan.org/vlc/
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com D739676F7613768D
deb http://ppa.launchpad.net/c-korn/vlc/ubuntu karmic main

#
# Extend with Web Development Packages Tools
#

# Drizzle
# Modular relational db optimised for Cloud and Net apps, a MySQL fork .. https://launchpad.net/drizzle
deb http://ppa.launchpad.net/drizzle-developers/ppa/ubuntu karmic main
deb-src http://ppa.launchpad.net/drizzle-developers/ppa/ubuntu karmic main

#
# Graphics Tools
#

# Shutter
# Feature-rich screenshot program .. http://shutter-project.org/
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 009ED615
deb http://ppa.launchpad.net/shutter/ppa/ubuntu karmic main
deb-src http://ppa.launchpad.net/shutter/ppa/ubuntu karmic main

#
# Windows/OS Emulators, Translators, Virtualizers, all that
#

# PlayOnLinux
# Run Windows wares and games .. http://www.playonlinux.com/en
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com FC6D7D9D009ED615
deb http://deb.playonlinux.com/ karmic main

# Setup a Virtual OS with Virtualbox (sure beats a dual-boot!)
# Virtualization software for guest OSes .. http://www.virtualbox.org
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com DCF9F87B6DFBCBAE
deb http://download.virtualbox.org/virtualbox/debian karmic non-free

# Wine
# Run Windows apps .. http://www.winehq.org/
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 58403026387EE263
deb http://wine.budgetdedicated.com/apt karmic main

#
# Package Management
#

# Subversion
# Software versioning .. http://subversion.tigris.org/
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 6298AD34413576CB
deb http://ppa.launchpad.net/anders-kaseorg/subversion-1.6/ubuntu karmic main
deb-src http://ppa.launchpad.net/anders-kaseorg/subversion-1.6/ubuntu karmic main

#
# Other Applications
#

# Google
# Picassa, Google Desktop and maybe other stuff .. er, google it!
# sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com A040830F7FAC5991
deb http://ppa.launchpad.net/chromium-daily/ppa/ubuntu karmic main
deb-src http://ppa.launchpad.net/chromium-daily/ppa/ubuntu karmic main

Tuesday, January 12, 2010

Backup & restore MySQL DB basics

http://www.devshed.com/c/a/MySQL/Backing-up-and-restoring-your-MySQL-Database/

Saturday, January 9, 2010

Glassfish v2 install tip

If port 8080 is taken (on Ubuntu - of course) by the tcp6 service run the following:
netstat -anp | grep 8080
sudo kill [Process_ID]

this way when you run ant -f setup.xml on your glassfish installation folder, you won't run into trouble

Friday, January 8, 2010

Extra repositories for Karmic Koala

http://journalxtra.com/2009/11/extra-repositories-for-karmic-koala/

Saturday, January 2, 2010

A session bean alternative: Spring

Clearly, EJB 3 session beans are not your only option in developing your applica-
tion’s business tier. POJOs managed by lightweight containers such as Spring could
also be used to build the business logic tier. Before jumping on either the EJB 3
session bean or Spring bandwagon, think about what your needs are.
If your application needs robust support for accessing remote components or the
ability to seamlessly expose your business logic as web services, EJB 3 is the clear
choice. Spring also lacks good equivalents of instance pooling, automated session
state maintenance, and passivation/activation. Because of heavy use of annotations,
you can pretty much avoid “XML Hell” using EJB 3; the same cannot be said of Spring.
Moreover, because it is an integral part of the Java EE standard, the EJB container
is natively integrated with components such as JSF, JSP, servlets, the JTA transaction
manager, JMS providers, and Java Authentication and Authorization Service (JAAS)
security providers of your application server. With Spring, you have to worry whether
your application server fully supports the framework with these native components
and other high-performance features like clustering, load balancing, and failover.
If you aren’t worried about such things, then Spring is not a bad choice at all and
even offers a few strengths of its own. The framework provides numerous simple,
elegant utilities for performing many common tasks such as the JdbcTemplate
and JmsTemplate. If you plan to use dependency injection with regular Java
classes, Spring is great since DI only works for container components in EJB 3.
Also, Spring AOP or AspectJ is a much more feature-rich (albeit slightly more com-
plex) choice than EJB 3 interceptors.
Nevertheless, if portability, standardization, and vendor support are important to
you, EJB 3 may be the way to go. EJB 3 is a mature product that is the organic
(though imperfect) result of the incremental effort, pooled resources, shared own-
ership, and measured consensus of numerous groups of people. This includes the
grassroots Java Community Process (JCP); some of the world’s most revered com-
mercial technology powerhouses like IBM, Sun, Oracle, and BEA; and spirited open-
source organizations like Apache and JBoss.


Source: Enterprise Java Beans 3 in Action,chapter 3, Manning publications, 2007