DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Coding Topics

article thumbnail
Git: Getting the history of a deleted file
We recently wanted to get the Git history of a file which we knew existed but had now been deleted so we could find out what had happened to it. Using a simple git log didn’t work: git log deletedFile.txt fatal: ambiguous argument 'deletedFile.txt': unknown revision or path not in the working tree. We eventually came across Francois Marier’s blog post which points out that you need to use the following command instead: git log -- deletedFile.txt I’ve tried reading through the man page but I’m still not entirely sure what the distinction between using – and not using it is supposed to be. If someone could explain it that’d be cool… From http://www.markhneedham.com/blog/2011/10/04/git-getting-the-history-of-a-deleted-file
October 10, 2011
by Mark Needham
· 49,198 Views · 1 Like
article thumbnail
Using AspectJ’s @AfterThrowing Advice in your Spring App
This may not be strictly true, but it seems to me that the Guy’s at Spring are always banging on about AspectJ and Aspect Oriented Programming (AOP), to the point where I suspect that it’s used widely under the hood and is an integral part of Spring and I say “widely used under the hood”, because I haven’t come across too many projects that do use AspectJ or AOP in general. I suspect that part of the reason for this is possibly down to the fact that AOP different is a concept to Object Oriented Programming (OOP). AOP, they say, is all to do with an application’s cross-cutting concerns, which translates to mean stuff that’s common to all classes within your application. The usual example given here is logging and example code usually demonstrates logging all method entry and exit details, which is something that I’ve never found that useful. The other reason that I’ve not seen it used is that the AspectJ documentation is a bit ropey. Today’s blog is a demonstration of how to implement AspectJ’s @AfterThrowing advice in a Spring application. The idea of the after throwing advice is that you intercept an exception after it’s thrown, but before it’s caught - as shown in this rather simplistic diagram: I said above that the AOP sample code usually demonstrates logging, and in that respect this blog is no different. The idea in this contrived scenario is to log to a simple Apache Commons log any exceptions thrown. The class that actually does all this is IncidentThrowsAdvice: @Aspect public class IncidentThrowsAdvice { // Obtain a suitable logger. private static Log logger = LogFactory.getLog(IncidentThrowsAdvice.class); /** * Called between the throw and the catch */ @AfterThrowing(pointcut = "execution(* *(String, ..))", throwing = "e") public void myAfterThrowing(JoinPoint joinPoint, Throwable e) { System.out.println("Okay - we're in the handler..."); Signature signature = joinPoint.getSignature(); String methodName = signature.getName(); String stuff = signature.toString(); String arguments = Arrays.toString(joinPoint.getArgs()); logger.info("Write something in the log... We have caught exception in method: " + methodName + " with arguments " + arguments + "\nand the full toString: " + stuff + "\nthe exception is: " + e.getMessage(), e); } } The class itself is fairly straight forward. It has one method myAfterThrowing(...), which takes two arguments of type: JoinPoint and Throwable. Taking each of these in turn, JoinPoint just an class that holds information that describes a point within your code. Applying it to this particular after throwing advice means that it’s the point in your code where the exception occurred. The second argument is more straight forward as it’s the actual exception that’s currently being thrown There are two annotations applied to this class: @Aspect and @AfterThrowing. @Aspect marks the AnyOldExampleBean class as an AspectJ class, whilst the second annotation: @AfterThrowing is more interesting. This annotation tells AspectJ to call the myAfterThrowing() method when an exception occurs. It has two attributes, pointcut and throwing. pointcut defines the circumstances in which the myAfterThrowing() method is called as defined by the expression * *.*(..). This, like the rest of AspectJ seems remarkably badly documented, however you can determine that this signifies a method signature. In this case we’re checking every method in every class. This expression breaks down as follows: * - The first star is method visibility and or the method return type. The following will work in this example: * public void void whereas public on its own throws a BeanCreationException exception when loading the Spring config. *.* - this represents the package and method, again, using the same wild card formatting; hence, the following are all valid: example_10_annotations.afterthrowing_annotation.Sneeze.sneeze *.* *.sneeze example_10_annotations.*.Sneeze.sneeze ...however, example_10_annotations.*.sneeze won’t match for some reason... (..) - Defines the method arguments. In this example, the following will match: (..) (String, String, int) (String, ..) Having defined an AspectJ after throwing advice, the next step is to integrate it into the Spring application and this is a matter of adding one line to your Spring config file together with the appropriate schema reference in your : XML element: The important line in this file is: ...as it switches AOP on. The bean definitions that follow it demonstrate how the after throws advice works. The Sneeze class simply throws an exception when its called and the AnyOldExampleBean is a simple test class that calls Sneeze.sneeze(...) as shown below: public class Sneeze { /** * Throw an exception */ public void sneeze(String arg0, String arg1, int i) throws Exception { throw new Exception("Simulate an error"); } } public class AnyOldExampleBean { private Sneeze sneeze; /** * @return */ public Sneeze getSneeze() { return sneeze; } /** * @param sneeze */ public void setSneeze(Sneeze sneeze) { this.sneeze = sneeze; } /** * Do something * * @return */ public void run() { try { sneeze.sneeze("arg0", "arg1", 42); } catch (Exception e) { System.out.println("Caught e"); } finally { System.out.println("the end..."); } } } The code to run the above is: ApplicationContext ctx = new ClassPathXmlApplicationContext("example10_throwsadvice.xml"); AnyOldExampleBean myExampleBean = ctx.getBean(AnyOldExampleBean.class); myExampleBean.run(); ...and when running this code, you should get the following output: This is the after throwing exception handler 13:41:46,399 INFO ClassPathXmlApplicationContext:456 - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4ce2cb55: startup date [Sun Aug 14 13:41:46 BST 2011]; root of context hierarchy 13:41:46,462 INFO XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [example10_throwsadvice.xml] 13:41:46,863 INFO DefaultListableBeanFactory:555 - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@663257b8: defining beans [org.springframework.aop.config.internalAutoProxyCreator,exceptionHandler,example_10_annotations.afterthrowing_annotation.AfterThrowingBean#0,sneeze]; root of factory hierarchy Okay - we're in the handler... 13:41:47,171 INFO IncidentThrowsAdvice:42 - Write something in the log... We have caught exception in method: sneeze with arguments [arg0, arg1, 42] and the full toString: void example_10_annotations.afterthrowing_annotation.Sneeze.sneeze(String,String,int) the exception is: Simulate an error java.lang.Exception: Simulate an error at example_10_annotations.afterthrowing_annotation.Sneeze.sneeze(Sneeze.java:20) at example_10_annotations.afterthrowing_annotation.Sneeze$$FastClassByCGLIB$$5c47789.invoke() at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149) at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at ...THE REST HAS BEEN REMOVED FOR CLARITY... Caught e the end... As I said above, AspectJ seems very badly documented as can be borne out by the JavaDocs, which if you look through means that the code contains very little documentation, which in turn means that I’m glad I’m not working on it... Finally, in covering the after throwing advice, this blog only really touches on AspectJ and there are other useful AspectJ advice annotations that I will probably be covering in the near future. From http://www.captaindebug.com/2011/09/using-aspectjs-afterthrowing-advice-in.html
October 9, 2011
by Roger Hughes
· 36,422 Views · 1 Like
article thumbnail
ExtJS 4: How to Add Tooltip to Grid Header
This tutorial will walk through out how to add a tooltip to a Grid Header.
October 7, 2011
by Loiane Groner
· 22,378 Views
article thumbnail
The Benefits and Dangers of using Opensource Java Libraries and Frameworks
Everyone in the Java world seems to use various opensource libraries and frameworks... and why not, there are hundreds available covering virtually every type of programming problem you’re likely to come across in today’s programming landscape. This blog takes a quick look at the reasons for using opensource artifacts and examines what could go wrong... The first reason for using them is reduced cost as it’s cheaper for your project to grab hold of an opensource library than it is for your to write the same thing yourself. The second reason for using opensource artifacts is reduced cost: you get free support from a bunch of capable and enthusiastic developers, usually in the form of copious amounts of documentation and forums. The third reason is reduced cost: you get free updates and enhancements from the opensource community and free bug fixes, although you don’t get to choose which enhancements are added to the project. Some projects, such as Tomcat, have a mechanism for voting on what enhancements are made, but at the end of the day it’s down to what really interests the developers. There are also a couple of unspoken reasons for using popular opensource libraries and frameworks: firstly, they make your CV look good. If opensource X is popular and you put that on your CV then your chances of getting a pay rise or a better job will improve. Secondly, if you work on one of the opensource projects, then you’ll earn some kudos, which, again, makes your CV look good improves the chances of you increasing the size of your pay-packet. There is an obvious downside to using opensource artifacts and that is all projects have an natural life-cycle. New versions of libraries are released, old libraries are deprecated, falling out of use because the technology’s too old, the developers have lost interest or moved on, or the rest of the community found something else that’s better and jumped on that bandwagon deserting yours. So, the problems of finding yourself saddled with retired and deprecated opensource libraries are firstly extra cost: there’s no support, no forum and no bug fixes. You’re on your own. You can often manage to download the source code to retired projects and support it yourself, but that’s not guaranteed and that costs money. The second problem of using deprecated code is extra cost: old code usually encompasses obsolete architecture and patterns, which contain known flaws and problems - after all, that’s why they’re obsolete. Using obsolete patterns and architecture encourages and in some cases forces developers to write bad code, not because your developers are bad, but that’s just the way it is... For example, there are some very obsolete JSP tags that blatantly mix database calls with business and presentation logic, which is a well know way of producing crumby, unmaintainable, spaghetti code. The third problem is, believe it or not, extra cost: I’ve recently come across a project where the code is so old that there are JAR file clashes, with different JARs containing different versions of the same API being dragged into the classpath. Certain bits of the code use one version of the API whilst other bits use the other version. eclipse didn’t know what to make of it all. There are also hidden costs: no one in there right mind wants to work on obsolete spaghetti code - it damages moral and saps the will to live, whilst damaging your ability to find that next, more highly paid, job. Plus, when people do leave, you’ve got the extra cost of finding and training their replacements. Never forget that the best people will be the first to leave, leaving you with the less experienced developers, again driving up your cost So, what can you do when faced with obsolete opensource libraries and frameworks? 1) Do nothing, continue using the obsolete library and hope everything will be alright. 2) Scrap the whole project and start again from scratch - the Big Bang Theory. 3) Refactor vigorously to remove the obsolete opensource code. This could also be seen as a way of changing the architecture of an application, updating the programming practices of the team and improving the code and whole build process. From the above I guess that you can figure out that in my opinion I prefer option 3. Option 1 is very risky, but then again, so is option 2: starting from scratch wastes time simply re-inventing the wheel, and whilst you do that, you don’t have a product, plus you may also end up with a big a mess as you started with. Option 3 is evolution and not revolution, quite the most sensible way to go. Having said all this, I definitely won’t stop using opensource code... From http://www.captaindebug.com/2011/09/benefits-and-dangers-of-using.html
October 6, 2011
by Roger Hughes
· 10,689 Views
article thumbnail
Using Spring Interceptors in your MVC Webapp
I thought that it was time to take a look at Spring’s MVC interceptor mechanism, which has been around for a good number of years and is a really useful tool.
September 29, 2011
by Roger Hughes
· 71,406 Views
article thumbnail
Adding SLF4J to Your Maven Project
Learn how to add SLF4J, or Simple Logging Facade for Java, to your Maven project in this tutorial.
September 28, 2011
by Roger Hughes
· 264,110 Views · 6 Likes
article thumbnail
Brute forcing a bin packing problem
Even a basic planning problem, such as bin packing, can be notoriously hard to solve and scale. One might consider the brute force algorithm. Let's take a look at how that algorithm works out on the cloud balance example of Drools Planner: Given a set of servers with different hardware (CPU, memory and network bandwidth) and given a set of processes with different hardware requirements, assign each process to 1 server and minimize the total cost of the active servers. The brute force algorithm is simple: try every combination between processes where each process is assigned to each server. For example, if we have 6 processes (P0, P1, P2, P3, P4, P5) and 2 servers (S0, S1), we'd try these solutions: P0->S0, P1->S0, P2->S0, P3->S0, P4->S0, P5->S0 P0->S0, P1->S0, P2->S0, P3->S0, P4->S0, P5->S1 P0->S0, P1->S0, P2->S0, P3->S0, P4->S1, P5->S0 P0->S0, P1->S0, P2->S0, P3->S0, P4->S1, P5->S1 ... P0->S1, P1->S1, P2->S1, P3->S1, P4->S1, P5->S1 On my machine, it takes 15ms to calculate the score of these 2^6 combinations. When I scale out to 9 processes and 3 servers, which are 3^9 combinations, it becomes 1582ms. So it scales like this: Notice that despite that the number of processes has not even doubled, the running time multiplied by 100! For comparison, I 've added the running time of the First Fit algorithm. And it gets worse: for 12 processes and 4 servers, which are 4^12 combinations, it take more than 17 minutes: What if we want to distribute 3000 processes over 1000 servers? With this kind of scalability, it will take too long. In fact, the brute force algorithm is useless. Luckily, Drools Planner implements several other optimization algorithms, which can handle such loads. If you want to know more about them, take a look at the Drools Planner manual or come to my talk at JUDCon London (31 Oct - 1 Nov). This article was originally posted on the Drools & jBPM blog.
September 26, 2011
by Geoffrey De Smet
· 9,977 Views
article thumbnail
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.jar org.springframework.asm-3.0.6.RELEASE.jar org.springframework.aspects-3.0.6.RELEASE.jar org.springframework.beans-3.0.6.RELEASE.jar org.springframework.context.support-3.0.6.RELEASE.jar org.springframework.context-3.0.6.RELEASE.jar org.springframework.core-3.0.6.RELEASE.jar org.springframework.jdbc-3.0.6.RELEASE.jar org.springframework.orm-3.0.6.RELEASE.jar org.springframework.transaction-3.0.6.RELEASE.jar. org.springframework.expression-3.0.6.RELEASE.jar commons-logging-1.0.4.jar log4j.jar aopalliance-1.0.jar dom4j-1.1.jar hibernate-commons-annotations-3.2.0.Final.jar hibernate-core-3.6.4.Final.jar hibernate-jpa-2.0-api-1.0.0.Final.jar javax.persistence-2.0.0.jar jta-1.1.jar javassist-3.1.jar slf4j-api-1.6.2.jar mysql-connector-java-5.1.13-bin.jar commons-collections-3.0.jar For 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 works Let 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 superHeroList = new ArrayList(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 getSuperHeroList() { return superHeroList; } public void setSuperHeroList(List 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 HibernateTemplatethrough HibernateDAOSupportso 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: com.justice.league.**.* org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/my_test root password true org.hibernate.dialect.MySQLDialect 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 create 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 superHeroList = getSuperHeroList(); league.setSuperHeroList(superHeroList); league.setJusticeLeagueMoto("Guardians of the Galaxy"); league.setNumberOfMembers(superHeroList.size()); service.handleJusticeLeagureCreateUpdate(league); } private static List getSuperHeroList() { List superHeroList = new ArrayList(); 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 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. From http://dinukaroshan.blogspot.com/2011/09/hibernate-by-example-part-1-orphan.html
September 24, 2011
by Dinuka Arseculeratne
· 47,861 Views
article thumbnail
Lucene and Solr's CheckIndex to the Rescue!
while using lucene and solr we are used to a very high reliability. however, there may come a day when solr will inform us that our index is corrupted, and we need to do something about it. is the only way to repair the index to restore it from the backup or do full indexation? no – there is hope in the form of checkindex tool. what is checkindex ? checkindex is a tool available in the lucene library, which allows you to check the files and create new segments that do not contain problematic entries. this means that this tool, with little loss of data is able to repair a broken index, and thus save us from having to restore the index from the backup (of course if we have it) or do the full indexing of all documents that were stored in solr. where do i start? please note that, according to what we find in javadocs, this tool is experimental and may change in the future. therefore, before starting to work with it we should create a copy of the index. in addition, it is worth knowing that the tool analyzes the index byte by byte, and thus for large indexes the time of analysis and repair may be large. it is important not to run the tool with the -fix option at the moment when it is used by solr or other applications based on the lucene library. finally, be aware that the launch of the tool in repairing mode may result in removal of some or all documents that are stored in the index. how to run it to run the utility, go to the directory where the lucene library files are located and run the following command: java -ea:org.apache.lucene... org.apache.lucene.index.checkindex index_path -fix in my case, it looked as follows: java -cp lucene-core-2.9.3.jar -ea:org.apache.lucene... org.apache.lucene.index.checkindex e:\solr\solr\data\index\ -fix after a while i got the following information : opening index @ e:solrsolrdataindex segments file=segments_2 numsegments=1 version=format_diagnostics [lucene 2.9] 1 of 1: name=_0 doccount=19 compound=false hasprox=true numfiles=11 size (mb)=0,018 diagnostics = {os.version=6.1, os=windows 7, lucene.version=2.9.3 951790 - 2010-06-06 01:30:55, source=flush, os.arch=x86, java.version=1.6.0_23, java.vendor=sun microsystems inc.} no deletions test: open reader.........ok test: fields..............ok [15 fields] test: field norms.........ok [15 fields] test: terms, freq, prox...ok [900 terms; 1517 terms/docs pairs; 1707 tokens] test: stored fields.......ok [232 total field count; avg 12,211 fields per doc] test: term vectors........ok [3 total vector count; avg 0,158 term/freq vector fields per doc] no problems were detected with this index. it mean that the index is correct and there was no need for any corrective action. additionally, you can learn some interesting things about the index broken index but what happens in the case of the broken index? there is only one way to see it – let’s try. so, i broke one of the index files and ran the checkindex tool. the following appeared on the console after i’ve run the checkindex tool: opening index @ e:solrsolrdataindex segments file=segments_2 numsegments=1 version=format_diagnostics [lucene 2.9] 1 of 1: name=_0 doccount=19 compound=false hasprox=true numfiles=11 size (mb)=0,018 diagnostics = {os.version=6.1, os=windows 7, lucene.version=2.9.3 951790 - 2010-06-06 01:30:55, source=flush, os.arch=x86, java.version=1.6.0_23, java.vendor=sun microsystems inc.} no deletions test: open reader.........failed warning: fixindex() would remove reference to this segment; full exception: org.apache.lucene.index.corruptindexexception: did not read all bytes from file "_0.fnm": read 150 vs size 152 at org.apache.lucene.index.fieldinfos.read(fieldinfos.java:370) at org.apache.lucene.index.fieldinfos.(fieldinfos.java:71) at org.apache.lucene.index.segmentreader$corereaders.(segmentreader.java:119) at org.apache.lucene.index.segmentreader.get(segmentreader.java:652) at org.apache.lucene.index.segmentreader.get(segmentreader.java:605) at org.apache.lucene.index.checkindex.checkindex(checkindex.java:491) at org.apache.lucene.index.checkindex.main(checkindex.java:903) warning: 1 broken segments (containing 19 documents) detected warning: 19 documents will be lost note: will write new segments file in 5 seconds; this will remove 19 docs from the index. this is your last chance to ctrl+c! 5... 4... 3... 2... 1... writing... ok wrote new segments file "segments_3" as you can see, all the 19 documents that were in the index have been removed. this is an extreme case, but you should realize that this tool might work like this. the end if you remember about the basisc assumptions associated with the use of the checkindex tool you may find yourself in a situation when this tool will come in handy and you will not have to ask yourself a question like “when was the last backup was made?”
September 22, 2011
by Rafał Kuć
· 21,792 Views · 1 Like
article thumbnail
Deploying Applications to Weblogic Using Maven
When developing JEE applications as part of the development cycle, it’s important to deploy to a development server before running end to end or integration tests. This blog demonstrates how to deploy your applications to your Weblogic server using Maven and, it transpires that there are at least two ways of doing this. The first way is using a the weblogic-maven-plugin available from Oracle and you can find an article on how to install this available on the Oracle website. The unfortunate thing about this is that Oracle don’t deploy their JARs to a Maven repository, which means that you have to do some jiggery-pokery messing around setting up your local repository. The Oracle article defines three steps: creating a plug-in jar using the wljarbuilder tool, extracting the pom.xml and then installing the results to your local repository using mvn install:install-file. In order to use this plug-in, you’ll need to add the following to your program’s POM file: com.oracle.weblogic weblogic-maven-plugin 10.3.4 t3://localhost:7001 weblogic your-password true deploy false true ../marin-tips-ear/target/marin-tips.ear ${project.build.finalName} install deploy The second method of deploying an application to your Weblogic server is by using a ‘good-ol’ Ant script. This method is simpler as you don’t need to bother creating plug-in JARs or installing them in your local repository. The POM file additions are: org.apache.maven.plugins maven-antrun-plugin 1.6 deploy-to-server pre-integration-test run I prefer the old fashioned Ant way more purely because it’s less hassle and adheres to the Keep It Simple Stupid rule of programming as, unless Oracle make their JAR files available on some repository, then extra set-up steps aren’t really an improvement. From http://www.captaindebug.com/2011/09/deploying-applications-to-weblogic.html
September 22, 2011
by Roger Hughes
· 29,682 Views · 7 Likes
article thumbnail
Creating OSGi projects using Eclipse IDE and Maven
f you want to create any of these projects listed below using Eclipse IDE, OSGi Application Project OSGi Bundle Project OSGi Composite Bundle Project OSGi Fragment Project Blueprint File you need to have IBM Rational Development Tools for OSGi Applications installed. Why do we need these tools? Create and edit OSGi bundles, composite bundles, bundle fragments, and applications. Import and export OSGi bundles, composite bundles, bundle fragments, and applications. Convert existing Java Enterprise Edition (Java EE) web, Java Persistence Application (JPA), plug-in, or simple Java projects into OSGi bundles. Edit OSGi bundle, application, and composite bundle manifest files. Create and edit OSGi blueprint configuration files. Edit OSGi blueprint binding configuration files. Diagnose and fix problems in your bundles and applications using validation and quick fixes. Eclipse Plugin Installation Before you install the tools, you must have the Eclipse Helios v3.6.2 package, Eclipse IDE for Java EE Developers installed. 1. Click on Help > Install New Software 2. Point to this update site – http://public.dhe.ibm.com/ibmdl/export/pub/software/rational/OSGiAppTools – and click on Add. 3. You’ll see a list of tools – OSGi Application Development Tools, OSGi Application Development Tools UI, OSGi context-sensitive help, OSGi Help documentation, Rational Development Tools for OSGi Applications help documentation. Select all those are listed (you can ignore help stuff) and go ahead with the installation. As of writing this, the development tools’ version is 1.0.3. Maven Integration If you want to manage any of these OSGi projects using Maven, you can right-click on it and select Maven > Enable Dependency Management. You need to have Maven Integration for Eclipse(m2e) installed for this which you can find in Eclipse Marketplace. If you use Maven, you can try using the plugins provided by Apache Felix project for bundling (building an OSGi bundle). More on this plugin @ http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html, http://felix.apache.org/site/apache-felix-maven-osgi-plugin.html References: http://www.ibm.com/developerworks/rational/downloads/10/rationaldevtoolsforosgiapplications.html#download From http://singztechmusings.wordpress.com/2011/09/12/creating-osgi-projects-using-eclipse-ide-and-maven/
September 21, 2011
by Singaram Subramanian
· 26,295 Views
article thumbnail
Using RESTful URLs on your Spring 3 MVC Webapp
This blog comes as an answer to a question from a reader. Now, as a rule, I don’t do request blogs, but I thought that this sounded like an interesting topic. The question refers to my blog from July 11 on accessing request parameters using Spring 3 MVC and was “Do you know how to encode the uuid so it is not visible to the user for security concerns?”. The answer is “Yes”, but that would make for a very short blog. In this case I’m assuming that the question is talking about using RESTful URLs to maintain session state information between pages. REST is a subject that’s had many words written about it, but putting it in very simplistic terms I’m defining it as not storing session or state information on your web server between browser calls. Even more simply put, it means not using the HttpSession interface implementations. Not maintaining state on the server gives you at least two obvious benefits; the first being improved loading. This is because your server is not using memory for storing state data which may, or may not be needed. The second benefit is scaling. If you’re using a domain with multiple servers, then tying session state to one server is problematic as you can’t usually guarantee that subsequent sequential calls to the domain will be directed to the same physical server. There are various techniques use to solve this problem, including making everything form based and storing state information in hidden fields, using cookies, and manipulating URLs. This blog demonstrates the third technique of encrypting state data and tagging it onto the end of a URL, so that it’s passed back and forth between the browser and the server as a request parameter: http://www.mywebsite.com/thepageIwant?session=ThisIsEncodedData An example scenario for this technique would an e-commerce site. In this case, you’d select a couple of items and add them to your basket. You’d then login and review your basket and then perhaps modify the delivery address before proceeding to pay. In doing all this, you conceptually remain logged in to the server but, in the RESTful world, the server doesn’t remember you. This example uses three screens to demonstrate this idea. The first screen logs you in, the second contains a URL that includes some session data, and the third displays the session data for review. The screen shot above shows a simple login screen. Note that I’ve used a clear text password for demonstration purposes only. The second screen in this scenario is the one that contains the encrypted session information; namely the user name and password, which has both been displayed and glued on to the end of the href of an anchor tag. The last screen shows the decoded session information demonstrating that we’ve still got it and that it’s correct. Moving on to the actual Java code for this demo... The simple bean below I’ve called Session and it holds all the state data we want encoding. public class Session { private static final String SEP = "=/="; private String name; private String password; public Session() { // Blank } public Session(String combined) { String[] split = combined.split(SEP); name = split[0]; password = split[1]; } public String getName() { return name; } public void setName(String username) { this.name = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return name + SEP + password; } } If you look at the code above, you’ll see that it contains two features that give it context in the application. The toString(...) returns a string that the application can encode and the single argument constructor can create a full bean from its argument. This works cohesively with the controller code, which is shown below... @Controller public class RewriteController { private static final String ENCODING_KEY = "ThisWillBeTheKey"; /** * Create the initial blank form */ @RequestMapping(value = "/loginform", method = RequestMethod.GET) public String getCreateForm(Model model) { model.addAttribute("Session", new Session()); return "login.page"; } /** * This is where you login... */ @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(Session userDetails, Model model) throws UnsupportedEncodingException { byte[] encodedBytes = encodeURL(userDetails); String encodedURL = new String(Base64.encodeBase64(encodedBytes)); model.addAttribute("encodedURL", encodedURL); return "display.encoded.url"; } private byte[] encodeURL(Session userDetails) throws UnsupportedEncodingException { RC4Lite rc4 = getRC4Lite(); byte[] in = userDetails.toString().getBytes("UTF8"); byte[] out = new byte[in.length]; rc4.encrypt(in, 0, out, 0, in.length); return out; } private RC4Lite getRC4Lite() throws UnsupportedEncodingException { RC4Lite rc4 = new RC4Lite(); rc4.setKey(ENCODING_KEY.getBytes("UTF8")); return rc4; } /** * This is where you're still in the REST session and re-validate the user */ @RequestMapping(value = "/decode", method = RequestMethod.GET) public String someSessionMethod( @RequestParam(value = "session") String sessionParam, Model model) throws UnsupportedEncodingException { byte[] encodedBytes = Base64 .decodeBase64(sessionParam.getBytes("UTF8")); String decodedString = decodeURL(encodedBytes); Session session = new Session(decodedString); model.addAttribute(session); return "display.decoded.url"; } private String decodeURL(byte[] encodedBytes) throws UnsupportedEncodingException { RC4Lite rc4 = getRC4Lite(); byte[] out = new byte[encodedBytes.length]; rc4.decrypt(encodedBytes, 0, out, 0, encodedBytes.length); return new String(out); } } The controller class above contains three handler methods. The first handler method, getCreateForm(...), is fairly straight forward and simply adds a Session bean the model before displaying the login in form. The second handler method, login(...), is where all the action takes place. There are two parts to encoding the session data (the name and password). Part one is to encrypt the data and for that I’ve simply borrowed my RC4Lite class from my RC4 Encryption blog1. Once encrypted, the RC4 bytes will need converting into ASCII and for that I’ve used Apache’s Base64 class as described in my base64 blog. Converting to ASCII ensures that the characters are printable and don’t cause any problems. The string is then added to the model where it’s attached to the anchor tag as shown in the following JSP snippet: The final handler method, someSessionMethod(...) receives the input from the above link, decodes it using a reverse process to encoding It then creates a new Session object and puts that into the model, which is then displayed on the final page. Remember that this is only a sample, it just demonstrates the idea of encrypting session information and adding to a URL as a parameter. There are improvements you could make here, for example: using a interceptor to authenticate with the server upon each request before doing the business logic in the controller, or using a better encryption class, but in essence the principle applies to any webapp. There are also other techniques you can use for achieving secure web communications, so more on those later perhaps... 1 There are better ways of doing encryption than RC4, it's used here only for convenience in this demonstration. From http://www.captaindebug.com/2011/09/using-restful-urls-on-your-spring-3-mvc.html
September 21, 2011
by Roger Hughes
· 12,975 Views
article thumbnail
Practical PHP Refactoring: Replace Record with Data Class
We often find ourselves tempted by the shortcut of using directly a record-like data structure provided by the language or a framework. There are many example scenarios where a record emerges: when you use a database for persistence (not only a with relational one) there can be a data structure containing the results of a query. when you use associative arrays, often they have a small number of fixed keys. Record-like structures are the equivalent of C structs, or Ruby hashes. This refactoring is a generalization of Replace Array with Object: in this case the starting point is not just an array which always has the same number and type of fields, but any data structure homoegeneous to it: Zend_Db_Table_Row, implementing a Row Data Gateway and giving access to a row in the database. stdClass instances (or arrays) fetched by PDOStatement. In some languages (see C) the record is a particular data structure which is not an object; in PHP, it is always an array or an object of some vendor class. Even ORMs based on Active Record are more advanced than this kind of usage: they usually let you add methods on the model classes, which are populated with data by the ORM itself. In this refactoring, we are talking about a data structure managed by the language of the persistence layer, and whose code you cannot modify. Why replacing a record-like structure? Generic classes do not let you add methods to manipulate their data: when using directly a Zend_Db_Table_Row or an associative array for storage of the result of a query, you have to resort continuously to foreign methods. Each time you need new logic, you have to compromise encapsulation on the object itself, and these methods get duplicated in various instance of client code. Solutions There are different ways to eliminate the coupling to a record-like structure. The first is to refactor to subclassing, where the data structure becomes an Active Record. You extends the vendor class with your own one: this option is only available if the structure is defined as an object. Moreover, the name of the class to instantiate must be configurable in the persistence mechanism. Zend_Db_Table_Record supports this kind of usage. A second option is to refactor to composition: Zend_Db examples exist also for this case. This approach can be used to avoid large hierarchies: your model classes compose the Zend_Db objects and hide the database; methods can be added for once at your own models. A third and final alternative is to use hydration: data is copied to your model objects, and records are thrown away after the fact. Doctrine 2 and Data Mappers in general choose this approach. Steps I will describe a short procedure for refactoring to hydration since it is the most complex approach and it is always applicable. The other are instead specific for the particular data structure (for example with Zend_Db you have to write some subclasses and configure some protected fields to contain the right class names.) Create a new class, as one of your models. Its state should be represented by one row (or more rows joined into one) in the database. This class should gain a private field for each of the record's fields, usually with getters and setters. This class should accept in the constructor or in a Factory Method an instance of the record, so that it can produce a new instance. If you want to decouple from the persistsnce, or you want to go two ways (also save and not only visualize, since this is not just a presentation model), look for a Data Mapper such as Doctrine 2, which will even hide all the record structures from you and manager associations where objects compose other ones. Example In the example, the data of a single user are returned in an array. I chose an array as the record-like structure to minimize the external dependencies of this code. find(42); $this->assertEquals('Giorgio', $giorgio['name']); } } /** * This is a Fake Table Data Gateway. The machinery for making it work with * a database will be distracting for our purposes, so they will be omitted. */ class UsersTable { /** * @return mixed the returned value can be a Zend_Db_Table_Row, * an Active Record, a stdClass, an associative array... * It should just represent a single entity. */ public function find($id) { // execute a PDOStatement and fetch the data return array('id' => 42, 'name' => 'Giorgio'); } } After the refactoring, we have a User class where we can add all the methods we need: find(42); $this->assertEquals('Giorgio', $giorgio->getName()); } } /** * This is a Fake Table Data Gateway. The machinery for making it work with * a database will be distracting for our purposes, so they will be omitted. */ class UsersTable { /** * @return mixed the returned value can be a Zend_Db_Table_Row, * an Active Record, a stdClass, an associative array... * It should just represent a single entity. */ public function find($id) { // execute a PDOStatement and fetch the data return User::fromRecord(array('id' => 42, 'name' => 'Giorgio')); } } class User { private $id; private $name; public static function fromRecord(array $record) { $object = new self(); $object->id = $record['id']; $object->name = $record['name']; return $object; } public function getName() { return $this->name; } }
September 19, 2011
by Giorgio Sironi
· 11,130 Views
article thumbnail
Practical Introduction into Code Injection with AspectJ, Javassist, and Java Proxy
The ability to inject pieces of code into compiled classes and methods, either statically or at runtime, may be of immense help. This applies especially to troubleshooting problems in third-party libraries without source codes or in an environment where it isn’t possible to use a debugger or a profiler. Code injection is also useful for dealing with concerns that cut across the whole application, such as performance monitoring. Using code injection in this way became popular under the name Aspect-Oriented Programming (AOP). Code injection isn’t something used only rarely as you might think, quite the contrary; every programmer will come into a situation where this ability could prevent a lot of pain and frustration. This post is aimed at giving you the knowledge that you may (or I should rather say “will”) need and at persuading you that learning basics of code injection is really worth the little of your time that it takes. I’ll present three different real-world cases where code injection came to my rescue, solving each one with a different tool, fitting best the constraints at hand. Why You Are Going to Need It A lot has been already said about the advantages of AOP – and thus code injection – so I will only concentrate on a few main points from the troubleshooting point of view. The coolest thing is that it enables you to modify third party, closed-source classes and actually even JVM classes. Most of us work with legacy code and code for which we haven’t the source codes and inevitably we occasionally hit the limitations or bugs of these 3rd-party binaries and need very much to change some small thing in there or to gain more insight into the code’s behavior. Without code injection you have no way to modify the code or to add support for increased observability into it. Also you often need to deal with issues or collect information in the production environment where you can’t use a debugger and similar tools while you usually can at least manage somehow your application’s binaries and dependencies. Consider the following situations: You’re passing a collection of data to a closed-source library for processing and one method in the library fails for one of the elements but the exception provides no information about which element it was. You’d need to modify it to either log the offending argument or to include it in the exception. (And you can’t use a debugger because it only happens on the production application server.) You need to collect performance statistics of important methods in your application including some of its closed-source components under the typical production load. (In the production you of course cannot use a profiler and you want to incur the minimal overhead.) You use JDBC to send a lot of data to a database in batches and one of the batch updates fails. You would need some nice way to find out which batch it was and what data it contained. I’ve in fact encountered these three cases (among others) and you will see possible implementations later. You should keep the following advantages of code injection in your mind while reading this post: Code injection enables you to modify binary classes for which you haven’t the source codes The injected code can be used to collect various runtime information in environments where you cannot use the traditional development tools such as profilers and debuggers Don’t Repeat Yourself: When you need the same piece of logic at multiple places, you can define it once and inject it into all those places. With code injection you do not modify the original source files so it is great for (possibly large-scale) changes that you need only for a limited period of time, especially with tools that make it possible to easily switch the code injection on and off (such as AspectJ with its load-time weaving). A typical case is performance metrics collection and increased logging during troubleshooting You can inject the code either statically, at the build time, or dynamically, when the target classes are being loaded by the JVM Mini Glossary You might encounter the following terms in relation to code injection and AOP: Advice The code to be injected. Typically we talk about before, after, and around advices, which are executed before, after, or instead of a target method. It’s possible to make also other changes than injecting code into methods, e.g. adding fields or interfaces to a class. AOP (Aspect Oriented Programming) A programming paradigm claiming that “cross-cutting concerns” – the logic needed at many places, without a single class where to implement them – should be implemented once and injected into those places. Check Wikipedia for a better description. Aspect A unit of modularity in AOP, corresponds roughly to a class – it can contain different advices and pointcuts. Joint point A particular point in a program that might be the target of code injection, e.g. a method call or method entry. Pointcut Roughly spoken, a pointcut is an expression which tells a code injection tool where to inject a particular piece of code, i.e. to which joint points to apply a particular advice. It could select only a single such point – e.g. execution of a single method – or many similar points – e.g. executions of all methods marked with a custom annotation such as @MyBusinessMethod. Weaving The process of injecting code – advices – into the target places – joint points. The Tools There are many very different tools that can do the job so we will first have a look at the differences between them and then we will get acquainted with three prominent representatives of different evolution branches of code injection tools. Basic Classification of Code Injection Tools I. Level of Abstraction How difficult is it to express the logic to be injected and to express the pointcuts where the logic should be inserted? Regarding the “advice” code: Direct bytecode manipulation (e.g. ASM) – to use these tools you need to understand the bytecode format of a class because they abstract very little from it, you work directly with opcodes, the operand stack and individual instructions. An ASM example: methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); They are difficult to use due to being so low-level but are the most powerful. Usually they are used to implement higher-level tools and only few actually need to use them. Intermediate level – code in strings, some abstraction of the classfile structure (Javassist) Advices in Java (e.g. AspectJ) – the code to be injected is expressed as syntax-checked and statically compiled Java Regarding the specification of where to inject the code: Manual injection – you have to get somehow hold of the place where you want to inject the code (ASM, Javassist) Primitive pointcuts – you have rather limited possibilities for expressing where to inject the code, for example to a particular method, to all public methods of a class or to all public methods of classes in a group (Java EE interceptors) Pattern matching pointcut expressions – powerful expressions matching joint points based on a number of criteria with wildcards, awareness of the context (e.g. “called from a class in the package XY”) etc. (AspectJ) II. When the Magic Happens The code can be injected at different points in time: Manually at run-time – your code has to explicitly ask for the enhanced code, e.g. by manually instantiating a custom proxy wrapping the target object (this is arguably not true code injection) At load-time – the modification are performed when the target classes are being loaded by the JVM At build-time – you add an extra step to your build process to modify the compiled classes before packaging and deploying your application Each of these modes of injection can be more suitable at different situations. III. What It Can Do The code injection tools vary pretty much in what they can or cannot do, some of the possibilities are: Add code before/after/instead of a method – only member-level methods or also the static ones? Add fields to a class Add a new method Make a class to implement an interface Modify an instruction within the body of a method (e.g. a method call) Modify generics, annotations, access modifiers, change constant values, … Remove method, field, etc. Selected Code Injection Tools The best-known code injection tools are: Dynamic Java Proxy The bytecode manipulation library ASM JBoss Javassist AspectJ Spring AOP/proxies Java EE interceptors Practical Introduction to Java Proxy, Javassist and AspectJ I’ve selected three rather different mature and popular code injection tools and will present them on real-world examples I’ve personally experienced. The Omnipresent Dynamic Java Proxy Java.lang.reflect.Proxy makes it possible to create dynamically a proxy for an interface, forwarding all calls to a target object. It is not a code injection tool for you cannot inject it anywhere, you must manually instantiate and use the proxy instead of the original object, and you can do this only for interfaces, but it can still be very useful as we will see. Advantages: It’s a part of JVM and thus is available everywhere You can use the same proxy – more exactly an InvocationHandler – for incompatible objects and thus reuse the code more than you could normally You save effort because you can easily forward all calls to a target object and only modify the ones interesting for you. If you were to implement a proxy manually, you would need to implement all the methods of the interface in question Disadvantages You can create a dynamic proxy only for an interface, you can’t use it if your code expects a concrete class You have to instantiate and apply it manually, there is no magical auto-injection It’s little too verbose Its power is very limited, it can only execute some code before/after/around a method There is no code injection step – you have to apply the proxy manually. Example I was using JDBC PreparedStatement’s batch updates to modify a lot of data in a database and the processing was failing for one of the batch updates because of integrity constraint violation. The exception didn’t contain enough information to find out which data caused the failure and so I’ve created a dynamic proxy for the PreparedStatement that remembered values passed into each of the batch updates and in the case of a failure it automatically printed the batch number and the data. With this information I was able to fix the data and I kept the solution in place so that if a similar problems ever occurs again, I’ll be able to find its cause and resolve it quickly. The crucial part of the code: LoggingStatementDecorator.java – snippet 1 class LoggingStatementDecorator implements InvocationHandler { private PreparedStatement target; ... private LoggingStatementDecorator(PreparedStatement target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Object result = method.invoke(target, args); updateLog(method, args); // remember data, reset upon successful execution return result; } catch (InvocationTargetException e) { Throwable cause = e.getTargetException(); tryLogFailure(cause); throw cause; } } private void tryLogFailure(Throwable cause) { if (cause instanceof BatchUpdateException) { int failedBatchNr = successfulBatchCounter + 1; Logger.getLogger("JavaProxy").warning( "THE INJECTED CODE SAYS: " + "Batch update failed for batch# " + failedBatchNr + " (counting from 1) with values: [" + getValuesAsCsv() + "]. Cause: " + cause.getMessage()); } } ... Notes: To create a proxy, you first need to implement an InvocationHandler and its invoke method, which is called whenever any of the interface’s methods is invoked on the proxy You can access the information about the call via the java.lang.reflect.* objects and for example delegate the call to the proxied object via method.invoke We’ve also an utility method for creating a proxy instance for a Prepared statement: LoggingStatementDecorator.java – snippet 2 public static PreparedStatement createProxy(PreparedStatement target) { return (PreparedStatement) Proxy.newProxyInstance( PreparedStatement.class.getClassLoader(), new Class[] { PreparedStatement.class }, new LoggingStatementDecorator(target)); }; Notes: You can see that the newProxyInstance call takes a classloader, an array of interfaces that the proxy should implement, and the invocation handler that calls should be delegated to (the handler itself has to manage a reference to the proxied object, if it needs it) It is then used like this: Main.java ... PreparedStatement rawPrepStmt = connection.prepareStatement("..."); PreparedStatement loggingPrepStmt = LoggingStatementDecorator.createProxy(rawPrepStmt); ... loggingPrepStmt.executeBatch(); ... Notes: You see that we have to manually wrap a raw object with the proxy and use the proxy further on Alternative Solutions This problem could be solved in different ways, for example by creating a non-dynamic proxy implementing PreparedStatement and forwarding all calls to the real statement while remembering batch data but it would be lot of boring typing for the interface has many methods. The caller could also manually keep track of the data it has send to the prepared statement but that would obscure its logic with an unrelated concern. Using the dynamic Java proxy we get rather clean and easy to implement solution. The Independent Javassist JBoss Javassist is an intermediate code injection tool providing a higher-level abstraction than bytecode manipulation libraries and offering little limited but still very useful manipulation capabilities. The code to be injected is represented as strings and you have to manually get to the class-method where to inject it. Its main advantage is that the modified code has no new run-time dependencies, on Javassist or anything else. This may be the decisive factor if you are working for a large corporation where the deployment of additional open-source libraries (or just about any additional libraries) such as AspectJ is difficult for legal and other reasons. Advantages Code modified by Javassist doesn’t require any new run-time dependencies, the injection happens at the build time and the injected advice code itself doesn’t depend on any Javassist API Higher-level than bytecode manipulation libraries, the injected code is written in Java syntax, though enclosed in strings Can do most things that you may need such as “advising” method calls and method executions Disadvantages Still little too low-level and thus harder to use – you have to deal a little with structure of methods and the injected code is not syntax-checked The injection is done manually, there isn’t support for injecting the code automatically based on a pattern (though I’ve once implemented a custom Ant task to do execution/call advising for Javassist) Only build-time injection (See GluonJ below for a solution without most of the disadvantages of Javassist.) With Javassist you create a class, which uses the Javassist API to inject code int targets and run it as a part of your build process after the compilation, for example as I once did via a custom Ant task. Example We needed to add some simple performance monitoring to our Java EE application and we were not allowed to deploy any non-approved open-source library (at least not without going through a time-consuming approval process). We’ve therefore used Javassist to inject the performance monitoring code to our important methods and to the places were important external methods were called. The code injector: JavassistInstrumenter.java public class JavassistInstrumenter { public void insertTimingIntoMethod(String targetClass, String targetMethod) throws NotFoundException, CannotCompileException, IOException { Logger logger = Logger.getLogger("Javassist"); final String targetFolder = "./target/javassist"; try { final ClassPool pool = ClassPool.getDefault(); // Tell Javassist where to look for classes - into our ClassLoader pool.appendClassPath(new LoaderClassPath(getClass().getClassLoader())); final CtClass compiledClass = pool.get(targetClass); final CtMethod method = compiledClass.getDeclaredMethod(targetMethod); // Add something to the beginning of the method: method.addLocalVariable("startMs", CtClass.longType); method.insertBefore("startMs = System.currentTimeMillis();"); // And also to its very end: method.insertAfter("{final long endMs = System.currentTimeMillis();" + "iterate.jz2011.codeinjection.javassist.PerformanceMonitor.logPerformance(\"" + targetMethod + "\",(endMs-startMs));}"); compiledClass.writeFile(targetFolder); // Enjoy the new $targetFolder/iterate/jz2011/codeinjection/javassist/TargetClass.class logger.info(targetClass + "." + targetMethod + " has been modified and saved under " + targetFolder); } catch (NotFoundException e) { logger.warning("Failed to find the target class to modify, " + targetClass + ", verify that it ClassPool has been configured to look " + "into the right location"); } } public static void main(String[] args) throws Exception { final String defaultTargetClass = "iterate.jz2011.codeinjection.javassist.TargetClass"; final String defaultTargetMethod = "myMethod"; final boolean targetProvided = args.length == 2; new JavassistInstrumenter().insertTimingIntoMethod( targetProvided? args[0] : defaultTargetClass , targetProvided? args[1] : defaultTargetMethod ); } } Notes: You can see the “low-levelness” – you have to explicitly deal with objects like CtClass, CtMethod, explicitly add a local variable etc. Javassist is rather flexible in where it can look for the classes to modify – it can search the classpath, a particular folder, a JAR file, or a folder with JAR files You would compile this class and run its main during your build process Javassist on Steroids: GluonJ GluonJ is an AOP tool building on top of Javassist. It can use either a custom syntax or Java 5 annotations and it’s build around the concept of “revisers”. Reviser is a class – an aspect – that revises, i.e. modifies, a particular target class and overrides one or more of its methods (contrary to inheritance, the reviser’s code is physically imposed over the original code inside the target class). Advantages No run-time dependencies if build-time weaving used (load-time weaving requires the GluonJ agent library or gluonj.jar) Simple Java syntax using GlutonJ’s annotation – though the custom syntax is also trivial to understand and easy to use Easy, automatic weaving into the target classes with GlutonJ’s JAR tool, an Ant task or dynamically at the load-time Support for both build-time and load-time weaving Disadvantages An aspect can modify only a single class, you cannot inject the same piece of code to multiple classes/methods Limited power – only provides for field/method addition and execution of a code instead of/around a target method, either upon any of its executions or only if the execution happens in a particular context, i.e. when called from a particular class/method If you don’t need to inject the same piece of code into multiple methods then GluonJ is easier and better choice than Javassist and if its simplicity isn’t a problem for you then it also might be a better choice than AspectJ just thanks to this simplicity. The Almighty AspectJ AspectJ is a full-blown AOP tool, it can do nearly anything you might want, including the modification of static methods, addition of new fields, addition of an interface to a class’ list of implemented interfaces etc. The syntax of AspectJ advices comes in two flavours, one is a superset of Java syntax with additional keywords like aspect and pointcut, the other one – called @AspectJ – is standard Java 5 with annotations such as @Aspect, @Pointcut, @Around. The latter is perhaps easier to learn and use but also little less powerful as it isn’t as expressive as the custom AspectJ syntax. With AspectJ you can define which joint points to advise with very powerful expressions but it may be little difficult to learn them and to get them right. There is a useful Eclipse plugin for AspectJ development – the AspectJ Development Tools (AJDT) – but the last time I’ve tried it it wasn’t as helpful as I’d have liked. Advantages Very powerful, can do nearly anything you might need Powerful pointcut expressions for defining where to inject an advice and when to activate it (including some run-time checks) – fully enables DRY, i.e. write once & inject many times Both build-time and load-time code injection (weaving) Disadvantages The modified code depends on the AspectJ runtime library The pointcut expressions are very powerful but it might be difficult to get them right and there isn’t much support for “debugging” them though the AJDT plugin is partially able to visualize their effects It will likely take some time to get started though the basic usage is pretty simple (using @Aspect, @Around, and a simple pointcut expression, as we will see in the example) Example Once upon time I was writing a plugin for a closed-source LMS J2EE application having such dependencies that it wasn’t feasible to run it locally. During an API call, a method deep inside the application was failing but the exception didn’t contain enough information to track the cause of the problem. I therefore needed to change the method to log the value of its argument when it fails. The AspectJ code is quite simple: LoggingAspect.java @Aspect public class LoggingAspect { @Around("execution(private void TooQuiet3rdPartyClass.failingMethod(..))") public Object interceptAndLog(ProceedingJoinPoint invocation) throws Throwable { try { return invocation.proceed(); } catch (Exception e) { Logger.getLogger("AspectJ").warning( "THE INJECTED CODE SAYS: the method " + invocation.getSignature().getName() + " failed for the input '" + invocation.getArgs()[0] + "'. Original exception: " + e); throw e; } } } Notes: The aspect is a normal Java class with the @Aspect annotation, which is just a marker for AspectJ The @Around annotation instructs AspectJ to execute the method instead of the one matched by the expression, i.e. instead of the failingMethod of the TooQuiet3rdPartyClass The around advice method needs to be public, return an Object, and take a special AspectJ object carrying information about the invocation – ProceedingJoinPoint – as its argument and it may have an arbitrary name (Actually this is the minimal form of the signature, it could be more complex.) We use the ProceedingJoinPoint to delegate the call to the original target (an instance of the TooQuiet3rdPartyClass) and, in the case of an exception, to get the argument’s value I’ve used an @Around advice though @AfterThrowing would be simpler and more appropriate but this shows better the capabilities of AspectJ and can be nicely compared to the dynamic java proxy example above Since I hadn’t control over the application’s environment, I couldn’t enable the load-time weaving and thus had to use AspectJ’s Ant task to weave the code at the build time, re-package the affected JAR and re-deploy it to the server. Alternative Solutions Well, if you can’t use a debugger then your options are quite limited. The only alternative solution I could think of is to decompile the class (illegal!), add the logging into the method (provided that the decompilation succeeds), re-compile it and replace the original .class with the modified one. The Dark Side Code injection and Aspect Oriented Programming are very powerful and sometimes indispensable both for troubleshooting and as a regular part of application architecture, as we can see e.g. in the case of Java EE’s Enterprise Java Beans where the business concerns such as transaction management and security checks are injected into POJOs (though implementations actually more likely use proxies) or in Spring. However there is a price to be paid in terms of possibly decreased understandability as the runtime behavior and structure are different from what you’d expect based on the source codes (unless you know to check also the aspects’ sources or unless the injection is made explicit by annotations on the target classes such as Java EE’s @Interceptors). Therefore you must carefully weight the benefits and drawbacks of code injection/AOP – though when used reasonably, they do not obscure the program flow more than interfaces, factories etc. The argument about obscuring code is perhaps often over-estimated. If you want to see an example of AOP gone wild, check the source codes of Glassbox, a JavaEE performance monitoring tool (for that you might need a map not to get too lost). Fancy Uses of Code Injection and AOP The main field of application of code injection in the process of troubleshooting is logging, more exactly gaining visibility into what an application is doing by extracting and somehow communicating interesting runtime information about it. However AOP has many interesting uses beyond – simple or complex – logging, for example: Typical examples: Caching & et al (ex.: on AOP in JBoss Cache), transaction management, logging, enforcement of security, persistence, thread safety, error recovery, automatic implementation of methods (e.g. toString, equals, hashCode), remoting Implementation of role-based programming (e.g. OT/J, using BCEL) or the Data, Context, and Interaction architecture Testing Test coverage – inject code to record whether a line has been executed during test run or not Mutation testing (µJava, Jumble) – inject “random” mutation to the application and verify that the tests failed Pattern Testing – automatic verification that Architecture/Design/Best practices recommendations are implemented correctly in the code via AOP Simulate hardware/external failures by injecting the throwing of an exception Help to achieve zero turnaround for Java applications – JRebel uses an AOP-like approach for framework and server integration plugins – namely its plugins use Javassist for “binary patching” Solving though problems and avoiding monkey-coding with AOP patterns such as Worker Object Creation (turn direct calls into asynchronous with a Runnable and a ThreadPool/task queue) and Wormhole (make context information from a caller available to the callee without having to pass them through all the layers as parameters and without a ThreadLocal) – described in the book AspectJ in Action Dealing with legacy code – overriding the class instantiated on a call to a constructor (this and similar may be used to break tight-coupling with feasible amount of work), ensuring backwards-compatibility o , teaching components to react properly on environment changes Preserving backwards-compatibility of an API while not blocking its ability to evolve e.g. by adding backwards-compatible methods when return types have been narrowed/widened (Bridge Method Injector – uses ASM) or by re-adding old methods and implementing them in terms of the new API Turning POJOs into JMX beans Summary We’ve learned that code injection can be indispensable for troubleshooting, especially when dealing with closed-source libraries and complex deployment environments. We’ve seen three rather different code injection tools – dynamic Java proxies, Javassist, AspectJ – applied to real-world problems and discussed their advantages and disadvantages because different tools may be suitable for different cases. We’ve also mentioned that code injection/AOP shouldn’t be overused and looked at some examples of advanced applications of code injection/AOP. I hope that you now understand how code injection can help you and know how to use these three tools. Source Codes You can get the fully-documented source codes of the examples from GitHub including not only the code to be injected but also the target code and support for easy building. The easiest may be: git clone git://github.com/jakubholynet/JavaZone-Code-Injection.git cd JavaZone-Code-Injection/ cat README mvn -P javaproxy test mvn -P javassist test mvn -P aspectj test (It may take few minutes for Maven do download its dependencies, plugins, and the actual project’s dependencies.) Additional Resources Spring’s introduction into AOP dW: AOP@Work: AOP myths and realities Chapter 1 of AspectJ in Action, 2nd. ed. Acknowledgements I would like to thank all the people who helped me with this post and the presentation including my colleges, the JRebel folk, and GluonJ’s co-author prof. Shigeru Chiba. From http://theholyjava.wordpress.com/2011/09/07/practical-introduction-into-code-injection-with-aspectj-javassist-and-java-proxy/
September 18, 2011
by Jakub Holý
· 38,706 Views · 1 Like
article thumbnail
Apache CXF: How to add custom SOAP headers to the web service request?
Here’s how to do it in CXF proprietary way: // Create a list of SOAP headers List headersList = new ArrayList(); Header testHeader = new Header(new QName("uri:singz.ws.sample", "test"), "A custom header", new JAXBDataBinding(String.class)); headersList.add(testHeader); ((BindingProvider)proxy).getRequestContext().put(Header.HEADER_LIST, headersList); The headers in the list are streamed at the appropriate time to the wire according to the databinding object found in the Header object. This doesn’t require changes to WSDL or method signatures. It’s much faster as it doesn’t break streaming and the memory overhead is less. More on this @ http://cxf.apache.org/faq.html#FAQ-HowcanIaddsoapheaderstotherequest%2Fresponse%3F From http://singztechmusings.wordpress.com/2011/09/08/apache-cxf-how-to-add-custom-soap-headers-to-the-web-service-request/
September 17, 2011
by Singaram Subramanian
· 27,998 Views
article thumbnail
Renaming a DOMNode in PHP
A recent work assignment had me using PHP to pull HTML data into a DOMDocument instance and renaming some elements, such as b to strong or i to em. As it turns out, renaming elements using the DOM extension is rather tedious. Version 3 of the DOM standard introduces a renameNode() method, but the PHP DOM extension doesn’t currently support it. The $nodeName property of the DOMNode class is read-only, so it can’t be changed that way. A node can be created with a different name in the same document, but if you specify a value to go along with it, any entities in that value are automatically encoded, so it’s not possible to pass in the intended inner content of a node if it contains other nodes. The only method I’ve found that works is to replicate the attributes and child nodes of the original node. Attributes are fairly easy, but I ran into an issue replicating children where only the first child of any given node was replicated within its intended replacement and the remaining children were omitted. Here’s the original code that was exhibiting this behavior. foreach ($oldNode->childNodes as $childNode) { $newNode->appendChild($childNode); } The reason for this behavior is that the $childNodes property of $oldNode is implicitly modified when $childNode is transferred from it to $newNode, so the internal pointer of $childNodes to the next child in the list is no longer accurate. To get around this, I took advantage of the fact that any node with any child nodes will always have a $firstChild property pointing to the first one. The modified code that takes this approach is below and has the behavior I originally set out to implement. while ($oldNode->firstChild) { $newNode->appendChild($oldNode->firstChild); } If you’re curious, below is the full code segment for renaming a node. $newNode = $oldNode->ownerDocument->createElement('new_element_name'); if ($oldNode->attributes->length) { foreach ($oldNode->attributes as $attribute) { $newNode->setAttribute($attribute->nodeName, $attribute->nodeValue); } } while ($oldNode->firstChild) { $newNode->appendChild($oldNode->firstChild); } $oldNode->ownerDocument->replaceChild($newNode, $oldNode); Another potential “gotcha” is the argument order of the replaceChild() method, which is the new node followed by the old node rather than the reverse that most people might expect. Thanks to Joshua May for pointing that one out to me; I might never have understood why I was getting a “Not Found Error” DOMException otherwise.
September 15, 2011
by Matthew Turland
· 8,718 Views
article thumbnail
EC2 Interview – AWS Interview – Cloud Interview – 8 Questions
If you're looking for a cloud expert, specifically someone who knows Amazon Web Services and EC2, you'll want to have a battery of questions to assess their knowledge.
September 15, 2011
by Sean Hull
· 111,875 Views · 1 Like
article thumbnail
Spring and PersistenceContextType.EXTENDED
Recently I was introduced to a project that’s already 4 months in development. After a day of coding I realized there’s something wrong with the session and transaction management. Then I found something that I’ve never used and didn’t quite know when it should be used – the EntityManager was injected into DAO objects via @PersistenceContext(type=PersistenceContextType.EXTENDED) First thing to do – google. Found this spring forum discussion, which made it clearer, but not quite. Then I started debugging and realized that the application is de-facto using the session-per-application anti-pattern. Not only that, but each DAO got its own entity manager (and underlying session) instance. An important note here – I say “entity manager and underlying session”, because Hibernate simply wraps its Session with an implementation of the standard EntityManager interface. So it makes a little difference whether we talk about entity manager or session. What happens? PerssitenceContextType.EXTENDED means that you, rather than spring, are in charge of managing your session. All spring does is create it on startup and close it on shutdown. The other option (which is the default – PerssitenceContextType.TRANSACTION) lets spring’s transaction managers create the entity manager (and session) for each request, start a transaction, and when you are finished – commit the transaction and close the session. This is called session and transaction management, and it is one of the most important things to do in a spring & JPA project. It should be done right almost from the start, so the next time you do such a project, spend extra days to get this right. But what is wrong with the above situation? Here are some effects of the extended manager: Each DAO gets a different instance of the EntityManager so you can’t do any meaningful work that involves two DAOs. If you insert a records with one EntityManager and try to use it in another one – it won’t work. The first hasn’t been flushed, and the second does not have the 1st level cache. If a session does not get closed it accumulates entities (it stores them in memory so that it doesn’t have to fetch them multiple times from the DB). Which is a pure memory leak. It is not thread-safe. The Session and EntityManager objects are not thread-safe. Since you are most likely to inject them in a singleton DAO object you will start getting weird results due to concurrent access How did this happen and why it got unnoticed for so long? I have a theory. 1. People started using the DAO layer directly from the web layer 2. Something wasn’t working for someone, so he changed the type of the persistence context, which made his code work. 3. As the project is not having many inserts, people were mainly reading data and didn’t stumble upon the various problems. 4. There hasn’t been extensive testing, with multiple people on the same instance, so the concurrency problems were not spotted. One more thing – PersistenceContextType.EXTENDED is useful in limited scenarios. The so called long-running session or session-per-conversation. When you have wizards you can have multiple requests with the same session, which saves some detaching and merging. But should you use that, make sure you don’t do it for the whole application and that you are absolutely know what you are doing. And close the session when the conversation ends. Another scenario is usage in EJB stateful beans. (In general, the extended persistence context makes more sense in a JavaEE environment) So to summarize: Spend a lot of time to properly configure session and transaction management and try to get it right Almost never use PersistenceContextType.EXTENDED in spring (outside a JavaEE container at least) Don’t use the DAO layer directly from the web layer. A base service class with wrappers for the most used operations would not be too verbose, but will save you countless headaches Code reviews should be thorough, or commit rights to core classes and configurations should be limited to a number of people that know what they are doing From http://techblog.bozho.net/?p=417
September 13, 2011
by Bozhidar Bozhanov
· 13,826 Views · 35 Likes
article thumbnail
Memory Barriers/Fences
In this article I'll discuss the most fundamental technique in concurrent programming known as memory barriers, or fences, that make the memory state within a processor visible to other processors. CPUs have employed many techniques to try and accommodate the fact that CPU execution unit performance has greatly outpaced main memory performance. In my “Write Combining” article I touched on just one of these techniques. The most common technique employed by CPUs to hide memory latency is to pipeline instructions and then spend significant effort, and resource, on trying to re-order these pipelines to minimise stalls related to cache misses. When a program is executed it does not matter if its instructions are re-ordered provided the same end result is achieved. For example, within a loop it does not matter when the loop counter is updated if no operation within the loop uses it. The compiler and CPU are free to re-order the instructions to best utilise the CPU provided it is updated by the time the next iteration is about to commence. Also over the execution of a loop this variable may be stored in a register and never pushed out to cache or main memory, thus it is never visible to another CPU. CPU cores contain multiple execution units. For example, a modern Intel CPU contains 6 execution units which can do a combination of arithmetic, conditional logic, and memory manipulation. Each execution unit can do some combination of these tasks. These execution units operate in parallel allowing instructions to be executed in parallel. This introduces another level of non-determinism to program order if it was observed from another CPU. Finally, when a cache-miss occurs, a modern CPU can make an assumption on the results of a memory load and continue executing based on this assumption until the load returns the actual data. Provided “program order” is preserved the CPU, and compiler, are free to do whatever they see fit to improve performance. Figure 1. Loads and stores to the caches and main memory are buffered and re-ordered using the load, store, and write-combining buffers. These buffers are associative queues that allow fast lookup. This lookup is necessary when a later load needs to read the value of a previous store that has not yet reached the cache. Figure 1 above depicts a simplified view of a modern multi-core CPU. It shows how the execution units can use the local registers and buffers to manage memory while it is being transferred back and forth from the cache sub-system. In a multi-threaded environment techniques need to be employed for making program results visible in a timely manner. I will not cover cache coherence in this article. Just assume that once memory has been pushed to the cache then a protocol of messages will occur to ensure all caches are coherent for any shared data. The techniques for making memory visible from a processor core are known as memory barriers or fences. Memory barriers provide two properties. Firstly, they preserve externally visible program order by ensuring all instructions either side of the barrier appear in the correct program order if observed from another CPU and, secondly, they make the memory visible by ensuring the data is propagated to the cache sub-system. Memory barriers are a complex subject. They are implemented very differently across CPU architectures. At one end of the spectrum there is a relatively strong memory model on Intel CPUs that is more simple than say the weak and complex memory model on a DEC Alpha with its partitioned caches in addition to cache layers. Since x86 CPUs are the most common for multi-threaded programming I’ll try and simplify to this level. Store Barrier A store barrier, “sfence” instruction on x86, forces all store instructions prior to the barrier to happen before the barrier and have the store buffers flushed to cache for the CPU on which it is issued. This will make the program state visible to other CPUs so they can act on it if necessary. A good example of this in action is the following simplified code from the BatchEventProcessor in the Disruptor. When the sequence is updated other consumers and producers know how far this consumer has progressed and thus can take appropriate action. All previous updates to memory that happened before the barrier are now visible. private volatile long sequence = RingBuffer.INITIAL_CURSOR_VALUE; // from inside the run() method T event = null; long nextSequence = sequence + 1L; while (running) { try { final long availableSequence = dependencyBarrier.waitFor(nextSequence); while (nextSequence <= availableSequence) { event = dependencyBarrier.getEvent(nextSequence); eventHandler.onEvent(event, nextSequence == availableSequence); nextSequence++; } sequence = event.getSequence(); // store barrier inserted here !!! } catch (final Exception ex) { exceptionHandler.handle(ex, event); sequence = event.getSequence(); // store barrier inserted here !!! nextSequence = event.getSequence() + 1L; } } Load Barrier A load barrier, “lfence” instruction on x86, forces all load instructions after the barrier to happen after the barrier and then wait on the load buffer to drain for that CPU. This makes program state exposed from other CPUs visible to this CPU before making further progress. A good example of this is when the BatchEventProcessor sequence referenced above is read by producers, or consumers, in the corresponding barriers of the Disruptor. Full Barrier A full barrier, "mfence" instruction on x86, is a composite of both load and store barriers happening on a CPU. Java Memory Model In the Java Memory Model a volatile field has a store barrier inserted after a write to it and a load barrier inserted before a read of it. Qualified final fields of a class have a store barrier inserted after their initialisation to ensure these fields are visible once the constructor completes when a reference to the object is available. Atomic Instructions and Software Locks Atomic instructions, such as the “lock ...” instructions on x86, are effectively a full barrier as they lock the memory sub-system to perform an operation and have guaranteed total order, even across CPUs. Software locks usually employ memory barriers, or atomic instructions, to achieve visibility and preserve program order. Performance Impact of Memory Barriers Memory barriers prevent a CPU from performing a lot of techniques to hide memory latency therefore they have a significant performance cost which must be considered. To achieve maximum performance it is best to model the problem so the processor can do units of work, then have all the necessary memory barriers occur on the boundaries of these work units. Taking this approach allows the processor to optimise the units of work without restriction. There is an advantage to grouping necessary memory barriers in that buffers flushed after the first one will be less costly because no work will be under way to refill them. From http://mechanical-sympathy.blogspot.com/2011/07/memory-barriersfences.html
September 12, 2011
by Martin Thompson
· 26,152 Views · 8 Likes
article thumbnail
Asynchronous Method calls with Groovy: @Async AST
At work, I needed to create a very simple background job, without any concern about what I could get back, because mostly all the hard work was just batch processing and persistence, and all exceptions or roll-back concerns were already taking care of. At the beginning I used a very simple way to call my background job, using Java's: Executors.newSingleThreadExecutor() void myBackgroundJob() { Executors.newSingleThreadExecutor().submit(new Runnable() { @Override public void run() { //My Background Job } }); } And it worked great, just what I needed. Using Groovy facilitate even more the way to create a new Background job, as simple as: def myBackgroundJob() { Thread.start { //My Background Job } } Then, after this simple way to send something into the background, I decided to create a new AST in groovy, that remove the need to remember or copy and paste the same logic. I created two annotations that help to identify the class and the methods that are going to be put into a new Thread. One for the Class: package async import org.codehaus.groovy.transform.GroovyASTTransformationClass import java.lang.annotation.* import xml.ToXmlTransformation @Retention (RetentionPolicy.SOURCE) @Target ([ElementType.TYPE]) @GroovyASTTransformationClass (["async.AsyncTransformation"]) public @interface Asynchronous { } And the other for the Method: package async import org.codehaus.groovy.transform.GroovyASTTransformationClass import java.lang.annotation.* import async.AsyncTransformation @Retention (RetentionPolicy.SOURCE) @Target ([ElementType.METHOD]) @GroovyASTTransformationClass (["async.AsyncTransformation"]) public @interface Async { } then the Asynchronous Transformation, using the AstBuilder().buildFromString(). Here I combined a GroovyInterceptable to connect the method being call with the AST transformation to wrapped with the Thread logic. package async import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.transform.* import org.codehaus.groovy.ast.* import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.ast.builder.AstBuilder import org.codehaus.groovy.ast.stmt.ExpressionStatement import org.codehaus.groovy.ast.expr.MethodCallExpression import org.codehaus.groovy.ast.expr.ClosureExpression import org.codehaus.groovy.ast.expr.ConstantExpression import org.codehaus.groovy.ast.stmt.BlockStatement import org.codehaus.groovy.ast.expr.ClassExpression import org.codehaus.groovy.ast.expr.ArgumentListExpression @GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS) //CompilePhase.SEMANTIC_ANALYSIS class AsyncTransformation implements ASTTransformation{ void visit(ASTNode[] astNodes, SourceUnit sourceUnit) { if (!astNodes ) return if (!astNodes[0] || !astNodes[1]) return if (!(astNodes[0] instanceof AnnotationNode)) return if (astNodes[0].classNode?.name != Asynchronous.class.name) return def methods = makeMethods(astNodes[1]) if(methods){ astNodes[1]?.interfaces = [ ClassHelper.make(GroovyInterceptable, false), ] as ClassNode [] astNodes[1]?.addMethod(methods?.find { it.name == 'invokeMethod' }) } } def makeMethods(ClassNode source){ def methods = source.methods def annotatedMethods = methods.findAll { it?.annotations?.findAll { it?.classNode?.name == Async.class.name } } if(annotatedMethods){ def expression = annotatedMethods.collect { "name == \"${it.name}\"" }.join(" || ") def ast = new AstBuilder().buildFromString(CompilePhase.INSTRUCTION_SELECTION, false, """ package ${source.packageName} class ${source.nameWithoutPackage} implements GroovyInterceptable { def invokeMethod(String name, Object args){ if(${expression}){ Thread.start{ def calledMethod = ${source.nameWithoutPackage}.metaClass.getMetaMethod(name, args) calledMethod?.invoke(this, args) } }else{ def calledMethod = ${source.nameWithoutPackage}.metaClass.getMetaMethod(name, args)?.invoke(this,args) } } } """) ast[1].methods } } } The example: package async @Asynchronous class Sample{ String name String phone @Async def expensiveMethod(){ println "[${Thread.currentThread()}] Started expensiveMethod" sleep 15000 println "[${Thread.currentThread()}] Finished expensiveMethod..." } @Async def otherMethod(){ println "[${Thread.currentThread()}] Started otherMethod" sleep 5000 println "[${Thread.currentThread()}] Finished otherMethod" } } println "[${Thread.currentThread()}] Start" def sample = new Sample(name:"AST EXample",phone:"1800-GROOVY") sample.expensiveMethod() sample.otherMethod() println "[${Thread.currentThread()}] Finished" Final Notes: As you can see on the example I need to have the Asynchronous annotation on the class still. It could be better without it and just annotate the methods, something like the Groovy's SynchronizedASTTransformation. If you have any idea to complement this small example, please clone the source code [here], and let me know what you think. I could used the @javax.ejb.Asynchronous or the Spring's @org.springframework.scheduling.annotation.Async, but I only needed a very simple solution without any other configuration or library inclusion. The remain logic here could be play more with multi threading and expect some results like: java.util.concurrent.Future and its java.util.concurrent.Future.get() method or maybe integrated with another frameworks like Spring. Source: [Here]
September 11, 2011
by Felipe Gutierrez
· 28,287 Views · 4 Likes
  • Previous
  • ...
  • 862
  • 863
  • 864
  • 865
  • 866
  • 867
  • 868
  • 869
  • 870
  • 871
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×