RadialContext in FireFox 3.5



if you (like me) want to continue using radialcontext-mz 1.1 under Firefox 3.5, you could.
just tweak it that way:

* download the xpi
* open it with a zip-program of your choice
* edit install.rdf with the editor of your choice
* change line 28 from em:maxVersion=”3.0.*” to em:maxVersion=”3.5.*”
* put it back in the zip (xpi)
* start Firefox
* drop xpi in
* be happy

or

just download it here

Uh, that was quick….

no graphic artists were hurt during the process…



that was fun. not that i actually liked these bonbon-buttons, but the disclaimer on their page is hilarious.
having a second look, that layout-manager concept can be actually useful.

m2eclipse on Galileo usable



despite rumours, m2eclipse seems usable on eclipse 3.5 Galileo, so that we can happily upgrade. just added MoreUnit as well as the mylyn atlassian connector, and it all seems to work seamlessly.

Looking for Galileo release notes ?

Design hint : introduce Null Object


I’m currently reading Refactoring from Martin Fowler. Overall, it’s an interesting book from which much could be said but tonight I would like to speak only of the “introduce Null object” hint provided in it.

The basic idea is pretty simple, instead of checking for null return from various call, just provide a “null object”. It means a real object but with no content. The clue is that this object knows how to handle method calls, rendering the right enum/int value/you name it according to its logic.

As such, no need to return null and then check for null everywhere. No result for search of Bla ? Simple, return the missingBla object !

Apparently it helped them quite a lot to skip of these redundant checkings, allowing as well to easily display objects full of others objects instances. Indeed, one instance being null is not an issue any more : calling person.getAdress() and then address.getStreet() providing now a missingAddress then a null street string. Some NPE may still appear, but way less than before apparently.

It’s the first time I see this hint and at first look it seems promising. Does someone have some second thought on it ? I’ll search more on it later on, maybe some caveats are known which would explain its relative anonymity !

NB : instead of using the term Null Object they use “missing object” apparently, which might avoid some confusions… Still on the “note side”, please note as well that the “missing objects” are always constant, making their usage pretty easy (and singleton like).

For resources, I found while writing this post that Martin provides a full list of each of the design hints he writes about, and even more (he provides updates and new ones). For the Null Object, it’s there, and probably better than my quick explanation. Great !

see ya !

joseph



A nice GWT app


Nice UML app made using GWT. Quite a change from the previous I had seen !

Time to look again at GWT maybe…

++


Please welcome…



As you might already have seen, there is a new Author on codesmell.org. Please welcome my workmate Joseph Pachod on this blog. I plan to ask some other mates to blog here as well occasionally about java/wicket/agile/whatnot… stay tuned.

InnoDB checks UNIQUE and FOREIGN KEY constraints row-by-row


Hi


For my first post here, let me speak about this issue which bogged us down a few time ago :

InnoDB checks UNIQUE and FOREIGN KEY constraints row-by-row

It may sound trivial, but it means that unique and foreign key constraints aren’t transaction safe. But, when using some ORM like hibernate, it’s pretty easy and apparently harmless to switch two values using an intermediate in memory variable (save first value, move second value to the first, put the saved value in the second). In a transaction, it should normally work… But not with innodb !

As such, you’re better off not using unique and foreign key constraints with innodb if you’re serious about transactions, since it could blow up at anytime for actions which should have been possible . Quite a pity isn’t it ?

As as side note, this issue made me realize the value of the documentation’s paragraphs dealing with “Deviation from SQL standards”… which clearly states this kind of deviations, as you can check there : http://dev.mysql.com/doc/refman/6.0/en/innodb-foreign-key-constraints.html for the current issue.

To conclude : beware of innoDb transaction handling !

++

joseph



Scrum Master certification



i did an CSM course last week. Trainer was Roman Pichler, whom you might know from his german Scrum book. even though i was a little disappointed with too little time for Q&A and having read his book, this course does not bring additional theoretical knowledge, it was a good experience.

  • first of all, Roman is a good instructor. he manages to keep the level of attention very high by varying methods and presentation.
  • second, listening to his experience and getting some insight of applied Scrum in other than the own context is definitely worth the time.
  • last but not least, exchanging experiences with the other students helps a lot not to duplicate their mistakes.

another one bites the dust



this was not particularly hard to predict, but twitter looks to abandon rails for scalability problems.

despite of this, there are _still_ some clueless people out there that wont stop preaching that ruby on rails is going to be ‘the next big thing’ (for years now).

i really don´t get it.

50+ Guicy Tips



Parleys shares “50+ Tips to Guice up your Java”-Talk from Crazy Bob, held at JavaPolis 2007.

Guicy JSR



this is awesome news. First of all, it is nice, that Spring and Guice find some common ground. More importantly, independence of any EEish API is absolutely necessary for this to become interesting.
Not that Guice needed a specification to back it up, but it is good to push it more into the mainstream.



IDetachListener saves the day



i just asked this on the Wicket user list:
we have a problem here, which we think might be a common one, so i´d like to discuss.

from time to time we create models (mostly LDMs) that are not actually reachable by components. (yes, you can argue that this is stupid, but it happens where 1:1 mapping between component and model is not easy to apply)

the problem arising from there is of course that wicket does not know about this IModel and so wont detach() it.

yes, we could use Component.detach() as a hook to detach that LDM as well, but i tend to forget that.

and i´d like to share what came out of it. The important lines are:

 Java |  copy code |? 
01
02
public class ReflectiveDetachListener implements IDetachListener
03
{
04
    public void onDetach(final Component component)
05
    {
06
        final Class< ?> clazz = component.getClass();
07
        Set<field> fields = this.fieldMap.get(clazz);
08
        if (fields == null)
09
        {
10
            fields = findFields(clazz);
11
            this.fieldMap.put(clazz, fields);
12
        }
13
 
14
        for (final Field field : fields)
15
        {
16
            if (isToBeDetached(field.getType()))
17
            {
18
                final IDetachable d = (IDetachable) getFieldValue(component, field.getName());
19
                if (d != null)
20
                {
21
                    d.detach();
22
                }
23
            }
24
        }
25
    }
26
 
27
    private boolean isToBeDetached(final Class< ?> type)
28
    {
29
        return IDetachable.class.isAssignableFrom(type) && (!Component.class.isAssignableFrom(type));
30
    }
31
    // ....
32
}
33
</field>

You get the picture… if you need more info or source, i´ll be happy to send it over.

Good News for Java Developers in a Tight Economy



Despite crisis, the Job market does not look that bad for Java developers:

Certified IT skills that saw pay increases include HP/Certified Systems Engineer with a 14.3% increase in pay, and Sun Certified Programmer for Java Platform, which experienced an increase of 13.5% in pay. IT professionals with EMC Proven Professional certifications experienced a 12.5% increase in pay, as did IBM Certified Specialists. Systems Security Certified Practitioner pay increased in the first quarter by 12.5%.

more…

Wicket 1.3.6 Release



Wicket 1.3.6 was released. The best news for me there is, that using Guice and persistent Sessions is probably going to work now (did not check yet.)

ridiculous



this looks rather weird to me.

Orlando Scrum as it operated until this spring is no more. After reviewing my other commitments and a request to sign a licensing agreement with Scrum Alliance I am ending my involvmet with the group. Today I received an email from Scrum Alliance asking me to sign and agree to a licensing document for a logo they created for Orlando Scrum users group.

I am not aware of any request for Scrum Alliance to do this for us. Additionally, they have laid claim to the mark “Scrum User Group”. As this is/was a volunteer effort and Scrum Alliance is making such requests of a legal nature, I am discontinuing my involvement in what was Orlando Scrum.

Regards,
Chad Eaves


even though, they recognized later on this was kind of bad communication:

Do not let this licensing agreement hinder or stop you from meeting as an organized group of Scrum users. If you do not wish your local user group to be registered as a Scrum Alliance Scrum User Group then there is no need for you to sign a licensing agreement with the Scrum Alliance.


instantly thinking of that scene from “Life of Brian”…


Teamwork as an individual skill



a very interesting talk about accountability and responsibility can be found here.

Fun on the Guice mailing list



i had to look twice reading this sentence on the google guice mailing list:
If you’re looking for a stable, future-proof build that’s suitable for
use in production, I recommend the recent snapshot.

pretty weird :)

Atlassian Stimulus Package



In case you always wanted to use JIRA Enterprise, now is your chance to do so. They sell 5 user licenses for 3 years as low as 5$, and they even spend it for charity. clever move, ‘get them, when the teams are small and the budget is tight’ :)

we all know, there currently is no compareable bugtracking system, or is there?

PS: the sell confluence for that price, too.

oh bollocks

10 ways to better code



10 Ways to better code is a nice presentation: educating as well as entertaining. nothing exactly revolutionary, but nice.

gitready



If you share my interest in git, you may find gitready.com a very useful resource. unfortunately, the lack of good eclipse integration still keeps me away from using it in every day work.

Web Blackbox Tests done right



Most people know HtmlUnit, which is a nice way of creating Black-Box-Tests for web applications. The problem with HtmlUnit is that its JavaScript unit (namely Rhino) is not going to do, what your favorite browser will be doing. This probably leads to unit-tests that ignore the JavaScript-focused parts of the UI. Unfortunately, JavaScript based behaviour of WebPages is anywhere on today´s web-apps, so that ignoring it in your tests gets more risky ever day.

Using the user´s browser to test the UI would be the optimal solution, but the usual record&playback oriented tests have some severe drawbacks:

  • it is often not junit/testng, which makes it hard to integrate with the rest of your tests using CI etc.
  • it probably needs repetition, like always starting from a login page etc.
  • it does not use abstraction, so when you change signifcant parts of your pages, you´ll end up patching all of these tests without the help of a good IDE
This is where WebDriver comes to the rescue. If you have 30 mins to spare, take a look at its talk at GTAC.

Maven 2.1



spread the word: Maven release 2.1.0

for me, this is one of the most important:

[MNG-2433] - Maven looks for snapshots in offline mode

while this is most interesting:
[MNG-3379] - Parallel resolution of artifacts

Migrate Data from Postgres to MySQL



if you ever come to the need to migrate Data from Postgres to MySQL, you should stay away from using dumps. It is a hell lot easier to use export/import to/from CSV Data, because you do not need to synchronize column-names and it is special-char-proof.

Postgres syntax for exporting:
COPY tablename [ ( column [, ...] ) ]
    TO { 'filename' | STDOUT }
    [ [ WITH ] 
          [ BINARY ]
          [ OIDS ]
          [ DELIMITER [ AS ] 'delimiter' ]
          [ NULL [ AS ] 'null string' ]
          [ CSV [ HEADER ]
                [ QUOTE [ AS ] 'quote' ] 
                [ ESCAPE [ AS ] 'escape' ]
                [ FORCE QUOTE column [, ...] ]

so you end up like:
COPY article(title,text) TO '/tmp/pg_articles.csv';

and import it on MySQL-side with
LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name'
    [REPLACE | IGNORE]
    INTO TABLE tbl_name
    [CHARACTER SET charset_name]
    [{FIELDS | COLUMNS}
        [TERMINATED BY 'string']
        [[OPTIONALLY] ENCLOSED BY 'char']
        [ESCAPED BY 'char']
    ]
    [LINES
        [STARTING BY 'string']
        [TERMINATED BY 'string']
    ]
    [IGNORE number LINES]
    [(col_name_or_user_var,...)]
    [SET col_name = expr,...]

like
LOAD DATA INFILE '/tmp/pg_articles.csv' INTO mysqlarticles (headline, articleText);



Riena 1.0 released



please note that Riena 1.0 was released. i´m really greedy on getting opinions about it, so if you should have tried it already, please drop me a note. One interesting sidenote: they seem to use Caucho´s Hessian as wire protocol.

Blog moved



our contract for the old server came to its end and so we moved to another facility. during the process of reorganizing the server´s resources (utilizing OpenVZ), i decided to shift the blog´s content to another platform. unfortunately, content-import on that was not too exciting, so that dates, formatting etc of the older blog-entries are screwed up. at least you can still find em here, even though you´d have to take a look at the HTML source if necessary.

Performance of Wicket vs Seam + JSF



even though Gavin King expectedly disagrees, i find this article
a very useful benchmark. not that much of a surprise, but the actual numbers are more than impressive.


JDBC Batch updates



As you probably know or guess, doing bulk inserts using JPA is not as fast as it should be, due to the full stack involved. So when using real
bulk inserts, something like that would be terrible:

 Java |  copy code |? 
1
2
for (String name: listOfNames){
3
  PersonEntity p = new PersonEntity(name);
4
  entityManager.persist(p);
5
}
6
                


Possible suggestions floating around only tackle parts of the problem (like evicting from 1st Level Cache after persisting). So what we really need with a large number of rows is to get down to JDBC, and remove the necessity to send every single SQL command to the database, but instead prepare only one and parametrize it with a bunch of values.


Serverside-prepared-statements are one (but a rather complex) solution to this. I found another which is kind of basic JDBC, but in fact, i did not know about:

 Java |  copy code |? 
01
02
Connection c = ...
03
// make sure the JDBC Driver is capable of using this feature.
04
// assert c.getMetaData().supportsBatchUpdates();
05
 
06
String sql = "INSERT INTO MyTable (col1,col2,col3,col4) VALUES (?,?,?,?)";
07
PreparedStatement ps = null;
08
try
09
{
10
  ps = c.prepareStatement(sql);
11
  for (...)
12
  {
13
     // populate values for one insert
14
     ps.setInt(1, ...);
15
     ps.setInt(2, ... );
16
     ps.setLong(3, ... );
17
     ps.setInt(4, ... );
18
     // and add them to the batch
19
     ps.addBatch();
20
  }
21
  ps.executeBatch();
22
  c.commit();
23
}
24
catch(...
25
                


As always when using JDBC directly:

Please make absolutely sure to release the Statement as well as the connection reliably, and make sure to use non-autoCommit.

sun certified enterprise architect



sun’s the certification database says:


This report shows the total points that could have been awarded in each section and the actual amount of points you were awarded.
This information is provided in order to give you feedback on your relative strengths on a section basis.
The maximum number of points you could have received is 100, minimum to pass is 70.

Class Diagram (44 maximum) …………………….. 38
Component Diagram (44 maximum) …………………. 40
Sequence/Colloboration Diagrams (12 maximum) …….. 12


which makes me a sun certified enterprise architect. in fact, that makes me “sun certified <you name it>”, because i finally got any java related certification they offer, excluding the brandnew (and somewhat ridiculous) netbeans cert.


americans with a sense of humor



did you ever buy at CDBABY.COM !? how fun is that?


Your CDs have been gently taken from our CD Baby shelves with
sterilized contamination-free gloves and placed onto a satin pillow.
A team of 50 employees inspected your CDs and polished them to make
sure they were in the best possible condition before mailing.

Our packing specialist from Japan lit a candle and a hush fell over
the crowd as he put your CDs into the finest gold-lined box that money
can buy.

We all had a wonderful celebration afterwards and the whole party
marched down the street to the post office where the entire town of
Portland waved “Bon Voyage!” to your package, on its way to you, in
our private CD Baby jet on this day, Thursday, December 18th.

I hope you had a wonderful time shopping at CD Baby. We sure did. Your picture is on our wall as “Customer of the Year.” We’re all
exhausted but can’t wait for you to come back to CDBABY.COM!!

Thank you, thank you, thank you!


Sigh…



servlet registration at runtime



awesome! did you have a look at the servlet 3.0 API PD?


I did not yet, but was amazed to see something like this:

 Java |  copy code |? 
1
2
public void contextInitialized(ServletContextEvent sce) {
3
      ServletContext sc = sce.getServletContext();
4
 
5
      ServletRegistration sr = sc.addServlet("NewServlet", "test.NewServlet");
6
      sr.setInitParameter("servletInitName", "servletInitValue");
7
      sc.addServletMapping("NewServlet", new String[] {"/newServlet"});
8
  }
9
                


full article


wonder, if servlets and filters can be removed at runtime as well


one thing bugs me though: why the hell has the servlet’s name to be a parameter to addServletMapping !?


shouldn’t it be only possible to map the servlet bound to this ServletRegistration object? in that case, repeating the name is a source of possible error, right?


Criteria API



Good Lord, i’m happy to see this
. Looks like the JPA2.0 EG will (finally) bring us a Criteria API.


Eclipse QuickFix for IF



Joseph just wrote:


I recently stumbled upon this short flash demo about IF and Ctrl 1 in


Eclipse : http://eclipser-blog.blogspot.com/2008/11/eclipse-tip-ctrl1-and-ifs.html
.


I didn’t know all these possibilities, so in case I wasn’t the only


one…



well, he wasn’t, so…


Flex



There is a nice article about using Flex from a Java Developers point of view here
.


To sum it up, let me rephrase what I have said in a simpler statement:


Flex is not agile (enough)


If you are into an agile framework that can boost up your developers productivity, Flex might not be for you and you might be happier with something else.



Pagelink considered harmful



ahhh. doesn’t wicket offer a great model of programming webpages? isn’t it too easy to do things like this?

 Java |  copy code |? 
1
2
add(new ListView("mylist",someList){
3
  @Override
4
  protected void populateItem(ListItem item){
5
    item.add(new PageLink("deleteThisEntry",new DeletePage(item.getModel())));
6
  }};
7
});
8
                


but wait PageLink(Page) is deprecated:

 Java |  copy code |? 
01
02
/**
03
 * This constructor is ideal if a Page object was passed in from a previous Page. Construct a
04
 * link to the Page. Warning: DO NOT use this for constructing links to pages you didn't already
05
 * have an instance of. This constructor is strongly discouraged for anything other than linking
06
 * back to the same page.
07
 *
08
 * @param id
09
 *            See component
10
 * @param page
11
 *            The page
12
 * @deprecated rather than using this class/ constructor, use normal {@link Link links} and call
13
 *             setResponsePage in their {@link Link#onClick() onClick} methods.
14
 */
15
@Deprecated
16
public PageLink(final String id, final Page page)
17
                


why is that? if you look at it, it is very obvious.
because it is not lazy that means that you’re creating a big bunch of pages without needing them and all of them need to be serialized, maybe replicated etc.


it gets worse: when not reusing listitems, you’ll do that on every rendering of the example code!


even more worse, if your fellow programmer did something funny like:

 Java |  copy code |? 
01
02
@SomeFunkyAnnotationForInterception
03
class DeletePage extends WebPage{
04
 public DeletePage(IModel objectToDelete){
05
   deleteObject(objectToDelete.getObject());
06
   setResponsePage(DeletionDonePage.class);
07
 }
08
 //...
09
}
10
                


which at leastcould
be a valid usecase.


so please, please, please - with sugar on top - replace

 Java |  copy code |? 
1
2
new PageLink(id,new XYPage(...))
3
                


by

 Java |  copy code |? 
1
2
new Link(id){
3
 public void onClick(){
4
  setResponsePage(new XYPage(...));
5
 }
6
}
7
                


in order to create the page only when needed.


Quartz fits



whenever you have any need for cron-like functionality within your java application, Quartz is the obvious chose for quite a long time now.


i did not need much of what quartz had to offer, so i went with a home-grown implementation. why? the fear of having to integrate a good, but feature-rich framework, you really don’t need most of the time.



well, that was a mistake. Quartz offers a very easy and stable API and a bunch of good helper classes, designed after common usecases. but there is one more important quality that every good framework nowadays has to have: it is non-intrusive in regards to creating its objects.



my ’special’ case was integration with guice, so that i could use @Inject to implement my jobs. i was pleased to learn that it was as easy as this:
 Java |  copy code |? 
01
02
final class GuiceJobFactory implements JobFactory
03
{
04
    private final Injector guice;
05
 
06
    @Inject
07
    public GuiceJobFactory(final Injector guice)
08
    {
09
        this.guice = guice;
10
    }
11
 
12
    @Override
13
    public Job newJob(final TriggerFiredBundle bundle) throws SchedulerException
14
    {
15
        JobDetail jobDetail = bundle.getJobDetail();
16
	Class jobClass = jobDetail.getJobClass();
17
        return (Job) guice.getInstance(jobClass);
18
    }
19
 
20
}
this example class is used to delegate the actual object creation to Guice. this makes Quartz integration a no-brainer, whatever environment you need it in.



all you have to do then is create the Scheduler accordingly:
 Java |  copy code |? 
01
public class Quartz
02
{
03
    private final Scheduler scheduler;
04
 
05
    @Inject
06
    public Quartz(final SchedulerFactory factory, final GuiceJobFactory jobFactory) throws SchedulerException
07
    {
08
        scheduler = factory.getScheduler();
09
        scheduler.setJobFactory(jobFactory);
10
        scheduler.start();
11
    }
12
 
13
    public final Scheduler getScheduler()
14
    {
15
        return scheduler;
16
    }
17
 
18
    public void shutdown()
19
    {
20
        try
21
        {
22
            scheduler.shutdown();
23
        }
24
        catch (SchedulerException e)
25
        {
26
      // ... handle it
27
        }
28
    }
29
}
30
}
and bind it all together like:
 Java |  copy code |? 
01
public class QuartzModule extends AbstractModule
02
{
03
    @Override
04
    protected void configure()
05
    {
06
        bind(SchedulerFactory.class).to(StdSchedulerFactory.class).in(Scopes.SINGLETON);
07
        bind(GuiceJobFactory.class).in(Scopes.SINGLETON);
08
        bind(Quartz.class).in(Scopes.SINGLETON);
09
    }
10
}
what did i learn from that?



frameworks are easy to integrate as long as they do not necessarily claim to manage the lifecycle of (even their own) objects unless absolutely necessary.


want another proof? see Wicket: Application.newSession(…)

protected Constructors



Did you ever try to create an instance of a class with a protected constructor from outside its package?


I ran into this need when working with JPA-Entities of which i wanted to know initial field values. (yeah, i know. kind of black magic…)


It is actually easier, than getting protected Fields:

 unknow |  copy code |? 
01
02
public static <t> T newInstance(final Class</t><t> c)
03
    {
04
        try
05
        {
06
            Constructor</t><t> constructor = c.getDeclaredConstructor(new Class[] {});
07
            if (constructor != null)
08
            {
09
                constructor.setAccessible(true);
10
                return constructor.newInstance((Object[]) null);
11
            }
12
            else
13
            {
14
                throw new IllegalArgumentException("Cannot find empty Contructor for class '" + c.getName() + "'");
15
            }
16
        }
17
        catch (SecurityException e)
18
        {
19
            throw ExceptionHelper.wrap(e);
20
        }
21
        catch (IllegalArgumentException e)
22
        {
23
            throw ExceptionHelper.wrap(e);
24
        }
25
        catch (InstantiationException e)
26
        {
27
            throw ExceptionHelper.wrap(e);
28
        }
29
        catch (IllegalAccessException e)
30
        {
31
            throw ExceptionHelper.wrap(e);
32
        }
33
        catch (InvocationTargetException e)
34
        {
35
            throw ExceptionHelper.wrap(e);
36
        }
37
        catch (NoSuchMethodException e)
38
        {
39
            throw ExceptionHelper.wrap(e);
40
        }
41
    }
42
                </t>

AnchoredBookmarkablePageLink



Another Wicket Gem. Obvious but helpful.

 Java |  copy code |? 
01
02
import org.apache.wicket.PageParameters;
03
import org.apache.wicket.markup.ComponentTag;
04
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
05
import org.apache.wicket.model.IModel;
06
 
07
/**
08
*  @author Thijs Vonk
09
**/
10
public class AnchoredBookmarkablePageLink extends BookmarkablePageLink {
11
 
12
 private static final long serialVersionUID = 1L;
13
 
14
 private IModel stringAnchor;
15
 
16
 public AnchoredBookmarkablePageLink(String id, Class pageClass, IModel anchor) {
17
   super(id, pageClass);
18
   this.stringAnchor = anchor;
19
 }
20
 
21
 public AnchoredBookmarkablePageLink(String id, Class pageClass, PageParameters params, IModel anchor) {
22
   super(id, pageClass, params);
23
   this.stringAnchor = anchor;
24
 }
25
 
26
 @Override
27
 protected CharSequence appendAnchor(ComponentTag tag, CharSequence url) {
28
   url = url + "#" + stringAnchor.getObject().toString();
29
   return url;
30
 }
31
 
32
}
33

Ever heard of asynchronous Exceptions?



Really weird, what Heinz Kabutz digs out of the java language


Read this
newsletter to find out, how System.otu.println(”foo”) can throw a SQLException


His statement on checked and unchecked seems rather incomplete, though:


My personal opinion is that checked exceptions are not as useful as we would hope. For example, the class java.io.IOException has 74 subclasses in Java 6. So whenever you catch IOException, it could have been any one of 74 different error conditions. None of our code would cope with all of them every time we catch IOException.




An old discussion, but never too old



From an Email conversation this evening:


what do you think about it?




For a while, I was “all flame” about Checked exceptions, but then I


read about their limitations (which are why they aren’t included in


C#, more about it there :


http://blogs.msdn.com/csharpfaq/archive/2004/03/12/88421.aspx
) and


since I wonder what’s the best solution.



i was all behind checked exceptions at first too, until some frameworks i used went nuts on them. that’s where i got interested in the ‘other’ side: don’t use them at all in order not to dictate your user how to handle exceptional behaviour.


that camp, though never really got me.


to me - like most people about software development - this has 80% to do with common sense and 20% with how your belly feels:


the 80% questions are:


1. can your caller
reasonably recover from your exception?


2. do you really WANT to FORCE him to handle this?


good example: FileOutputStream throwing FileNotFoundExceptions


the caller needs to know that, needs to take this possibility into account and
CAN reasonably recover from that.


lousy example: FileOutputStream.close() throws IOException.


what the hell am i going to do with that one?


the 20% come in when you realize, that your client’s code must be inevitably cluttered with try/catch statements beyond the acceptable because, for example, any method of your DAO can throw EntityNotFound-exceptions :>


that’d be a showstopper for any acceptence


but if in doubt, i try Checked before unchecked, and see if it really gets THAT messy. -> Safety first


Should I follow Bruce Eckel recommendation : no checked exception,


only runtime ones so they don’t get in the way ? Some good old days


return codes ? Checked exception ?



i think checked exceptions do have a serious advantage, especially for ‘not-that-incredibly-experienced-programmers’ that are forced to think of all possible execution paths, they had missed otherwise.


almost noone cares about the exception in:

                    void foo( int i) throws IllegalArgumentException
                


until he finally hits it.


Maven Eclipse Integration



As a happy Q4E User, i did not waste too much time lately on keeping an eye on the other maven-eclipse-integration projects. Now i stumbled upon this wiki page
showing a very detailed feature comparison matrix between the usual suspects. One thing that stroke me is, that m2eclipse is proposed at eclipse.org as well as q4e is. Actually the feature-set of m2eclipse is quite impressive and it looks like, their authors have made quite some improvement lately.


Anyone with a detailed experience of a later m2eclipse version?


Article about Wicket vs. Tapestry 5



The article is about Tapestry 4.1, not v5 as mentioned in the title.


Some say, Tapestry can compare with Wicket. And from a certain perspective, they’re obviously right. In case you have not made up your mind yet, this developerworks article
might help you. In there is a thorough side-by-side comparison of tapestry against wicket. Their conclusion:


Tapestry and Wicket are popular representatives of the component-based Web frameworks and probably the most exceptional ones from that camp. With their help, it is possible to build applications of any level of complexity.



While Tapestry offers a declarative approach in component specification, Wicket brings pure Java programming with no XML and no annotations. Wicket has a few strong advantages in page versioning and multi-window support. Wicket also has a few more helpful implementations, including breadcrumbs, a feedback panel, and many of the funny stuff found in dynamic HTML, such as tabbed panels and dialogs.



and of course, the usual word of warning, you can find in any tapestry-related publication:


Finally, Tapestry is in a period of transition today. Tapestry V5 promises many enhancements over V4.1, but there is no planned backward-compatibility.



Buy this book



… if your intereseted in Scrum. I have read quite a few, but this one is different:



  • very, very compact

  • funny to read

  • no fluff

  • no “why it works”


just: “we do it this way, and it worked” and “we did it that way, and it sucked”.


A must read, at least for Scrum beginners:


Scrum and XP from the Trenches


User Stories and Release Planning



Quite a good talk (Face & Slides) on InfoQ about the (in Scrum speak) Product Owner’s work on agile development.


Watch it


Wicket and AJAX



Here
is an interesting interview with three of the wicket committers (or, should i say legends, personal heros …) about how Wicket hides the complexity of AJAX-related JavaScript coding from the productive programmer:


Learning JavaScript is not hard, what is hard is learning FireFox JavaScript, IE6 JavaScript, IE7 JavaScript, Opera JavaScript, WebKit JavaScript, etc. The differences are subtle but can cause huge hang ups and are very annoying to Java developers who are used to Java being much more consistent. Another pain point is the lack of a really good JavaScript debugger, which is a tool Java developers take for granted.



and further


Wicket takes care of users having to marshall and unmarshall data between server and browser by working around the problem. Instead of sending data to the client Wicket renders the components on server side and sends the rendered markup. This might not be as efficient, but it sure makes it much easier and faster to develop ajaxified behaviors. For example, if one wants to update a panel that shows user information on the client via Ajax all that is necessary is to tell Wicket that the panel should be updated. There is no marshalling the User object into a JSON representation, and no unmarshalling it on client, neither is there code to manipulate the DOM on the client.



Wicket, Guice and java.lang.reflect.Type



if there is anyone suffering from


https://issues.apache.org/jira/browse/WICKET-1403


, i added a quick hack to make it possible to restart the server while persisting the application’s state.


not a final solution, but it works for now and makes the development cycle much faster (for me)


The Problem is, that java.lang.reflect.Type is not Serializable right now. The solution was to store it in the Application’s MetaData, which is of course lost when restarting the Application.


What i do here is using XStream in order to ’serialize’ the Type to XML, which then can be serialized normally, so that the MetaData-stuff can be dropped.


This is of course not a valid solution to the above problem, as it introduces a dependency to XStream, but it temporarily makes the roundtrip with guice possible.


To anyone using this hack: note that XStream does not necessarily behave consistently on any JVM:


http://xstream.codehaus.org/faq.html#Compatibility
.


 unknow |  copy code |? 
01
02
package org.apache.wicket.guice;
03
 
04
import java.lang.annotation.Annotation;
05
import java.lang.reflect.Type;
06
 
07
import org.apache.wicket.Application;
08
import org.apache.wicket.proxy.IProxyTargetLocator;
09
 
10
import com.google.inject.Key;
11
import com.google.inject.TypeLiteral;
12
import com.thoughtworks.xstream.XStream;
13
import com.thoughtworks.xstream.io.xml.DomDriver;
14
 
15
class GuiceProxyTargetLocator implements IProxyTargetLocator
16
{
17
    private static final long serialVersionUID = 1L;
18
 
19
    private final Annotation bindingAnnotation;
20
 
21
    private transient Type type;
22
    private final String serializedType;
23
 
24
    GuiceProxyTargetLocator(final Type type, final Annotation bindingAnnotation)
25
    {
26
        this.type = type;
27
        final XStream xstream = new XStream(new DomDriver());
28
        this.serializedType = xstream.toXML(type);
29
        this.bindingAnnotation = bindingAnnotation;
30
    }
31
 
32
    public Object locateProxyTarget()
33
    {
34
        final GuiceInjectorHolder holder = (GuiceInjectorHolder) Application.get().getMetaData(
35
                GuiceInjectorHolder.INJECTOR_KEY);
36
 
37
        if (this.type == null)
38
        {
39
            final XStream xstream = new XStream(new DomDriver());
40
            this.type = (Type) xstream.fromXML(this.serializedType);
41
        }
42
 
43
        // using TypeLiteral to retrieve the key gives us automatic support for
44
        // Providers and other injectable TypeLiterals
45
        final Key< ?> key;
46
 
47
        if (this.bindingAnnotation == null)
48
        {
49
            key = Key.get(TypeLiteral.get(this.type));
50
        }
51
        else
52
        {
53
            key = Key.get(TypeLiteral.get(this.type), this.bindingAnnotation);
54
        }
55
        return holder.getInjector().getInstance(key);
56
    }
57
}
58
                


Thinking twice, we could get away
without special serialization requirements for at least any Type extending Class….
This does not solve all cases, but might help some people already.

 unknow |  copy code |? 
01
02
package org.apache.wicket.guice;
03
 
04
import java.lang.annotation.Annotation;
05
import java.lang.reflect.Type;
06
 
07
import org.apache.wicket.Application;
08
import org.apache.wicket.proxy.IProxyTargetLocator;
09
 
10
import com.google.inject.Key;
11
import com.google.inject.TypeLiteral;
12
 
13
class GuiceProxyTargetLocator implements IProxyTargetLocator {
14
    private static final long serialVersionUID = 1L;
15
    private final Annotation bindingAnnotation;
16
    private transient Type type;
17
    private Class serializableType;
18
    GuiceProxyTargetLocator(final Type type, final Annotation bindingAnnotation) {
19
        this.type = type;
20
        if (type instanceof Class) {
21
            this.serializableType = (Class) type;
22
        }
23
        this.bindingAnnotation = bindingAnnotation;
24
    }
25
    public Object locateProxyTarget() {
26
        final GuiceInjectorHolder holder = (GuiceInjectorHolder) Application.get().getMetaData(
27
                GuiceInjectorHolder.INJECTOR_KEY);
28
        if (this.type == null) {
29
            if (this.serializableType != null) {
30
                this.type = this.serializableType;
31
            }
32
            else {
33
                throw new IllegalStateException("Used a non-Class type for injection, which is not Serializable.");
34
            }
35
        }
36
        // using TypeLiteral to retrieve the key gives us automatic support for
37
        // Providers and other injectable TypeLiterals
38
        final Key< ?> key;
39
        if (this.bindingAnnotation == null) {
40
            key = Key.get(TypeLiteral.get(this.type));
41
        }
42
        else {
43
            key = Key.get(TypeLiteral.get(this.type), this.bindingAnnotation);
44
        }
45
        return holder.getInjector().getInstance(key);
46
    }
47
}

Wicket DropDownChoice with eye-candy



thinking twice, ajax-indicators are not at all eye-candy, but useful from an usablity perspective.

 unknow |  copy code |? 
01
02
/**
03
 * Adds an AJAX-Indicator to DropDownChoice
04
 * @author Eyal Golan
05
 */
06
class DropDownChoiceWithAjaxIndicator extends DropDownChoice implements IAjaxIndicatorAware
07
{
08
    private static final long serialVersionUID = 1365817942506006686L;
09
    private final WicketAjaxIndicatorAppender indicatorAppender = new WicketAjaxIndicatorAppender();
10
 
11
    public DropDownChoiceWithAjaxIndicator(final String id, final IModel choices, final IChoiceRenderer renderer,
12
            final MarkupContainer markupContainer)
13
    {
14
        super(id, choices, renderer);
15
        init(markupContainer);
16
    }
17
 
18
    public DropDownChoiceWithAjaxIndicator(final String id, final IModel model, final IModel choices,
19
            final IChoiceRenderer renderer, final MarkupContainer markupContainer)
20
    {
21
        super(id, model, choices, renderer);
22
        init(markupContainer);
23
    }
24
 
25
    public DropDownChoiceWithAjaxIndicator(final String id, final IModel model, final IModel choices,
26
            final MarkupContainer markupContainer)
27
    {
28
        super(id, model, choices);
29
        init(markupContainer);
30
    }
31
 
32
    public DropDownChoiceWithAjaxIndicator(final String id, final IModel model, final List<serializable> data,
33
            final IChoiceRenderer renderer, final MarkupContainer markupContainer)
34
    {
35
        super(id, model, data, renderer);
36
        init(markupContainer);
37
    }
38
 
39
    public DropDownChoiceWithAjaxIndicator(final String id, final IModel model, final List</serializable><serializable> choices,
40
            final MarkupContainer markupContainer)
41
    {
42
        super(id, model, choices);
43
        init(markupContainer);
44
    }
45
 
46
    public DropDownChoiceWithAjaxIndicator(final String id, final IModel choices, final MarkupContainer markupContainer)
47
    {
48
        super(id, choices);
49
        init(markupContainer);
50
    }
51
 
52
    public DropDownChoiceWithAjaxIndicator(final String id, final List</serializable><serializable> data,
53
            final IChoiceRenderer renderer, final MarkupContainer markupContainer)
54
    {
55
        super(id, data, renderer);
56
        init(markupContainer);
57
    }
58
 
59
    public DropDownChoiceWithAjaxIndicator(final String id, final List</serializable><serializable> choices,
60
            final MarkupContainer markupContainer)
61
    {
62
        super(id, choices);
63
        init(markupContainer);
64
    }
65
 
66
    public DropDownChoiceWithAjaxIndicator(final String id, final MarkupContainer markupContainer)
67
    {
68
        super(id);
69
        init(markupContainer);
70
    }
71
 
72
    public String getAjaxIndicatorMarkupId()
73
    {
74
        return this.indicatorAppender.getMarkupId();
75
    }
76
 
77
    private void init(final MarkupContainer markupContainer)
78
    {
79
        add(this.indicatorAppender);
80
    }
81
} </serializable>

Wicket SecureForm



posted by mighty Igor on the Wicket-User list:


Here is a simple demonstration of how to prevent “Cross-Site Request Forgery”

 unknow |  copy code |? 
01
02
/**
03
 * Form that uses a random uuid token in order to prevent nasty people from messing around (also known as cross site request forgery) ;)
04
 * @author igor vaynberg
05
 */
06
class SecureForm extends Form
07
{
08
    public SecureForm(final String id)
09
    {
10
        super(id);
11
    }
12
    private static final long serialVersionUID = 1L;
13
    private static final String TOKEN_NAME = "SECURE_FORM_TOKEN";
14
    private String token;
15
 
16
    @Override
17
    protected void onBeforeRender()
18
    {
19
        super.onBeforeRender();
20
        this.token = UUID.randomUUID().toString();
21
    }
22
 
23
    @Override
24
    protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag)
25
    {
26
        super.onComponentTagBody(markupStream, openTag);
27
        getResponse().write("<input type='hidden' name='" + this.TOKEN_NAME + "' value='" + this.token + "'/>");
28
    }
29
 
30
    @Override
31
    public boolean process()
32
    {
33
        if (!this.token.equals(getRequest().getParameter(this.TOKEN_NAME)))
34
        {
35
            throw new IllegalStateException("token mismatch");
36
        }
37
        return super.process();
38
    }
39
}