What's New Here?


Web-service learnings with Apache CXF

In my last couple of projects I worked with web-services, creating them at some places and consuming them at others. I felt that the standard tasks like creating a client, creating a web service etc are quite straight forward and there are enough resources if you get stuck. But with web services, it is some trivial task that can take a lot of your time and you feel quite frustrated when you can not get that simple thing right. Logging In one of the projects, we created web-services using Apache CXF and things were working fine. There was just one issue Apache CXF uses java.util logger for logging and used to print all sorts of logs. Our application was using Log4J, so task was simple make use of Log4J for Cxf and control logging. Configuring the logger to use Log4J is a starightfoward task as mentioned on Apache CXF site, here is what the page says: Add the file META-INF/cxf/org.apache.cxf.Logger to the classpath and make sure it contains the following content: org.apache.cxf.common.logging.Log4jLogger Simple you need add a file to the META-INF directory and it will be done. We were having a maven project to generate war, so I created the file in the META-INF folder that gets generated for the war i.e. at src/main/webapp/META-INF. Now, the file is there but the logging was still out of control, CXF was still using java logger. I spent some more time on it to figure out what I have done wrong. Some more effort was required to realize that I have missed and important instruction “in the classpath“. The META-INF folder that gets generated besides the WEB-INF is not in the classpath and a META-INF folder is required in the classes folder of the war. After words looking back at this issue, it was silly for me to miss the classpath part, but also I could not understand why the CXF guys choose the META-INF folder for their configuration files. META-INF is there on Java platform for services and class loaders. It becomes quite ambiguous when frameworks start using it for their configurations and then there are multiple folders to play around, which can make things quite unclear. Soap Handlers At another place we had a requirement where we need to intercept the incoming / outgoing soap requests and then do something with it. Apache CXF provides interceptors that can be used to accomplish this task. You can have some inbound and out bound and they will do as asked. But we were using the jaxws implementation that gets shipped with java. Not intending to shift our existing clients to CXF , as we were having quite a few clients, it took us quite some time to figure it out how you can accomplish this with the jaxws. Basically, according to the JAX-WS specification you can have some SoapHandlers that can be configured with the client. The handler will be called every time there is a SOAP message exchange. In the handler you can determine if this is an in-bound message or an out-bound and then do your logic. These are the steps required to configure a handler : Create a class extending the SoapHandler interface and implement the handle message method: class CustomHandler implements SOAPHandler<SOAPMessageContext>{ // TODO: implement other methods public boolean handleMessage(SOAPMessageContext context) { // Check for message status Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (null == outboundProperty || !outboundProperty) { log.debug("not an outbound message"); return true; } } }Handlers are like servlet filters. They are in a chain and gets called one by one. So we need to create a XML file in which we can configure all the handlers we want. <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <javaee:handler-chains xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <javaee:handler-chain> <javaee:handler> <javaee:handler-class>pkg.CustomHandler</javaee:handler-class> </javaee:handler> </javaee:handler-chain> </javaee:handler-chains>Also the configuration file needs to be in the classpath as this will be imported in the web service clients that we create. After this is done, we need to enable this chain of handlers on a web service client. @WebServiceClient(.....) @HandlerChain(file="handlerFile.xml") public class SampleServiceImpl extends Service{ }The handler concept is from the jaxws specification and would work on all of its implementations like metro, CXF etc. Reference: Web-service learnings from our JCG partner Rahul Sharma at the “The road so far….” blog. Related Articles :Apache CXF Load Balancing And Failover Web Services in Ruby, Python and Java JAX–WS with Spring and Maven Tutorial Spring 3 RESTful Web Services Java Tutorials and Android Tutorials list...

Java SE 7, 8, 9 – Moving Java Forward

Today (NOTE: October 4, 2011) was keynote day. JavaOne Keynote was happening this early morning from 8:30 to 10:30 am and one more time my press pass got me into it quite early. So I had the time taking some very personal pictures from all the key players while they were getting ready and probably nervous. Ballroom A+B is quite a big room. In contrast to last year they changed the arrangement and put the stage on the long side. That brought many people closer to the happenings and it was a great feeling at all. I also partly enjoyed the little warm-up movie. Even if there was a odd feel to it seeing all the diverse people running around. Even if I am slightly overweight, I would prefer to see some very cool kids running through such a video. Anyway: Nice work. Next time please try to get the Black Eyed Peas for that ;) Intel outside please The Keynote began with Doug Fisher, CVP Intel. He brought a number of colleagues onto stage together with their Oracle peers to reviewed Intel’s long association with Java and their optimization work for the Java platform on Intel hardware. it was all about performance gains and being x times faster than they were before. The guys seem to all read from the teleprompters and it really wasn’t a great joy to watch them making jokes they were obviously practicing before. What should I tell you? Nice slides. Next slide deck please!It was boring and would have made a reasonable Open World Keynote at all. Many commercial products in it and not a word about what they really brought forward in terms of Java. This was something I wouldn’t mind if it is missing next year. And this did not get better as Oracle’s Ashok Joshi came onstage to very very briefly introduce Oracle’s NoSQL solutions (hardly without naming it…). You can find out on the web about it. I guess all is out about this one since today. But I will skip the details here until I got my hands on it. Welcome to the Future – Java 7 After a little confusions about who and what is next, Mark Reinhold, Chief Architect of the Java Platform Group appeared on stage and took the attendees on a ride through the recent history of Java 7. All along the way with “Plan B” and the pragmatic approach of including Project Coin (JSR 334), InvokeDynamic (JSR 292), and the Fork/Join Framework. Special guest was Charles Oliver Nutter from Engine Yard. He gave a very brief overview about the performance advantages InvokeDynamic made possible for JRuby.Mark has a good way in presenting and he even got the hardest bits out with lightweight slides and fluent words so it was a pleasure to follow him along the benefits of these key features of Java 7. Most important for all developers is, that “Not only are these features available in Java 7 today,” noted Reinhold, “but as of last week, they are now supported in all three of the major Java IDEs.” Moving forward – Java SE 8 Followed by what was already known since some time Mark detailed the plans for Java 8 a bit. After having the evolutionary release with Java 7 this is going to be a revolutionary one with the features far beyond those introduced with Java 7. Project Lambda (JSR 335) will bring closures to the Java programming language.And Project Jigsaw (JSR TBD) aims to define a standard module system — not just for application code, but for the platform itself. Especially the latest makes it possible to only have the needed bits with your distribution of choice. As he states, there will be Java distributions available starting at 10 MB. A new Java Script Implementation called “Project Nashorn” will also be part of it. Followed by Type Annotations (JSR 308), the new Data/Time API (JSR 310) and Sensors which should be a way to natively connect to a device’s hardware sensors available. “Plus more to come …” is the last bullet point on this slide. So, we have to expect some more stuff beside the ones mentioned. General Availability of JavaFX 2.0 JavaFX was next. As many already expected it took quite some time away from the keynote. Richard Bair, Chief Architect, Client Java Platform, official announced JavaFX 2.0 and gave some stunning demos of the new facilities.According to him, JavaFX 2.0 was designed to offer: - Cross Platform - Leverage Java - Advanced Tooling - Developer Productivity - Amazing User Interfaces.No longer being eye-candy “user interfaces that look good and work well” are a requirement for the things we do, said Bair. The most important aspect of any UI technology are good visual development tools. Surprise was, that the early access for the JavaFX Scene Builder, which will first be made available to select partners, then expanded to a general beta, and then a full release. You can get your hands on and early build it at JavaOne at the DEMOgrounds. Most applause came from the fact, that the official demos and documentations are BSD licensed and part of the bundle, you can download. This simple stuff was followed by a series of stunning demos by Oracle’s Jasper Potts. He showed the possibilities of the new client platform including animated 2D and 3D, audio EQ mapping, and a navigable 3D virtual room that featured live video. Is that Rain? – Java EE 7 in the cloud! With all the rain going on in San Francisco some could think, Oracle did too much with all the cloud topics around. Anyway, Java EE.next as announced last year will be driven by the cloud. Linda DeMichiel, Java EE 7 SpecLead did a nice job explaining the upcoming Java EE 7 release. “We’re moving Java EE into the Cloud.” DeMichiel said. The focus on this release is providing support for Platform as a Service (PaaS). Java EE will provide ways for it’s users to leverage public, private and hybrid clouds.It will all be about the platform as a service itself, which will be leveraged in cloud environments. After a real short general introduction, which could lead to the impression, she is not knowing what she is talking about (which isn’t true btw!) Arun Gupta came on stage. You all know him as the GlassFish and Java EE Evangelist! He demonstrated the latest GlassFish 4.0 Bits with a Java EE 7 cloud deployment. You can do this yourself following the instructions provided at: http://glassfish.java.net/javaone2011/ JavaCard Finally Hinkmond Wong, of Oracle’s Java Embedded group gave an overview of the latest in JavaCard technologies. By that time attendees started moving out of the keynotes. It was a very long one with a lot of topics in general and so I can understand every single one moving out. Interpretation What does all this mean? Any surprises? Anything unclear or need further thoughts? Not really. Compared to last years excitement there are hardly any exciting things on the agenda. Nobody is complaining, no big surprises. This is good. It means we have calmed down a bit. The trust is building and Oracle is obviously doing more stuff in the open (especially the works around OpenJDK should be mentioned here) and we do see a lot of technical progress in the complete platform in general. Of course, we do miss some faces from last year. And knowing a little more than you out there, I can think of a few more things to come over the next few months. But this will not be negative surprises, so it’s easy for me to keep the secrets for some more time. Reference: Java SE 7, 8, 9 – Moving Java Forward from our JCG partner Markus Eisele at the “Enterprise Software Development with Java” blog. Related Articles :Java EE Past, Present, & Cloud 7 Developing and Testing in the Cloud The OpenJDK as the default Java on Linux Official Java 7 for Mac OS X – Status Grow Up Java! Proposing Java Desktop Edition Java Tutorials and Android Tutorials list...

Hibernate by Example – Part 2 (DetachedCriteria)

So last time we helped out justice league to effectively manager their super heroes. Today we focus on how The Avengers will be using Hibernate’s Detached Criteria to find out their enemies with respect to each superhero so as to protect their super heroes. You can download the working example from here. In this example we take only two entities into consideration. The Avenger & The Villain. We build a relationship between the two using a join table. Let us have a look at the domain mappings used in this example. package com.avengers.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Type; /** * The domain class representing each member of the avengers * * @author Dinuka.Arseculeratne * */ @Entity @Table(name = "Avengers") public class Avenger implements Serializable { /** * The primary key of the Avenger table */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "avenger_id") private Long avengerId; /** * The name of the avenger member */ @Column(name = "avenger_name") private String avengerName; /** * A flag which holds whether the avenger's powers are awesome */ @Type(type = "yes_no") @Column(name = "is_awesome") private boolean isAwesome; /** * The list of enemies the avenger has */ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable(name = "AVENGERS_AND_VILLAINS", joinColumns = { @JoinColumn(name = "avenger_id") }, inverseJoinColumns = { @JoinColumn(name = "villain_id") }) private List<Villain> enemyList = new ArrayList<Villain>(); public Long getAvengerId() { return avengerId; } public void setAvengerId(Long avengerId) { this.avengerId = avengerId; } public String getAvengerName() { return avengerName; } public void setAvengerName(String avengerName) { this.avengerName = avengerName; } public boolean isAwesome() { return isAwesome; } public void setAwesome(boolean isAwesome) { this.isAwesome = isAwesome; } public List<Villain> getEnemyList() { return enemyList; } public void addEnemy(Villain enemy) { enemyList.add(enemy); } @Override public String toString() { return "Avenger [avengerId=" + avengerId + ", avengerName=" + avengerName + ", isAwesome=" + isAwesome + ", enemyList=" + enemyList + "]"; } }This class maps an avenger. I have used minimal fields in order to keep this example as simple and short as possible. And the Villain domain looks as follows; package com.avengers.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.Type; /** * This class represents the Villain forces against the avengers * * @author Dinuka.Arseculeratne * */ @Entity @Table(name = "Villains") public class Villain implements Serializable { /** * The primary key of the Enemy table */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "villain_id") private Long villaiId; /** * The name of the enemy */ @Column(name = "villain_name") private String villainName; /** * A flag which checks whether the villain is super awesome */ @Type(type = "yes_no") @Column(name = "is_awesome") private boolean isAwesome; public Long getVillaidId() { return villaiId; } public void setVillaidId(Long villaidId) { this.villaiId = villaidId; } public String getVillainName() { return villainName; } public void setVillainName(String villainName) { this.villainName = villainName; } public boolean isAwesome() { return isAwesome; } public void setAwesome(boolean isAwesome) { this.isAwesome = isAwesome; } @Override public String toString() { return "Villain [villaiId=" + villaiId + ", villainName=" + villainName + ", isAwesome=" + isAwesome + "]"; } }Ok now that we have defined our domains, let us see how data retrieval happens with DetachedCriteria. I have used DetachedCriteria here because The Avengers were very specific and said they do not want anything to do with the Hibernate session, so hence i used DetachedCriteria which does not require a hibernate session to be present. Our primary objective is to retrieve The Avenger to whom a villain belongs to. Note that this assumes the same villain cannot be a villain to more than one superhero. So moving on i give below the method that retrieves an avenger based on the villain name passed. public Avenger retrieveAvengerByVillainName(String villainName) { Avenger avenger = null; /** * Selected a detached criteria so we do not need a session to run it * within. */ DetachedCriteria criteria = DetachedCriteria.forClass(Avenger.class); /** * Here we are doing an inner join with the Villain table in order to do * a name comparison with the villainName passed in as a method * parameter */ DetachedCriteria villainCriteria = criteria.createCriteria("enemyList"); villainCriteria.add(Restrictions.eq("villainName", villainName)); villainCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); @SuppressWarnings("unchecked") List<Avenger> avengerList = getHibernateTemplate().findByCriteria( criteria); if (!avengerList.isEmpty()) { avenger = avengerList.get(0); getHibernateTemplate().initialize(avenger.getEnemyList()); } return avenger; }In this method what we do is first we create a criteria for our master class which in this case is Avenger.class. Then we need to do a join with the Villain table and hence we create a sub criteria from our main criteria with the name of the list we defined within the Avenger domain class. Then it is a matter of equaling the property of the Villain domain to the villain name passed in. The power of the Criteria API is such that you can create dynamic queries with ease which would be a hassle if we were to use pure HQL which would require substantial string concatenations in order to achieve the same. A sample test class called AvengerTest.java is given with the attachment which you can find at the top of the most. Note that you need to remove the comment on avenger-context.xml in order to create the tables needed for this example. So that is about it. The Avengers can be risk averse now that they have a system by which they can relate any super villain to a super hero within their league. As always your comments and suggestions are always welcome and appreciated. Thank you for taking the time to read!!!! Reference: Hibernate by Example – Part 2 (DetachedCriteria) from our JCG partner Dinuka Arseculeratne  at the My Journey Through IT blog Related Articles :Hibernate by Example – Part 1 (Orphan removal) Hibernate Gotchas to Watch out 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 Tutorials and Android Tutorials list...

Hibernate by Example – Part 1 (Orphan removal)

So i thought to do a series of hibernate examples showing various features of hibernate. In the first part i wanted to show about the Delete Orphan feature and how it may be used with the use of a story line. So let us begin :) Prerequisites: In order for you to try out the following example you will need the below mentioned JAR files:org.springframework.aop-3.0.6.RELEASE.jarorg.springframework.asm-3.0.6.RELEASE.jarorg.springframework.aspects-3.0.6.RELEASE.jarorg.springframework.beans-3.0.6.RELEASE.jarorg.springframework.context.support-3.0.6.RELEASE.jarorg.springframework.context-3.0.6.RELEASE.jarorg.springframework.core-3.0.6.RELEASE.jarorg.springframework.jdbc-3.0.6.RELEASE.jarorg.springframework.orm-3.0.6.RELEASE.jarorg.springframework.transaction-3.0.6.RELEASE.jar.org.springframework.expression-3.0.6.RELEASE.jarcommons-logging-1.0.4.jarlog4j.jaraopalliance-1.0.jardom4j-1.1.jarhibernate-commons-annotations-3.2.0.Final.jarhibernate-core-3.6.4.Final.jarhibernate-jpa-2.0-api-1.0.0.Final.jarjavax.persistence-2.0.0.jarjta-1.1.jarjavassist-3.1.jarslf4j-api-1.6.2.jarmysql-connector-java-5.1.13-bin.jarcommons-collections-3.0.jarFor anyone who want the eclipse project to try this out, you can download it with the above mentioned JAR dependencies here. Introduction: Its year 2011. And The Justice League has grown out of proportion and are searching for a developer to help with creating a super hero registering system. A developer competent in Hibernate and ORM is ready to do the system and handle the persistence layer using Hibernate. For simplicity, He will be using a simple stand alone application to persist super heroes. This is how this example will layout:Table design Domain classes and Hibernate mappings DAO & Service classes Spring configuration for the application A simple main class to show how it all worksLet the Journey Begin…………………. Table Design: The design consists of three simple tables as illustrated by the diagram below;As you can see its a simple one-to-many relationship linked by a Join Table. The Join Table will be used by Hibernate to fill the Super hero list which is in the domain class which we will go on to see next. Domain classes and Hibernate mappings: There are mainly only two domain classes as the Join table in linked with the primary owning entity which is the Justice League entity. So let us go on to see how the domain classes are constructed with annotations; package com.justice.league.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.Type; @Entity @Table(name = "SuperHero") public class SuperHero implements Serializable { /** * */ private static final long serialVersionUID = -6712720661371583351L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "super_hero_id") private Long superHeroId; @Column(name = "super_hero_name") private String name; @Column(name = "power_description") private String powerDescription; @Type(type = "yes_no") @Column(name = "isAwesome") private boolean isAwesome; public Long getSuperHeroId() { return superHeroId; } public void setSuperHeroId(Long superHeroId) { this.superHeroId = superHeroId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPowerDescription() { return powerDescription; } public void setPowerDescription(String powerDescription) { this.powerDescription = powerDescription; } public boolean isAwesome() { return isAwesome; } public void setAwesome(boolean isAwesome) { this.isAwesome = isAwesome; } } As i am using MySQL as the primary database, i have used the GeneratedValue strategy as GenerationType.AUTO which will do the auto incrementing whenever a new super hero is created. All other mappings are familiar to everyone with the exception of the last variable where we map a boolean to a Char field in the database. We use Hibernate’s @Type annotation to represent true & false as Y & N within the database field. Hibernate has many @Type implementations which you can read about here. In this instance we have used this type. Ok now that we have our class to represent the Super Heroes, lets go on to see how our Justice League domain class looks like which keeps tab of all super heroes who have pledged allegiance to the League. package com.justice.league.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "JusticeLeague") public class JusticeLeague implements Serializable { /** * */ private static final long serialVersionUID = 763500275393020111L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "justice_league_id") private Long justiceLeagueId; @Column(name = "justice_league_moto") private String justiceLeagueMoto; @Column(name = "number_of_members") private Integer numberOfMembers; @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, orphanRemoval = true) @JoinTable(name = "JUSTICE_LEAGUE_SUPER_HERO", joinColumns = { @JoinColumn(name = "justice_league_id") }, inverseJoinColumns = { @JoinColumn(name = "super_hero_id") }) private List<SuperHero> superHeroList = new ArrayList<SuperHero>(0); public Long getJusticeLeagueId() { return justiceLeagueId; } public void setJusticeLeagueId(Long justiceLeagueId) { this.justiceLeagueId = justiceLeagueId; } public String getJusticeLeagueMoto() { return justiceLeagueMoto; } public void setJusticeLeagueMoto(String justiceLeagueMoto) { this.justiceLeagueMoto = justiceLeagueMoto; } public Integer getNumberOfMembers() { return numberOfMembers; } public void setNumberOfMembers(Integer numberOfMembers) { this.numberOfMembers = numberOfMembers; } public List<SuperHero> getSuperHeroList() { return superHeroList; } public void setSuperHeroList(List<SuperHero> superHeroList) { this.superHeroList = superHeroList; } } The important fact to note here is the annotation @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, orphanRemoval = true). Here we have set orphanRemoval = true. So what does that do exactly? Ok so say that you have a group of Super Heroes in your League. And say one Super Hero goes haywire. So we need to remove Him/Her from the League. With JPA cascade this is not possible as it does not detect Orphan records and you will wind up with the database having the deleted Super Hero(s) whereas your collection still has a reference to it. Prior to JPA 2.0 you did not have the orphanRemoval support and the only way to delete orphan records was to use the following Hibernate specific(or ORM specific) annotation which is now deprecated; @org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) But with the introduction of the attribute orphanRemoval, we are now able to handle the deletion of orphan records through JPA. Now that we have our Domain classes DAO & Service classes: To keep with good design standards i have separated the DAO(Data access object) layer and the service layer. So let us see the DAO interface and implementation. Note that i have used HibernateTemplate through HibernateDAOSupport so as to keep away any Hibernate specific detail out and access everything in a unified manner using Spring. package com.justice.league.dao; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.justice.league.domain.JusticeLeague; @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public interface JusticeLeagueDAO { public void createOrUpdateJuticeLeagure(JusticeLeague league); public JusticeLeague retrieveJusticeLeagueById(Long id); }In the interface layer i have defined the Transaction handling as Required. This is done so that whenever you do not need a transaction you can define that at the method level of that specific method and in more situations you will need a transaction with the exception of data retrieval methods.  According to the JPA spec you need a valid transaction for insert/delete/update functions. So lets take a look at the DAO implementation; package com.justice.league.dao.hibernate; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.justice.league.dao.JusticeLeagueDAO; import com.justice.league.domain.JusticeLeague; @Qualifier(value="justiceLeagueHibernateDAO") public class JusticeLeagueHibernateDAOImpl extends HibernateDaoSupport implements JusticeLeagueDAO { @Override public void createOrUpdateJuticeLeagure(JusticeLeague league) { if (league.getJusticeLeagueId() == null) { getHibernateTemplate().persist(league); } else { getHibernateTemplate().update(league); } } @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = false) public JusticeLeague retrieveJusticeLeagueById(Long id){ return getHibernateTemplate().get(JusticeLeague.class, id); } } Here i have defined an @Qualifier to let Spring know that this is the Hibernate implementation of the DAO class. Note the package name which ends with hibernate. This as i see is a good design concept to follow where you separate your implementation(s) into separate packages to keep the design clean. Ok lets move on to the service layer implementation. The service layer in this instance is just acting as a mediation layer to call the DAO methods. But in a real world application you will probably have other validations, security related procedures etc handled within the service layer. package com.justice.league.service; import com.justice.league.domain.JusticeLeague; public interface JusticeLeagureService { public void handleJusticeLeagureCreateUpdate(JusticeLeague justiceLeague); public JusticeLeague retrieveJusticeLeagueById(Long id); }package com.justice.league.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.justice.league.dao.JusticeLeagueDAO; import com.justice.league.domain.JusticeLeague; import com.justice.league.service.JusticeLeagureService; @Component("justiceLeagueService") public class JusticeLeagureServiceImpl implements JusticeLeagureService { @Autowired @Qualifier(value = "justiceLeagueHibernateDAO") private JusticeLeagueDAO justiceLeagueDAO; @Override public void handleJusticeLeagureCreateUpdate(JusticeLeague justiceLeague) { justiceLeagueDAO.createOrUpdateJuticeLeagure(justiceLeague); } public JusticeLeague retrieveJusticeLeagueById(Long id){ return justiceLeagueDAO.retrieveJusticeLeagueById(id); } }Few things to note here. First of all the @Component binds this service implementation with the name justiceLeagueService within the spring context so that we can refer to the bean as a bean with an id of name justiceLeagueService. And we have auto wired the JusticeLeagueDAO and defined an @Qualifier so that it will be bound to the Hibernate implementation. The value of the Qualifier should be the same name we gave the class level Qualifier within the DAO Implementation class. And Lastly let us look at the Spring configuration which wires up all these together; Spring configuration for the application: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.justice.league" /> <context:annotation-config /> <tx:annotation-driven /> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="packagesToScan"> <list> <value>com.justice.league.**.*</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop> <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/my_test</prop> <prop key="hibernate.connection.username">root</prop> <prop key="hibernate.connection.password">password</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> </props> </property> </bean> <bean id="justiceLeageDAO" class="com.justice.league.dao.hibernate.JusticeLeagueHibernateDAOImpl"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>Note that i have used the HibernateTransactionManager in this instance as i am running it stand alone. If you are running it within an application server you will almost always use a JTA Transaction manager. I have also used auto creation of tables by hibernate for simplicity purposes. The packagesToScan property instructs to scan through all sub packages(including nested packaged within them) under the root package com.justice.league.**.* to be scanned for @Entity annotated classes. We have also bounded the session factory to the justiceLeagueDAO so that we can work with the Hibernate Template. For testing purposes you can have the tag <prop key=”hibernate.hbm2ddl.auto”>create</prop> initially if you want, and let hibernate create the tables for you. Ok so now that we have seen the building blocks of the application, lets see how this all works by first creating some super heroes within the Justice League A simple main class to show how it all works: As the first example lets see how we are going to persist the Justice League with a couple of Super Heroes; package com.test; import java.util.ArrayList; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.justice.league.domain.JusticeLeague; import com.justice.league.domain.SuperHero; import com.justice.league.service.JusticeLeagureService; public class TestSpring { /** * @param args */ public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "spring-context.xml"); JusticeLeagureService service = (JusticeLeagureService) ctx .getBean("justiceLeagueService"); JusticeLeague league = new JusticeLeague(); List<SuperHero> superHeroList = getSuperHeroList(); league.setSuperHeroList(superHeroList); league.setJusticeLeagueMoto("Guardians of the Galaxy"); league.setNumberOfMembers(superHeroList.size()); service.handleJusticeLeagureCreateUpdate(league); } private static List<SuperHero> getSuperHeroList() { List<SuperHero> superHeroList = new ArrayList<SuperHero>(); SuperHero superMan = new SuperHero(); superMan.setAwesome(true); superMan.setName("Clark Kent"); superMan.setPowerDescription("Faster than a speeding bullet"); superHeroList.add(superMan); SuperHero batMan = new SuperHero(); batMan.setAwesome(true); batMan.setName("Bruce Wayne"); batMan.setPowerDescription("I just have some cool gadgets"); superHeroList.add(batMan); return superHeroList; } } And if we go to the database and check this we will see the following output; mysql> select * from superhero; +---------------+-----------+-----------------+-------------------------------+ | super_hero_id | isAwesome | super_hero_name | power_description | +---------------+-----------+-----------------+-------------------------------+ | 1 | Y | Clark Kent | Faster than a speeding bullet | | 2 | Y | Bruce Wayne | I just have some cool gadgets | +---------------+-----------+-----------------+-------------------------------+ mysql> select * from justiceleague; +-------------------+-------------------------+-------------------+ | justice_league_id | justice_league_moto | number_of_members | +-------------------+-------------------------+-------------------+ | 1 | Guardians of the Galaxy | 2 | +-------------------+-------------------------+-------------------+So as you can see we have persisted two super heroes and linked them up with the Justice League. Now let us see how that delete orphan works with the below example; package com.test; import java.util.ArrayList; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.justice.league.domain.JusticeLeague; import com.justice.league.domain.SuperHero; import com.justice.league.service.JusticeLeagureService; public class TestSpring { /** * @param args */ public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "spring-context.xml"); JusticeLeagureService service = (JusticeLeagureService) ctx .getBean("justiceLeagueService"); JusticeLeague league = service.retrieveJusticeLeagueById(1l); List<SuperHero> superHeroList = league.getSuperHeroList(); /** * Here we remove Batman(a.k.a Bruce Wayne) out of the Justice League * cos he aint cool no more */ for (int i = 0; i < superHeroList.size(); i++) { SuperHero superHero = superHeroList.get(i); if (superHero.getName().equalsIgnoreCase("Bruce Wayne")) { superHeroList.remove(i); break; } } service.handleJusticeLeagureCreateUpdate(league); } } Here we first retrieve the Justice League record by its primary key. Then we loop through and remove Batman off the League and again call the createOrUpdate method. As we have the remove orphan defined, any Super Hero not in the list which is in the database will be deleted. Again if we query the database we will see that batman has been removed now as per the following; mysql> select * from superhero; +---------------+-----------+-----------------+-------------------------------+ | super_hero_id | isAwesome | super_hero_name | power_description | +---------------+-----------+-----------------+-------------------------------+ | 1 | Y | Clark Kent | Faster than a speeding bullet | +---------------+-----------+-----------------+-------------------------------+So that’s it. The story of how Justice League used Hibernate to remove Batman automatically without being bothered to do it themselves. Next up look forward to how Captain America used Hibernate Criteria to build flexible queries in order to locate possible enemies. Watch out!!!! Have a great day people and thank you for reading!!!! If you have any suggestions or comments pls do leave them by. Reference: Hibernate by Example – Part 1 (Orphan removal) from our JCG partner Dinuka Arseculeratne  at the My Journey Through IT blog Related Articles :Hibernate Gotchas to Watch out 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 Tutorials and Android Tutorials list...

What Is CDI, How Does It Relate to @EJB And Spring?

A brief overview of dependency injection in Java EE, the difference between @Resource/@EJB and @Inject, and how does that all relate to Spring – mostly in the form of links. Context Dependency Injection (CDI, JSR 299) is a part of Java EE 6 Web Profile and itself builds on Dependency Injection for Java (JSR 330), which introduces @Inject, @Named etc. While JSR 330 is for DI only and is implemented e.g. by Guice and Spring, CDI adds various EE stuff such as @RequestScoped, interceptors/decorators, producers, eventing and a base for integration with JSF, EJBs etc. Java EE components such as EJBs have been redefined to build on top of CDI (=> @Stateless is now a CDI managed bean with additional services). A key part of CDI aside of its DI capabilities is its awarness of bean contexts and the management of bean lifecycle and dependencies within those contexts (such as @RequestScoped or @ConversationScoped). CDI is extensible – you can define new context scopes, drop-in interceptors and decorators, make other beans (e.g. from Spring) available for CDI. Resources to check:Contexts and Dependency Injection in Java EE 6 by Adam Bien – a very good explanation of the basics of CDI and how it differs from DI in Java EE 5 (hint: context awarness) Slideshow with a good overview of CDI and all it offers About CDI extensibility and SPIs (e.g. Seam 3 is basically a set of portable CDI extensions) Guice and Spring do not implement CDI (3/2011) – and Spring perhaps isn’t motivated to do so (it supports JSR 330, CDI would be too much work) DZone CDI Refcard may be handy CDI 1.0 vs. Spring 3.1 feature comparsion: bean definition & dependency injection: “in the area that I compared in this article [= DI], there is only little critical difference in the two technologies” (though Spring more fine-tunable) Java EE 6 (CDI / EJB 3.1) XOR Spring Core Reloaded: New projects should preferably start with pure Java EE including CDI and add Spring utilities such as JDBC/JMS when needed Oracle: CDI in the Java EE 6 Ecosystem – 62 pages slideshow, the stuff is explained more than in the previously mentioned slideshowNote: CDI 1.1 (JSR 346, Java EE 7) should have a standard way of bootstrapping it in non-EE environment (i.e. SE). Reference: What Is CDI, How Does It Relate to @EJB And Spring? from our JCG partner at the Holy Java blog. Related Articles :Java EE6 CDI, Named Components and Qualifiers Java EE6 Decorators: Decorating classes at injection time Java Modularity Approaches – Modules, modules, modules On domain-driven design, anemic domain models, code generation, dependency injection and more… Basic EJB References, Injection and Lookup Java Tutorials and Android Tutorials list...

Writing Code that Doesn’t Suck

Striving to write good code should be the goal of every Software Developer. Writing code that is easily maintainable, robust, simple, and makes sense is no easy task. It takes years of practice and uncountable hours of time to become a good Programmer, and the job is never really done. Recently I ran across these few lines of code that break many of the following tips I’m going to give you. I’ve seen some code that the Developer who wrote it clearly didn’t understand. It contained no error handling cases and only worked in the success case (1 out of 50 paths). In every other path it would fail! For example, in one situation, 10 variables are created (none are initialized, another problem) with names of x,x1,x2,x3,x4,x5… and so on. The Developer then proceeded to use these 10 variables in the next 500 lines of code. When I asked the Developer what these variables actually were, he couldn’t even explain it to me! With the above in mind, I thought of a few tips that would really help a few people write much better code. I realize that a good amount of the following tips are CS101 type comments, but without even following these, you have no hope of writing any sort of manageable code. How to combat it: Communication It’s far better to ask someone for help if you don’t understand how something should be done than to write some spaghetti code that may solve the problem for the Success now, but may become a minefield for every other case later on. Following some basic steps when writing codeNull checks – Don’t create mind field code that crashes on specific cases that you haven’t checked for Simplicity Don’t write 4 lines of code when 2 will do. If a block of code requires more lines of comments to explain what it does than the code itself, you need to rethink how it’s being done Comment frequently Having the problem of too many comments is always a better situation to be in than having no comments at all. I would rather see a story describing some method/function than no comments at all. Name variables that make sense Names like X and B are simply no help, and they show that you were simply too lazy to write a more descriptive name of the variable. This will quickly come back to haunt you when the code gets even slightly more complicated. Take the time to make informative variable names! You will thank yourself later.FactorizationAvoid Copy/Paste of Code! If you need to use a block of code over, it’s time to refactor that code into a function/method Anytime you can simplify code that has been written, do so! Reuse any code that is written as much as possible Always try to improve the code you have written.All right. I’ll get off my soap box now. I hope these tips help you become a better programmer. Feel free to let me know if you have some tips of your own. Reference: Writing Code that Doesn’t Suck from our JCG partner Isaac at the Prgramming Mobile blog. Related Articles :How many bugs do you have in your code? Java Tools: Source Code Optimization and Analysisr (MAT) Not doing Code Reviews? What’s your excuse? Code quality matters to the customers. A lot. Why Automated Tests Boost Your Development Speed Java Tutorials and Android Tutorials list...

Dealing with technical debt

We’re drowning in technical debt. We have a mountain to climb and don’t really know where to start. Sound familiar? For many of us working on legacy code bases this is the day-to-day reality. But what to do about it? How did we get here? Technical debt is always the fault of those “other guys”. Those idiot developers that were here a few years ago. Morons. Obviously couldn’t code their way out of a game of life if their on-going existence depended on it. I hate to tell you but: we are those other guys. The decisions we make today will look foolish tomorrow. We’ll have more information then, a different perspective; we’ll know how the product and technology were going to evolve. We can’t know that today, so many of our decisions will turn out to be wrong. Where to start Classes are like best-selling novels – some are spectacularly more popular / more debt-laden than others. One class, one package, one module – will be much worse than the others. There’ll be a handful of classes, packages etc… that are much worse than all the rest. How does this happen? Well, one class ends up with a bit of technical debt. Next time I come to change that class, I’m too lazy to fix the debt, so I just hack something together to get the new feature done. Then next time round, there’s a pile of debt – only that guy’s too busy to fix it so he adds in a couple of kludges and leaves it. Before you know it, this one class has become a ten thousand line monster that’s pure technical debt. It’s like the broken-windows theory – if code is already crappy, its much easier to just make it a little more crappy. If the code’s clean, it’s a big step to add in a hack. So little by little, technical debt accumulates in areas that were already full of debt. I suspect technical debt in code follows a power law – most classes have a little bit of debt, but a few are really shitty, with one diabolical class in particular:Where to start? Resist the temptation to make easy changes to relatively clean classes – start with the worst offender. It will be the hardest to fix, it might take a long time – but you’ll get the best bang-for-buck by fixing the most debt-heavy piece of crap code. If you can fix the worst offender, your debt will have to find somewhere else to hide. The 80/20 rule There’s a cliché that 80% of the cost of software is maintenance, only 20% is the initial build. Let’s imagine a team that has 1200 hours a month to spend on useful work. For that 1200 hours of useful work, we’ll spend four times that much over the lifetime of the software maintaining it – from the 80/20 rule. Although we completed 1200 hours of feature work this month, we committed ourselves to 4800 hours of maintenance over the lifetime of the code. That means next month, we have to spend a little of the 4800 hours of maintenance, with the rest of the time spent on useful, feature-adding work. However, adding new features commits us to even more maintenance work. The following month, we’ve got nearly twice the code to maintain so spend nearly twice the amount of time maintaining it and even less time producing value-adding features. Month-by-month we spend more and more time dealing with the crap that was there before and less and less time adding new features.Does this sound familiar? This is what technical debt feels like. After a couple of years the pace has dropped; you’re spending half your time refactoring and fixing the junk that was there before. “If only we could get rid of this technical debt”, you cry. What is technical debt? We can all point to examples of crappy, debt-laden code we’ve seen. But what’s the impact of technical debt? Technical debt is simply an inability to quickly make changes to an existing system. This is the cost to the business of technical debt – what should be quick changes take an unpredictably long time. What do we do when we remove technical debt? We generalize and find more abstract solutions. We clarify and simplify. We remove duplication and unnecessary complexity. The net effect of reducing technical debt, is to reduce inventory. Perhaps the amount of code – our inventory – is a good approximation for the amount of technical debt in a system. If I’m confronted with a million lines of code and need to make a change, it will probably take a while. However, if I’m only confronted by 1000 lines of code the change will be much quicker. But, if I’m confronted by zero lines of code, then there’s zero cost – I can do whatever I like. The cost of making a change to a system is roughly proportional to the size of the system. Large, complex systems take longer to make changes to than small, self-contained ones. All code is a liability – the more code you have, the bigger the debt. When we’re paying back technical debt – are we really just reducing inventory? Is what feels like technical debt actually interest payments on all the inventory we hold? What are the options? Big bang One option is to down-tools and fix the debt. Not necessarily throw everything out and rewrite, but spend some time cleaning up the mess. The big bang approach to dealing with technical debt. It’s pretty unusual for the business to agree to a plan like this – no new features for a year? Really? With no new features for a year what would all those product managers do all day? From the 80/20 rule, the lifetime cost for any piece of code is four times what it cost to create. If it took three months to make, it will take a year to pay back. So wait, we’re gonna down tools for a year and only pay back three months of technical debt? Seriously? We’ll be marginally better off – but we’ll still be in a debt-laden-hell-hole and we’ll have lost a year’s worth of features. No way! Dedicated Team Even if you try to do big bang, it ends up becoming the dedicated team approach. As a compromise, you get a specific team together to fix the debt, meanwhile everyone else carries on churning out new features. One team are removing debt; while another team are re-adding it. What are the chances that debt is being removed faster than it’s being added? Exactly. Nil. It makes sense – you need a team removing debt four times bigger than the team adding new features just to stay still. Boy Scout You could adopt a policy of trying to remove technical debt little and often – the boy scout approach. On every single development task try and remove debt near where you’re working. If there are no tests, add some. If the tests are poor, improve them. If the code’s badly factored, refactor it. The boy scout rule – leave the camp cleaner than you found it. This is generally much easier to sell, there’s only minimal impact on productivity: it’s much cheaper to make changes to a part of the system you understand and are already working in than to open up whole new ones. But over time you can massively slow down the rate at which debt grows. Inevitably the system will still grow, inevitably the amount of debt will increase. But if you can minimise the maintenance cost you’ll keep the code small and nimble for as long as possible. Professionalism If we can lessen the maintenance cost of code even just a little we can save ourselves a fortune over the life of the code. If we can reduce the multiple to just three times the initial cost, so our 1200 hours work only costs 3600 hours in maintenance, we’ve saved enough development capacity to build another feature of the same size! For free! Hey, product manager, if we do our job better it’ll take no longer and you’ll get free features. Who doesn’t want free features? If we can create well-crafted, DRY, SOLID code with good test coverage we have a good chance of minimising the lifetime maintenance cost. This is the best way we can keep our productivity up, to try and avoid getting mired in technical debt and keep the code base responsive to changing requirements. It’s the only way we can remain productive and agile. Frankly, anything else is just unprofessional. If you’re deliberately committing your company to spend excessive amounts maintaining your shitty code – what the fuck, exactly, are they paying you for? Reference: Dealing with technical debt from our JCG partner at the Actively Lazy blog. Related Articles :The true cost of technical debt If I had more time I would have written less code Services, practices & tools that should exist in any software development house On the importance of communication in the workplace You can’t be Agile in Maintenance? This comes BEFORE your business logic! You can’t be Agile in Maintenance? Java Tutorials and Android Tutorials list...

Eclipse 3.6 vs IntelliJ IDEA 10.5: Pros and Cons

After having worked with Eclipse for over 5 years I’ve came to use IntelliJ IDEA intensively on a J2EE project in three months and took this as an opportunity to compare the two. You can’t really compare 5 years and 3 months but I still believe that it is long enough to get a pretty good overview of what a tool is like. For the impatient: IntelliJ is a very good tool, its killing feature for me is its excellent support for other languages such as Groovy (e.g. for unit tests) and Clojure. Many details are more worked-out and with a higher usability then in Eclipse, f.ex. search & replace with match highlighting and replacement preview. Its support for navigability and refactoring across multiple languages (Java, JSP, JSF, HQL, Spring config in my case) is also an absolutely great feature for productivity. And of course I have to add it credits for being a Czech product [1] (interestingly enough, NetBeans also comes from the Czech Republic [2]; it’s a pity Eclipse hasn’t this link too. My main issue with IntelliJ is its performance. First, running tests is slow because IntelliJ only does (re)compile the test/source when you hit the run button as opposed to Eclipse’ incremental compilation. And that makes TDD very painful. (I tried to use the old Eclipse Mode plugin but it has problems with IntelliJ 9/10.) Second, sometimes the UI freezes* and you have to wait seconds or tens of seconds for it to respond again (even after disabling most plugins and some analysis). It doesn’t happen too often but often enough to be noticed, to be annoying, and to interrupt the development flow. (*) Update: UI freezes may be a specific issue of Mac 64b 1.6 JDK So I guess I’ll use either Eclipse or IntelliJ with respect to the needs of the project at hand and hope for IntelliJ to resolve its performance issues (as NetBeans did). The Software ComparedEclipse 3.6 – I’ve worked with Eclipse since 3.0 or may be even before on many commercial projects IntelliJ IDEA Ultimate (the commercial, full-featured edition; II community is good enough unless you need special support for frameworks like JavaEE, Spring, and Hibernate – see the editions comparison)What’s Cool in IntelliJ IDEA The things I’ve stumbled upon and considered them noteworthy (there are certainly more of such goodies):Great support for Groovy and Clojure (and others). I’ve used Groovy to write unit tests for my Java project and it worked pretty well (only click + Alt+Enter on a non-existing method to create it didn’t work unless the target class was a nested (static) class in the test itself) Out-of-the-box support for Spring*, namely you can click a bean class name in the applicationContext.xml to jump to it, deprecated classes are struck out, bean definitions are validated against available constructors and setters Refactoring Move can move more members/methods at once Move method is aware of the current class’ field of the target type so it is able to automatically insert fieldOfTargetType.movedMethod() – st- I miss a lot in Eclipse Rename takes care also of JSF EL expressions in JSPs and other non-Java references (I suppose it is more clever than just a simple text search & replace) Completion proposals are displayed as you type (without pressing a hotkey – I love that) AND they include types that haven’t been imported yet (@BeforeClass in a test…) (Auto)Completion proposals over multiple languages CSS classes in JSPs (and in CSS/style it proposes e.g. color names) Click-through in JSF EL expressions (well, at least sometimes) Usage search can find also method usages in JSPs, Spring config etc. Debugging The Variables window automatically shows not only the local variables but also expressions based on them that are used in the code such as “array_variable.length”- a good time saver JavaDoc: Closing tag completion – I’ve always missed that so much in Eclipse! When you generate a foreach loop (“itco” + tab) and change the source collection then it updates the element type automatically (in “for (Type t: sourceColl)”) Really helpful RegExp integration in find & replace in file – when typing, it shows both the first matched expression and what it will be replaced with General: Good at guessing resonable names for variables, … Possibility to define a module for a subdirectory of the main module => you may have a project using Java 1.4 with tests in Java 5+. Works great with Maven multi-module projects too. The Project view displays directly Java types so you can distinguish a class from an interface at the first glance (Eclipse shows a file icon and you need to expand it first) The Java file structure view can show a “property” instead of a getter and a setter, making it shortet and easier to find what’s really important(*) The Ultimate edition only (likely) I’d recommend reading also the responses to the StackOverflow question Things possible in IntelliJ that aren’t possible in Eclipse? – among others they mention click-through anything, autocomplete taking into account more of the context (e.g. the name of the variable), the rename method refactoring updating also JSPs, Spring config, etc.. In general I’d say that IntelliJ has strong focus on usability and productivity, tries to understand what developers usually do and need and helps them with that and is pretty good at it. The authors claim it to be “The Most Intelligent Java IDE” and I think they do not exaggerate (or at least not too much). Not So Cool (In no particular order.)Eclipse only needs two hotkeys: Completion (^space) for class/property/templates/surround-with and Quick Fix (^1 – the most powerful tool in E.) for fixes such as imports, refactorings etc. In II you’ve several hotkeys for completion, one for live templates, one for fixes (intentions) … – I’ve never managed to remember them all and to decide which one I should use in a particular situation No JavaDoc popup on mouse over (need ^J) The Live Template editor sucks, at least under Mac (can’t type end-of-line, a curly bracket on Norwegian keyboard with Alt+Shift+8, backspace, …). Fortunately you can select a code in an editor and Tools | Save as Live Template (though you should likely un-indent it first) No favorite static imports – for the first static method of a particular class I have to: 1) write the start of the method name; 2) press Ctrl+Alt+Space (Class name completion, don’t ask me why this); 3) select the desired method such as CoreMatchers.allOf and press Alt+Enter as suggested in the pop-up’s “status bar” -> select Import statically. Since that on, all the static methods of the class will appear in the normal Ctrl+Space completion list (that’s nice, though). In Eclipse I can add my belowed JUnit/Hamcrest/Mockito friends to favorite imports and have them always available. Slowness Slow testing – changed files are compiled just before a test is run while in Eclipse they have been compiled as soon as they were saved Sometimes II freezes for seconds/10s of seconds :’( Update: UI freezes may be a specific issue of Mac 64b 1.6 JDK Running analysis is SLOW (Checkstyle, …) and can kill your IDE (and you too if you’re of a weaker heart) The UI is little buggy, at least on Mac – dialogs not hidden when you click on another menu – not a big issue but annoying anyway Running webapp on Tomcat works great for some colleagues but not all – useless logging without any details, the server doesn’t start, no hints for how to solve, the Server -> Output window contains confusing “Disconnected from server”, Tomcat Log window contains only INFO logs (where are my debug logs?!), the file logs/catalina.out doesn’t exist anymore, Tomcat failure visible in browser yet nothing in the logs … JavaDoc – ‘#method’ + ^space in Eclipse generates {@link #method} automatically, not so in II; even worse, class lookup doesn’t work at all in II w/ot typing a @link first. I’ve found a workaround via a live template but I have to type its name and invoke it manually anyway. I miss Eclipse’ auto-dissapearing views (just click anywhere in the editor and they’ll disappear – though in II you can use Shift+Esc and if you un-pin a view then clicking in&out of it will hide it) and the ability to maximize any view with double-click The number of plugins for IntelliJ is smaller than for Eclipse though all the main projects likely target it tooI could perhaps live with the small annoyances (or may be learn the proper way to do what I’m trying to achieve?) but the performance issues are hard to accept. Useful ResourcesII docs: Intentions II docs: Code assistance – overview of the different features for code completion etc. StackOverflow: Things possible in IntelliJ that aren’t possible in Eclipse? StackOverflow: Hidden Features IntelliJ IDEA StackOverflow: IntelliJ Static Import CompletionReference: Comparison of Eclipse 3.6 and IntelliJ IDEA 10.5: Pros and Cons from our JCG partner Jakub Holy at the Holy Java blog. Related Articles :Eclipse Shortcuts for Increased Productivity Eclipse Memory Analyzer (MAT) What to do with IDE project files Eclipse: How attach Java source Java Tutorials and Android Tutorials list...

Best Of The Week – 2011 – W45

Hello guys, Time for the “Best Of The Week” links for the week that just passed. Here are some links that drew JavaCodeGeeks attention: * Developing a Service Provider using Java API: A tutorial showing how to develop a service provider using only the JDK classes, implementing a “poor man’s approach” to the Service Locator pattern. Also check out Java EE6 CDI, Named Components and Qualifiers. * I am a programmer: A very mature post on job security, job satisfaction and job payment, describes the most common scenarios of programmer’s workplaces and the advantages/disadvantages of each one of them. * The end of the geek culture: Here the author argues that the “geek culture” has come to an end, and that is because developers currently put less stocks in knowing one technology deep inside but instead broaden their skills. In other words, the times of specialists and experts in one narrow area have gone away. * Opportunistic Refactoring: Martin Fowler in this article encourages refactoring as an opportunistic activity,  i.e. it should be done whenever and wherever code needs to cleaned up – by whoever. Boy-scout rule applies here: always leave the code behind in a better state than you found it. Also check out Services, practices & tools that should exist in any software development house. * Security Vulnerabilities in Amazon and Eucalyptus: This article presents some security vulnerabilities in both Amazon and Eucalyptus infrastractures, which could be used to get complete control of the victim’s account and it’s associated stored data. The issues have been resolved but they definitely showcase one of the largest downsides of relying on a private cloud infrastructure. * Best Practices for Securing Apache Tomcat 7: A list of tips for securing your Tomcat installation, such as disabling the shutdown port, using the Security Lifecyle Listener, specifying the interface for the connectors etc. Also see Multiple Tomcat Instances on Single Machine and Zero-downtime Deployment (and Rollback) in Tomcat. * Apache Harmony Finale: The Apache Harmony project codebase has been put into the Apache Attic, i.e. further development has been stopped and only a read-only version of the code is provided. The project provided a clean-room viral-free implementation of the JDK and JVM and also strove to provide modularity. Harmony was also used by Google for their runtime library for Android. * Comparing Java 7 Garbage Collectors Under Extreme Load: An interesting comparison of the Java 7 Garbage Collectors under extreme load. which raises some concerns about the performance of the new G1 collector. * Coding Guidelines: Finding the Art in the Science: This article examines coding standards and provides some universal guidelines on how to produce more readable and thus more maintenable code. Quidelines include correctly used whitespace and fonts, conventional English usage, moderate use of comments etc. * Why would a developer invest time in your startup’s platform?: This article provides some tips on startups which wish to offer a platform to developers. Among them are to build a killer use case first, and then generalise it into a platform and to ruthlessly cut platform features which don’t apply to the current use case. * IT Projects: 400% Over-Budget and only 25% of Benefits Realized: This article presents the results of a Harvard Business Review study which show some alarming and disappointing numbers regarding IT projects realization. In short, projects running over budget and reaping little benefits. Also check out How many bugs do you have in your code?. * Startup Lesson: Why a Vacation is not just good for you: This is a story that displays the importance of allowing a sense of can-do attitude for a team and letting people realize the company is bigger than a single person and that everyone is replaceable. That’s all for this week. Stay tuned for more, here at JavaCodeGeeks. Related Articles:Best Of The Week – 2011 – W44 Best Of The Week – 2011 – W43 Best Of The Week – 2011 – W42 Best Of The Week – 2011 – W41 Best Of The Week – 2011 – W40 Best Of The Week – 2011 – W39 Best Of The Week – 2011 – W38 Best Of The Week – 2011 – W37 Best Of The Week – 2011 – W36 Best Of The Week – 2011 – W35...

Recycling objects to improve performance

Overview In a previous article I stated that the reason the deserialization of objects was faster was due to using recycled objects. This is potentially surprising for two reasons, 1) the belief that creating objects is so fast these days, it doesn’t matter or is just as fast as recycling yourself, 2) None of the serialization libraries use recycling by default. This article explores deserialization with and without recycling objects. How it not only is slower to create objects, but it slows down the rest of your program by pushing data out of your CPU caches. While this talks about deserializaton, the same applies to parsing text or reading binary files, as the actions being performed are the same. The test In this test, I deserialize 1000 Price objects, but also time how long it takes to copy a block of data. The copy represents work which the application might have to perform after deserializing.The test is timed one million times and those results sorted. The X-Axis shows the percentile timing. e.g. the 90% values is the 90% worst value (or 10% of values are higher). As you can see, the deserialization take longer if it has to create objects as it goes, however sometimes it takes much much long. This is perhaps not so surprising as creating objects means doing more work and possibly being delayed by a GC. However, it is the increase in the time to copy a block of data which is surprising. This demonstrates that not only is the deserialization slower, but any work which needs the data cache is also slower as a result. (Which is just about anything you might do in a real application) Performances tests rarely show you the impact on the rest of your application. In more detail Examining the higher percentile (longest times) you can see that the performance consistently bad if the deserialization has to wait for the GC.And the performance of the copy increases significantly in the worst case.The code Recycling example code Reference: Recycling objects to improve performance from our JCG partner Peter Lawrey at the Vanilla Java blog. Related Articles :Java Secret: Loading and unloading static fields C++ or Java, which is faster for high frequency trading? How to get C like performance in Java Low GC in Java: Use primitives instead of wrappers Java Tutorials and Android Tutorials list...
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books