Monday Sep 24, 2012

Join Me at JavaOne!

JavaOne 2012 is less than a week away! If you've already made plans to be there, you're probably getting pretty excited about it already...and if not, what are you waiting for?!?

Before I get to the session information, I want to point out that qualified students get free admission to JavaOne, so if you are (or know) a CS or IT (or other tech-leaning) student who might like to attend, follow the link and start making plans. There is so much there to learn and experience.

I'm happy to say I'll be a small part of the festivities. I'll be leading the following session:

CON3519 - Building Hybrid Cloud Apps: Local Databases + The Cloud = Extreme Versatility

In this session, learn how to design and develop applications that leverage both local storage and the cloud, maximizing the strengths of each. Using NetBeans, JavaServer Faces 2.0, GlassFish Server technology, JavaFX 2, Oracle Database, and Evernote, rapidly create prototypical applications that can be deployed in various environments and scaled up/out with enterprise cloud solutions. 

As a contributor to the JFXtras project, I also hope to attend the following "Birds Of a Feather" (BOF) session led by Gerrit Grunwald and Stephen Chin:

BOF5503 - JFXtras Super Happy Dev BOF

JFXtras, the open source JavaFX control and extensions project, is back for JavaFX 2.0. In this session, you will learn about the latest changes in JFXtras 2.0, including new components, controls, and features that integrate with the JavaFX 2.0 libraries. Expect to meet the JFXtras core team members as well as other interesting client RIA implementers and developers. Now that JavaFX is coded in Java, a few server-side hackers may even be let in the door.

If you're there, please stop by and introduce yourself! And to follow along with my J1 travels or keep in contact afterward, please follow me on Twitter or connect via G+ or Facebook (links in panel to right). Hope to see you there, but either way, keep the Java flowing!

All the best,
Mark 

Tuesday Jun 05, 2012

Quick Fix for GlassFish/MySQL NoPasswordCredential Found

Just the other day, I stood up a GlassFish 3.1.2 server in preparation for a new web app we've developed. Since we're using MySQL as the back-end database, I configured it for MySQL (driver) and created the requisite JDBC resource and supporting connection pool. Pinging the finished pool returned a success, and all was well.

Until we fired up the app, that is -- in this case, after a weekend. Funny how things seem to break when you leave them alone for a couple of days. :-) Strangely, the error indicated "No PasswordCredential found". Time to re-check that pool.

All the usual properties and values were there (URL, driverClass, serverName, databaseName, portNumber, user, password) and were populated correctly. Yes, the password field, too. And it had pinged successfully. So why the problem?

A bit of searching online produced enough relevant material to offer promise. I didn't take notes as I was investigating the cause (note to self), but here were the general steps I took to resolve the issue:

First, per some guidance I had found, I tried resetting the password value to nothing (using () for a value). Of course, this didn't fix anything; the database account requires a password. And when I tried to put the value back, GlassFish politely refused. Hmm.

I'd seen that some folks created a new pool to replace the "broken" one, and while that did work for them, it seemed to simply side-step the issue. So I deleted the password property - which GlassFish allowed me to do - and restarted the domain. Once I was back in, I re-added the password property and its value, saved it, and pinged...success! But now to the app for the litmus test.

The web app worked, and everything and everyone was now happy. Not bad for a Monday.  :-D

Hope this helps,
Mark

Thursday Apr 19, 2012

Basic Bean Building: How to Quickly Create a JSF Managed "Look-up" Bean

If you're called upon to build a JSF application (large or small), NetBeans is a great tool to help you gain traction, and fast. I've mentioned previously how much I like the ability to do a quick first cut by creating your data structures and using NetBeans to generate a basic web app as a starting point. You go from nothing to working web application in short order, albeit a bit bare-bones. Still, what a great time-saver!

Let me toss out a few reminders and disclaimers. First, I'm a firm believer in rapid, iterative, and thoughtful development. No "paralysis of analysis" allowed, but OTOH, each step should be considered carefully as you go. Plan, execute, evaluate. Lather, rinse, repeat.  :-)

Second, build from small to large. Plan ahead, but make things work on a small scale and build out. This goes hand-in-hand with point #1, but it bears mentioning separately.

With those points in mind, I created a small sample project for use in this and future discussions: The Mighty Bean Coffee Company. Java is a wonderful thing in almost any form, so why not double our pleasure?

For the first iteration of our new project, I created an initial set of tables in a new MySQL database. These are the ones we'll be considering on our quest to create a JSF managed "look-up" bean:

Next, I created a new Java Web project, Web Application in NetBeans called MightyBeansWeb. Defaults were fine for our purposes here with the exception of selecting JavaServer Faces under Frameworks.

With the project created, I right-moused on MightyBeansWeb in the tree browser, chose "New Entity Classes from Database", and made the connections to the data source. Selecting the two tables modeled above, NetBeans provided us a couple of nicely-formed entity classes: Customer.java and CoffeeOrder.java.

Creating the JSF pages was also a snap. Right-moused again on the app, chose "New JSF Pages from Entity Classes", selected the classes and specified destination packages, and clicked finish. Et voila! We now have a working JSF web app. Go ahead, try it out. I'll be right here when you get back.  :-)

(Side note: Please feel free to a) update the toString() methods for more meaningful contents - this will come in very handy later! - and b) to refer to our recent article NetBeans, JSF, and MySQL Primary Keys using AUTO_INCREMENT to enable primary key auto-generation within MySQL.)

"That's great!" you say. But wouldn't it be nice to see which customer we've selected for our order? That brings us to the topic of this article. Let's whip up a look-up bean and make that happen now.

Right-mouse once more on the web app and choose "New JSF Managed Bean". Pick a name (I called this one "CustomerLookupBean") and a package and click finish. No need to do anything else on that panel since we're using Java EE 6.

Opening the class, we see it has annotations for @ManagedBean and @RequestScoped which serve our needs nicely. We just need to add a couple of very small things to wrap up our bean-work.

Since EJBs are non-reentrant, we can simply inject an instance of EntityManager into our lookup bean by adding the following lines to the class definition:
    @PersistenceContext(unitName = "MightyBeansWebPU")
    EntityManager em;
Clicking on the warnings in the left column prompts you to let NetBeans fix the imports. Yes, please!

Next and finally, we need to create a method to return the desired customer, something along the order of this:


This method issues a named Customer query using the ID provided and returns a single result. Since createNamedQuery returns a generic object, we cast it to what we know is coming back to us (a Customer object), then return the customer's full name. Not pretty, but good enough for a first cut.

Editing the appropriate list.xhtml file to display the customer's name instead of number is as simple as replacing <h:outputText value="#{item.customer}"/> with <h:outputText value="#{customerLookupBean.getName(item.customer.id)}"/> to query and receive the full customer name, taking us from this:

To this:

"Pretty" comes later, but this is a start. Any thoughts, comments, or questions? Please drop me an email or comment below!

All the best,
Mark

Sunday Mar 25, 2012

NetBeans, JSF, and MySQL Primary Keys using AUTO_INCREMENT

I recently had the opportunity to spin up a small web application using JSF and MySQL. Having developed JSF apps with Oracle Database back-ends before and possessing some small familiarity with MySQL (sans JSF), I thought this would be a cakewalk. Things did go pretty smoothly...but there was one little "gotcha" that took more time than the few seconds it really warranted.


The Problem

Every DBMS has its own way of automatically generating primary keys, and each has its pros and cons. For the Oracle Database, you use a sequence and point your Java classes to it using annotations that look something like this:


@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="POC_ID_SEQ")

@SequenceGenerator(name="POC_ID_SEQ", sequenceName="POC_ID_SEQ", allocationSize=1)


Between creating the actual sequence in the database and making sure you have your annotations right (watch those typos!), it seems a bit cumbersome. But it typically "just works", without fuss.


Enter MySQL. Designating an integer-based field as PRIMARY KEY and using the keyword AUTO_INCREMENT makes the same task seem much simpler. And it is, mostly. But while NetBeans cranks out a superb "first cut" for a basic JSF CRUD app, there are a couple of small things you'll need to bring to the mix in order to be able to actually (C)reate records. The (RUD) performs fine out of the gate.


The Solution

Omitting all design considerations and activity (!), here is the basic sequence of events I followed to create, then resolve, the JSF/MySQL "Primary Key Perfect Storm":

  1. Fire up NetBeans.
  2. Create JSF project.
  3. Create Entity Classes from Database.
  4. Create JSF Pages from Entity Classes.
  5. Test run. Try to create record and hit error.

It's a simple fix, but one that was fun to find in its completeness. :-) Even though you've told it what to do for a primary key, a MySQL table requires a gentle nudge to actually generate that new key value. Two things are needed to make the magic happen.


First, you need to ensure the following annotation is in place in your Java entity classes:


@GeneratedValue(strategy = GenerationType.IDENTITY)


All well and good, but the real key is this: in your controller class(es), you'll have a create() function that looks something like this, minus the comment line and the setId() call in bold red type:


    public String create() {

        try {

            // Assign 0 to ID for MySQL to properly auto_increment the primary key.

            current.setId(0);

            getFacade().create(current);

            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CategoryCreated"));

            return prepareCreate();

        } catch (Exception e) {

            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));

            return null;

        }

    }


Setting the current object's primary key attribute to zero (0) prior to saving it tells MySQL to get the next available value and assign it to that record's key field. Short and simpleā€¦but not inherently obvious if you've never used that particular combination of NetBeans/JSF/MySQL before. Hope this helps!


All the best,

Mark



About

The Java Jungle addresses topics from mobile to enterprise Java, tech news to techniques, and anything even remotely related. The goal is to help us all do our work better with Java, however we use it.

Your Java Jungle guide is Mark Heckler, an Oracle Java/Middleware/Core Engineer with development experience in numerous environments. Mark's current work pursuits and passions all revolve around Java and leave little time to blog or tweet - but somehow, he finds time to do both anyway.

Mark lives with his very understanding wife, three kids, and dog in the St. Louis, MO area.



Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today