Monday, July 27, 2009

Jackson 1.2: BYOC (Bring Your Own Constructors)*; Use Your Objects & Do More (with less)!

* (or Factory Methods)

1. What's up, Doc?

One of 2 Coolest Features of upcoming Jackson v 1.2 -- and the Top Feature by actual user requests (and Jira user voting) -- is the ability to (finally!) use arbitrary constructors and factory methods a class has, for their intended purpose: constructing bean instances. And specifically, constructing beans without having to mess with setter methods whose sole purpose is to initialize the value.

So, if you have class like:


public class Name {
  private final String givenName, familyName;

  public Name(String given, String fam)
  {
   givenName = given;
   familyName = fam;
  }

  public String getGivenName() { return givenName; }
  public String getFamilyName() { return familyName; }
}

you can actually use it (almost) as is, without having to add setters and default constructor like you so far have had to:


public class Name {
  private String givenName, familyName;

  // Used to have to add these:
  private Name() { }

  void setGiveName(String str) { givenName = str; }
  void setFamilyName(String str) { familyName = str; }
  public String getGivenName() { return givenName; }
  public String getFamilyName() { return familyName; }
}

So what is this "almost" part? Well, you do have to decorate the constructor (or factory method) to let Jackson know which constructor/factory method to use (by @JsonCreator); and bind names to parameters (using @JsonProperty), like so

  @JsonCreator
  public Name(@JsonProperty("givenName") String given, @JsonProperty("familyName") String fam)

or, if you prefer factory methods:

  @JsonCreator
  public static Name constructIt(@JsonProperty("givenName") String given, @JsonProperty("familyName") String fam) {
 // construct and return an instance...
  }

and that's it.

My now-resolved earlier pet peeve was the inability to use Jackson with immutable value classes. Not so any more: now you can not only remove the setters, but can also make member fields constructor-assigned and final, i.e. value class immutable.

2. Soap Box Time

Ok now: after demonstrating this new, nifty and long-awaited feature, let's consider why this is a Fundamentally Big Thing.
(ok, I may rant a bit, perhaps even go monologuing a bit. Humor me here)

So: this is Big, because it nicely demonstrates 2 core Jackson Credos:

  • Use Your Objects (aka "Have It Your Way")
  • Do More (with less)

3. Jackson Credo: Use Your Objects

(aka "Have it Your Way", but that's (tm) by some fast food chain)

This is directly related to those alternative data binding (or object serialization) frameworks that take strict Schema-first approach.
This includes formats like Protocol Buffers.As nifty as these frameworks are for some purposes, they fundamentally want to rule their own sandbox; to the degree that objects to use are "Their Objects, Not Yours" (Tony-principle?). That is: they define Their Objects, using Schema you (have to) provide. And if you play nice, you just might get to borrow Their Objects for your personal temporary use.
But make no mistake, you do NOT get to provide the toys, specifically not Your Objects. It is clear who's the boss.

Jackson, on the other hand, is not that bossy. It lets YOU bring YOUR Objects, and it'll play nicely with them, as per YOUR instructions.

Sounds fair? Good, since we are ready to move to the other Credo.

4. Jackson Credo: Do More (with less)

Up until version 1.1, Jackson has sort of played catch up with other best-of-class data mapping/binding frameworks (and by-passed good many inferior ones, but I digress). But now it is rather close to true feature parity.

Good mature frameworks like JAXB are reasonably feature-filled. But one benefit Jackson has, specifically wrt. JAXB, is that the data format it uses (JSON) is simpler. Simplicity has many benefits, but the main thing is that it allows one to quickly solve the "simple" parts (parsing, writing) -- without sacrificing other important parts like API simplicity and performance -- and then move on to more advanced (and arguably more value-additive) features.

I claim that if it wasn't for complexities of XML (or, worse, complexities of XML Schema). JAXB might be much more full-featured. In fact, it seems little odd that it does not yet allow you to BYOC doesn't it? But considering scope of what has already been (it is a HUGE undertaking, akin to building a cathedral), it would be unfair to blame its creators. At some point you have done enough and move on. I gather that point was reached at some point in the past. So with all the usefulness, project is realistically in maintenance mode: good, stable, but not going anywhere fast.

But the important point here is that this point has not at all been reached with Jackson; nor is it likely to be reached any time soon. In fact, there is a boatload of New Features to consider for many new releases; and solid plan to get there; to develop new useful things, and have some fun along the way. We plan to enjoy the ride, so hang on loosely and enjoy the new scenery.

Oh, and the "with less" part is mostly meant to related to YOU having to do less; but it also applies to part of JSON itself providing less, but perhaps counter-intuitively making the whole package offer much more. I think there's some fundamentally neat principle hidden down there; but that's, as they, another story.

5. Next Up: Mix-in Annotations

Ok; and after introducing this allegedly cool new feature, be prepared to get your mind blown with next entry: we will be visiting the Feature Known as "Mix-in Annotations". Stay tuned!

Tuesday, July 21, 2009

Bean Validation API looks good, even after reading the spec

Here's another update: I wrote a bit about Bean Validation API (jsr-303) earlier, suggesting it might be something to look for.

And lo + behold, after finally taking time to read the underlying JSR specification (still a draft, not finalized, but rather complete it seems), I still like it! In fact, I think it's amongst the best JSRs I have read (granted, I have read but maybe dozen all in all -- quality of other hundred or so completed ones I can only speculate freely about).

So why is it good? Here are some reasons:

  1. Its scope is well-defined: the thing covers validation of beans, and only limited number of additions (like localization of error messages -- not needed for all use cases, but is for the "obvious" case of validating user input)
  2. "New" language features (like generics, annotations, enums) are used professionally: used when useful and/or necessary, but not going wild for sake of using them
  3. Innovative design within above bounds
  4. Specification itself is well-written as a technical document: concise, formal (enough) but readable (enough non-toy-examples, but not too many)

I am especially intrigued by #3: I think the way that validator factories are constructed is sensible, clever, and a clear improvement over way that many earlier JSRs defined creation of factories (like JAXP et al). The innovation parts is that instead of first locating a factory implementation and returning it for application to configure, order is actually reversed: process starts by constructing configuration object, and after it has been built (using fluent/fluid/builder style), only then the factory is created. The beauty of this is that the resulting factory is immutable and hence thread-safe (and specified to be so by the specs). Why is this such a big deal? Because it is now possible to safely instantiate just one (or at most couple) of such factories, to be shared by the whole application or subsystem. Although this can be done de factor for most factories (JAXB, DOM, Stax etc etc), this is not guaranteed by respective specification.

But benefits of this style extend beyond thread-safety part: it also allows for clean way of adding custom configurations (with help of using generics to define configurator objects), with bit more type safety. If you do know the provider to use (or at least extension(s) it defines), you can configure things, but still within same framework.

If above description seems fuzzy, go ahead and read the specification. It should make more sense, especially if you have had to create such pluggable-provider-factory frameworks.

So anyway, hats off to writers of JSR-303. I hope other aspiring (or veteran) JSR members will learn from it.

Thursday, July 16, 2009

Better Coffee, Better Work (results?)

Well, although this article ("Top 10 Tips and Tricks for Better Coffee") does NOT claim above, I do. So now I'm off to find a cheap coffee press to improve my code, I mean, coffee, quality! :-)
Interesting reading, and readily applicable. Sweet.

... and if (read: when) it works, what you will see is a significant incremental revenue for a well-known general merchandise on-line retailer.
Feel free to buy more of AMZN shares based on this tip & thank me later when you have earned a fortune due to rocket-like run on share price after said revenue increase. It's a good investment at any rate, and planned to pay for my next year home renovation project (unless I can somehow convince my dear readers to be more inquisitive regarding commercial interludes you see on the right-hand side -- in which case it'll be another big-name online company that'll pay for it!).

(Q: should I maybe cut back on coffee consumption, before writing blog entries? You be the judge...)

Wednesday, July 15, 2009

Michael has left the building?

I assume this was inevitable: question(s) are now emerging regarding relationship between Jackson Project and late King of Pop. We of course deny all such allegations; or at least can not confirm them. Even if it can be said that Jackson (the JSON processor) IS the King of JSON (0wns the space, so to sp33k!), that's where similarities end.

Very entertaining. I think this beats the previous silly association; someone commenting he (or she?) liking Jackson because it was named after his cat... :-)

ps. If I ever write a YAML parser, I guess I have to name it either "Aaron" or "Presley"...

Friday, July 10, 2009

Seattle Super Stars: Bruce Lee

Here's something else I did not know: that the iconic Kung Fu hero Bruce Lee was a Seattleite! And that he is a "permanent resident" now, being buried in Lakewood Cemetery. Fascinating! So Seattle not only produces (or at least refines) first-class axe men (Jimi; guys of Pearl Jam & other big names of grunge), geeks (Bill G, Jeff B) but also first class ass-kickers.

I also need to keep this in mind next time I feel like giving hard time for waiters at local (Intl. District, near my day job) hole-in-the-wall joints...

Thursday, July 09, 2009

Are GAE developers a bunch of

ignorant, incompetent boobs... or what?

Usually I avoid ranting, at least on my blog entries. Thing is, negative output creates negative image: there is little positive in negativity. If you have nothing good to say, say nothing, and so on.

But sometimes enough is enough. This is the case with Google, and their pathetic attempts at Creating Java(-like) platforms.

1. Past failures: Android

In the past I have wondered at the clusterfuck known as Android: API is a mess, concoction of JDK pieces included (and mixed with arbitrary open source APIs and implementation classes) is arbitrary and incoherent. But since I don't really work much in the mobile space, I have just shook my head when observing it -- it's not really my problem. Just an eyesore.

But it is relevant in that it set the precedent for what to expect: despite some potentially clever ideas (regarding the lower level machinery), it all seems like a trainwreck, heading nowhere fast. And the only saving grace is that most mobile development platforms are even worse.

2. Current problems: start with ignorance

After this marvellous learning experience, you might expect that the big G would learn from its mistakes and get more things right second time around. No such luck: Google App Engine was a stillbirth; plagued by very similar problem as Android. Most specifically, significant portion of what SHOULD be available (given their implied goal of supporting all JDK5 pieces applicable to the context) was -- and mostly still is -- missing. And decisions again seem arbitrary and inconsistent; but probably made by different bunch of junior developers.

My specific case in point (or pet peeve) is the lack of Stax API on GAE (it is missing from white-list, which is needed to load anything within "javax." packages). It seems clear that this was mostly due to good old ignorance -- they just didn't have enough expertise in-house to cover all necessary aspects of JDK. Hey, that happens: maybe they have no XML expertise within the team; or whoever had some knowledge was busy farting around doing something else. Who knows? Should be easy to fix, whatever gave.

3. From ignorance to excuses

Ok: omission due to ignorance would be easily solved. Just add "javax.xml.stream" on the white list, and be done with that. After all, what could possibly be problematic with an API package? (we are not talking about bundling an implementation here)

But this is where things get downright comical: almost all "explanations" center around the strawman argument of "there must be some security-related issue here". I may be unfair here -- it is possible that all people peddling this excuse are non-Googlians (if so, my apologies to GAE team). But this is just very ridiculous (dare I say, retarded?) argument, because:

  1. Being but an API package, there is no functionality that could possibly have security implications (yes, l know exactly what is within those few classes -- the only actual code is for implementation discover, which was copied from SAX), and
  2. If there are problems with implementations of the API (which should be irrelevant, but humor me here), same problems would affect already included and sanctioned packages (SAX, DOM, JAXP, bundled Xerces implementation of the same)

Perhaps even worse, these "explanations" are served by people who seem to have little idea about package in question. I could as well ask about regular expression or image processing packages it seems.

4. Misery loves company

About the only silver lining here (beyond my not having to work on GAE...) is that there are other packages that got similarly hosed (I think JAXB may be one of those; and many open source libraries are affected indirectly, including popular packages like XStream). So hopefully there is little bit more pressure in fixing these flaws within GAE.

But I so hope that other big companies would consider implementing sand-boxed "cloudy" Java environments. Too bad competitors like Microsoft and Amazon tend to focus on other approaches: both doing "their own things", although those being very different from each other (Microsoft with their proprietary technology; Amazon focusing on offering low-level platform (EC2) and simple services (S3, SQS, SWF -- simple storage, queue, workflow service -- etc), but not managed runtime execution service.

Wolf Power! (coolest Mockumercial for t-shirts ever)

Ok, here's yet another Internet Phenomenon I had so far missed: Three Wolf Moon t-shirt, #1 seller at Amazon Apparel store. Be sure to check out customer reviews -- they are AWESOME (almost as good as ones Tuscan Whole Milk, Wedding Chapel and Badonkadonk Tank; or ones that Brass Balls and Beluga Caviar used to have).

It is kind of cool that this T-shirt has gotten some majic (see its YouTube mockumercial!) by sheer luck. And its also amazing how useful such viral "marketing" can be (quotes since this had NOTHING to do with manufacturer itself); especially for smaller companies: get Internet-scale sales, even if you are a small player. As long as you get into this strange crowd-a-review cyclone. :-)

Now the main question is: how many should I order!

Tuesday, July 07, 2009

Fear and Loathing with Windows Vista

Ok: so far I have been wondering if there's a reason why Windows Vista has gotten bad rap. I mean, up until now. No wonder any more -- I have tried using Vista for past week or so. And now it is quite clear why people might hate, despite and loathe it. My number one guess: it sucks like no tomorrow.

I mean: a simple thing like printing to a network printer is apparently beyond capabilities of this marvel of engineering. At work I tried printing a 2 page document to a network printer. Workflow for this task goes like so:

  1. Ask Vista nicely to locate printers in da hood: it will find 9 out of 200+ printers there are, none of which is in the same building; I am not entirely convinced these are not just random names drawn out of some sw engineers a$$. At any rate, none is a real printer within building I work at.
  2. Lend Vista a helping hand (first with just one finger raised...): tell it IP name to have a look at.
  3. Stare at the popup that claims it has no idea what type of a printer this might be; offering a not-so-helpful list of 79 known printer manufacturers, most with 500+ types of printers
  4. Go check the actual type of printer (from its side), write it carefully down
  5. Cross-check with list Vista gave you: notice that there is no such printer amongst thousands listed (I wonder if these are even real printers... maybe they were just generated using Jabberwocky)
  6. Try using something that is as close to the actual type as possible (same manufacturer, same product line, same number, couple of same letters)
  7. Try printing
  8. Observe Vista producing to print a stack of paper thicker than your local phone book -- likely because it saw no problem in seding Postscript file to what appears to be a PCL printer.
  9. Count your blessing when half-way through printing there is paper jam that prevents some of paper waste
  10. Wonder out aloud how is it that previous versions of Windows managed get above (minus printing tons of crap; replaced with printing out the actual doc) done with fewer steps. As does MacOS; and even Linux.

Now, some of you may think I just made above up. I so wish this was the case, but no, it is a sad but true story. And the rest (who heard me curse, and wave that stack of paper angrily, in general direction of my laptop); pardon my french. Yes, that kind of language is not suitable for corporate setting, I know. Next time I will use my mother tongue for expressing my true feelings.

I don't know if there is already a law outlawing manu(factu)re, distribution and selling of Vista. But if not, I sure hope Obama admistration considers it a crime punished by something severe. Like having to use Vista for all your work, for term to exceed 20 years. Without parole.

Monday, July 06, 2009

Another Not-so-well-known Gem: Ant Maven Task

Ok: I thought it was common knowledge that:

  1. Maven repositories are great for storing versions of product artifacts (jars), but
  2. Converting projects to Maven is sometimes big hassle, since it requires everything to be set up the Way Maven Wants (which is the key to keeping configuration to minimum, convention-over-configuration)

and that these two points are somewhat conflicting.
So: while it is an absolutely great idea to provide jars of non-Maven projects through Maven repositories, it may be royal PITA to get that done by Mavenizing builds. Or, well, at least extra work that is easily deferred, given half a chance.

But fortunately you can both ship your dog food, and staunchly refuse to eat it: just use Ant Maven Task to publish ("deploy") any Ant-produced (or whatever you use) into Maven repositories (including snapshot repos)! And allow those diligent Maven users (or smarties who use, say, Ivy, but with Maven repos!) to use your great library, without giving in to demands of converting to this new religion. :-)

So why am I writing this entry? Because it looks like there are still developers who do not know this nifty shortcut! But no more -- you have been advised: get the artifacts out; it's good for you and others.

ps. This is quite similar to how you REALLY should also make sure your jars are actual OSGi bundles. How? By either: (a) using Maven (which has bundle generation targets), or (b) Just Use Ant (JUA), with the nifty -- yes, you guessed it! -- Ant OSGi Bundle task... :-)

Sunday, July 05, 2009

Green Day still Rocks

Last friday I did something I haven't done in a while: go to a rock concert. Turns out it has been way too long -- it was a very positive surprise. Need to be doing this stuff more often. It was also the very first time I've heard Green Day live, and they did very good job: although I can't compare it to what's their standard, it was probably the best live concert I have ever attended. And perhaps luckily it was not perfect (... how could they leave out my favorite song? all the other hits were included fortunately) -- just very very good -- so there is a small chance of seeing something even better in future. At any rate, well done. I better go buy their last album, so I can give American Idiot little bit of rest.

Also: I think it is quite fitting to do this on July 3rd, to get bit of counter-balance to celebrations of the day following... with somewhat nationalistic (not just "patriotic") tendencies (luckily, this year things are bit better, maybe due to centrist president, or perhaps due to economy, whatever). Little bit of punky snot rock (with fascism-inspired video wall as background etc) is always good antidote for that stuff. Kind of like how sour works well with sweet, and why Pixar movies mop the floor with Disney ("classic", not including Pixar...) movies. You need bit of edge to get enjoyable, not just agreeable, tabste. But I digress.

One more thing that I respect about GD guys is their involvement of audience -- they actually let an audience member play rhythm guitar on "Jesus of Suburbia". Unless that was staged (kind of doubt that, wouldn't fit well with the image?) it takes some balls to try that out, I think. I can only imagine letting someone from "worst of American Idol auditions" sing: just because someone REALLY wants to sing with their idols doesn't mean they can, or even should.

Anyway: that's that: tomorrow, back to work. And I better blog something about my new gig too: things are off to a good start; I feel excited, think I have a good chance to actually dig deep into domain and get something solved deeply rather than broadly. And best of all, see some of my earlier work having come to fruition, so that I don't even really start from scratch this time.

(and after these personal digressions, I need to get back to factual writing, Jackson 1.2 plans; maintenance work for Woodstox and all the usual content)



Related Blogs

(by Author (topics))

Powered By

About me

  • I am known as Cowtowncoder
  • Contact me at@yahoo.com
Check my profile to learn more.