Monday, November 12, 2007

Two Hats

So did you hear the one about 2 hats on a hat rack?

 

The first one said to the other - "You stay here, I'll go on a head."

 

get it go on a head....

Friday, November 09, 2007

H:SelectOneMenu

This is the JSF tag that causes me more frustration than just about any other tag.   Probably documented the worst - probably a relation ship there...

So here is an example of the tag:

 

<h:selectonemenu value="#{selectManager.selectedTheme}">
<a4j:support actionlistener="#{treeManager.filterWorkspaces}"
ajaxsingle="true"
rerender="workspaceTree"
event="onchange">
<f:selectitems value="#{selectManager.themes}">
</h:selectonemenu>

 


Aside from from the a4j:support tag (we'll talk about that later) it is pretty much a text book example. The problem is what happens in the selectManager. 


We have 2 values we are binding to this component one is the #{selectManager.selectedTheme} and the other is #{selectManager.themes}.  If we take a step back and remember what the HTML select/option guys do we can figure out what is going on the selectedTheme variable is going to be one Object that is submitted on the post - the tricky part is that the themes object supposedly can be a List, an Array , a Set but really you just want to use a List.  Everything else just causes problems.


So the data backing the selectOneMenu is kind of important.  The API and documentation says that you need to use SelectItem objects and when you create a new one it takes an Object and a String (there are other constrcutors but this one works good for me)in it's constructor one is the value the other is the label.  Fair enough...


Here is the really important part the Object for the value really needs to be a String.  Now you can go and jump through all kinds of hoops to write converters and modify all your config files but just make the darn thing a String and be done with it.  If you want to put in your fancy objects I wish you the best of luck but keep the complex stuff in your code not the transmission between the jsps and your controllers.


So, the a4j:support part... this is the fancy stuff that is given to us from ajax4jsf library it makes your select component make ajax calls to the bound listener (#{treeManager.filterWorkspaces}) in our case.  It submits to a method that needs to accept an ActionEvent and return nothing.  Once you get into that method it is super easy to get the selected item - notice the selectOneMenu has a bound value #{selectManager.selectedTheme} that value is updated via the DHTML it has nothing to do with AJAX or form submits anytime you change the select list that value is changed... So when you're in your event method all you have to do is ask the FacesContext what the value is something like this:

SelectManager mgr = (SelectManager)FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("selectManager");
mgr.getSelectedTheme();

 


That's it... Pretty easy huh?


-Aaron

My New Java Shirt

Check out my new Java shirt! You're probably jealous now aren't you.

Thursday, November 08, 2007

Java Server Faces and AJAX

So, to carry on the theme from the previous post I've been playing with JSF quite a bit lately.  I've recently been moved over to the Architecture team and this team isn't so Java savvy.  They do learn quickly they/we are working on a proof of concept application and they opted to do Spring MVC in lieu of Java Server Faces.  Mostly do to the very steep learning curve; they wanted to learn something fairly easy to help meet their delivery dates.  Since they don't have much of any Java experience it was probably a wise choice.

Except for the fact that the development team that they are supposedly leading doesn't use Spring MVC for anything!!!  The dev team is a strict Struts shop until the last project that I did which introduced JSF, which seemed to be a very successful experience, although a rather painful learning curve.

Having said that what exactly does it mean to have a standard if the people that should be defining don't follow it?  <- that is mostly just a complaining kind of question I suppose.

My real question is with all of the web frameworks out there (and that isn't even a comprehensive list, especially if you start looking at various JSF Implementations ) how can you ever decide what should be your company's standard?  A search of JSF at Dice dot com shows 1,605 jobs Struts has 2,318.  I'm sure there is a bit of cross over but that is a significant difference.  Supposedly JSF is the direction the industry is moving towards - in fact IBM is not longer actively supporting Struts on their portal servers, so I guess that must mean something.

So why do enterprise development teams set standards if the technology moves so quickly?  As soon as you set them they're out of date...  So why then?

  • Performance
  • Scalability
  • Stability
  • Development Speed
  • Easily found skill set
  • Licensing
  • Support Structure
  • Long term viability of the technology

I guess that is a decent list - not terribly comprehensive but things to think about when deciding on a standard.  What things would you think about?  What frameworks are standard where you work?

Monday, November 05, 2007

JPA Code Examples

So here are the goodies:

first you need to make your persistence.xml file look kind of like this:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" xsi:schemalocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="TestJPA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.agnostic.software.jpa.entities.Users</class>
<properties>
<property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"></property>
<property name="hibernate.connection.url" value="jdbc:mysql://serverName/dbName"></property>
<property name="hibernate.connection.username" value="webUser"></property>
<property name="hibernate.connection.password" value="myPassword"></property>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"></property>
</properties>
</persistence-unit>
</persistence>

 


Notice the properties section and the lack of jta-data-source tag, this will create a problem if you want to use this persistence file to deploy to the app server.


Your Entities won't need to change, they'll work the same. 


Your Junit tests can be configured lots of ways but this is how I did mine:

public class TestUsers extends TestCase {
private EntityManagerFactory emf;
private EntityManager em;
@Override
protected void setUp() throws Exception {
emf = Persistence.createEntityManagerFactory("TestJPA");
em = emf.createEntityManager();
}
public void testRetrieveUsers(){
em.getTransaction().begin();

List<Users> users = null;
try{
Query query = em.createQuery("Select u from Users u");
users = (List<Users>)query.getResultList();
} catch (Exception e){
e.printStackTrace();
}
assertNotNull(users);
for (Users u : users){
System.out.println(u);
}
System.out.println("returning: " + users.size() + " users");
em.close();
emf.close();
}
}

That is it in a nutshell, I'm surprised that this isn't documented somewhere better but here it is for your testing enjoyment... So don't give me any excuses test that code!

Testing JPA

So, I've gotten very comfortable with the whole Spring/Hibernate mashup.  I really can't think of a better way to do database transactions than using hibernate to map the database and Spring to inject the Hibernate sessions into which ever component needs it.  It is simple and it just simply works...

 

One of my favorite things about using Hibernate is the Criteria search capabilities.  Basically it is a very OO way to do simple queries - you can get kind of clever with them but for the most part simple is better.   And in my opinion if you're writing queries that can't be done with Criteria's your data model probably sucks and needs to be re-worked... like that is ever an option.

 

Anyway I've recently joined the Architecture team and I was having a conversation espousing the glory and ease of use of these criteria's when somebody popped their head up over the cube wall and said "Why would you use Criteria's anyway they're not supported by the JPA specification."

 

Which is unfortunately true... for now anyway.

 

So, my last project was with JSF which was delivered successfully but it was extremely painful.  Mostly due to IBM's horrible implementation with their 5.0 portal server - heh, yeah it was even jdk1.3 how cool is that?

 

As that project is closing off I've been thinking on some of the pain points of that my team and I went through.  This contemplation led me to SEAM which led me to EJB3 and JPA.

 

So that's twice that JPA has come up recently so I decided to start poking around and see if I can figure the new specification out.  Indeed I have lost my beloved criteria's and once again an forced to contaminate my java code with SQL like syntax.  I can live without that temporarily anyway as long as I have a robust testing model.  So far the best I've seen is integrating with Spring to do it.  But isn't EJB3 supposed to handle the IOC for me? 

 

So after more searching than their should have been I found this article that takes you to a Sun Tutorial on desktop Java so with just a little bit massaging I can now run Junit test cases with just JPA, very sweet...

Thursday, October 04, 2007

Wednesday, October 03, 2007

Picture I saw on the way to work the other day.

Monday, September 10, 2007

Intention

I have had several blog entries in the past about intentions.  So, excuse me for repeating myself but my thoughts often return to this subject and my misunderstanding of them in the past and present.

For those of you who may read this and not really know me I have an 11 year old boy, a 8 year old girl, and a 3 year old girl as well.  Lately the 11 year old has taken quite an attitude with pretty much everyone but mostly with his oldest sister.

This morning he was exceptionally grouchy about her whistling on the way to the car.  On and off throughout the day I had thought about what I could say that would let him know that the problems that he has with her are mostly in his perspective of reality.  In other words her whistling or crunching on some popcorn loudly maybe rude but are mostly problems because of what he brings to the experience. 

Pema Chodron has a book called "No Time to Lose" that talks about how we should react when people do things that we perceive to hurt (or irritate) us.  The advice in that book is to act as though the people had as much intention or control over themselves as a tree dropping one of it's limb's on our head.  A tree would have no intention of hurting us so it would be silly to be angry  at the tree.

So here I am explaining this to my son in the context of his sister being the tree; her irritating habits are only irritating to him because he chooses to be angry at her.

He then corrects me and proceeds to explain to me that he is trying to get her to stop so that when she is at school she won't behave that way - and then people won't tease or make fun of her the way they did him, and that he gets angry because she ignores his advice.  Her not showing the proper response to his advice is what makes him angry not that she is chewing with her mouth open or whistling...


The conversation was pretty much over at that point.  His intention is sound, he is just not carrying it through properly...

 

... Amazing ...

 

-Aaron

Wednesday, August 15, 2007

Teachers...

So, I realize that I have a different view on things...

I suppose I always have and probably always will.  I'm okay with that, however it does seem to cause the occasional friction or concern that no one else has but me. 

Today someone put in their 2 weeks notice here at work.  Many people were quite happy that he did, not me though.  Admittedly this fellow  is very hard to work with, he does not hesitate to interrupt conversations, refuses to follow the development process we have in place, and doesn't ask for help when he doesn't know what to do. 

However, he really cared about the quality of his work and would argue his point until you were forced to listen, but would eventually concede when/if the case was lost.

We were at odds a lot of times and I think that I'm the only one who had any respect for him at all.  I did (usually) like him as a developer and a person.  

Not that I didn't get frustrated and occasionally angry with him.  I just can't help but think of the Buddhist teaching that tells us to be thankful for the people in our lives that we struggle to get along.  It is through them that we learn compassion, patience and wisdom...

 

So, see you later V. P. I hope your next job treats you better...

-A

Wednesday, August 01, 2007

I always wondered how to do that!

So, have you ever been writing code and new there was a probability an exception was going to get thrown. For whatever reason you want to do something with the stack trace kind of unusual, and you want more than just the exception.getMessage() in fact you want the whole stack trace.

Now I never claimed to be a rocket scientist. Some days I don't even claim to be clever. Today I took the time to figure out how to catch the exception and turn the complete stack trace into a String that you can do whatever you want to with. Here is the snippet I used.

catch (Exception e){
confirmMessageButton.setText("Exit");
OutputStream os = new ByteArrayOutputStream();
PrintWriter writer= new PrintWriter(os);

e.printStackTrace(writer);
writer.flush();
String myMessage = new String(
((ByteArrayOutputStream)os).toByteArray());
//do something with the string
}


So, like I said it's not rocket science but it is something I always wondered how to do.


-Aaron


Monday, July 30, 2007

A dash of ruby

So, I've been playing with ruby on and off now for about 2-3 months.  After going through the pick axe book and a rails book I have pretty much set it down, mostly so I could focus on some Java issues at work. 

After our last release the Java work has settled down and now my interest in Ruby has once again returned, not Rails so much (However, I do think that the Java Community has a lot to learn from Rails though).  So here is the problem I had...

The company that I work for is completely in love with EJBs (2.1).  We use them with Spring so it's not as bad as it might sound.  Anyway to stub out an EJB it takes about an hour.  That is without any methods that actually do something.

So just in the event that you 're working on an application server that doesn't support JEE 5 or higher (I think that is the write acronym - they keep changing) here are the things you need (this is the spring version so there are a few extra interfaces in there to make it more fun):

Server Side Components

  1. The implementation that does something.  This should extend the interface in the client
  2. The EJB that implements the interface in the client and and Spring's AbstractStatelessSessionBean

Client Side Components

  1. The interface that defines what is supposed to happen
  2. The LocalHome interface this guy extends EJBLocalHome and simply has a create() method
  3. The Local interface this guy extends our interface and EJBLocalHome.  Oddly enough he has no methods (spring takes care of it for us).
  4. The Remote  interface he extends EJBObject and has the same method signatures as the interface (unless you don't want them exposed through remote objects)
  5. The RemoteHome interface that extends the EJBHome he has one method method called create()

 

So to hand code all of these things correctly takes me around an hour more or less depending on distractions.  So here is a fancy little ruby script that will prompt you for package names implementation names and a few other things and generate those guys for you.  Of course you will still need to configure the spring files and ejb-jar.xml file as well as whatever custom config files your appserver needs but it was a fun task to do with Ruby.

 

-Aaron

Friday, July 20, 2007

Life is like that I guess

So, my dad is dying...  Ok, so he is technically my step dad but he raised me nonetheless.  Many of my best (or worse attributes) come from him.

Anyway, last year he lost a kidney to cancer.  The one he has left is only working at 50% capacity (so that is 25% over all).   It turns out on top of all that he has a small spot of lung cancer as well...

So, yeah.  He's feeling fine now but we don't know how long that will last.  He is taking treatments for the bladder/kidney cancer several times a week now.  And the doctors are trying to figure out what to do about the lung cancer now.

On the flip side he has a Grand Daughter who is about to get married, his house is paid off, he has his first Grand Son who will bear his name that will be born in a few months...

Life is like that I guess... Really bad things happen at the same time really bad things happen... It's never all bad or all good. 

It reminds me of the Zen story of where this guy is hanging from a vine while a tiger is looking down trying to get him, a poisonous snake is working it's way up to get him, and 2 mice begin to chew the vine.  With death coming from all around some honey starts dripping into the hole and he realizes how great the honey tastes. 

 

Yeah, Life is like that I guess.

 

-Aaron

Tuesday, July 17, 2007

Buddha is as Buddha does

So, I started reading a new book a few weeks ago.  It's called "Buddha is as Buddha Does" by Lama Surya Das.

 

I haven't read any of Lama Surya Das's other books but this one is really great.  However, it is not a fast reader the concepts are really quite deep.  It's one of those books that has to be digested slowly.  I find myself only able to read a couple of pages at a time.  The concepts just sit in my mind and slowly soak in.  Here is a particularly great paragraph (from chapter 1 - Generosity):

"Whenever we consider our inner thoughts about anything, it's crucial to bear in mind that we can change them.  Being visited by negative or selfish thoughts doesn't make us bad people.  It just means we're conditioned human beings.  Nor do we have to be forever at the mercy of these thoughts merely because they occurred to us.  We can cultivate positive thoughts to replace them, thus skillfully and intentionally reconditioning and eventually deconditioning our energy and ourselves.  When the Buddha said, 'We are what we think,' He was asking us to take responsibility for our inner life.  That's the crux of why meditation and awareness cultivation are such vital practices in Buddhism.  They enhance our ability to manage more skillfully our own thoughts and feelings, including our thoughts about generosity -- a truth that, again illustrates how all the paramitas are interrelated and mutually supportive.

It is a great comfort for me to remember throughout the day that the thoughts that arise in my mind are not necessarily a reflection of who and what I am.  Irrational anger can be caught and defused before it explodes.

The teachings of the Buddha give me great hope...

-A

Monday, July 16, 2007

Cool Little JavaScript goodie

Oddly enough one of the best web sites I've been to in a while is my local gas company.  They have this fancy little clock that tells you what time it is, I finally took the time to figure out how they did it.  Here is the short version...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Clock </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
/* =================================================== */
// Display Date / Time
var ie = /MSIE/.test(navigator.userAgent);
/* =================================================== */
var addEvent;
if (document.addEventListener) {
    addEvent = function(element, type, handler) {
        element.addEventListener(type, handler, null);
    };
} else if (document.attachEvent) {
    addEvent = function(element, type, handler) {
        element.attachEvent("on" + type, handler);
    };
} else {
    addEvent = new Function; // not supported
}
/* =================================================== */
// Display Date / Time
function clock(){
    if (!document.getElementById){ return }
    this.start = function(){
        var self = this;
        this.date = new Date();
        // ===== Set Timezone & Daylight Savings ===========
        var day = this.date.getDay();
        var month = this.date.getMonth() + 1;
        var week = Math.floor((this.date.getDate() - 1) / 7) + 1;
        var dst = Number(month +""+ week +""+ day);
        // daylight savings range
        var start = 327  // March(3): Second(2) Sunday(7) = 327;
        var end = 1117    // November(11): First(1) Sunday(7) = 1117;

        this.offset = (dst > start && dst < end)? -5 : -6;
        this.zone = "CT";
        this.utc = this.date.getTime() + (this.date.getTimezoneOffset() * 60000);
        this.d = new Date(this.utc + (3600000*this.offset));
        // ===== Format Date ===============================
        this.day = this.addZeros(this.d.getDate());
        this.month = this.getMonthName(this.d.getMonth());
        this.yr = this.d.getYear();
        this.year = (this.yr<1000)? (this.yr+=1900) : this.yr;
        self.addSeconds();
        window.setInterval(function() {self.addSeconds();},1000);
    };
    this.addSeconds = function() {
        this.d.setSeconds(this.d.getSeconds() + 1);
        var hours = this.setMeridian(this.d.getHours());
        var minutes = this.addZeros(this.d.getMinutes());
        var seconds = this.addZeros(this.d.getSeconds());
        document.getElementById("dateTime").innerHTML = this.month+" "+this.day+" "+this.year+" "+hours+":"+minutes+":"+seconds+" "+meridian+" "+this.zone;
    };
    this.getMonthName= function(nMonth){
        var months = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
        return months[nMonth]
    };
    this.setMeridian = function(hours){
        meridian = (hours < 12)? "AM" : "PM";
        return (hours > 12)? hours-12 : (hours==0)? 12 : hours;
    };
    this.addZeros = function(digits){
         return (Number(digits) < 10) ? "0"+digits : digits;
    };
}
addEvent(window,'load',startClock);
function startClock(){
    var theClock = new clock();
    theClock.start();
}
/* =================================================== */
//-->
</SCRIPT>
<STYLE TYPE="text/css" TITLE="">
t body { margin:0px; padding:0px; border:0px; text-align:center; background:#FFF; }
body { margin:0px; padding:0px; border:0px; text-align:center; background:#FFF; }
body * { font-family: Tahoma, Arial, Helvetica, sans-serif; }
#header ul.navitems  { position:absolute; top:8px; left: 165px; z-index:10; margin:0px; padding:0px; list-style-type:none; }
#header ul.navitems li { float:right; font:normal 10px Arial, Helvetica, sans-serif; color:#898688; padding-left:10px; }
#header ul.navitems li.stock { background:transparent url(../images/arrow.gif) no-repeat 0px 0px; padding-right:10px;  }
#header ul.navitems li#dateTime { border-left:1px solid #CCC; margin-left:10px; display:block; width:140px; padding:0px 10px 0px 10px; white-space:nowrap; }
#header ul.navitems li a { position:relative; top:2px }
</STYLE>
</HEAD>

<BODY >
<div id="header">
    <ul class="navitems">
        <li id="dateTime">&nbsp;</li>
    </ul>
</div>
</BODY>
</HTML>

Saturday, July 14, 2007

One More...

Releasing the Cows as told by Thich Naht Hahn

So one day the Buddha was sitting with a number of monks in the woods. They had just finished their mindful lunch and were about to start a Dharma discussion when a farmer came by. He was lost and said: “Dear Venerables did you see my cows passing by here?”, and the Buddha answered “No we have not seen any cows”.

“I have 3 cows, and this morning I don’t know why, all of them have run away. And this year the insects have eaten up all of our crops I think I’m going to die.” The farmer expressed his sufferings and worries.

The Buddha said “Dear friend, we have not seen your cows passing by here, you might try to look in the other direction.” The farmer thanked the Buddha and went away.

The Buddha turned to his monks smiling he looked at them and said “Dear Friends, do you know that you are happy people? Do you know that you are lucky people? You don’t have any cows to lose!”

So the practice here is to identify the cows that you have. The cows that you think you can not be separated from. The cows that you think are essential to your happiness but these cows actually cause you suffering.

Odds and Ends pt 6

And finally....

How far you go in life
Depends on your being
Tender with the young
Compassionate with the aged
Sympathetic with the striving
Tolerant of the weak and the strong

Because someday in life you will have been all of these

-George Washington Carver

Odds And Ends pt 5

A prayer heard from Jack Kornfield

Dear God,
So far today I've done alright. 
I haven't gossiped, lost my temper,
haven't been greedy, nasty, selfish or
over-indulgent.

I'm really glad about that.

But in a few minutes God I'm going to
get out of bed.

And from then on I'm probably going to
need a lot more help.

Thank you.

Odds and Ends pt 4

Traditional Zen Blessing on food

Innumerable labor's brought us this food
we should know how it comes to us

Receiving this offering
we should consider wether our virtue and practice deserve it

Desiring the natural order of mind
we should be free from greed hate and delusion

Odds And Ends pt 3

Let me not pray to be sheltered from dangers
but to be fearless in facing them.

Let me not beg for the stilling of my pain
but for the heart to conquer it.

Let me not look for allies in life's battlefield
but to my own strength.

Let me not crave in anxious fear to be saved
but hope for patience to win my freedom.

- Ancient Buddhist Prayer