## Wednesday, April 26, 2006

### Null vs. Errors

I am not particularly a fan of  JCS (Jakarta Cache System) as I find ehcache code very clean and simple. But I have to say the author has some good comments on the site:

Nulls vs. Errors

I started to support ObjectNotFoundExceptions for failed gets but the overhead and cumbersome coding needed to surround a simple get method is ridiculous. Instead the JCS return null.

For having seen too many times the ObjectNotFoundException "pattern", I can only agree!

### Algorithms in Java (Third Edition) Book Review

The book Algorithms in Java is huge, but unlike the usual huge books, the content is very interesting. It can be used as reference material, or as toilet book (to learn things while you're wasting time in the toilets).

You will learn simple things, like what is the "raison d'être" of linked lists. The author gives very good examples to illustrate his propositions. He explains through the sieve of erathostene and through Josephus problem the advantages of arrays or linked list.

You will learn step by step everything that is to be known in algorithms. Recursion, divide and conquer, Tree knowledge will be useful for the later sorting and searching chapters.

The chapter on Hashing will make you understand very clearly why the source of String.hashCode() is
public int hashCode() {
  int h = hash;
  if (h == 0) {
     int off = offset;
     char val[] = value;
     int len = count;
     for (int i = 0; i <  len; i++) h = 31*h + val[off ++];
     hash = h;
  }
  return h;
}

There might be too much info on different types of sorting algorithms and the book becomes there more a reference book than anything else. But overall, you will learn plenty with this book. It is very well written, complete, and will refresh one's memory. I find it useful to read back things I learnt after a few years as I then have a very different view of the subject, and I pay closer attention to some details I completely missed the first time (sometimes).
Tags:

## Monday, April 24, 2006

### Last week Javablogs.com top 10

Most read last week

1. Why I hate tomcat (326): Everyone uses tomcat, and nobody believes the tiny minority of us who hate it. Tomcat sucks, plain and simple. For such an important piece of infrastructure, [read]

2. Java Everywhere - especially at Google (234): Just in case some people missed it, there are some heavy-hitter Java evangelists over at Google, many of whom went over to the Googly side about 1.5 years ago. There’s Joshua Bloch, [read]

3. Grails: Ruby on Rails feeling the heat (231): Up until now I have not wanted to be drawn into a Grails vs Rails debate, clearly not wanting to start a flame war with the Ruby community, [read]

4. Linux, what a crappy OS (225): Yea, I said it - Linux is a crappy OS. I started developing on Linux, not just deploying to it, and the fact that I can't easily find a terminal that supports horizontal scrolling is baffling. [read]

5. How long do you stay a programmer (212): I wondered today if you become bored of programming, the everyday cut and thrust of programming problems. [read]

6. Humor: Hani's First Day at the JCP (210): Hani Suleiman, the voice - or something - behind The BileBlog, is now a member of the JCP's Executive Committee. In this latest Tale from the ServerSide, [read]

7. 10 Things I Hate About Wikis (208): OK, so wikis are a great idea. I have “embraced the wiki” as a great communication tool, and there are many, many benefits. But still they manage to get to me. [read]

8. Scott McNealy Leaving (as CEO) Sun Microsystems? (206): I just got a call from someone that was high up at sun saying "Do I know what's happening next week at Sun". He told me that scott is leaving his post next week. [read]

9. PHP and Ruby: Evolution before Revolution (206): It has been a pleasure to use Rails for web applications that are suited to it, especially green field applications. But not all projects are green fields, [read]

Most read last week-end

1. Java Everywhere - especially at Google (234): Just in case some people missed it, there are some heavy-hitter Java evangelists over at Google, many of whom went over to the Googly side about 1.5 years ago. There’s Joshua Bloch, [read]

2. Grails: Ruby on Rails feeling the heat (231): Up until now I have not wanted to be drawn into a Grails vs Rails debate, clearly not wanting to start a flame war with the Ruby community, [read]

3. OR Mapping vs. Active Record (129): I'm working thru the Ruby on Rails book and I'm finding Active Record interesting. I've always preferred a rich domain model, but the price for that has been mapping to a relational database. [read]

4. SOA: dead man walking (113): Could not have said it better myself: “What do you think we should do about SOA?” Which weirdly, nobody had asked me before, and I could find only one answer: “Don’t do anything. [read]

5. SOA is too complex and ‘just vendor BS’ (107): …and don’t flame me :) - those are the words of Tim Bray. “What do you think we should do about SOA?” Which weirdly, nobody had asked me before, [read]

6. Russell Beattie's "Last Page" (107): Russ wrote his last page on his notebook/weblog. Hey Russ, I am looking forward to the 1st page, your first chapter of your new "book"... Lot's of great contributions by you, [read]

7. Rails realities part 11 (semi-frozen rails) (101): You know those times when something all of a sudden stops working for seemingly no reason at all? Well about a half hour ago was one of those times for my rails app. [read]

8. Using log4j to monitor web application errors (100): When monitoring a production website (especially with a dozen or so application servers) you don’t want to rely on combining the logs and reviewing them manually for exceptions, [read]

9. 6 Java sourceforge projects you may find interesting (Spring/Hibernate/...) (99): Here is a list of java sourceforge projects I went into that I found interresting, by interresting I mean new ideas, nice code, [read]

## Wednesday, April 19, 2006

### Caching HTTP Responses in Java

Caching HTTP response can dramatically improve performance of your app if what you generate is in reality not very dynamic. There are many free caching frameworks in Java. Most popular seem to be ehcache, oscache, jcs and JBoss Cache.

ehcache is quite simple to use and its code is clean. They have a CachingFilter that you can put in your webapp server to cache transparently HTTP responses. However as the framework only allows you to store Objects (which makes sense for most uses), I was wondering how they cached the HttpResponse which is a stream. I was a bit disappointed by the answer, they just create a copy ByteArrayOutputStream and call toBytes() to store it in the cache. While this is optimal for a memory cache store (the whole response will anyway be in the cache, although I am not sure if they check for particularly big responses to avoid caching those or try to cache those) I don't think it is that good for a disk cache store.

Ideally one would like the response to be stored using a buffer, to avoid having the whole response in memory. This would enable a much higher concurrent use. I think it is doable by writing your own CachingFilter and by using the concurrent utils Queue to block writing when the buffer is full.

I googled for this kind of stuff without success. I only found solutions similar to ehcache one (for example sun CachingResponseWrapper and CachingFilter or oscache CacheFilter (a bit more careful, but still a toBytes())) I wonder why it is not already done and public.

## Tuesday, April 18, 2006

### Javablogs.com 2005 Top 20

Most read in 2005

1. New in Hibernate 3: Criteria API enhancements (816): Projection, aggregation, subselects, detatched criterias - its all there in the Hibernate 3 Criteria API. Let me show you some examples, starting with the new projection API.… [read]

2. Hello, IDEA! (555): From the recent Java IDE discussions, it seems like there's a good portion of Java programmers who don't know IntelliJ IDEA, or simply haven't tried it yet. In this short screencast,… [read]

3. Hey Gosling: This is why we don’t use Java 5.0 yet! (461): Whenever there is a major JDK update everyone on the Sun Microsystems side seems to love to beat the drum of upgrading.… [read]

5. The worst code I've ever seen. Yes, that's true. (422): I've been in this business for 25 years and have been programming since the mid seventies. Even when I was a young pup, full of bright ideas and hubris and those around me were at least as bad,… [read]

6. JSP is officially dead (407): Well, it looks like with the Final Draft of Java EE 5, the final nail has been placed in JSP's coffin.… [read]

7. My wife is hot and she can code, too (400): My wife Keri loves puzzle games--tetris, scrabble, crosswords, text twist--any game where you have to figure something out, she's on it. She has a degree in CS, and is employed as a UI specialist,… [read]

8. IBM announced SOMA - Service-Oriented Modelling and Architecture (396): [read]

9. G-mail runs on Tomcat???!!!!! (390): Well, hello guys and gals...haven't been in the Java blog scene recently, but am glad to know Java is going strong as ever (not that I ever doubted it,… [read]

10. Web Services articles (374): [read]

11. Bill Gates tries Firefox (362): Tim Weber of the BBC reporter rustles up Bill Gates quote of 2005: Bill Gates is one of the people with Firefox on his computer, so I asked him for his opinion. I played around with it a bit,… [read]

12. Language Oriented Programming: Everything is a Language (361): Some people don't 'get' Language Oriented Programming. It's a different perspective. Once you make the mental shift, everything starts to fall into place. Over the past few months,… [read]

13. The killer app for Web 2.0 has arrived (356): Time to throw in the towel, 37 Signals. The future has arrived: iClock (via flocksucks) [read]

14. New Search Engine Blows Google Away (356): After months of incredibly secret development, PreviewSeek Limited has launched the PreviewSeek search engine. My initial impression? It blows google away with its far more powerful searches. [read]

15. Death to Apache (356): So our Apache heros have now decided that it isn't quite enough to prove to the world that they are abysmal failures at producing a J2EE container,… [read]

16. WebSphere 6.0 System Management Enhancements (356): [read]

17. It's Official, Struts is History! (352): [read]

18. What Steve isn't telling us (348): So the rumors were true, Apple is really switching to Intel.  There are a lot of interesting things in Steve Jobs' keynote, as usual, but the most interesting part is,... [read]

19. RE: Why I Ditched Hibernate (346): I saw this post and couldn't help but respond. The post's author, Bruce, is ditching Hibernate and Spring b/c he wants to use a connection pool (configured in Tomcat) instead.… [read]

### How To Use Java With Blogger: A Tutorial

Blogger has a REST API. I use it to retrieve particular posts or to post transformed data. There is no Java API that I know of, but you will see here it is not very difficult to interface with Blogger API in Java using plain old XML.

Using libraries commons-httpclient and DOM4J it would be quite easy to implement your own Java Blogger API as the following code will suggest.

Authenticate
All requests need to be authenticated and are done in HTTPS. I use common-httpclient to perform requests. Here is how to setup the client:
private  HttpClient initHttpClient(){  HttpClient client  = new HttpClient();  List authPrefs =  new ArrayList(2);  authPrefs.add(AuthPolicy.DIGEST );  authPrefs.add(AuthPolicy.BASIC);  client.getParams().setParameter (AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);  client.getParams().setAuthenticationPreemptive(true);  Credentials defaultcreds = new UsernamePasswordCredentials(user, password);   client.getState().setCredentials(new AuthScope( "www.blogger.com", 443, AuthScope.ANY_REALM), defaultcreds);  return client;          }

To retrieve the posts, you just have to query the right url, and parse the XML response. I prefer to use DOM4J, because of its handy asXML() method to print a node as XML. For simplicity I use a Map to store an XML entry.

public Collection getPosts() throws  HttpException, IOException, ParserConfigurationException, SAXException, DocumentException {  GetMethod get = new  GetMethod("https://www.blogger.com/atom" +"/"+blogId);  int  statusCode = client.executeMethod(get);  if   (statusCode !=  HttpStatus.SC_OK)  {    throw new RuntimeException(" Could not make HTTP  request properly: " +get.getStatusLine());  }  InputStream response  = get.getResponseBodyAsStream();  SAXReader reader = new  SAXReader();  Document doc = reader.read(response);  Collection posts = new ArrayList();  List entries  = doc.getRootElement().elements("entry");  if (LOG.isDebugEnabled())   {    LOG.debug("found  "+entries.size()+"  entries");  }  for (int  i = 0; i <entries.size();i ++)  {    Element entry  = (Element) entries.get(i);     Map m = new  HashMap();    for (Iterator it = entry.elementIterator();it. hasNext();)    {      Element detail =  (Element) it.next();      String name = detail.getName();      if (name.equals("link"))      {        m.put("link ",detail.attribute("href").getValue());      }      else if (name. equals("content"))      {        m.put("content",detail.asXML());      }      else      {         m.put(name,detail.getTextTrim());      }     }    posts.add(m);                       if  (LOG.isDebugEnabled())    {      LOG.debug( "found="+m.get(" title")+", url= "+m.get("link"));     }  }  return  posts;}

Create XML for a new Post
Nothing particular here, just XML production.
private String createXmlForCreatePost(String postTitle, String postContent) throws   IOException, DocumentException{  SAXReader xmlReader =  new SAXReader();  xmlReader.setValidation(false );  Document doc = DocumentHelper.createDocument();  QName rootName  = DocumentHelper.createQName("entry", new  Namespace("", "http://purl.org/atom/ns# "));  Element root = doc.addElement(rootName);  Element title = root.addElement("title");   title.addAttribute("mode"," escaped");  title.addAttribute("type ","text/plain");  title.setText (postTitle);  Element generator = root.addElement("generator ");  generator.addAttribute("url" , "http://31416.org");  generator. setText("31416 Java Generator ");  Element content = root.addElement("content ");  content.addAttribute("type" , "application/xhtml+xml");  //Element  div = content.addElement(DocumentHelper.createQName("div",new  Namespace("","http://www.w3.org/1999/xhtml")));  //div.add(...); //YOUR XHTML HERE  StringWriter result = new  StringWriter();  XMLWriter writer = new XMLWriter (result);  writer.write(doc);  writer.close();  return result.toString();}

That's it

### Last week Javablogs.com top 10

Most read last week

1. Stupid Command Prompt Tricks (289): These Stupid (Windows) Command Prompt Tricks actually look rather useful. [read]

2. The truth about Tudu Lists!! (260): I've now been working on Tudu Lists for more than one year, and I'm releasing today version 1.1. With this latest release, it is now time for me to tell the truth about Tudu Lists.… [read]

3. Toplink vs hibernate (258): I still remember the excitement I felt when I started working on Toplink. It was early 2000. Before that, I was working mainly in visual c++.… [read]

4. Why RedHat bought JBoss (249): RedHat has a market cap of roughly 20x revenues, which quite frankly is unheard of; most companies would kill to have a P/E ratio that high, let alone a price-to-sales ratio!… [read]

5. Red Hat Acquires JBoss (214): It is official. Now the corp office is in my back yard!… [read]

6. Google Calendar is now live (212): The subject says it all... Go ahead: log in, play around and post your suggestions and impressions as long as it's not "It doesn't work on Safari" (usually the... [read]

7. Why is Tomcat called Tomcat (208): Every now and again the topic of why Tomcat is called Tomcat pops up and I don't know anyone who actually knew Anyway I thought I would look it up so if anyone else asked me I could tell them the… [read]

8. RANT: Eclipse Sucks (186): Eclipse has an AI engine that realizes when I haven't used it often enough for it to have burned me recently to kick in and do something really painful to me.… [read]

9. Top ten use case mistakes (170): Top ten use case mistakes -Tyner Blain: We’re reiterating the top five use case mistakes from Top five use case blunders and adding five more. For details on the first five, go back to that post.… [read]

Most read last week-end

1. Top ten use case mistakes (170): Top ten use case mistakes -Tyner Blain: We’re reiterating the top five use case mistakes from Top five use case blunders and adding five more. For details on the first five, go back to that post.… [read]

2. Netbeans versus Eclipse (155): Eclipse has been the leader of the pack for the last five years but with Netbeans becoming free, is Eclipse's title of most popular IDE coming to an end.… [read]

3. MacBook vs. Athlon XP Java benchmark (150): So i finally made a first mini benchmark regarding my new hardware. Of course i was curious how the macBook performs against my old (somewhat outdated) PC platform.… [read]

4. Eclipse 3.2 RC1 Released (143): Eclipse 3.2 RC1 is out and is available for download. Other Callisto release projects are releasing over the next two weeks. 39 words.… [read]

5. 7 Hour Daily Commute (139): This person does an astonishing 7 hour commute to get to work. Everyday. And he's been doing it since 1989. I'm too astonished to criticize. Also, it's just too easy..... [read]

6. Google Calendar - Oh so close! (135): It took me a few years to switch from Yahoo!… [read]

7. MacBook Pro Update (121): I’m loving my new MacBook Pro, but… it’s definitely far from perfect.… [read]

8. Next Generation Frameworks are only superficially competitors (117): There's an interesting thread over on the Grails mailing list.… [read]

9. Is Memory Management in Java Garbage? (117): A friend of mine who was learning C# commented he felt C# was a more powerful because you had to memory manage yourself and it took more effort to create and destroy objects.… [read]

## Monday, April 10, 2006

### Web Services No Better Than CORBA?

Richard Monson-Haefel (RMH), author of the famous Enterprise Java Beans (O'Reilly) and of a Web Services book is making an alarming claim about JAX-WS, the new Java web services standard:
JAX-WS still sucks!

In an effort to write a client to real world web services (for Google, Amazon, Ebay), he mostly failed. Errors seem to be largely related to WSDL to Java conversion. Jason Green, a JBoss developer, managed to get quickly a web service working for Ebay, but analysis by RMH suggest that hundreds of classes were generated for this simple one method web service.

Recently I had to try to do CORBA client classes by hand in Java since the rmic tool was not working that well to generate classes that could be run on a client JVM of different version than the server JVM. It proved to be a no-go in the end, because of the complexity involved not only in coding, but more on maintaining those modified generated classes. This would have required coding a tool dedicated for that purpose. We chose to pass simpler objects, differently, which looks just like a hack to avoid having CORBA issues. I am amazed that after that many years of CORBA, there are still simple cases where it does not work properly automatically.

Seeing that there is the same kind of problem with Web Services (IDL to Java translation) makes me wonder about Web Services "improvement" over CORBA. And WSDL is definitely less readable than CORBA IDL.

## Friday, April 07, 2006

### Is your UML Composition French or American?

The French Way
In many French books/lessons (a lesson here, another from caen university , one from UQAM), UML composition does not seem to mean the same as their English counterparts. They write:
Si l'agrégat est détruit (ou copié), ses composants le sont aussi.
or
les composants (en tant qu'ils sont composants) ont une durée de vie incluse dans celle de leur composé.

translated to English:
If the aggregate is destroyed (or copied), its components are destroyed (or copied) as well.
or
components (while they are components) lifetime is included in the one of their aggregate

But then what does it mean to have a cardinality of 0 on the aggregate side?
Few French lessons give an answer (UQAM does, maybe because it's half French only). The component can be created before the aggregate but must be destroyed when the aggregate is.

The American Way

Most English books/lessons describe composition more accurately. Ootips definition is simple and clear:
Composition [...] is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.

However Martin Fowler in UML distilled explicitly writes:
The "no sharing" rule is the key to composition . Another assumption is that if you delete the polygon, it should automatically ensure that any owned Points also are deleted .

By using the word "assumption" he is avoiding a clear meaning. So I looked up in the UML specifications from uml.org. The specs are actually very near ootips definition and even more explicit:
An association may represent a composite aggregation (i.e., a whole/part relationship). Only binary associations can be aggregations. Composite aggregation is a strong form of aggregation that requires a part instance be included in at most one composite at a time. If a composite is deleted, all of its parts are normally deleted with it. Note that a part can (where allowed) be removed from a composite before the composite is deleted, and thus not be deleted as part of the composite. Compositions define transitive asymmetric relationships—their links form a directed, acyclic graph.

So it turns out that some French definitions were not wrong, but imprecise. Their true meaning becomes only clear after reading the English UML specs.

Ootips has also a good example of difference between aggregation and association. If you have an aggregation relation between two Node entities, it means you represent a tree of Nodes, not a graph of Nodes. See the link for more details.

## Tuesday, April 04, 2006

### Are UML Aggregation and Composition Good Concepts?

Yesterday a work collegue made the remark that the notions of aggregation and composition were not very clear. I was a bit surprised at first. But I actually almost always use just associations relations, sometimes composition, I was not sure anymore about the difference between aggregation and association and the one between composition and aggregation. I had to look up in a book to remember what it was all about.

The French book we looked at was really bad. In the end we did not understand fully the differences except a notion of "stronger coupling", some kind of "asymetry"!?! The difference between aggregation and composition was more explicit since in a composition, the "child" can only have one parent.

The UML Distilled book is much more explicit and I recommend that book to anybody doing UML:
• Aggregation is strictly meaningless ; as a result, I recommend that you ignore it in your own diagrams .If you see it in other people's diagrams, you'll need to dig deeper to find out what they mean by it . Different authors and teams use it for very different purposes.
• Composition is a good way of showing properties that own by value, properties to value objects (page 73), or properties that have a strong and somewhat exclusive ownership of particular other components.

Bertrand Meyer prefers to describe relationships using only two concepts, client and heir, basically UML association and specialization and therefore avoids the distinction between aggregation and composition and association:
• B is a client of A if every object of type B may contain information about one or more objects of type A.
• B is an heir of A if B denotes a specialized version of A.
He then uses "class invariants" to specify the nature of the client relationship.