Featured FREE Whitepapers

What's New Here?

eclipse-logo

Eclipse: How attach Java source

In Eclipse, when you press Ctrl button and click on any Class names, the IDE will take you to the source file for that class. This is the normal behavior for the classes you have in your project. But, in case you want the same behavior for Java’s core classes too, you can have it by attaching the Java source with the Eclipse IDE. Once you attach the source, thereafter when you Ctrl+Click any Java class names (String for example), Eclipse will open the source code of that class. To attach the Java source code with Eclipse,When you install the JDK, you must have selected the option to install the Java source files too. This will copy the src.zip file in the installation directory. In Eclipse, go to Window -> Preferences -> Java -> Installed JREs -> Add and choose the JDK you have in your system. Eclipse will now list the JARs found in the dialog box. There, select the rt.jar and choose Source Attachment. By default, this will be pointing to the correct src.zip. If not, choose the src.zip file which you have in your java installation directory. Similarly, if you have the javadoc downloaded in your machine, you can configure that too in this dialog box.  Done! Here after, for all the projects for which you are using the above JDK, you’ll be able to browse the Java’s source code just like how you browse your own code. Reference: Attaching Java source with Eclipse IDE from Veera Sundar one of our JCG partners. Related Articles :Debugging a Production Server – Eclipse and JBoss showcase JVM options: -client vs -server Java Developer Most Useful Books Reasons Why Solaris Is a Great Java Development Platform...
android-logo

Android Game Development – Design In-game Entities – The Strategy Pattern

In this part I will try to explain what I understand on good game design elements. I will use droids in the examples and I will script a basic fight simulator to see how they behave. The problem: I command a single robot and I want to obliterate my enemies. To face the same type of enemy all over again is boring. I need new challenges and this means new types of enemies. For example in the first level I want only to practice my target. So I need a pretty dumb enemy that does not do much but takes the shots. After I mastered that skill (shooting a helpless droid), I need a bit of a challenge and I want the enemy droid to fight back, but because I am still a beginner I don’t want to die quickly so I need weak droids. After I am over with them I want a tougher challenge. I need better and stronger droids. Not just stronger, but different in behaviour as well as it can get boring killing the same type of enemy over and over again. The obvious solution: Create 3 classes for the 3 types of enemy droids. To keep it simple, each droid has 2 abilities: move and attack. It makes sense to create a Droid interface with these two methods and have each droid implement them. They can move and shoot. Well, not all of them but we can provide an empty implementation for the ones that do nothing. The droid types:Decoy Droid – will have no weapon and can’t move. Scout Droid – will have a weak weapon and moves fast. Assault Droid – will have a heavy weapon and moves slowly.Looking at the 3 types we can implement the following simple class diagram:The interface has 3 simple methods which the droids need to implement: public interface Droid {// display some info of the droid public void display();// move the droid public void move(int x, int y);// attack position public void shoot(int x, int y); }The 3 classes are as follow: DecoyDroid.java public class DecoyDroid implements Droid {@Override public void display() { System.out.println("I am a DECOY droid"); } @Override public void move(int x, int y) { System.out.println("Can't move."); }@Override public void shoot(int x, int y) { System.out.println("Have no weapon."); } }ScoutDroid.java public class ScoutDroid implements Droid {private float damage = 0.5f;@Override public void display() { System.out.println("I am a scout droid"); }@Override public void move(int x, int y) { System.out.println("Moving QUICKLY to: " + x + "," + y + "."); }@Override public void shoot(int x, int y) { System.out.println("Light Laser Canon targeting: " + x + "," + y + ". Damage: " + damage); } }AssaultDroid.java public class AssaultDroid implements Droid {private float damage = 2.5f; private boolean loaded = true;@Override public void display() { System.out.println("I am an ASSAULT droid"); }@Override public void move(int x, int y) { System.out.println("Moving SLOWLY to: " + x + "," + y + "."); }@Override public void shoot(int x, int y) { if (loaded) { System.out.println("Heavy laser targeting: " + x + "," + y + ". Damage: " + damage); loaded = false; } else { System.out.println("Reloading..."); loaded = true; } } }Both ScoutDroid and AssaultDroid have the argument damage. This holds the value of the damage inflicted by them. To give the AssaultDroid a heavy weapon with a slow reload time we added the loaded variable. This way it takes the assault droid two turns to fire its weapon once. I have created a simple simulator for the droids to take turns to move and shoot. Run the simulator for this design: BadDroidSimulator.java public class BadDroidSimulator {public static void main(String[] args) { // for generating random numbers Random rand = new Random();Droid scout = new ScoutDroid(); Droid assailant = new AssaultDroid(); Droid decoy = new DecoyDroid();scout.display(); assailant.display(); decoy.display();// shoot-out - each droid fires once per turn for (int i = 1; i <= 5; i++) { System.out.println("\n<=== BEGIN TURN " + i + " ===>"); scout.shoot(rand.nextInt(10), rand.nextInt(10)); // we assume this is an enemy position scout.move(rand.nextInt(10), rand.nextInt(10)); System.out.println(); assailant.shoot(rand.nextInt(10), rand.nextInt(10)); assailant.move(rand.nextInt(10), rand.nextInt(10)); System.out.println(); decoy.shoot(rand.nextInt(10), rand.nextInt(10)); decoy.move(rand.nextInt(10), rand.nextInt(10)); System.out.println("<=== END TURN " + i + " ===>"); } } }The result (console output) will look like this: I am a scout droid I am an ASSAULT droid I am a DECOY droid <=== BEGIN TURN 1 ===> Light Laser Canon targeting: 9,0. Damage: 0.5 Moving QUICKLY to: 4,6.Heavy laser targeting: 6,2. Damage: 2.5 Moving SLOWLY to: 9,1.Have no weapon. Can’t move. <=== END TURN 1 ===><=== BEGIN TURN 2 ===> Light Laser Canon targeting: 3,4. Damage: 0.5 Moving QUICKLY to: 6,5.Reloading… Moving SLOWLY to: 1,6.Have no weapon. Can’t move. <=== END TURN 2 ===><=== BEGIN TURN 3 ===> Light Laser Canon targeting: 6,7. Damage: 0.5 Moving QUICKLY to: 9,7.Heavy laser targeting: 7,1. Damage: 2.5 Moving SLOWLY to: 2,0.Have no weapon. Can’t move. <=== END TURN 3 ===><=== BEGIN TURN 4 ===> Light Laser Canon targeting: 3,7. Damage: 0.5 Moving QUICKLY to: 1,4.Reloading… Moving SLOWLY to: 5,9.Have no weapon. Can’t move. <=== END TURN 4 ===><=== BEGIN TURN 5 ===> Light Laser Canon targeting: 0,8. Damage: 0.5 Moving QUICKLY to: 3,9.Heavy laser targeting: 1,2. Damage: 2.5 Moving SLOWLY to: 3,2.Have no weapon. Can’t move. <=== END TURN 5 ===>Challenges to extend the design The droids take turns to move and shoot. This is all good, but:What if you want to create a hybrid droid? A droid that moves as fast as the scout but with a heavy weapon? You will have to create a new class and copy paste the respective methods from the Scout and Assault droid, right? Also imagine that the shooting mechanism is not that simple and it needs collision detection and so on. For each droid the same redundant code needs to be rewritten. What if the fire power could be enhanced with power ups? What if the droid gains self-conscientiousness and finds a weapon to use it instead of the current one?I am sure you have plenty ideas on how to enhance the gameplay and extend the world but the most obvious solution (described above) seems ill-suited for this. It requires new droid classes to be created and each droid type will implement its methods separately. Many of these methods are identical. The current design doesn’t allow you to change the droid’s internals at runtime without significant effort. Here is one proposed solution: Composition and the Strategy Pattern. Designing a Droid (properly) A very simple droid consists of a weapon put on a chassis. The first design consisted of a “is a” type relationship. A ScoutDroid is a generic Droid with some peculiarities. Composition is based on “has a” relationships. A Droid has a Chassis. A Droid has a Weapon. What type of components a droid has, determines its type. Let’s decompose the Scout Droid for example. The Scout Droid is a Droid which has a Light Laser Canon has a set of Wheels to move. We want to make the scout move quickly with a light weapon. The Assault Droid on the other hand is a Droid too but it has a Heavy Laser Canon and it runs on Tracks. This makes it extremely powerful but a bit slow. Think from a factory perspective. How does a car production line work? You get the chassis with a specific place for the engine, wheels, drive-shaft, gear-box and so on. All these components are produced separately. The teams that produce them have no idea of the other parts. They must fulfil one criteria: the gearbox must fit in perfectly in its place and connected up with the engine.. Different makes have different ways of doing this. The connector in this instance is the interface. The engine has a similar story. If it hooks up nicely with the wheels and gearbox then it can be fitted. Its internal design, capacity, power, fuel consumption can be completely different. The engine is one of the car’s components. So is our droid. But to keep it simple we have only 2 components. We need one generic droid that has all the wirings built so its components will be triggered by the droid through those interfaces. For example a droid needs to only pull the trigger of the weapon and doesn’t care what type of weapon it is as long as it has a trigger. The droid needs to understand the pullTrigger method and to do this it needs to be implemented, in order for us to give weapons to the droid to use. The same thing with the changing of location. It needs to trigger the movement. The wheels or track or anti-gravity propulsion will take the droid there. The droid only needs to set the coordinates. To fulfil this we need a class with implemented methods instead of an interface. We create the abstract Droid class. We make it abstract because we actually implement the methods that trigger the weapon, and action the moving mechanism but we don’t have concrete weapons and movement mechanisms attached to the droid. The assembly of a concrete droid will be delegated to the type constructor along with the description method. public abstract class Droid {protected Weapon weapon; // the weapon which will be used in fights protected Chassis chassis; // the chassis on which the droid is placedpublic void moveToPosition(int x, int y) { System.out.print(id + " > " ); chassis.moveTo(x, y); }/** * Engages the position on the screen whether it is occupied by * an enemy or not. Each strategy should decide how to do it. */ public void attackPosition(int x, int y) { System.out.print(id + " > "); weapon.useWeapon(new Vector2f(x, y)); }/** * Displays some info on the droid */ public abstract void display(); }If you examine the class you will see that the Droid has 3 methods from which 2 are implemented. It also has two components: Weapon and Chassis. The components are interfaces so the droid does not know what it is doing when triggering the actions on them. It is all delegated to the implementation. The interfaces are as follows: Weapon.java public interface Weapon { /** * The trigger to use the weapon. * @param target - where on the map is the target */ public void useWeapon(Vector2f target);/** * Returns the description of the weapon */ public String getDescription(); }Chassis.java public interface Chassis { /** * Delegates the movement to the supporting chassis and * tries to move the unit to x,y */ public void moveTo(int x, int y);/** * Returns the description of the chassis */ public String getDescription(); }We will enhance our base Droid class. We will add setter and getter methods for both Weapon and Chassis. This will allow us to change the droid’s behaviour at runtime. This is what the strategy pattern is all about. A Droid has behaviours: it can use a weapon and it can move. These two strategies (behaviours) need to be implemented. We also add an id which will be unique in our game for each droid instance. I use a very simple id generation strategy. I increment the nextId static field and append it to the concrete droid type prefix in the constructor for each type. Here is the new Droid class: public abstract class Droid {protected static int nextId = 0; // the next available IDprotected String id; // unique id protected Weapon weapon; // the weapon which will be used in fights protected Chassis chassis; // the chassis on which the droid is placed// the unique ID of the droid in the game public String getId() { return id; }public Weapon getWeapon() { return weapon; } public void setWeapon(Weapon weapon) { this.weapon = weapon; }public Chassis getChassis() { return chassis; } public void setChassis(Chassis chassis) { this.chassis = chassis; }public void moveToPosition(int x, int y) { System.out.print(id + " > " ); chassis.moveTo(x, y); }/** * Engages the position on the screen whether it is occupied by * an enemy or not. Each strategy should decide how to do it. */ public void attackPosition(int x, int y) { System.out.print(id + " > "); weapon.useWeapon(new Vector2f(x, y)); }/** * Displays some info on the droid */ public abstract void display(); }Let’s build some weapons NoWeapon.java /** * This is a null object. A null object is a dummy that does nothing and it * is a mere place-holder and eliminates the need to check for null. * @author impaler * */ public class NoWeapon implements Weapon {@Override public void useWeapon(Vector2f target) { // We are doing nothing System.out.println("No weapon equipped!"); }@Override public String getDescription() { return "Nothing"; } }This is the null object. The class description should give you an idea what it is. LightLaserCanon.java /** * This is a light laser cannon whit a quick reload time and high accuracy * * @author impaler * */ public class LightLaserCanon implements Weapon {private float damage = 0.5f; // the damage inflicted@Override public void useWeapon(Vector2f target) { System.out.println("Shooting my laser canon to " + (int)target.getX() + "," + (int)target.getY() + ". Bang on! Done " + damage + " damage."); }@Override public String getDescription() { return "First generation laser canon. Street use only!"; } }HeavyLaserCanon.java /** * This is a heavy assault laser cannon with high accuracy but slow reload time. * @author impaler */ public class HeavyLaserCanon implements Weapon {private boolean loaded = true; // after fire needs to be reloaded private float damage = 1.5f; // the damage is considerable@Override public void useWeapon(Vector2f target) { if (loaded) { // we fire the canon System.out.println("Eat this! Laser beam hit target (" + (int)target.getX() + "," + (int)target.getY() + ") and dealt " + damage + " damage."); // next time needs reloading loaded = false; } else { System.out.println("Darn! Out of ammo! Reloading..."); loaded = true; } }@Override public String getDescription() { return "DASS-5000 - The ultimate in siege weaponry provided by Obviam Enterprises."; } }You might notice the Vector2f class. This is a very basic 2D vector class which currently holds the x and y coordinates. Nothing more. You can find it in the downloaded source. Let’s build some chassis The getDescription() method says what the chassis is like. NoChassis.java – null object (see weapons) public class NoChassis implements Chassis {@Override public void moveTo(int x, int y) { System.out.println("It's just a frame. Can't move."); }@Override public String getDescription() { return "It's just a frame."; } }SteelStand.java public class SteelStand implements Chassis {@Override public void moveTo(int x, int y) { System.out.println("Can't move."); }@Override public String getDescription() { return "Unmovable reinforced steel stand ideal for turrets and defensive units."; } }Wheels.java public class Wheels implements Chassis {@Override public void moveTo(int x, int y) { System.out.println("Speeding to " + x + "," + y + " on my wheels!"); }@Override public String getDescription() { return "4 wheel drive, very fast on flat terrain but struggling through obstacles."; } }Track.java public class Track implements Chassis {@Override public void moveTo(int x, int y) { System.out.println("Don't get in my way! Moving slowly to: " + x + "," + y + "."); }@Override public String getDescription() { return "Slow moving tracks but able to go through many obstacles."; } }Now we can assemble our droids First let’s create a DecoyDroid. This droid will have no weapon and will be placed on a steel stand. It’s for our target practice, remember? DecoyDroid.java public class DecoyDroid extends Droid {public DecoyDroid() { id = "DCY-" + (++Droid.nextId); weapon = new NoWeapon(); chassis = new SteelStand(); }@Override public void display() { System.out.println("+--------------------------------------------------------------------------------------------+"); System.out.println("| I am a DECOY droid."); System.out.println("|\tID: " + id); System.out.println("|\tWeapon: " + weapon.getDescription()); System.out.println("|\tChassis: " + chassis.getDescription()); System.out.println("+--------------------------------------------------------------------------------------------+"); } }Examine the default constructor. It creates an id and assigns an instance of NoWeapon and SteelStand to the droid. The display() method is more elaborate than before but just to describe the droid better. It makes use of the components’ descriptions too. If you instantiate a DecoyDroid and call its display method you will get a nice description of it. +——————————————————————————————–+ | I am a DECOY droid. | ID: DCY-3 | Weapon: Nothing | Chassis: Unmovable reinforced steel stand ideal for turrets and defensive units. +——————————————————————————————–+Let’s build the rest of the types: ScoutDroid.java public class ScoutDroid extends Droid {public ScoutDroid() { id = "SCT-" + (++Droid.nextId); weapon = new LightLaserCanon(); chassis = new Wheels(); }@Override public void display() { System.out.println("+--------------------------------------------------------------------------------------------+"); System.out.println("| I am a SCOUT droid."); System.out.println("|\tID: " + id); System.out.println("|\tWeapon: " + weapon.getDescription()); System.out.println("|\tChassis: " + chassis.getDescription()); System.out.println("+--------------------------------------------------------------------------------------------+"); } }AssaultDroid.java public class AssaultDroid extends Droid {public AssaultDroid() { id = "ASS-" + (++Droid.nextId); weapon = new HeavyLaserCanon(); chassis = new Track(); }@Override public void display() { System.out.println("+--------------------------------------------------------------------------------------------+"); System.out.println("| I am an ASSAULT droid."); System.out.println("|\tID: " + id); System.out.println("|\tWeapon: " + weapon.getDescription()); System.out.println("|\tChassis: " + chassis.getDescription()); System.out.println("+--------------------------------------------------------------------------------------------+"); } }You will notice that the only things needed to be implemented are the constructor – which adds the chassis and weapon – and the display() method. The following diagram shows the new architecture:Let’s create a test script for it. We’ll simulate 5 turns in which each droid will use its weapon and move to a random location. Check the behaviour of each weapon and you will notice that the heavy laser will fire once every 2 turns. To make it interesting, in turn 4 we give a HeavyLaserCanon to DecoyDroid. Look at how it changes the droid’s behaviour and it starts firing. This is a hybrid droid created on the fly at runtime. The simulator code (DroidSimulator.java): public class DroidSimulator {public static void main(String[] args) { // for generating random numbers Random rand = new Random();Droid scout = new ScoutDroid(); Droid assailant = new AssaultDroid(); Droid decoy = new DecoyDroid();scout.display(); assailant.display(); decoy.display();// shoot-out - each droid fires once per turn for (int i = 1; i <= 5; i++) { System.out.println("\n<=== BEGIN TURN " + i + " ===>"); // in turn 3 decoy droid is given an assault canon if (i == 4) { decoy.setWeapon(new HeavyLaserCanon()); System.out.println("* " + decoy.getId() + " acquired " + decoy.getWeapon().getDescription() + "\n"); } scout.attackPosition(rand.nextInt(10), rand.nextInt(10)); // we assume this is an enemy position scout.moveToPosition(rand.nextInt(10), rand.nextInt(10)); System.out.println(); assailant.attackPosition(rand.nextInt(10), rand.nextInt(10)); assailant.moveToPosition(rand.nextInt(10), rand.nextInt(10)); System.out.println(); decoy.attackPosition(rand.nextInt(10), rand.nextInt(10)); decoy.moveToPosition(rand.nextInt(10), rand.nextInt(10)); System.out.println("<=== END TURN " + i + " ===>"); } } }The output: +——————————————————————————————–+ | I am a SCOUT droid. | ID: SCT-1 | Weapon: First generation laser canon. Street use only! | Chassis: 4 wheel drive, very fast on flat terrain but struggling through obstacles. +——————————————————————————————–+ +——————————————————————————————–+ | I am an ASSAULT droid. | ID: ASS-2 | Weapon: DASS-5000 – The ultimate in siege weaponry provided by Obviam Enterprises. | Chassis: Slow moving tracks but able to go through many obstacles. +——————————————————————————————–+ +——————————————————————————————–+ | I am a DECOY droid. | ID: DCY-3 | Weapon: Nothing | Chassis: Unmovable reinforced steel stand ideal for turrets and defensive units. +——————————————————————————————–+ <=== BEGIN TURN 1 ===> SCT-1 > Shooting my laser canon to 0,3. Bang on! Done 0.5 damage. SCT-1 > Speeding to 0,2 on my wheels!ASS-2 > Eat this! Laser beam hit target (3,4) and dealt 1.5 damage. ASS-2 > Don’t get in my way! Moving slowly to: 3,8.DCY-3 > No weapon equipped! DCY-3 > Can’t move. <=== END TURN 1 ===><=== BEGIN TURN 2 ===> SCT-1 > Shooting my laser canon to 4,0. Bang on! Done 0.5 damage. SCT-1 > Speeding to 5,0 on my wheels!ASS-2 > Darn! Out of ammo! Reloading… ASS-2 > Don’t get in my way! Moving slowly to: 1,6.DCY-3 > No weapon equipped! DCY-3 > Can’t move. <=== END TURN 2 ===><=== BEGIN TURN 3 ===> SCT-1 > Shooting my laser canon to 3,0. Bang on! Done 0.5 damage. SCT-1 > Speeding to 0,6 on my wheels!ASS-2 > Eat this! Laser beam hit target (9,1) and dealt 1.5 damage. ASS-2 > Don’t get in my way! Moving slowly to: 8,0.DCY-3 > No weapon equipped! DCY-3 > Can’t move. <=== END TURN 3 ===><=== BEGIN TURN 4 ===> * DCY-3 acquired DASS-5000 – The ultimate in siege weaponry provided by Obviam Enterprises.SCT-1 > Shooting my laser canon to 8,6. Bang on! Done 0.5 damage. SCT-1 > Speeding to 2,3 on my wheels!ASS-2 > Darn! Out of ammo! Reloading… ASS-2 > Don’t get in my way! Moving slowly to: 0,6.DCY-3 > Eat this! Laser beam hit target (9,4) and dealt 1.5 damage. DCY-3 > Can’t move. <=== END TURN 4 ===><=== BEGIN TURN 5 ===> SCT-1 > Shooting my laser canon to 1,7. Bang on! Done 0.5 damage. SCT-1 > Speeding to 1,9 on my wheels!ASS-2 > Eat this! Laser beam hit target (1,4) and dealt 1.5 damage. ASS-2 > Don’t get in my way! Moving slowly to: 3,6.DCY-3 > Darn! Out of ammo! Reloading… DCY-3 > Can’t move. <=== END TURN 5 ===>Note in turn 4 how DecoyDroid got the new weapon and changed its behaviour (the yellow line). Now you should understand the null object pattern as well. As it stands now, it is easy to create new weapons, chassis and droids by keeping the code to a minimum. Always favour composition over inheritance in these situations. You can create a very elaborate droid, with shields, sensors, an array of weapons and also an AI component which decides what weapons to use according to the situation. If you have noticed, I used the term “use” instead of fire, because a weapon can be a melee one too and not necessarily a ranged weapon. The downloadable project contains only the strategy pattern implementation. The simple inheritance approach is left out. Play with it and get the grips of this useful pattern as I will use it extensively and it is considered good design. It is a simple Java application, it is not Android enabled. Dowload the source here (obviam.compositions.part1.tgz). In the following parts I’ll try to add some AI capabilities and how to compose the final droid from images of its components. Reference: Design In-game Entities. Object Composition Strategies. Part 1 – The Strategy Pattern from our JCG partner Tamas Jano from “Against The Grain” blog. Do not forget to check out our new Android Game ArkDroid (screenshots below). You feedback will be more than helpful!Related Articles:Android Game Development Tutorials Introduction Android Game Development – The Game Idea Android Game Development – Create The Project Android Game Development – A Basic Game Architecture Android Game Development – A Basic Game Loop Android Game Development – Displaying Images with Android Android Game Development – Moving Images on Screen Android Game Development – The Game Loop Android Game Development – Measuring FPS Android Game Development – Sprite Animation Android Game Development – Particle Explosion Android Game Development – Using Bitmap Fonts Android Game Development – Switching from Canvas to OpenGL ES Android Game Development – Displaying Graphical Elements (Primitives) with OpenGL ES Android Game Development – OpenGL Texture Mapping Android Game Development – Design In-game Entities – The State Pattern Android Games Article Series...
java-logo

Double your money again

Overview A long time ago I wrote an article on using double for money. However, it is still a common fear for many developers when the solution is fairly simple. The problem with using double for money double has two types of errors. It have representation error. i.e. it cannot represent all possible decimal values exactly. Even 0.1 is not exactly this value. It also has rounding error from calculations. i.e. as you perform calculations, the error increases. double[] ds = { 0.1, 0.2, -0.3, 0.1 + 0.2 - 0.3};for (double d : ds) { System.out.println(d + " => " + new BigDecimal(d)); }prints 0.1 => 0.1000000000000000055511151231257827021181583404541015625 0.2 => 0.200000000000000011102230246251565404236316680908203125 -0.3 => -0.299999999999999988897769753748434595763683319091796875 5.551115123125783E-17 => 5.5511151231257827021181583404541015625E-17You can see that the representation for 0.1 and 0.2 is slightly higher than those values, and -0.3 is also slightly higher. When you print them, you get the nicer 0.1 instead of the actual value represented 0.1000000000000000055511151231257827021181583404541015625 However, when you add these values together, you get a value which is slightly higher than 0. The important thing to remember is that these errors are not random errors. They are manageable and bounded. Correcting for rounding error Like many data types, such as date, you have an internal representation for a value and how you represent this as a string. This is true for double. You need to control how the value is represented as a string. This can can be surprise as Java does a small amount of rounding for representation error is not obvious, however once you have rounding error for operations as well, it can some as a shock. A common reaction is to assume, there is nothing you can do about it, the error is uncontrollable, unknowable and dangerous. Abandon double and use BigDecimal However, the error is limited in the IEE-754 standards and accumulate slowly. Round the result And just like the need to use a TimeZone and Local for dates, you need to determine the precision of the result before converting to a String. To resolve this issue, you need to provide appropriate rounding. With money this is easy as you know how many decimal places are appropriate and unless you have $70 trillion you won’t get a rounding error large enough you cannot correct it. // uses round half up, or bankers' roundingpublic static double roundToTwoPlaces(double d) { return Math.round(d * 100) / 100.0; }// ORpublic static double roundToTwoPlaces(double d) { return ((long) (d < 0 ? d * 100 - 0.5 : d * 100 + 0.5)) / 100.0; }If you add this into the result, there is still a small representation error, however it is not large enough that the Double.toString(d) cannot correct for it. double[] ds = { 0.1, 0.2, -0.3, 0.1 + 0.2 - 0.3};for (double d : ds) { System.out.println(d + " to two places " + roundToTwoPlaces(d) + " => " + new BigDecimal(roundToTwoPlaces(d))); }prints 0.1 to two places 0.1 => 0.1000000000000000055511151231257827021181583404541015625 0.2 to two places 0.2 => 0.200000000000000011102230246251565404236316680908203125 -0.3 to two places -0.3 => -0.299999999999999988897769753748434595763683319091796875 5.551115123125783E-17 to two places 0.0 => 0Conclusion If you have a project standard which says you should use BigDecimal or double, that is what you should follow. However, there is not a good technical reason to fear using double for money. Reference: Double your money again from our JCG partner Peter Lawrey at the Vanilla Java. Related Articles:Low GC in Java: Use primitives instead of wrappers Java Lambda Syntax Alternatives How does JVM handle locks Erlang vs Java memory architecture Java Fork/Join for Parallel Programming Java Best Practices Series How to get C like performance in Java...
enterprise-java-logo

EJB 3.1 Global JNDI Access

As outlined in the previous parts of this series, the major drawback of the EJB v. 3.0 Specification was the lack of portable global JNDI names. This implies that there’s no portable way to link EJB references to a bean outside your application. The EJB v. 3.1 Specification fills this gap defining, in its own words: “a standardized global JNDI namespace and a series of related namespaces that map to the various scopes of a Java EE application.” This blog post will give you an overview of the Global JNDI Access as defined by the EJB v. 3.1 Specification. Namespaces and Scopes The EJB v. 3.1 Specification defines three distinct namespaces with its own scopes:Global. Application. Module.The specification requires compliant containers to register all of the session beans with the required JNDI names. Such standardized names are portable and your application components will be able to establish a reference to an EJB using a name that is portable across application servers. Global Names in the global namespace will be accessible to code in any application and conform to the following syntax: java:global[/<app-name>]/<module-name>/<bean-name>[!<interface-fqn>] <app-name> is the name of the Java EE application as specified in its standard deployment descriptor (application.xml) or, by default, the base name of the deployed EAR archive. This path fragment is used only if the session EJB is deployed within a Java EE application EAR file. If the session EJB is deployed in an EAR file, its <module-name> is the path name of the Java EE module that contains the bean (without extension) inside the EAR file. If the session bean is deployed as a standalone Java EE component in a JAR file or as part of a Java EE web module in a WAR file (which is now allowed by the Java EE 6 Specification), the <module-name> is the name of the archive (without extension). The <module-name> value can be overridden by the <module-name> element of the component’s standard deployment descriptor (ejb-jar.xml or web.xml). The <bean-name> is the EJB name as specified by the mechanisms described in the previous parts of this blog post. The <interface-fqn> part is the fully qualified name of the EJB business interface. The container has to register one JNDI global entry for every local and remote business interface implemented by the EJB and its no-interface view. Session EJB With One Business Interface or a No-Interface View If an EJB implements only one business interface or only has a no-interface view, the container is also required to register such a view with the following JNDI name: java:global[/<app-name>]/<module-name>/<bean-name> Application Names in the application namespace will be accessible only to code within the same application and conform to the following syntax: java:app/<module-name>/<bean-name>[!<interface-fqn>] Each path fragment retains the same meaning described for the global namespace JNDI names syntax in the previous section. The same publishing rules for a compliant container described in the previous section apply. Module Names in the module namespace will be accessible only to code within the same module and conform to the following syntax: java:module/<bean-name>l[!<interface-fqn>] Once more, each path fragment retains the same meaning described for the global namespace JNDI names. The same publishing rules for a compliant container described in the global namespace section. Local Clients It may be important to notice that, although global JNDI names for local interfaces (and no-interface views) are published, this does not imply that such an interface will be accessible to components running in another JVM. Conclusions The EJB v. 3.1 Specification, and other specifications in the Java EE 6 Platform, brings simplicity and adds many new features and tools to the developers’ toolboxes. “Global JNDI names” is an outstanding, although simple, feature because it finally fills a long-standing portability limitation of the previous revisions of this specification and, hence, of the entire Java EE platform. EJB 3.0 and EJB 3.1 provide a powerful, portable, yet simple component model to build enterprise applications. The “EJB sucks” day are gone but only time will tell if this technology will regain the trust of Us, The Developers. As far as it concerns myself, I feel pretty comfortable with Java EE 6, EJBs, CDI beans, the good support I have from IDEs such as NetBeans or JDeveloper (although the latter does not support EJB 3.1 yet), and all the specifications that build up this venerable platform Reference: EJB 3.1 Global JNDI Access from our JCG partner Grey at the The Grey Blog. Related Articles :An Introduction to EJB 3.0 Injection and Lookup Basic EJB References, Injection and Lookup EJB Programmatic Lookup References to EJBs Outside Your Application With Oracle WebLogic GWT EJB3 Maven JBoss 5.1 integration tutorial Java Generics Quick Tutorial How does JVM handle locks...
enterprise-java-logo

References to EJBs Outside Your Application With Oracle WebLogic

In the previous posts we made an overview of the EJB v. 3.0 and of the portable mechanisms it provides you to build your Java EE application. Since Java EE specifications are all about portability, at the risk of repeating ourselves we’ve often stressed the most important portability limit still present on the EJB v. 3.0 specifications: there is no portable way to declare and link a reference to an EJB outside your application. Although there exist other standards (such as Web Services) that let you loosely couple components of your applications, remote EJBs are still an ideal mean to accomplish this task because of their simplicity, their standardization, the good development support of many IDEs and the good performance they provide. In this blog post we’ll make an overview of the mechanisms provided by one of the leading Java EE application servers, Oracle WebLogic, to give support to references to EJBs outside the scope of your application. mappedName in Oracle WebLogic Java EE compliant application servers provide additional non-portable API, tools and mechanisms used to enhance the standard Java EE features they implement. One of the features we’ve mentioned in the first part of this series was the mappedName @EJB element. Although the EJB v. 3.0 Specification is willingly unclear about this element (that was sort of replaced by the lookup element introduced by the EJB v. 3.1 Specification), many application server vendors have implemented it with the intuitive behavior suggested by its own name: mapping an EJB to a global JNDI name. If you want to trade portability for simplicity, many application servers (such as Oracle WebLogic or GlassFish) will let you define a bean’s global JNDI name with the value of the mappedName element (or its corresponding deployment descriptor element.) As already stated, beware that Oracle WebLogic will assign global JNDI names to remote business interfaces only. This isn’t really a limitation since local business interfaces can always be referenced using the APIs described in the previous parts of this series. Oracle WebLogic Naming Conventions for EJB Remote Business Interfaces With such a mechanism in place, linking a reference to a bean outside your application is straightforward. JDeveloper’s EJB wizard, indeed, will put a default mappedName for you with an intuitive naming scheme that resembles somehow the new portable global JNDI names introduced by the EJB v. 3.1 specification, as shown in the following screenshot:The naming scheme suggested by JDeveloper is the following: mappedName = [application-name]-[module-name]-[bean-name] If adopted, this naming scheme provides an easy way to assign every bean an unique name throughout your applications. I recognize that such names are a bit awkward but, being non-portable, is a naming scheme as good as any other. Global JNDI Names for Remote EJB Interfaces in Oracle WebLogic The global JNDI names of the remote business interfaces of an EJB with a mappedName in Oracle WebLogic Application Server will be: mappedName#[interface-FQN] Using this naming scheme will allow you to build loosely coupled Java EE application that reuse each other EJBs. If you want to inspect your server JNDI tree and check the actual names of your deployed EJB, you can use WebLogic’s JNDI Tree inspector, which can be launched opening the WebLogic console, navigating to the Environment/Servers/[your-server] page and using the View JNDI Tree link. In the following screenshot you can examine the global JNDI entry for a bean defined as follows: package es.reacts;import ...;@Stateless(name = "EJBByMappedName", mappedName = "Application1-EjbTest0-EJBByMappedName") @Remote public class EJBByMappedNameBean implements RemoteByMappedName { [...] }In the screenshot you can appreciate the entry corresponding to the es.reacts.RemoteByMappedName business interface. Customizing the JNDI Name of an EJB Remote Interface Oracle WebLogic provides you the necessary tools to customize and override its default naming conventions for EJB remote interfaces. To assign or override the global JNDI name of an EJB remote interface you can use the WebLogic specific deployment descriptors. In the case of an EJB module, for example, you can use JDeveloper to quickly add a default weblogic-ejb-jar.xml or, if using another IDE such as NetBeans, you can create a new XML file named weblogic-ejb-jar.xml in the META-INF directory of your module. An empty weblogic-ejb-jar.xml file looks like this (as of Oracle WebLogic 10.3): <?xml version = '1.0' encoding = 'UTF-8'?> <weblogic-ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-ejb-jar http://www.bea.com/ns/weblogic/weblogic-ejb-jar/1.0/weblogic-ejb-jar.xsd" xmlns="http://www.bea.com/ns/weblogic/weblogic-ejb-jar"> </weblogic-ejb-jar>To assign or override a global JNDI name for a given EJB remote interface you can use the following elements: <?xml version = '1.0' encoding = 'UTF-8'?> <weblogic-ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-ejb-jar http://www.bea.com/ns/weblogic/weblogic-ejb-jar/1.0/weblogic-ejb-jar.xsd" xmlns="http://www.bea.com/ns/weblogic/weblogic-ejb-jar"> <weblogic-enterprise-bean> <ejb-name>SessionTest0</ejb-name> <stateless-session-descriptor> <business-interface-jndi-name-map> <business-remote>es.reacts.SessionTest0</business-remote> <jndi-name>global-jndi-name</jndi-name> </business-interface-jndi-name-map> </stateless-session-descriptor> </weblogic-enterprise-bean> </weblogic-ejb-jar> If you’re using JDeveloper, it provides you an easy GUI to edit the weblogic-ejb-jar.xml file:The JDeveloper GUI will let you easily customize the WebLogic deployment descriptor and configure other non-portable features of the WebLogic Application Server such as EJB clustering. Linking an EJB Reference to a Global JNDI Name In the previous section we made an overview of the tools that Oracle WebLogic Application Server provides to customize the execution environment and establish a global JNDI name for a remote interface of an EJB. In the same way, Oracle WebLogic provides you other tools to link an EJB reference to a specific target EJB using a global JNDI name. In the examples seen so far, we’ve always linked an EJB reference to a target using the portable mechanisms provided by the EJB v. 3.0 Specification. If you need to establish a target to a remote EJB outside the scope of your application, you can use the WebLogic-specific deployment descriptor of the module that acts as the EJB client. In the case of the Java EE module we’ve used so far, you can use JDeveloper to add the WebLogic-specific deployment descriptor called weblogic.xml. If you’re using other IDEs, the skeleton of this file is the following (as of Oracle WebLogic 10.3): <?xml version = '1.0' encoding = 'UTF-8'?> <weblogic-web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-web-app http://www.bea.com/ns/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd" xmlns="http://www.bea.com/ns/weblogic/weblogic-web-app"> <ejb-reference-description> <ejb-ref-name>ejb/myGlobalRef</ejb-ref-name> <jndi-name>global-jndi-name</jndi-name> </ejb-reference-description> </weblogic-web-app>This weblogic.xml deployment descriptor links the EJB reference ejb/myGlobalRef with the object stored with the global JNDI name global-jndi-name, that is the name we’ve specified in the weblogic-ejb-jar.xml file described in the previous section. This reference will be declared as usual with a @EJB annotation or in the standard deployment descriptor (in this case, the web.xml file). If you’re using JDeveloper, a GUI will help you build the WebLogic-specific deployment descriptor. The GUI is well done and is also able to scan you module’s EJB references and let them choose from a list when customizing them. Reference: References to EJBs Outside Your Application With Oracle WebLogic from our JCG partner Grey at the The Grey Blog. Related Articles :An Introduction to EJB 3.0 Injection and Lookup Basic EJB References, Injection and Lookup EJB Programmatic Lookup EJB 3.1 Global JNDI Access GWT EJB3 Maven JBoss 5.1 integration tutorial Java Generics Quick Tutorial How does JVM handle locks...
enterprise-java-logo

EJB Programmatic Lookup

In our previous post we learnt about EJB references and EJB injection. Even though EJB injection is a powerful container facility that eases modular application development, sometimes performing a programmatic EJB lookup is instead desirable. Let’s suppose, for example, that a set of distinct EJBs implement a common strategy, defined by a common business interface. Depending on the result of some choice algorithm (such as a business rule), a different strategy is chosen and hence a different EJB will be executed in the scope of a business process. In such a scenario the target EJB cannot be chosen at injection time since annotation elements (such as @EJB’s) are defined at compilation time and deployment descriptors are defined at deployment time. The only solution to this problem is a programmatic JNDI lookup. The same mechanisms described in the previous posts will apply. EJB references will be declared and linked against a name in your application private namespace using the @EJB annotation or the corresponding elements of your Java EE module deployment descriptor. Lookup in the Application Private Namespace The portable way to establish an indirection level between the namespace used in your lookup code and the target EJBs is using your application private namespace. This kind of indirection level is quite common in the Java EE platform: not only it is used for EJB references but for all sorts of resource references such as JDBC data sources, JMS queues, JavaMail sessions, etc. In the case of EJBs, as seen in our previous post, you simply define a private name used by lookup and injection code of your application. This is a private application-scoped name and is a subelement of the java:comp/env JNDI entry. With the aid of the @EJB annotation and of the deployment descriptors, you can establish a link between this name and a target EJB. The only difference is that instead of relying on the container to inject a reference into a component of yours, your application algorithms will choose the appropriate EJB and will look it up dynamically. As we’ve seen in part 2 of this series, the @EJB annotation can be used at type, method and field level to declare a reference to an EJB and, optionally, to link it to the target bean without the need of writing any deployment descriptor code. If the case of dynamic programmatic JNDI lookup, instead of annotating a field (or a property) as an injection target, you can annotate a class (such as a Servlet) to establish a reference to an EJB. In the following example we’ll see how to do it with both the @EJB annotation and the deployment descriptor.  Declaring a Reference to an EJB In the test servlet we’ve used throughout our previous posts, we can use the @EJB annotation at class level to declare a reference to an EJB in the private name ejb/ejbLocalRef: @EJB(name = "ejb/ejbLocalRef", beanInterface = es.reacts.SessionTest0Local.class, beanName = "EJBServer1.jar#SessionTest1") public class ServletTest1 extends HttpServlet { [...] }The annotation in the previous example is functionally equivalent to the following deployment descriptor (in this case, the web.xml file) fragment: <ejb-local-ref> <ejb-ref-name>ejb/ejbLocalRef</ejb-ref-name> <ejb-ref-type>Session</ejb-ref-type> <local>es.reacts.SessionTest0Local</local> <ejb-link>EJBServer1.jar#SessionTest1</ejb-link> </ejb-local-ref>The most important difference between the @EJB semantics in this example and in the examples in the previous post is that in this case we’re providing all of the information required to establish the reference and the link to the target EJB without injecting nor even relying on information coming from the injection target (such as the beanInterface). Although the annotation is applied at a class level, it is effectively equivalent to adding the corresponding deployment descriptor elements and, therefore, the declared reference will be available throughout your Java EE module. In this case, any other servlet in your Java EE web module will be able to inject or lookup the very same EJB referenced by the ejb/ejbLocalRef name: @EJB(name = "ejb/ejbLocalRef") SessionTest0Local lc4;Additional “plumbing” here is not necessary since the reference declaration contains all of the information that is required to resolve the target EJB. EJB Programmatic Lookup Since a reference has been declared and linked, our code is now able to make a JNDI lookup and retrieve a reference to the desired business interface of our target EJB. The JNDI lookup code is the good ole lookup code we’re used to (with a little difference we’ll point out later): InitialContext ctx = new InitialContext(); Object obj = ctx.lookup("java:comp/env/ejb/ejbLocalRef"); if (obj instanceof SessionTest0Local) { SessionTest0Local lc = (SessionTest0Local) obj; [...] }(* Please note that the previous fragment has been stripped of the required exception handling code.) The good news with EJB 3.0 is that you don’t need to narrow the reference using the PortableRemoteObject.narrow() method as was required by the EJB v. 2.1 Specification. In the example code we can directly test the reference with the instanceof operator and use a Java native cast to set a SessionTest0Local reference. There’s absolutely no difference between looking up local and remote business interfaces. Only in the case you rely on the deployment descriptor, the declaration and the linking of the EJB references will be performed using an <ejb-ref> or an <ejb-local-ref> according to the EJB business interface type. As far as it concerns your application, the lookup code will be identical. Patterns In scenarios in which you don’t use EJB injection and rely on lookup instead, there are both advantages and disadvantages in using annotations or the deployment descriptors to declare and link EJB references. The advantages of annotations is that they’re easier to write and use than the corresponding deployment descriptors elements. Moreover, as far as it concerns my experience, IDE support for code autocompletion might be a better tool than some deployment descriptor editors which are “obscure”, at best (with notable exceptions such as Oracle JDeveloper’s and NetBeans’.) The advantage of the deployment descriptor is that it can centralize resource references declarations. If the same EJB reference is used throughout the code of your Java EE module and is not confined to a single class, a best option is using the deployment descriptor to declare and link the EJB (and other resource) reference and avoid using annotations at all. This is a design choice that has to be taken carefully. In the uses cases in which a lookup is desirable, chances are that EJB linking might be performed in the application assembly and deployment stages. Having references well documented and declared in a central repository might still be preferable instead of having @EJB annotation scattered throughout your code and the task of the deployer might get considerably eased. Reference: EJB Programmatic Lookup from our JCG partner Grey at the The Grey Blog. Related Articles :An Introduction to EJB 3.0 Injection and Lookup Basic EJB References, Injection and Lookup References to EJBs Outside Your Application With Oracle WebLogic EJB 3.1 Global JNDI Access GWT EJB3 Maven JBoss 5.1 integration tutorial Java Generics Quick Tutorial How does JVM handle locks...
java-logo

The Perfect Singleton

From time to time I met Java programmers that are not really sure how they should implement Singleton pattern properly. (if you don’t have an idea what Singleton is just try Wikipedia: Singleton pattern). And I’m not talking about proper implementation in threaded environment. But using the most common implementation you can find over internet you can easily create as many singletons as you like. Just imagine you have the following common singleton implementation: public final class NonSafeSingleton implements Serializable {private static final NonSafeSingleton INSTANCE = new NonSafeSingleton();private NonSafeSingleton() {}public static NonSafeSingleton getInstance() { return INSTANCE; } } Now concentrate on Serializable word. Think for one more second… Yes you’re right. If you send this stuff over RMI you’ll get second instance. It should even be enough to do some in memory serialization and de-serialization and kaboom! You’ve just blown away general Singleton contract. That’s not very nice. But how to fix that? Generally there are two ways I use:The hard way (or you use 1.4 or older Java) You need to implement readResolve method in your Singleton class. This small thing is used to override what serialization mechanism has created. What you return there will be used instead of data that came from serialization (for details check: Serializable Javadoc). Just return your instance here: ... protected Object readResolve() throws ObjectStreamException { return INSTANCE; } ...The easy way (Yes, I’m using 1.5 or newer) Change your singleton class to enum and remove private constructor and getInstance method. Yes it’s really that simple. You get this for free then. public enum SafeSingleton implements Serializable {INSTANCE; }Just keep this in mind when implementing next Singleton. It can make your life easier if you use RMI heavily. Reference: The Perfect Singleton from our JCG partner Marek Piechut at the Development world stories. Related Articles :The dreaded double checked locking idiom in Java Java Secret: Using an enum to build a State machine Dependency Injection – The manual way Java Generics Quick Tutorial How does JVM handle locks...
enterprise-java-logo

Basic EJB References, Injection and Lookup

In the first part of this series we’ve introduced the mechanisms provided by the Enterprise JavaBeans v. 3.0 Specification to define EJB components, declare a reference to an EJB and wiring them up both by dependency injection or programmatic JNDI lookup. In this blog post we’ll examine some basic examples to understand how to use the EJB API. A Basic EJB An EJB is basically a POJO with some extra EJB metadata. The required metadata to deploy it as an EJB component can be provided both by using the EJB annotations or by the standard deployment descriptor. The following class implements a very basic stateless session EJB: package es.reacts;import javax.ejb.Stateless;@Stateless(name = "UniqueLocalSessionEJB") public class UniqueLocalSessionEJBBean implements UniqueLocalBusinessInterface { public UniqueLocalSessionEJBBean() { }public String sayLocalHello() { return this.getClass().getName() + "::" + "Local hello."; } } As you may recollect from our previous blog post, the @Stateless annotation is used to define a stateless session bean. The optional name element is used to define the session bean name. This element is analogous to the <ejb-name/> element of the standard deployment descriptor. This element defaults to the unqualified name of the bean class (UniqueLocalSessionEJBBean in the example above), and the example above uses it to rename the bean to UniqueLocalSessionEJB. Since we’re using the @Stateless annotation, there’s no further need to declare the EJB in the deployment descriptor. In this example, we’re assuming that the EJB is packaged in an EJB module that depends on the module containing the definition of its business interface (as explained in the following section.) Business interfaces Every EJB implements one or more business interfaces. Business interfaces can be local or remote. The most important differences between the two types of business interfaces can be summarized as follows:Local business interfaces use pass-by-reference semantics for their methods and method invocations cannot cross the JVM boundary. Local business interfaces are available only to callers in the same application and JVM instance of the callee. Remote business interfaces use pass-by-value semantics for their methods and method invocations can cross the JVM boundary. Remote business interfaces are available to callers outside the application of the callee.In the previous example, the business interface UniqueLocalBusinessInterface is declared as follows: package es.reacts;import javax.ejb.Local;@Local public interface UniqueLocalBusinessInterface { String sayLocalHello(); }In the EJB v. 3.0 world a business interface is just a plain old Java interface annotated with either the @Local or @Remote annotation. Packaging Business Interfaces In this example we’re assuming that the EJB business interface is packaged in a JAR file that the EJB module depends on. Since EJB clients only depend on an EJB business interface, it’s a good practice to package the business interfaces in a separate library in order to ease the interface distribution and to decouple them from their implementations. Injecting an EJB into a Java Servlet Now that we’ve defined an EJB, we’re ready to use it from a servlet in a Java EE web module. Assuming that there’s only one EJB implemented the UniqueLocalBusinessInterface in our application, we can inject it using an empty @EJB annotation: package es.reacts;import java.io.IOException; import java.io.PrintWriter;import javax.ejb.EJB;import javax.servlet.*; import javax.servlet.http.*;public class ServletTest1 extends HttpServlet { @EJB UniqueLocalBusinessInterface lc;public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { [...] lc.sayLocalHello(); [...] }The first thing to note is that the EJB is injected into our servlet by the application server since the bean interface alone is sufficient to identify the target EJB. In this case the beanInterface element of the @EJB annotation takes on its default value, as explained in our previous post, that is the type of the injected field: UniqueLocalBusinessInterface. Since there’s just one EJB in the application that implements this business interface, the lc field of the servlet is injected with a reference to an instance of such a class. The second thing worth pointing out is that we’re injecting an EJB into a servlet field safely because the EJB is stateless. Since servlet are stateless by default, you should not inject stateful resources into servlet fields properties otherwise you may run into concurrency-related problems. If you needed to use a stateful EJB into a servlet, you should retrieve a reference by programmatic JNDI lookup since that will guarantee that a new instance is returned for every lookup operation. Let’s deploy and run our application and we’ll see that the servlet is injected its target EJB and the method invocation to the sayLocalHello() method of its business interface is carried out correctly. If we wanted to inject a reference to a remote interface the client code would not be affected. If you try and change the UniqueLocalBusinessInterface from @Local to @Remote, you’ll see that the servlet sees no change and continues to work correctly. What Happens If More Than One EJB Implements the Same Interface? Let’s suppose that the we add another EJB in our EJB module in this application that implements the same interface as the previous one, UniqueLocalBusinessInterface. In this case, since the bean interface is not sufficient any longer to determine the target bean for injection, you’ll be returned an error. Deploying such an application in the WebLogic Application Server, for example, results in the following error being thrown: [08:46:25 PM] Caused by: weblogic.deployment.EnvironmentException: [J2EE:160199]Error resolving ejb-ref 'es.reacts.ServletTest1/lc1' from module 'WebTest0' of application 'EJBTestApp'. The ejb-ref does not have an ejb-link and the JNDI name of the target bean has not been specified. Attempts to automatically link the ejb-ref to its target bean failed because multiple EJBs in the application were found to implement the 'es.reacts.UniqueLocalBusinessInterface' interface. Please specify a qualified ejb-link for this ejb-ref to indicate which EJB is the target of this ejb-ref.Injecting a Reference to a Specific EJB Instance To solve the problem occurred in the previous section we need to provide the application server with the required information to identify the target EJB. As explained in our previous post, we can use the following two methods:Either we use the name element of the @EJB annotation (or the corresponding <ejb-ref-name/> element of the deployment descriptor) to declare an EJB reference in the private namespace of the application and link it to the target bean using the deployment descriptor. Or we use the beanName element of the @EJB annotation (or the corresponding <ejb-link/> element of the deployment descriptor) to do it directly in our code.Mapping an EJB into the Private Namespace Using the first method we’ll end up with the following code in our servlet: @EJB(name = "ejb/bean-name") UniqueLocalBusinessInterface lc;and the following element in the deployment descriptor (web.xml) of our Java EE web module that acts as an EJB client: <ejb-local-ref> <ejb-ref-name>ejb/bean-name</ejb-ref-name> <ejb-ref-type>Session</ejb-ref-type> <local>es.reacts.UniqueLocalBusinessInterface</local> <ejb-link>UniqueLocalSessionEJB</ejb-link> </ejb-local-ref>The <ejb-link/> element contains the bean name that we defined at the beginning of our example with the annotation: @Stateless(name = "UniqueLocalSessionEJB")in the EJB implementation class. Please note that, in this example, we used the @EJB name element explicitely but we could have established the link using its default value. The default value of the name element is: [qualified class name]/[property or field name] that, in this case, would be: es.reacts.ServletTest1/lc The disadvantage of using the default auto-generated name together with EJB linking using <ejb-link/> is that every time you refactor your code you’ll have to check the deployment descriptors. Although developers sometimes think otherwise, the Java EE Specification defines some other roles such as the assambler and the deployer. In large corporate environments, it’s not uncommon for such profiles to override developers’ annotations to “plumb” the components used by the applications. Annotation override is one of the reasons why standard deployment descriptors still exist. This is especially true when references are to remote components, inside or outside your application. For this reason I suggest you do not rely on auto-generated names and use custom well documented names instead. Linking an EJB to a Reference in the Private Namespace The second method provides a direct way to link the reference to its target bean using the beanName element of the @EJB annotation. The servlet code will use the following EJB reference: @EJB(beanName = "UniqueLocalSessionEJB") UniqueLocalBusinessInterface lc;and we need no additional information in the deployment descriptor. Although this method allows the developer to link a reference to an EJB without relying on the deployment descriptor, the suggestion given at the end of the previous section is still valid. Remember that annotations can be overridden at deployment time! Do not link an EJB to a reference if you know beforehand that such a reference is eligible for override. In such cases, prefer assigning a name to the reference instead, as explained in the previous section. Reference: Basic EJB References, Injection and Lookup from our JCG partner Grey at the The Grey Blog. Related Articles :An Introduction to EJB 3.0 Injection and Lookup EJB Programmatic Lookup References to EJBs Outside Your Application With Oracle WebLogic EJB 3.1 Global JNDI Access GWT EJB3 Maven JBoss 5.1 integration tutorial Java Generics Quick Tutorial How does JVM handle locks...
enterprise-java-logo

An Introduction to EJB 3.0 Injection and Lookup

Introduction The Enterprise JavaBeans Specification v. 3.0 introduces a simplified, annotation based API for EJB injection and lookup. EJB 3.0 are now POJOs and can be injected in other components (such as EJBs and Servlets) using simple annotations. EJB 3.0 is one of many other POJO-based specifications that made it to Java EE 6, such as JSR-229 “Contexts and Dependency Injection for the Java EE Platform” (formerly known as “Web Beans”). Java EE has never been so easy! Nevertheless, while EJB 3.0 annotations hide away from the programmer the complexities of assembling a Java EE application and wiring all of its components, there are some subtleties that you should be aware of. Some of them, such as “global JNDI names”, were address by the Enterprise JavaBeans Specification v. 3.1. Meanwhile, until Java EE 6 application servers are widely deployed, you might be exposed to the risk of writing code that relies upon non-portable application server specific behaviour. To make things worse, some of the problems you might encounter show up when using an EJB local interface, which supposedly is an application-scoped interface of a bean of your own. Since local business interfaces actually imply a local method call (they use a pass-by-reference semantics and are restricted to the same JVM instance) such interfaces are the preferred choice when accessing the business interfaces of the components in your application. Often, this use case will make up most of the EJB calls in your Java EE application. Declaring an EJB According to the EJB v. 3.0 Simplified API Specification, when declaring a session bean you may use two annotations, depending on the session bean type:@Stateless @StatefulBoth annotations share two common annotation elements: name and mappedName. name The annotation element name defines the bean “name” and defaults to the unqualified name of the bean class. The bean name must be unique in the scope of the module containing the EJB. mappedName The EJB 3.0 Specification defines mappedName as a “product-specific name that the session bean should be mapped to.” Often, application server use mappedName to map a session bean to a global JNDI name. The EJB 3.1 specification sort of deprecates the mappedName element and introduces the concept of “portable global JNDI name”. We’ll soon see how and when to use such metadata. EJB References To establish a reference to an EJB, you may use the @EJB annotation or the standard deployment descriptors (via <ejb-ref/> and <ejb-local-ref/>). The @EJB annotation is defined as follows: @Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface EJB { String name() default ""; Class beanInterface() default Object.class; String beanName() default ""; String mappedName() default ""; String description() default ""; } name The name element defines the injected EJB name “in the application environment”. The EJB name, then, is the location of the injected object in the private namespace java:comp/env. Its default value it’s the fully qualified name of the annotated class field or property. When the @EJB annotation is used at class level the name element is mandatory. The name element is the equivalent of the <ejb-ref-name/> element in the deployment descriptor: <ejb-ref> <ejb-ref-name>bean name</ejb-ref-name> [...] </ejb-ref>beanInterface The beanInterface is the business interface type of the injected component. By default, it’s the type of the annotated field or property. When the @EJB annotation is used at class level the beanInterface element is mandatory. The beanInterface element is the equivalent of the <remote/> or <local/> elements in the deployment descriptor: <ejb-ref> <ejb-ref-name>bean name</ejb-ref-name> <remote>bean interface</remote> [...] </ejb-ref>beanName The beanName element specifies the bean “name” as declared in the @Stateful and @Stateless annotations via the name element or in the deployment descriptor via the <ejb-name/> element. The beanName element is most useful when more than one EJB implement the same business interface in an application: the beanName lets the developer reference a specific EJB in a specific module. The syntax to use in this case is: <ejb module>#<ejb name>The bean name is resolved automatically if there’s only one EJB implementing the requested business interface in the application. The beanName element is the equivalent of the <ejb-link/> element in the deployment descriptor: <ejb-ref> <ejb-ref-name>bean name</ejb-ref-name> <remote>bean interface</remote> <ejb-link>linked ejb</ejb-link> [...] </ejb-ref>mappedName As in the case of the mappedName element of the @Stateless and @Stateful annotations, the mappedName is a product-specific metadata whose use is not portable. The mappedName element is the equivalent of the <mapped-name/> element in the deployment descriptor: <ejb-ref> <ejb-ref-name>bean name</ejb-ref-name> <remote>bean interface</remote> <ejb-link>linked ejb</ejb-link> <mapped-name>mapped name</mapped-name> [...] </ejb-ref>What About Beans in Other Applications? If you review the mechanisms described so far, you should notice that there’s no (portable) way to declare a dependency (an EJB reference) to a bean outside the application. The EJB Specification v. 3.1 addresses this problem and defines portable global JNDI names. No changes will be required for a compliant EJB v. 3.0 to be assigned a portable global JNDI name in a compliant EJB v. 3.1 container. Meanwhile, to wire a reference to an EJB outside your application, you should rely on the mechanisms provided by your application server. Do Not Rely on Non-Portable Global JNDI Names to Lookup an EJB As outlined in the previous sections, before EJB v. 3.1 there was no portable way to lookup an EJB with a global JNDI name and the deployer has to rely on application server specific tools and metadata to establish a link between an EJB reference and an EJB global JNDI name. Such a link, moreover, is necessary when establishing a reference to a bean outside your application. Even if it’s appealing to avoid using the @EJB annotation elements (or their corresponding deployment descriptor elements) and use global JNDI names instead, you should always rely on EJB references and lookup in your java:comp/env private namespace. Your private namespace and the mapping mechanism provide you the level of indirection that will isolate your code from configuration changes. This also means that, if you’re restricted to EJB v. 3.0, you should always use the beanName (<ejb-link/>) mechanism and performing lookups in your private java:comp/env namespace. Many times I’ve heard the story of some developer inspecting the global JNDI tree of an application server to deduce the application server global JNDI naming scheme for EJBs and then experiencing some NamingException here and there. For this reason, avoid using the @EJB mappedName element and rely on name and beanName instead. Some application servers, for example, publish both remote and local EJB business interfaces with global JNDI names. Others simply don’t. Oracle WebLogic is one of the latter. The EJB v. 3.0 specification, indeed, does not require a local business interface to be available in the global JNDI tree. Looking Up Remote and Local Business Interfaces As far as it concerns the caller, the process of acquiring a reference to a remote and to a local business interface should be identical. Unfortunately, that’s not always the case if you don’t rely only on portable mechanisms. References to local interfaces of EJBs can always be resolved with the beanName mechanism. This is not always the case for references to remote interfaces since such EJB might live outside your application. Here’s, then, another reason not to rely on global JNDI names in your code: not only such a code would be not portable, but it would require you to use different strategies to lookup remote and local business interfaces (depending on the application server.) The business interface type would not be transparent and a change in a business interface type could break your code. An Easy Pattern to Establish EJB References Although they might be necessary in some scenarios, avoid EJB lookups and rely on @EJB references “auto-wiring”. Respecting some easy patterns guarantees that your EJB references will be declared and satisfied in a completely automatic way:Try to reduce the number of EJB that share business interfaces: if just one EJB implement a specific business interface in an application, an EJB reference can be automatically declared and wired with a default @EJB annotation. If sharing business interfaces improves your application design, define a clear naming policy for beans of your application and avoid duplications: if there’s only one bean with a specific name, an EJB reference can be automatically declared and wired with a @EJB(beanName=”[name]“) annotation. If there’s more than one bean with the same name, you’ll be forced to use the @EJB(beanName=”[ejb-module-path]#[ejb-name]“) syntax when declaring references. If you need to lookup EJB references programmatically, declare a location for your EJBs in your local namespace using the @EJB name element (or the <ejb-ref-name/> element) and link it to the target EJB with the @EJB beanName element (or the <ejb-link/> element.)Reference: An Introduction to EJB 3.0 Injection and Lookup from our JCG partner Grey at the The Grey Blog. Related Articles :Basic EJB References, Injection and Lookup EJB Programmatic Lookup References to EJBs Outside Your Application With Oracle WebLogic EJB 3.1 Global JNDI Access GWT EJB3 Maven JBoss 5.1 integration tutorial Java Generics Quick Tutorial How does JVM handle locks...
jboss-hibernate-logo

Hibernate Gotchas to Watch out

I’ve been using Hibernate for some time now and when I don’t work on a hibernate project for a while I find myself doing the same mistakes I did the previous times. So here is a sort of watch list for my self hopefully will be useful to someone else as well. Implement hashCode and equals You should always implement these methods in general but for your entities you should pay a bit more attention.The first thing you think when I say equals is probably to use the Id to distinguish between instance. Well, that’s gonna cause you a lot of troubles. You need to keep in mind that you are working with db entities and not normal POJOs. When Hibernate is fetching objects is your using collections and hence equals and hashCode to know if an object you are looking for is in the session. For new objects id will be null or 0. That means when trying to save two objects of the same class the second is going to overwrite the first one. Also when hibernate saves a new instance it will set the id, thus making it a different object while it is exactly the same. You need to use some business keys. Unique codes are great but if you can’t think of anything just use a meaningful field and some timestamp (like creation date) to make it unique. This is a good reference if you want to understand a bit further what’s happening. Careful with One-to-One and Many-to-One relations   This is something you really need to know. When mapping a relation as One-to-One or Many-to-One on the “One” side of the relation you can’t have lazy loading unless you specify the field as not nullable.Why is that?Essentially on the many side of the relation hibernate can use collection proxies and lazily load instances when required. On the “One” side there is no collection interface but instead a reference to one of your model classes.Hibernate can proxy that one as well but only if it is sure the reference will never be null! So remember if you want to have lazy loading use the not null on the one side together with the lazy annotation (or xml equivalent). If your relation can be null but you still really want to make it lazy then you have some options:Create a value to represent that. For example if you have a relation like Person -&amp;amp;gt;Partner  just use a specific instance of Partner that means “no partner”. Use build time instrumentation. Check this Fake the one side using a List and getting the field with get(0)Read more on the hibernate documentation. Enable the statement logging This is the only way to verify Hibernate is really doing what you expect him to do. Luckily enough there are different logging parameters that you can use to find out what is happening both at the HQL or if you want at the SQL level. You’ll be surprised how many times hibernate is running queries and you did not except it. Try to this from the very beginning and help the team understand the importance of having the best and least possible queries or you’ll surely have performance issue when running the application on some real data. To enable logging just set this property in the session configuration file hibernate.show_sql=trueIf you want to see it nicely formatted add hibernate.format_sql=trueWatch what goes in the toString method.   This one is again related to what Hibernate fetches for you without you really being aware. Lots of times when you see queries but can’t figure out why some lazy list is being loaded then check the toString method. It might be the culprit! What are your hibernate gotchas? Reference: Hibernate Gotchas! from our JCG partner at the Development in progress blog. Related Articles :Hibernate autocommit commands force MySQL in excessive disk I/O DataNucleus 3.0 vs Hibernate 3.5 Hibernate mapped collections performance problems Spring MVC3 Hibernate CRUD Sample Application...
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close