Tuesday, December 28, 2010

BigDecimal: Logarithms and other higher math functions.

(My Apologies to those who read this blog for web-application technology and not specifically Java. This Blog involves Java only.)

I'm modeling some high level math calculations in my current software, and I'm disappointed in the BigDecimal class. It only provides arithmetic functionality. What's up with that? Is precision not equally important when evaluating the logarithm or other higher-math calculations?

I wanted a quick, neatly packaged bundle of functions to be applied to BigDecimals. What I found was this single Java Class, written by Ronald Mak in his book, Java number cruncher: the Java programmer's guide to numerical computing:

Link to the Class BigFunctions: download.

  • Download it
  • Include it on your class path
  • Use it
  • Take into consideration any licensing issues prior to using in a commercial product (ie. change it up significantly so that you can claim to own it...?)
If this was helpful, please comment. I enjoy your comments BigTime.

Sunday, November 7, 2010

PrimeFaces or RichFaces?

This blog is intended for developers familiar with RichFaces or other JSF component suites, looking for a...

Complete Review of PrimeFaces.



I've been using PrimeFaces for about a year, since version 0.9.3, when they were still getting off the ground. I've used PrimeFaces on one enterprise-scope intranet application and several small sized apps. I've incorporated PrimeFaces as the standard component suite for my Java developers in my unit, and we're pumping out small to medium sized business apps with PrimeFaces very quickly. Now I'm here to tell you what I've learned.

Richness - Score: 10
Richness is about bringing the capability, intuitiveness, and interface of your web app as close as possible to that of a desktop application. The folks at PrimeFaces seek to demonstrate this with their mock OS X presentation found here: MOCK OS X
In my opinion, that presentation is a vast understatement of the total rich desktop capability of the suite. For example, see how one component, the layout component, might help you develop a browser-based application with flyout areas common to I.D.E.s: layout component.
Additionally, with their suite-wide skinning capabilities, defining and changing a common theme among your components is easier and more visually appealing than any of the other component suites out there.
I give it a score of 10 out of 10 because I have not found a rich need that PrimeFaces does not currently deliver.

Stability - Score: 7
The component suite is modular and integrating multiple components generally works seamlessly and exactly as intended. Embed calendar selection drop downs with datatables, dynamic layouts, accordions, etc, and behavior is almost always as you'd expect. With version 2.1, PrimeFaces has standardized a majority of their components on JQuery, moving away from the YUI Yahoo library. This had brought stability in leaps and bounds, as it seems that the UI development industry has latched onto JQuery and adopted it as a standard. Prior to version 2.1, embedding components within one another could sometimes yield odd behavior, but I have not seen this at all since the JQuery implementation in 2.1.
I give it a score of 7
out of 10 because version 2.1 did bring production-acceptable levels of stability, but not yet perfection. Older versions of PrimeFaces were a little brittle, and they are still establishing our trust.

Documentation - Score: 9
You may have the greatest tool in the world, but without some easy to read instructions, what good is it? Sometimes tools behave as you'd expect, and documentation feels just a little less important. In both of these regards, PrimeFaces is the best I've ever seen. The API's are predictable and intuitive. The documentation is not only complete, but also easy and fun to read.
However, if you're looking for documentation on an older version of PrimeFaces, you're out of luck. They provide documentation for their most recent stable release only.
I give it a score of 9 because the documentation is the best I've ever found, but was crestfallen to discover that I couldn't find the documentation for the application I built with PrimeFaces 1.0 last year.

Support - Score: 9
PrimeFaces offers two levels of support - free community support, and paid enterprise support. I only have experience with the free community support. What I tell my upper management and colleagues in the industry constantly is that PrimeFaces' #1 feature is that they listen and react to their community. I've never seen a small development team such as theirs do it so well. Founder Cagatay is incessantly pulling wicked hours on the forum, answering questions, organizing defect reports, and helping the world use his tool. I once posted a show-stopper defect on their forum, they reacted to me quickly, and a stable release 3 weeks later contained a fix for me. It was incredible.
I give it a score of 9 out of 10 because the support team is thoroughly dedicated, but small and struggling to keep up as their community grows exponentially.

My Recommendation after a year with PrimeFaces
  • Use Facelets
    PrimeFaces no longer support their 1.x version, which was for JSP view-controlled JSF.
  • Use the latest stable release, not the release candidate.
    PrimeFaces is growing more quickly than any component suite I've seen (IceFaces, RichFaces, Trinidad, etc), and the release candidate that their showcase may attract you to is truly on the bleeding edge. Play it safe with their stable release, 2.1 at this time.
  • Archive the documentation
    PrimeFaces only hosts the documentation for their latest release. If you develop a product with 2.1, and they release 2.2, then 2.1 documentation will be lost to you
  • Invest Time into the Showcase
    Knowing what tools are in your toolbelt is what makes you powerful as a developer. How can you make incredible rich interface suggestions to your customer if you're not aware of all of your options? Spend hours unapologetically playing with that showcase and get a feel for what you are (and are not) capable of with PrimeFaces.

If you enjoyed this review, please comment! Your comments are the reason I do this :)
-Lance

Thursday, October 21, 2010

JSF Converter for SelectItem Value, made SIMPLE!

Ok, guys and gals. You're here either because you have no idea what a JSF converter is but you've been told that using one will fix your exception, or else you know exactly what one is and you're sick of writing a different converter for every friggin object that needs to be used in a menu in your app.

... Or maybe you're clueless about software development all together and stalking me for pleasure. Either way, welcome and read on!

The Universal JSF Converter
One converter to rule them all...

I've developed a single converter that can be applied to any JSF UISelect component requiring one. For example, selectOneMenu, selectManyListbox, selectOneRadio, etc etc.... I've developed a rough crack at what JSF should have included from the get go so that developers don't need to write converter code, converting their business objects into Strings for representation in a menu.

So we've got a list of Objects that we want to show in a SelectItem list. Some String value will need to be used in the "value" attribute of the rendered element.

<option value="?????" >Employee 1</option>

Why should we care what value is used?? Why doesn't JSF just assign some random identifier to each object? Really, there's no need to write a different converter for each object, depending on that object's primary key value, or other data. Any object can be converted to a String to display on the screen and then converted back into an object after being selected. Why does JSF force us to write a converter? There should be a better default converter. A universal default converter.

Enough hubbub, here's the solution: JsfUniversalConverter.java
private static final String objectCacheKey = "JSF_UNIVERSAL_CONVERTER_OBJECT_CACHE";

@Override
public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
if (string == null || string.length() == 0) {
return null;
}
Object returnObject = getObjectCache(fc).get(string);
return returnObject;
}

@Override
public String getAsString(FacesContext fc, UIComponent uic, Object o) {
if (o == null) {
return "";
}
String returnString = null;
Map objectCache = getObjectCache(fc);
//search cacheMap to see if this has already been converted.
for (Map.Entry cacheEntry : objectCache.entrySet()) {
Object cachedObject = cacheEntry.getValue();
if (cachedObject==null) continue;
if ( o.equals(cachedObject) || o==cachedObject ) {
returnString = cacheEntry.getKey();
}
}
if (returnString==null) {
returnString = UUID.randomUUID().toString();
objectCache.put(returnString, o);
}
return returnString;
}

private Map getObjectCache(FacesContext fc) {
HttpSession session = (HttpSession) fc.getExternalContext().getSession(true);
Object object = session.getAttribute(objectCacheKey);
if (object!=null && object instanceof Map) {
return (Map) object;
} else {
Map objectCache = new HashMap();
session.setAttribute(objectCacheKey, objectCache);
return objectCache;
}
}

Be sure to plug this into your faces-config.xml:
<converter>
<converter-id>universal</converter-id>
<converter-class>my.package.JsfUniversalConverter</converter-class>

</converter>



And if you're really good, just build a jar file that contains the class and faces-config.xml, and include this jar file on every JSF project.

From here on out, you solve all of your menu conversion issues with ONE converter:
<h:selectOneMenu converter="universal" ...



Caveat: If you use this and receive "invalid value" errors:
  1. Remember to properly implement the equals and hashcode methods of your business objects
    OR
  2. Ensure that your managed bean providing the List is returning the exact same instances of the objects in the SelectItem value every time.

Exciting? Thank me by leaving a comment. Your comments are what I do all this for. Thanks!

Friday, August 13, 2010

BlackJack Simulator ... with Java !

I've done something border-lining between brilliant and ultimately geeky. I'll prefer, instead, to compare it to the badass Ocean's 11 movies.
I've developed a completely object oriented API for simulating a deck of cards. There is a Deck object, which has a collection of Card objects within it. The deck has some member method operations such as draw(), which returns a Card, or shuffle(), which implements the popular Knuth Shuffle algorithm. There is also a Hand object, so that you can move cards from a deck and into a hand... This API seeks to be your utility for simulating any card game you'd like from your Java code.
If you'd like to see a JavaDoc of the API, you can see it here: http://www.freelance-webs.com/blackjack/doc/. Be warned, though, I didn't do a lot of documenting, and there are actually more objects than I'm eluding to in this blog.
So, I went on building more classes in order to use this API to simulate a BlackJack Game. I developed a configurable application to simulate an entire BlackJack game. You create a new Game object, pass in the number of decks you'd like to play (the game is over when the dealer runs out of enough cards to continue dealing), and pass in a Strategy object.
I designed a Strategy interface that you simply need to implement in order to create a decision engine for whether to hit, stand, etc. I then implemented a Strategy using the EXACT strategy shown here:
Now, there's much more to it than just this (I've probably got about 30 hours into this damn thing), but basically by creating a Game object and passing in my Strategy, I can run an entire blackJack game, simulating a player sitting down at a single deck table and flat-betting 5 dollars, of course altering his/her bet appropriately with splits, double downs, and surrenders. The player then gets up and walks away when the deck is through. The Game object returns a double primitive data type containing how much the player won or lost. If it's a negative number, then that's how much he lost.
So in one line of code you simulate all this. Now:
  • I put that one line of code in a for loop
  • Simulate this entire Game 100,000 times.
  • Average the result to find out how successful the strategy was.
Result: On average, with this strategy, at a single deck table where the dealer stands on soft 17, late surrender is allowed, flat betting $5, the player will walk away $0.20 richer. It's a positive number. It's a winning strategy.
For now, the view is all console output...


My next goal is to slap a rich web application interface on this using PrimeFaces where a user can fill out a grid like the one pictured above, click a big "simulate" button, and find out how much money their strategy wins or loses them after a 10,000 games or so.
Now I've just got to figure out how to make money off this freakin thing.

Friday, April 23, 2010

The Holy Grail of rapid application development

Lately I've been toying with the concept of rapid application development with little to no code-writing.

  1. Gather your business requirements
  2. Model your business objects
  3. Diagram/design your use-case flow
  4. Press the big green "win" button
  5. Deploy and profit
I'm aware of IBM tools (and others) that have attempted this concept with very limited success, but if I can pull this off on a pilot project via my own tools, I'd like to bring this notion to fruition and train my developer unit to begin developing applications this way.

Okay, allow me to refine the list above. Here's how I've been making this happen:
  1. Gather your business requirements
  2. Define and model your business objects via UML Class Diagram
  3. Design the rest of your app via detailed and complete UML Class Diagram
  4. Use an IDE such as MyEclipse or Netbeans to generate Java code directly from your class diagram
  5. Use Hibernate's JPA implementation and annotations to allow Hibernate to generate your database schema entirely from the POJOs generated in step 4
  6. Use MyEclipse & Hibernate's Reverse Engineering to generate all of your Data Access Objects (DAO).
  7. Fill in the blanks, implement business algorithms where necessary
  8. Deploy, test, refine.
In combination with an MVC framework like JSF, it seems that the only blanks you'd need to fill in (step 7) are the backing-bean action methods. What happens when each button is clicked is up to you, but at that point in time, all you'll be doing is tying together business objects and passing them back and forth between DAO methods, which you didn't need to take the time to write either.

Strap some rich PrimeFaces components into the view and you've got yourself a rich business application with little to no Java code writing at all.

In my fantasy world, where I've yet brought this concept to life, I imagine 6 months development projects taking 3 to 4 months tops. You'll still have all the same testing and bug-fixing as ever, but an increased level of design will leverage exponential gains in development time. If you're a seasoned developer, you've seen design pay off during development over and over again.

If I can find the time to run a pilot project behind the scenes and pull this off, I'll check back in and write up a conclusion!

-Lance

Monday, July 27, 2009

Getting Image Dimensions with Java

Retrieving the dimensions of an image file is a pretty common requirement for a web application. My current project is no exception, and needed to run a validation on uploaded images to ensure their width and height are not too big.

First, I tasked myself with learning to use the javax.imageio api to read through the metadata of an image file. Although this was doable... it was cumbersome. If all you'd like to do is find the image dimensions, you need to iterate through an awful lot of irrelevant information just to find it. After about 80 lines of code, I decided that was not the way to go.

The solution was this:
Image img = new ImageIcon("C:\\prototype.jpg").getImage();
System.out.println("width is "+ img.getWidth(null) );
System.out.println("height is "+ img.getHeight(null) );

Wow. Three lines of code. I think we've got a winner. You'll only need two imports to make this happen:
import java.awt.Image;
import javax.swing.ImageIcon;

This does, obviously, depend on you having the file written to local disk. If you don't (perhaps the file has come through the HTTP Request and is only in RAM), then I'd suggest writing it to the system's temporary file directory, so that you may get the dimensions while it's on the file system, but it will be deleted later. You may get the system's temporary directory like this:
String tempDir = System.getProperty("java.io.tmpdir");

Good luck. =)

Thursday, May 21, 2009

WebScarab and WebGoat - learning security!

Application Development: the funnest job in the world, right? But how do you feel about that fun when early in your career you first encounter the classic adage: "80% of your code will run only 20% of the time?" Bullet-proofing your code can be a real buzz kill for the wonder lusted developer.

Well fret no more. Securing an application isn't a tedious bore - it's an opportunity to step into the exciting shoes of a web hacker/cracker and have yourself a truly fun learning experience. I've spent the last two days using WebScarab and WebGoat, both open and free software provided by OWASP, as reliable (and awesome) learning tools to hack legitimate applications:
  • Tamper with request parameters on the fly
  • Embed Cross Site Scripting (XSS) attacks and Injection attacks to hijack sessions and elevate application authorization (make me an admin, please... woot. )
  • Manipulate requests to take advantage of vulnerabilities in Web Services.
the list goes on, but honestly I had the most fun just tampering with hidden input fields, altering drop down, and adding parameters to a request. I was able to do some amazing stuff, including hack into admin accounts and cause my own application to kick off emails in a malicious manner... A true learning experience.

Enough gab Here's the deal:

WebGoat:
This is a well designed application that is built to contain vulnerabilities on purpose. It is ready for you to do some Cross Site scripting and other common hacks on it, and feel the thrill of hacking into a system! It downloads and runs on its own servlet container right out of the box.
->Download here: http://code.google.com/p/webgoat/downloads/list
->Install Instructions here: http://www.owasp.org/index.php/WebGoat_Installation
At this time, version 5.2 is the latest release. Download the zip, run the batch file, and access the app at your localhost domain, running on either port 80 or 8080 depending on which batch file you ran. It's that easy. Linux users may want to check out the documentation I just linked above.

WebScarab:
This is a tool which will intercept your outgoing HTTP Requests and incoming HTTP Responses, giving you a chance to change them any way you like as you go. You just filled in a username and password? Let's see what happens when you decide to add onto the request a cookie that you stole from someone else's session, logging you in as them...
->Download here: http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project#Download

I am failling to find good instructions for this tool, but it's not hard to figure out. It's most compatible with firefox, so don't waste your time with IE. Simply change your firefox proxy settings to point to localhost, port 8008 (and remember to clear out the NO PROXY FOR field!!), fire up WebScarab, and click the "intercept requests" checkbox within WebScarab. WebScarab will act as a proxy, but if you use a proxy to the internet anyhow, then you'll need to tell WebScarab which proxy to forward to... Simply click the Proxies toolbar at the top of WebScarab and punch in your proxy server address. Port 3128 is pretty standard for a proxy.

Have fun guys