A Single Line of Code Which Keeps Your REST/Hessian/HTTP Client State 📎
import java.net.CookiePolicy;
import java.net.CookieManager;
import java.net.CookieHandler;
public class HessianStatefulTimeEndpoint {
private TimeService timeService;
@Before
public void initProxy() throws MalformedURLException {
CookieHandler.setDefault(new CookieManager(null /*=default in-memory store*/, CookiePolicy.ACCEPT_ALL));
String url = "http://localhost:8080/EJB31AndHessian/TimeService";
HessianProxyFactory factory = new HessianProxyFactory();
this.timeService = (TimeService) factory.create(TimeService.class,url);
assertNotNull(timeService);
}
@Test
public void statefulness(){
int numberOfSessions = this.timeService.getNumberOfSessions();
int nextInvocation = this.timeService.getNumberOfSessions();
assertEquals(numberOfSessions,nextInvocation);
}
}
On the server server you can inject @SessionScoped beans into the HessianServlet:
public class HessianTimeEndpoint extends HessianServlet implements TimeService{
@Inject
CurrentTime currentTime;
...
}
@SessionScoped
public class CurrentTime implements Serializable{
private static AtomicInteger instanceCount = new AtomicInteger(0);
@PostConstruct
public void onNewSession(){
System.out.println("On new session: " + new Date());
instanceCount.incrementAndGet();
}
public int getNumberOfSessions(){
return instanceCount.get();
}
public long nanos(){
return System.nanoTime();
}
}
You will find the executable project (tested with Netbeans 7 and Glassfish v3.1) in: http://kenai.com/projects/javaee-patterns/ [project name: EJB3AndHessian - the original project was updated].
[See also Service Facade pattern, page 69 Real World Java EE Patterns - Rethinking Best Practices]