Wednesday, May 14, 2014

Connected rooms in Inform 7

So here's a little snip for an Inform 7 story that allows one to connect rooms.  A connected room is a room that is slightly different than an adjacent room.  Say I'm sitting in a living room in an open concept house.  I can see the kitchen from the living room, identify distinct things in the kitchen, but I am not actually in the kitchen.

In this regard, the kitchen is connected to the living room.  If I want to look at something in the kitchen, I sort of can, but really I need to move to the kitchen and out of the living room to do that.

This little rule modification can add this simple connected rooms ability to your story.  It's not fully featured, like if something was really huge and could be clearly seen from all angles, but it will get the job done for things like big hallways.

So here's the code.

Section 1 - Basic Rules

Intervisible relates rooms to each other in groups.  The verb to be connected with implies the intervisible relation.

Definition: a room is inter-visible if it is connected with more than one room.

After deciding the scope of the player when the location is an inter-visible room:
 repeat with other place running through adjacent rooms which are connected with the location:
  unless the other place is the location, place the other place in scope.
  
Rule for reaching inside a room (called target) which is connected with the location:
 let way be the best route from the location to the target;
 if the way is not a direction:
  say "You can't get over to [the target] from here.";
  deny access;
 say "(first heading [way])[command clarification break]";
 try going way;
 if the player is in the target, allow access;
 otherwise deny access.

After looking when the location is an inter-visible room:
 repeat with other place running through adjacent rooms which are connected with the location:
  if the other place is not the location, describe locale for other place.

Sunday, April 06, 2014

MRI 1.2.1 in LO 4.2

I'm happy to say that I've done some pretty extensive testing with MRI 1.2.1 on LO 4.2 and it works flawlessly.

That is all...

Friday, February 14, 2014

Pentaho Scriptable Data Source and grabbing the underlying JNDI connection

This post is a little stray from the usual posts I've been putting up about LibreOffice.  This one deals with using Pentaho!  Now for those not in the know, Pentaho is a BI software suite.  At my job, one of my duties is Big Data and building reporting, analytic models, and dashboards for distribution of the collected data.

Well, I tend to play with the software in my off-time to get to know it and the source code.  Now one of the things coming from a Java programming background is having direct access to the underlying database.  Now if you setup your BI suite correctly, you should never need access to the database itself.  However, there was this one time where I wanted to create a temp table on the database and not in memory, I wanted direct access to the database.  After talking to myself for a while, I decided to not break my rule of trying to get direct access to the database through the report.  I changed my method and report was made...

However, after that moment, I was left with an itch to figure out, "How does someone go about grabbing a data source object from the BI server?"  For about a year or so, the urge to sit down and code an example came and went.  Most of the time I distracted myself with some other project, but always in the back of my mind was this thing that I hadn't done before and it was killing me.  So fast forward to about two weeks ago.  I finally, decided to bury the hatchet and code up an example of a report grabbing the data source from the JNDI tree.

So let's begin!!!

Today, I'm breaking out the "trusty" Windows system (because it's the one I randomly grabbed to start typing this post).  I'm going to assume the following, if none of this applies to you and you don't know how to get to these points, then this post isn't going to be very helpful for you.


  1. You have Pentaho Report Designer (CE or EE edition)
  2. You have a running instance of Pentaho BI Server that you can publish to!!
  3. Your PRD install has a proper simple-jndi setup already.
  4. Your BI server instance has the JNDI connections setup in the application context within Tomcat.
  5. You already know a bit about the PRD scriptable data source.

That being said, go ahead and fire up Pentaho Report Designer.

Step one will be to start a new scriptable data source.
Starting a scriptable data source

A scriptable data source invokes the Rhino environment to execute your Java/Groovy/JavaScript code.  I'll be using plain Jane Java here (also know as Beanshell to the Rhino environment).

Go ahead and add a query and type the following in:
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import org.pentaho.reporting.engine.classic.core.util.TypedTableModel;

InitialContext cxt = new InitialContext();
//DataSource ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/PROD_RM_JNDI");
DataSource ds = (DataSource) cxt.lookup("RM_SYS_1_JNDI");

Connection c = ds.getConnection();
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM ACC_CODES_PTE");

String [] columnNames = new String [] {"Column 1"};
Class [] columnTypes = new Class [] {String.class};

TypedTableModel model = new TypedTableModel(columnNames, columnTypes);

while(rs.next())
 model.addRow(new Object [] {rs.getString(1)});

c.close();
return model;
Now notice how I have one of those context lookups commented out. There is a reason for that.  Within the standard PRD environment, you are provided a FULL JNDI tree, you are actually using a little project called simple-jndi to provide pseudo-JNDI functionality.  When you switch over to the BI server, go ahead and comment out the current context lookup and use the lookup with the big huge path.  That's a proper JNDI path on the Tomcat server.

Once you've added an element to represent your data into the details section of the report, preview it.  You see that the system grabs a connection from the JNDI pool, uses it, and then tosses it back into the pool.  The model is then sent back to the report for processing and reporting.

It's pretty simple and this now allows you to create a temp table when the report runs on the DB.  Just remember that you need to take care to get rid of temp tables when you no longer need them, especially if you are using Tomcat's connection pooling.

Saturday, February 08, 2014

Excellent file for LO and AOO Base users

If you have ever wanted to understand more about LO or AOO Base.  An excellent resource is:

http://www.pitonyak.org/database/AndrewBase.odt

This shows quite a bit about using the UNO API to do all kinds of wonderful things.

Additionally, LO 4.2 is now out!  You should go check it out.  I highly disagree with the new startup screen and rather have the old one, but I'm pretty sure this new one will grow on me.

Saturday, February 01, 2014

Using MRI and a basic spreadsheet macro

Introduction:


That being said, I'll be using LO 4.1 on Mac OS X 10.9, however, you'll find that most of everything covered here is quite true for the Linux or Windows version as well.  However!!  If you by chance do find some difference between what I've got here and what is on your screen, then feel free to drop a comment telling me what you found and what not.

For this post, I am just going to quickly go over the most basic macro possible and tie in MRI along with it.  Our macro will be to quickly create a table that says "Hello, world!" in one column and in the second column have a number counting up from zero to ten.  That is, a total of eleven rows.

Starting up the macro:

The first thing we need to do is start up the macro editor and MRI.  To start up the macro editor, first open a new blank spreadsheet, then from the main menu select:  Tools | Macros | Organize Macros | LibreOffice Basic...   This brings up the macro organizer.


You'll see a box on the left called "Macro From", this indicates where the macro in question is coming from.  You will always have at least three sources here.  The first is your personal macros that are common to anything you open in LO (My Macros), the second is the macros that come with your extensions and the default install of LO, and the third and final location is from an open document (in this case our open spreadsheet).  It is actually possible to have more than three locations to pull macros from as the location list includes all of the currently open files.

We will create today's macro within the spreadsheet, so that when I pass off the spreadsheet, someone else will be able to run the macro.  Usually, you do not want to do this because that can be a security risk, especially if you are not signing your documents before distribution.  However, for example, we will let it pass.  Just click on the "New" button after selecting the spreadsheet from the "Macro From" box.  A dialog will appear to ask you to name the new module, just go ahead and accept the default "Module1".  Finally, the macro editor appears.


Starting up MRI:

I'm going to start up MRI so that I can follow along and do introspection while I'm writing the macro.  To begin MRI I'll need to head to Tools | Add-ons | MRI.





MRI may be a bit confusing at first but it'll make sense in a bit.  Note the box on the top left.  It should state com.sun.star.lang.XComponent.  XComponent is an UNO interface that is used by a lot of stuff.  Remember that MRI, and for that matter everything else that doesn't own the actual spreadsheet document, is looking from outside in.  So XComponent is generic enough to begin getting access to underlying stuff.  MRI doesn't know at this time that what it is looking at is indeed a spreadsheet, hence the XComponent interface.

You'll notice four buttons:  Attributes, Methods, Interfaces, and Services.  For the most part you'll be dealing with Attributes and Interfaces when you write a macro, however, that's not exactly a hard and fast rule and more complex stuff will use all four.

For the time being, go ahead and head over to XComponent's methods.  I'm going to be covering that in just a second.

ThisComponent:

When you start up a macro, you automatically receive at a global scope a value called ThisComponent.  ThisComponent is the component that owns the macro.  However, it is passed to your macro as a generic XComponent interface.  It's up to you to test the XComponent to ensure that it is actually a spreadsheet and what-not (thing called type safety).  However, I'm going to skip all of that because we're doing a simple macro that is going to be traveling with the spreadsheet.  So type safety be damn...

So ThisComponent in macro is equal to our com.star.lang.XComponent that MRI is currently showing.  If we look at the methods for this interface we will see that there is a method called getSheets.  In the second column we will see the call signature which is () or no parameters are expected with this call.  In the third column we can see that calling this method will return .sheets.XSpreadsheets, which as you can tell from the X at the beginning, it's an interface as well.  So calling this method will return us an interface to ALL of the spreadsheets in the document.

Now just to be totally clear, if we were in say Writer and making a macro, we'd see in MRI that ThisComponent would still point to com.star.lang.XComponent, however you wouldn't have a getSheets() method in that because a writer document doesn't have sheets.  Again, that's because XComponent is a generic interface that we use to get more specific things.  If you look at the fourth column in MRI for the getSheets() method, you'll see that the method is actually provided by .sheets.XSpreadsheetDocument.  So within your XComponent MRI found a XSpreadsheetDocument.  When you fire MRI up in writer, you'll notice your XComponent doesn't have a XSpreadsheetDocument within it.

Writing the code:

Time to write the code.  So our XComponent has multiple sheets (at least in theory, right now there's only one sheet in the entire workbook), so when we call the getSheets() method we're going to receive every single one of them.  Because of that, we don't have a lot of functionality exposed to us in the macro.  So we need to focus on just one sheet before we can get more methods to play with our sheet.

In MRI if you double click on the getSheets method name, which will look weird because it's just a text box so its a bit difficult the first time to know if you are doing it right, it'll call that method within the introspection window.  If you now look in the top left window, you'll notice that the current interface that you are inspecting is com.sun.star.sheet.XSpreadsheets.  Notice the getByIndex and getByName methods.  Both take in a parameter and return an any type.  Any type just means that the returning type is depending on how you call it.  Let's double click on the getByIndex, you'll be prompted to provide a value.  Since pretty much everything in UNO is zero based indexes, your first sheet is sheet 0, so push a zero as the int argument for getByIndex.

You will now notice that the interface that you are browsing is com.sun.star.sheet.XSpreadsheet, which is the correct interface for doing whatever it is we want to do with a given spreadsheet.  So when you look at some macros, you'll notice something common, they all pretty much begin with the following.
REM  *****  BASIC  *****

Sub Main

 Dim oSheet
 oSheet = ThisComponent.getSheets().getByIndex(0)

End Sub
That's because the first thing you'll do is get a reference to the spreadsheet that you want to work with.  Once you have that reference you can grab cells, rows, columns, and what not that happen to be on that sheet.  So let's move to our main objective which should now be pretty clear on how to do this.

The macro:

The easiest way of dealing with this is to just grab each cell that we need.  You'll notice a method within .sheet.XSpreadsheet called getCellByPosition(int, int).  We will use this method for the time being to access our cell.  Go ahead and double click on the method, this dialog should appear:

Just enter 0 for both items.  You should now have a .table.XCell interface.  Switch over to the Properties tab (which I know, hasn't had much love so far) and you can see all the fun things that you can mess with for the XCell interface.  You'll notice that in the fifth column you can see if the Property has been marked as ReadOnly, WriteOnly, or blank which usually means Read/Write, but not always.

Now if you are coming from an Excel background, I can already hear you, "Oh!  I know, we pass a string in via the .Value property to set the value of the cell."  Nope, wrong.  UNO makes a distinction between numbers and strings.  The Value property is what you will use if you want to explicitly state that the cell is a numeric value.  The String property is what you will use if you want to explicitly state that the cell is a text value.  This is also a Formula property which does exactly what you think it does.

So with that out of the way now, let's look at our Macro's code:
REM  *****  BASIC  *****

Sub Main

 Dim oSheet
 oSheet = ThisComponent.getSheets().getByIndex(0)

 For cRow = 0 to 10
  oSheet.getCellByPosition(0, cRow).String = "Hello, World!"
  oSheet.getCellByPosition(1, cRow).Value = cRow
 Next cRow

End Sub
As you can see, I used the String property to state that I'm passing a String and Value to state that I'm passing a number. Had I used the String property to pass in a number, it would treat the number as if it were a string, which might come in handy if you want that to happen.  Also notice that I didn't "Dim cRow".  Basic is pretty loose as a language, and while you should always Dim your variables, I've not done it here simply because I want to show that you don't really have to.

Press the F5 key while in the macro editor or click on the run macro button and voila, our desired results are produced.

Conclusion:

I hope this shows you the basics of using MRI and the macro editor together to get the results that you want out of the UNO framework that underpins LO and AOO.  MRI isn't a panacea for all the ills one might have with developing macros within AOO or LO, but it will help you understand the layout of the API if you get lost along the way.

Eventually, you'll want to pull in interfaces and create concrete objects from UNO that aren't directly connected to ThisComponent.  Unless you know the classname of what it is that you want and how to directly build it, MRI won't help you out much.

Any questions, comments, rants, wishes, or hating, feel free to do so in the comments below.  I'll stop by each weekend to check if anything has changed.

Getting started with using Apache OpenOffice/LibreOffice Basic (Installing MRI)

Introduction:

While I think macros with spreadsheets are typically a bad idea, every once and a while you will find yourself writing one.  Either to format a big spreadsheet quickly, change calculations, or add a bit of magic to your spreadsheet.  However, one of the biggest downsides to using LibreOffice (LO) or Apache OpenOffice (AOO) is that the libraries included with these products are insanely more confusing to new users than say Microsoft's offering in their Office suite.  Especially true if you are coming from a hard core background in MS Office, say like a power user of Excel or Access.

There are a ton of projects that are on-going to make LO and AOO, which both use the Universal Network Objects (UNO) framework to provide pretty much all of the functionality within the multitude of components within those suites, slightly easier to deal with.  One of those is MRI which is a plug-in for LO and AOO that allows you to do UNO introspection.  This allows you to browse easily the family of available UNO methods, objects, properties, and so forth.  MRI is an indispensable first tool when doing UNO macro programming.

The download:

So you may ask, where can I get this MRI?!  Well here's where you can get the latest version.  The AOO site has the latest and greatest whereas the LO site only has version 1.1.2 stable and 1.1.4 pre-release, both of which only work with LO 3.x series.


The nice thing about both AOO and LO both using UNO is that a lot of extensions for one will work on the other.  The downside is that because AOO and LO both use different versioning and they are slowly making their versions of UNO incompatible with each other (not out of spite but AOO is okay with Java depends and LO isn't, so LO is ditching a lot of interfaces that deal with that), their isn't a sure fire way to be absolutely sure that what works for AOO will work for LO and vice-versa.

Luckily, MRI works on AOO and LO versions 4.  That includes LO 4.1, but do note that I have not tested MRI 1.2.1 on LO 4.2 which is the next release.  There are quite a few changes in UNO in LO 4.2 so it will be interesting to see how MRI 1.2.1 works on that.

Install:

So once you download MRI, you'll need to add the extension to LO.  To do that, head over to Tools | Extension Manager in the main menu.  A dialog will appear

Extension Manager dialog
In the dialog click the "Add..." button.  This will open up a file browser.  From the file browser, find the MRI extension that you downloaded.  Once the extension is loaded, you'll need to restart LO to see the changes.

Double Check...

To double check that MRI was successful with the install.  Head over to the Tools menu again and you should see an option called "Add-Ons".  You should see in that menu "MRI" and "MRI ← selection".  The difference between the two is that "MRI" executes the extension with the current document as the parent object, the other uses whatever is currently selected as the parent object.

Make sure MRI is installed

Final:

With MRI you will now be able to perform introspection on the UNO tree, which as you will see soon enough, is pretty complex.  MRI allows one of the most important functions that the MS Office suite gets by default in its Basic environment, an object browser.  I will be referencing MRI a lot in the next few posts as I go over a bit of AOO/LO Basic.  So this is a good first step with learning the UNO basic environment.

Sunday, December 08, 2013

The case for copyrighted APIs

So Oracle is trying to sue Google over the idea that application program interfaces (known as APIs) are protected by copyright.  Now I won't go into a ton of detail but APIs expose to a programmer the pieces of software that can and cannot be used.  So if I needed to round a number, I might call a piece of code called, Math.round(56.73)

Now how exactly that piece of code actually rounds up, there is no doubt, the implementation is copyrighted.  But Oracle's argument is that the whole term, Math.round() is copyrighted, no matter how one implements it.

This would be akin to someone copyrighting the steering wheel.  Now a particular design of steering wheel understood, but the whole notion of a wheel that is used to control a car is just crazy.  The wheel is the expression (the API) of how the driver (programmer) interacts with whatever the steering mechanism is (the implementation).

I'm of the opinion that APIs fall outside copyright.  The reason being I cite Lotus Dev. Corp. v. Borland Int'l, Inc. 516 U.S. 233 (1996).  Here the Supreme Court ruled in favor of Borland that, "the set of available operations and the mechanics of how they are activated are not copyrightable."  This allowed Borland to use menus in their product called Quattro Pro that looked exactly like the menus in Lotus 1-2-3.  Just because the menus looked the same (there was a file, new worksheet, new formula, etc... menu) the underlying code behind those menu items were different enough to not constitute infringement of copyright.  How one goes about activating an operation is not the same as how that operation actually works.

Thus, the way I activate rounding, via the Math.round() is not the same as how that rounding occurs.  Thus, since Math.round() is the manner in which I actually activate that rounding, it should logically fall outside of copyright.

In an appeal to the DC circuit court Oracle is set to have a retrial on this very notion, is an API copyrightable?  "It seems to me that almost all computer code has to have a functional purpose, otherwise what's the purpose," --Judge Plager

While what Judge Plager says is true, all code at some point has a function, if the function is to express an underlying intent or implementation.  I believe that 17 USC 102(b) implies that if the function is simply expression of an idea, which an API would most certainly be that, it falls outside of the protection offered in 102(a).  Even if § 101 states clearly that API's fall into the definition of "computer program", 102(b) clarifies that definition to restrain application of copyright to broad ideas like, how do I call a number rounding piece of code?  If copyright existed on the notion of round(), then how would other's code their own implementation without eventually stepping on such broad claims?

There is no doubt, this case is bound for the Supreme Court, and the ramifications of copyrighted APIs would have broad implications on developers.  It would bring about a downward trend in interoperability.  Network protocols, web services, and more which rely on open APIs would suddenly become licensable technology.  Even worst, this could spill over into widely used standards for communication, imagine if the ability for one hospital to talk to another hospital was a commercial protocol via a copyrighted API.  Only if every hospital choose a single vendor would there be the ability to for hospitals to talk to each other.  Those who choose a different product would be in a different closed box from the others.  And trying to have proxy services that translate between the two of them would require a vendor to license from both vendors in question to make such a proxy, that would make such proxies insanely costly.

Open APIs are incredibly vital to developers, already developers face too many difficulties with "patented" software processes.  If APIs are ruled into the domain of copyright, developers will have increased pressure on design and ultimately will mean that some developers may never get out the door with the years it may take to do due-diligence to ensure copyright and patents aren't being broken.  API libraries may cease being freely usable, useful API libraries, it could take years before open APIs are completely untangled and ensured are infringement free, meaning that small software shops will suddenly have to invest thousands of dollars in commercial libraries or wait until whatever they were using gets untangled.  Either option could cost them more in the long run than they originally had to begin with.

It is clear that Oracle is doing this to take what they deem their piece of a multi-billion dollar industry within Android.  I can get they feel a bit jaded about the whole thing.  However, their argument would have much wider repercussions than on Android.  This would bring to an end anybody who mimics Amazon Web Services APIs for interoperability.  There is a lot of vendors that stand to lose out big time on this.  Additionally, current cloud services, like Azure, Amazon, Oracle, and yes even Google's could copyright their APIs and lock their customers programs forever, or until overturned, onto their platform.  Either a customer rewrites their entire application or pays out the ying-yang to build a proxy while they move from one to another platform.  Writing a program that can translate one API to another would be copyright infringement.

What can be done about it?  Not much at the current point in time, but it does highlight a warning sign that commercial vendors of software are ever looking for new ways to take traditional developer values and twist them into meanings that make them top dollar.  It is becoming clearing with each passing year that truly from the start open APIs will be the only sure fire way of avoiding having the rug pulled out from underneath you.

Ultimately HTML5 and the open web/format will be the only "safe" bet in town.  That is why organizations like Mozilla, Apache, The Document Foundation, the Qt Project, the Fedora Project and others are so vital to developers.  They stand for platforms, libraries, protocols, and formats that are free from surprises, free for implementation from the start, free to be used for the masses to communicate freely with the world.  Because they believe that developers and users have a right to exchange ideas with one another without fear that one day, they might get a knock at the door asking for money.

Copyrighted APIs will have yet another chilling effect, but only because we have thus far had good faith in those who created these APIs, that they wouldn't do something as stupid as Oracle has suddenly decided to do.  Maybe developers were naive, but it takes someone with a really cold heart to actually act on that.   I do hope that Oracle finds whatever their reward to be, should this all end in their favor, worth the irreparable damage that this has on the faith of developers.  As future developers will be extra cautious to not fall into some inescapable pit and freely distributed SDKs will be met with ever increased skepticism of how "free" that platform truly is.

Monday, November 18, 2013

Inform 7 First going.

So I've started using Inform 7 for writing IF (interactive fiction). I've used Inform 6 before and TADS, which I'm pretty partial towards TADS.

However, I've decided to give Inform 7 a go.  It's programming syntax is described as natural language.  Here is an example of me creating a room object, creating an enumerated property, creating a generic object, giving the generic object the enumerated property, and creating a few instances of the new object type.

Your Apartment is a room. 

Color is a kind of value. The colors are red, blue, and green.
A car is a kind of thing. A car has a color. The color of the car is blue.
Before printing the name of a car: say "[color] ".

The North Car is a car.
The South Car is a car.
The color of the North car is red.
The North Car is in your apartment.
The South Car is in your apartment.

Now obviously, I hope you don't really find cars in your apartment.  However this illustrates pretty well the construct of Inform 7's language.  I've created a room call "your apartment"  Created the enum color and given it {red, blue, green}.  Created a car type which has a enum value and set a default value of blue.  I've overridden the print name method of a car type to print the color, and I created two cars [North Car, South Car] and given North Car the color red.
So it's a little weird to work with at first and I'm still struggling a bit with the syntax but hopefully, I'll be able to do my first five room adventure with Inform soon enough.

Wish me luck!

Monday, July 15, 2013

The Qt dictate

So it is pretty apparent that I haven't been updating this blog in a while.  The reason for this is that we are going through a period where we are converting MS Access files into full fledged applications.

Now MS Access is fine and what not, but after a certain point, it can get a bit abused.  That point was crossed some time ago in my company that I work for.  So what are we switching to?  Not Java, no that would have been too awesome.  However, I can't say that I am really down about what platform we are going with.  We are going to be using Qt!  Qt 5 to be exact.

I'm a bit thrilled to be tasked to start working back in my favorite language, C++.  Not only that, Qt 5 supports many of the most recent additions to the C++ language.  I can hardly wait to start digging in.

I'm going to pick back up on the JSF tutorial here in a bit.  The next step it looks like was a read/write JSF managed bean.  So I'll do a quick run through of that, but I doubt that I'll have the namesapces match up with what they were in the previous post.

I don't fully remember where I was going with all of the JSF stuff, but I guess after the Read/Write thing, moving into AJAX in JSF.

Cheerio!

Friday, April 19, 2013

Moving on, using a managed bean

So let's try using what is known as JSF managed beans.  Managed beans are plain old Java objects (POJO) that get managed by the JSF controller.

How it technically works is that the JSF library will scan the classes in your project for the @ManagedBean annotation.  When it finds a class, it registers it as a managed type.

Once registered, you can create beans all over the place in your JSF pages.  Beans can have one of six scopes:

  • @RequestScope - This means the bean is created for the life of the HTTP request.  Once the HTTP request has been fully processed the bean is destroyed.  Basically, these beans exist so long as the request for a web page lasts.  Once the page has been serviced, the bean is no longer available.  This also applies to AJAX requests.
  • @SessionScope - This bean is created for the life of the HTTP session.  Once a HTTP session is started, the JSF library will create this bean and allow it to last so long as the HTTP session is still open.  Once the HTTP session ends, due to inactivity or closing the web page, the bean is destroyed.
  • @ViewScope - This is an interesting bean that will last through requests, so long as the current view has not changed.  This is useful is you present a single view to the user and then do a lot of AJAX in the background to modify that view.
  • @ApplicationScope - This is a bean that is created as soon as the application is started.  That means as soon as you publish it to the server or upon the first HTTP packet to the application (this is dictated by the eager=true flag, setting to true is as soon as you publish it.)  Only use this kind of bean for things that can safely be shared between instances of sessions.  Just FYI, don't assume that this automatically means thread safety.
  • @NoneScope - This is a bean that is created as soon as it is requested in a JSF page and destroyed as soon as it was created.  If you use the bean three times in your JSF page, then the bean is created and destroyed three times.  In my example to follow, the none scope would have sufficed.  Use this kind of bean for one shot stuff that doesn't need to be remembered, or if you intend on using this bean within another bean.
  • @CustomScope - This is exactly what it says.  You define when and where the bean exists and get destroyed by modifying a Map that is created for managing this bean.  When you add an entry to the Map, the bean is created, when you remove the entry the bean is destroyed.  Use this when nothing above seems to fit your use-case.
So let's create a bean!

Right mouse click on your project and select New » Other…

This screen appears
 Choose the JSF Managed Bean and click Next >

We're just going to go with the defaults here with a little bit of extra like package name, generally you are going to name this something actually useful.
Fill in the information about your bean and I'm going to set it to request scope.  The package will be lan.testing.  You can also add a little description to the bean.  No idea where this description gets saved at the moment.  Go ahead and click finish.

Now you will have a newly minted request bean.

New JSF Managed Bean
Now at the moment this bean does absolutely nothing other than suck memory.  So let's make it do something more interesting.  Let's add a field in the Java class called message.  We will make this field private.  So let's add that now.  While we are at it, let's set the fields default value by placing that in the constructor.

Adding a field to the bean

Now let's expose that bean so that it can be used on our pages.  We do that by creating standard getters and setters.  Just press Alt+Insert in the IDE to get a popup.

Select the Getter and Setter… option
Check the boxes of the fields you want to expose, since we have one, we are exposing them all.
Your Java class should look like the following:

Your field is now exposed by the bean.
Now that we have exposed the field, let's go ahead and add that to our JSF page.  To access JSF managed beans we need to replace the static text in our tag with #{}.  The pound sign and curly brackets indicate to the JSF libraries that it needs to look at all of the registered classes.

Once we type that into the value you'll notice a code completion pop-up appear.

Code completions is happening.
In the completion box you should see the name of your managed bean.  Go ahead and select it.  It will now appear as #{whateverYouNamedYourBean}.

Go ahead and type period to get the next bit, this will show you what has been exposed by this bean.

Our field exposed by the bean
Go ahead and select the exposed message field.

Our completed code
Once you have done that, go ahead and press the giant play button to see the results.

Ta-da!  Your field in the Java class is now exposed and being used by the JSF libraries.  Right now, not very useful, but good to know that it is working.  All of this on Tomcat!

Quick point:
Beans are meant to allow you to create useful components to be used in your JSF application.  Right now it might be a bit hard to see that, but eventually you'll start building beans that are for all kinds of purposes, with all kinds of different scopes.

The thing to remember about beans is that you should take the million little cogs approach with them.  As opposed to building one giant bean or one huge session bean and one huge request bean, beans should be for a specific purpose in your web application.  You may have one that hold the current user's profile information, another to hold the current conversation that they are in, and so on.

Right now we are only using the read function (get) of the bean.  I'll show you next how to write (set) to the bean and explain a bit about why it works.

First JSF web application on Tomcat 7

Okay as promised, here is the first Netbeans 7.3 + JSF 2.1 + Tomcat 7 web application.

First download Netbeans, if you haven't already.  Go ahead and select the full all out, no hold bars download.  Next install the software and make sure you install the Tomcat that is included with Netbeans installer.

Okay now that you have all of that out of the way, go ahead and start up Netbeans and head over to the services tab and start up the Tomcat Server installed on your system.

Starting up the Tomcat server.  Netbeans 7.3 automatically detects this installed if you did it with the installer from the web.

Now go ahead and start a new project.  Choose Java Web | Web Application.  See the following images for the wizard screenshots.

Step 1 - Title your new web application.

Step 2 - Choose the server to deploy to and the context to use.  MAKE SURE YOU SELECT THE TOMCAT INSTALL!

Step 3 - Include what libraries you might need.  Make sure you click the JavaServer Faces library.  Tomcat doesn't come with JSF built in, you must manually add it!



Okay you should now have a shell project with the default index file.

Behold!  The default index file!








So to ensure that we are running JSF and not that the server is doing some sort of pseudo translation here, let's use an actual JSF tag.

I'll use the tag which does exactly what it says, it outputs text.  Here I'll just use some static value for the value attribute.

Adding in a JSF tag, don't forget the
tag.

Now go ahead and click on the run project icon, it's that giant play button up there.  If your Tomcat server is running (you better go catch it, ha ha) then it will deploy the project to the server and open up your browser to the context that you provided.

Pushing the Play button.

Ta-da!  Our project runs!
 So there you go, your very first JSF 2.1 application on a Tomcat server.

Here's some highlights.  Tomcat 7 does not come with JSF baked in.  It is a simple servlet server.  Ergo, you must include the JSF library with your project.  The nice thing is that Netbeans will go ahead and do that for you, because it knows that Tomcat doesn't have these libraries by default.

Draw your attention to the highlighted area.
Now here's the deal.  If at some point down the road, you add these libraries to the Tomcat server itself, then you need to make sure that Netbeans doesn't try to "help" you out here.  To do that, you need to indicate that the libraries do not need to be pushed to the server with the application.  Right mouse click on the libraries icon and choose properties.

If you do not see Properties, then it's because you aren't right clicking in the correct 16x16 space.
Once you do that this window appears:

Notice the check boxes highlighted.  When they are checked, that means the library will be "packaged" with the application.  If the libraries are already on the server, you don't need to package them.

Disclaimer:
Don't include the JSF libraries inside your server, just package them with the application.  Once you toss the libraries into the server, that pretty much makes that server a JSF Tomcat server.

The downside of this is, this could potentially ruin any old JSP applications that you have on the server.  Now it shouldn't but I would count on something jacked up happening the second you toss JSF libraries on a Tomcat running JSP applications.

I'll start covering some more fun stuff with JSF next post!  Have fun!

Loss of data and moving on.

Of course,

I've lost the whole project that I was doing in JSP and Tomcat.  I really don't feel like going back and going over the whole things…again.

So I'm going to need a new project now.  Hmmm…

Okay, let's do the good old fashion Tomcat 7 + JSF 2.0 + NetBeans IDE.

Not to say that I don't like Eclipse, but I'm a bigger fan of NetBeans.  Sorry for all of the Eclipse fan boys out there.  If it helps, I use Eclipse everyday with Android stuff.

In fact!  How about something Android?  That sounds like fun too!  So here's what I'm going to do going forward.

Monday and Friday I'll do a post about JSF and pretty much J2EE stuff.

Wednesday I'll do something about Android.  Why the hate for Android?  Because I spend so much time developing Android stuff for work, I get tired of even looking at the IDE.  I guess that's why my interest in the JSP thing waned so much.

I'm so capricious it's not even funny.  I'll setup some labels.  We will name the J2EE stuff with the J2EE label and when it includes TomCat, I'll add in TomCat.  When it deals with Glassfish I'll add Glassfish.  For the Android stuff, I'll just add the label Android.

Okay, so there we go.  Something to do.  Oh look it's Friday!  Better start working on my first J2EE post.

Cheers!

Wednesday, February 27, 2013

Where have I been?

You'll have to excuse me, I haven't updated the blog in some time.  I've been doing the road warrior thing for a couple of weeks now, which keeps me from my standard machine that I use and have all my code on at home.

I'll jump back to the JSP demonstration here in a bit.  I know you've all heard that before.

Thursday, January 03, 2013

Doing this MVC thing! Part 1

Let's get back to our web application shall we?

First let's remove everything in our project and start fresh. Here is what I have for the Contact Keeper project.

My current layout for the project.

So basically all that we are keeping is the "com.blogger.contacts.beans" package and the JSTL libraries.  Now let's begin where any sensible project would begin.  On the information that we are trying to store.  In other words, I like to look at the problem as "what to store, before presentation."  Some developers like to work on presentation first and then data.  I always get confused when I work this way, hence the reason I like to focus on data first.  However, to each their own.

Now our "database" isn't going to be a real database, we are just going to use a memory structure to store the information.  If our server gets turned off, then we loose all of our information.  That's okay, because we are going to make the interface to our database generic so that if we decide to ditch the memory storage and replace it with a real DB like PostgreSQL later on, then it will require very little code change.

So the first thing we need to do is create the actual object that we plan to store.  That means we need to model our contact in Java code.  If we were using a real database then we'd add another layer on top of our contact model to implement JPA.  JPA is just a fancy system that you use to translate Java objects into SQL code automatically (I am really simplifying the heck out of JPA here, but the premise holds.)

So we are just going to have a basic naked model here.  Our contacts should have the following:
  • First name - string
  • Last name - string
  • Phone number - string (we are not going to deal with validation here, at least not now)
  • Age - integer (real contact keepers would ask for Birthdate and calculate age from that, be we aren't doing that here, at least not now)
That's it.  Pretty simple.  I want to keep it pretty simple for the time being.

So let's create your Java code for this model.  We are going to store this Java class in a new package called, "com.blogger.contacts.entity"  Entity is the technical term for an object that models to something one would store in a database (or relates to something in the real world if you want a much fuller idea of the term), honestly if you really want a better technical definition, feel free to hit up Wikipedia.  At any rate, we are going to create anything that maps to the real problem in the entity package.

So here is the code:


package com.blogger.contacts.entity;

import java.io.Serializable;

public class Contact implements Serializable {

 /**
  * Serial version of our contact class, so that version stay compatible. 
  */
 private static final long serialVersionUID = 1L;
 
 private String firstName;
 private String lastName;
 private String phoneNumber;
 private Integer age;
 
 public Contact() {
  this.firstName = null;
  this.lastName = null;
  this.phoneNumber = null;
  this.age = null;
 }
 
 public Contact(String firstName, String lastName, String phoneNumber,
   Integer age) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
  this.phoneNumber = phoneNumber;
  this.age = age;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getPhoneNumber() {
  return phoneNumber;
 }

 public void setPhoneNumber(String phoneNumber) {
  this.phoneNumber = phoneNumber;
 }

 public Integer getAge() {
  return age;
 }

 public void setAge(Integer age) {
  this.age = age;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((age == null) ? 0 : age.hashCode());
  result = prime * result
    + ((firstName == null) ? 0 : firstName.hashCode());
  result = prime * result
    + ((lastName == null) ? 0 : lastName.hashCode());
  result = prime * result
    + ((phoneNumber == null) ? 0 : phoneNumber.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Contact other = (Contact) obj;
  if (age == null) {
   if (other.age != null)
    return false;
  } else if (!age.equals(other.age))
   return false;
  if (firstName == null) {
   if (other.firstName != null)
    return false;
  } else if (!firstName.equals(other.firstName))
   return false;
  if (lastName == null) {
   if (other.lastName != null)
    return false;
  } else if (!lastName.equals(other.lastName))
   return false;
  if (phoneNumber == null) {
   if (other.phoneNumber != null)
    return false;
  } else if (!phoneNumber.equals(other.phoneNumber))
   return false;
  return true;
 }

 @Override
 public String toString() {
  return "Contact [firstName=" + firstName + ", lastName=" + lastName
    + ", phoneNumber=" + phoneNumber + ", age=" + age + "]";
 }

}


So you may be asking yourself, why isn't this a bean?  Well it is, to an extent, back in the day you'd be absolutely correct about this being a bean, as this used to be called an Entity Bean.  However, as Java EE matured it became clear that Entities were stuff that mapped to real world things, and Beans were used to access stuff.  So in a basic case like ours here, our Entity could very well function as the bean as well, since the logic needed to access our entity is pretty simple stuff.  However, in more complex cases we might want Access beans that handle the needed logic to access our entities.

For now what we are going to do is let our entity stand by itself and we will create a DAO (Data Access Object) bean that will provide the basic CRUD (Create, Read, Update, and Delete) that we need to have a functioning application.

So there is our entity.  I've provided a hash code function, an equals function, and a to string function.  I usually do this for my benefit rather than any application need.  Your taste to do so may vary.

There you go, we've created the entity.  Now we need to create somewhere to actually store these things!  This needs to be a memory based storage, remember what I said earlier, and it needs to be simple and not overly complex.  What I am going to do, and this isn't something you'd normally do on production code, is just create a regular old collection and set it to the application scope, so that any sessions can access it.  Now you don't do this in normal production code because it is not thread safe at all.  People could come in and create the same contact at the same time and there would be nothing to stop them, or they could delete a contact that was deleted by someone else while the first person was deleting it.  In other words, it could lead to all kinds of badness.

We are going to use a basic Array List collection because it is fast on insert (adding contacts), fast on update (changing information or updating a contact), normal speed on listing (viewing all contacts), and slow on delete and random access (getting rid of contacts and finding a contact).  The only down side is the last part, random access, a contact list's number one feature is "finding" contacts.  We could use a hash map, but then our program would a bit more memory hungry but finding contacts would be very fast, and since we are not actually going to be using this code in any production system, I doubt that our contact list will ever grow to the size where a hash map makes more sense than an array list.  (I would need at least the assumption that the contact list would be at least 100 contacts or more before I would consider the hash map a good fit.)

break time...

Just noticed it is getting late, better call it a night for the time being.  We will implement our Array List next and we are going to create an interface DAO and DAO for that implementation that implements our interface.  So in case you missed that, part two will do the following.


  • Implement our Array List to store our Contact entities.
  • Create an interface for our DAO so that we keep a standard interface regardless of if we are using memory or actually DB back ends.
  • Create a concrete object for our DAO interface that has all the logic to connect our interface and Array List implementation.

Sunday, December 30, 2012

Rough Holidays

So where have I been?

Doing some serious down time.  I've been forcing myself to really take it easy the last few weeks.  I was sick, got better, and then suddenly really got sick.

I didn't really want to come back to the computer until I had a few days of what might be called good health.  I'm still sick, don't get me wrong, but I'm at least well enough to post that I'm still on some downtime.

However, just to be me...

How to write a simple HTML5 Canvas web page.

HTML5 is pretty slick!  The neatest thing that I can show and not take five years trying to explain it is how to use the HTML5 canvas.

First you need a basic HTML file with the magical canvas tag included.  Here is an example of such an HTML file.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

   <head>
      <title>Canvas Example</title>
      <script src="canvas.js" type="text/javascript"></script>
   </head>
   
   <body style="background: #fefeef">
      <h3>Hi there!</h3>
   
   
      <canvas width="400px" height="400px" id="paintingCanvas" style="border: thick solid teal">

         Canvas not supported. 
         
      </canvas>     
   </h:body>  
   
</html> 

So as you can a pretty easy to understand HTML file. As you can see, this file alone does absolutely nothing. All the magic is in the canvas.js file.  However, do note the DOCTYPE html tag, that is needed for most browsers to understand that the file is an HTML5 file.

So let's take a look at that instead.

window.addEventListener("load", function() {
   var canvas, context, painting;
   
   function init() {
      canvas = document.getElementById("paintingCanvas");
      if (canvas == null) return;
      
      context = canvas.getContext("2d");
      if (context == null) return;
   
      painting = false;
      
      context.strokeStyle = "#00f";
      context.lineWidth = 3;
      context.font = "15px Helvetica";
   }

   init();
   
   canvas.addEventListener("mousedown", function(ev) {
      painting = true;
      context.beginPath();
      context.moveTo(ev.offsetX, ev.offsetY);
   }, false);
   
   canvas.addEventListener("mousemove", function(ev) {
      updateReadout(ev.offsetX, ev.offsetY);

      if (painting) {
        paint(ev.offsetX, ev.offsetY);
      }
      function updateReadout(x, y) {
         context.clearRect(0, 0, 100, 20);
         context.fillText("x: " + x + ",  y: " + y, 5, 15);
      }
      function paint(x, y) {
         context.lineTo(ev.offsetX, ev.offsetY);
         context.stroke();
      }
         
   }, false);
   
   canvas.addEventListener("mouseup", function() {
      painting = false;
      context.closePath();
   }, false);
   
   
 }, false);

So that should be obvious to anyone who's ever worked in javascript, but just in case, here's the breakdown.

The first part adds a function that contains all our logic to the webpage's "load" trigger.  In other words, the code within will fire as soon as the page is loaded.  The first things we do is create a canvas, context, and painting variable.  The canvas var will hold the location of the canvas tag which we will be using to grab a context from.  The context var is the handle to the browser system resource for the 2d context, aka, that's what we are really going to be drawing to.  The painting var will act as a Boolean var telling us if we should be painting or not when we move the mouse.

Pretty simple stuff and if you've ever used Java's AWT then you might have noticed how similar this all looks to AWT.

We create a function within called init.  It gets the canvas tag, pulls the context from the tag (we use a simple test to make sure that this did happen for each step), set the painting flag to false, and store some states to the context.  (Basically, a state is something you set and it stays that way until you change it again.)

After creating that function, we call it.

Finally, we add some event listeners to the canvas tag, because you cannot add listeners to a context.  On the mouse down event, we set the painting flag to true, we tell the context "to put the pen down on the paper" at the current mouse position.

On the mouse move event we update the readout (which prints out the current mouse coordinates) and if the painting flag is on, we tell the pen to move to the current mouse coordinates.

On the mouse up event we turn off the painting flag and tell the pen to be "picked up."

That's it!  Pretty simple stuff.  Save the two files, open the HTML file in a nice browser (aka, not Internet Explorer) and poof!

Master Artist, I am not.

Pretty simple and fast HTML5 canvas demo!  Ta-da!

Sunday, December 16, 2012

Wow! Also, MVC theory

I just have to applaud the flu virus that I got, because it was kicking my butt and putting my name to shame...

Well, I'm on the mend now, not entirely mind you, so I figure I would get back to JSPs.


You might remember waaaaayyyyy back when I talked about servlets?  Well today, what I'm going to cover real quick is creating a servlet that will forward us to another JSP.

Basically, what the servlet will do when you try to access it is "forward" the request.  That's pretty much it.

So the overview is this, index.jsp will have a link that will send us to to ContactKeeper/App servlet.  The servlet will then send us to the welcome.jsp page.

The servlet will become the main hub for our application.  Basically, anytime we click on a link within the ContactKeeper application, it will just basically send us back to the ContactKeeper/App servlet.

In fact, let's skip the coding for now, I will get to that tomorrow.  For now let's learn a little theory.

The reason for this, primarily, is so that our application logic can be stored in the Servlet code.  Our display logic will be stored in the JSPs that we create.  This separation is the starting point for something known as Model-View-Controller or (MVC) for short.

Like I said we created beans so that we store data logic in Java code outside of the JSP.  Thus our JSPs focus more on just display and page control and the beans deal with storing the information.

At the moment our beans don't do much, they just store the information in memory.  However, we could easily change that so that we store the data in something like a database.

Our JSPs handle page control at the moment which is basically done via tags which is standard HTML stuff.  However, this pretty much leaves us in linear mode for page logic, which granted for an address book, you don't need a whole lot of logic.

However, what if we needed more powerful logic?  Javascript?  No way!  Putting Java code in the JSP?  No way!  We're trying to get away from that.  The goal would be to allow some piece of Java code decide where the application should go next based on the current session's values.  Enter the Servlet as the central hub.

To get an overview of what this looks like, here is a rough draft of what we will be doing.  (Shout out to http://www.draw.io, you all rock!)

Quick overview what exactly we will be doing.
Our client, aka the web browser, will keep sending HTTP GET requests to the servlet.  The Servlet then reads in all of the parameters on the URL and the current session's values to decide what to do next.  It can interpret values into request for either create, view, update, or remove data.

The servlet can send these request for data to the Data Access Object (DAO).  The DAO will handle all the little details about the actual data, so the servlet may ask to add a contact.  The DAO will actually know how to do this.  The DAO sends back to the servlet a pass or fail result, and then the servlet will forward the request to the proper JSP.

The servlet will pass to the JSP an entry point in the DAO to see the detail results of what was requested.  (Why a name couldn't be added, the name has been successfully added, the listing of all contacts, etc...)  The JSP will use that entry point to display the results from the DAO.


As you can see each section is concerned with one part of logic.  The Model deals with handling all of the data ins and outs.  It creates data, removes data, and so on.  It is the data handler.

The Controller makes sure that everything happens in a controlled manner.  If the model says that a name cannot be added, the controller forwards the client to the error page.  However, do note, that the Controller doesn't actually check to see if the incoming data is valid or not, that is the job of the Model.  The controller simply passes the data to the correct department to be handled and if the data is invalid, let's the user know that.

The view is what our users see.  It is primarily concerned with displaying what is going on and what has been requested.  The view presents all the forms our users will be entering and formats all of the data for the user that is sent to us from our Model.  Forms that get filled out and submitted are sent to the controller for processing, from there the controller may delegate the processing of a form to some other subsystem and so on...

So while the MVC architecture looks a bit confusing at first, it provides a method for separating the major functions of a web application into manageable bits.  Each bit is pretty independent of the other.

For example, we can change our JSPs to have a new style without messing up any of the navigation code or how we access a database.  We can change our system from a in-memory style system to an actual database so long as the DAO keeps the same interface for the controller to call.  We can implement a new navigation scheme by changing the controller, without messing up our JSPs or our data access.

The ability to break into independent pieces is a requirement for service flexibility.

You might notice that in my model I have the DAO using data beans and direct access.  Using direct access is sometimes a necessary evil in models.  Especially if your data requires a lot of calling stored procedures to get the data.  However, I recommend that you try to limit as much as possible "direct access".  Use data beans as much as possible, eventually I will get to entity frameworks and what ORM means, and this is like data beans on database steroids.

Okay I know I talked a whole lot and didn't give much code.  I'll do that next visit.  I'm just not strong enough yet to really do one of my go for the gusto posts where I talk forever and then code forever.  Maybe when I get over the flu completely I will come back to the twenty page posts.

cheers!

Wednesday, December 12, 2012

Sick

Sorry came down with the flu. Be back soon.

Sunday, December 09, 2012

Little break.

As you all may have guessed, I'm taking a bit of a break for the moment.

I'll pick back up Monday.

However, if you are new to Java you may want to read up on what exactly clone()does by checking out the Wikipedia page for it.

The reason for this is in our contact keeper web application that we will build, we are going to implement the ability to copy a contact.

Also, you may want to get familiar with what CRUD means.  Because other than the copy a contact function, we are going to stick pretty close to having a fully CRUD web application.

Cheers!

Monday, December 03, 2012

Read-Write Bean and JSP

Okay this will have to be a quickie because I have to be on site in six hours.

Okay we are going to create a simple test of creating a read-write bean.  Let's go ahead and in our ContactKeeper project create a new bean called com.blogger.contacts.beans.SimpleNameBean

Now your SimpleNameBean should have two fields, a firstName and a lastName field.  Generate your getters and setters this time in the wizard as opposed to just getters.  In the default constructor set the firstName and lastName fields to some value.  You should end up with this as your Java code:

package com.blogger.contacts.beans;

public class SimpleNameBean {

 private String firstName;
 private String lastName;
 
 public SimpleNameBean() {
  this.firstName = "First Name";
  this.lastName = "Last Name";
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

}

Pretty cut and dry code here, however, by having setter methods you make your bean opened up to being written to.

Now let's go ahead and create a new JSP called testname.jsp.  Here's the code for the JSP page and I'll explain each part:

<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:c="http://java.sun.com/jsp/jstl/core" version="2.0">
 <jsp:directive.page contentType="text/html; charset=UTF-8" 
  pageEncoding="UTF-8" session="true"/>
 <jsp:output doctype-root-element="html"
  doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
  doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
  omit-xml-declaration="true" />
<jsp:useBean id="namebean" class="com.blogger.contacts.beans.SimpleNameBean" type="com.blogger.contacts.beans.SimpleNameBean" scope="session"></jsp:useBean>
<jsp:setProperty property="*" name="namebean"/>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Insert title here</title>
</head>
<body>
 <p>
  Welcome ${namebean.firstName} - ${namebean.lastName}
 </p>
 <form method="post" action="testname.jsp">
 Enter new first name: <input type="text" name="firstName" />
 < br />
 Enter new last name: <input type="text" name="lastName" />
 < br />
 <input type="submit" name="action" value="Submit"/>
 </form>
</body>
</html>
</jsp:root>

Okay so this again is our JSP 2.0 page using the full out XML syntax (Also, let me know [if anyone is reading this] if you prefer the full XML syntax or the old JSP tag syntax. I know the XML syntax can be a bit verbose and I'm considering dropping it because it takes up a ton of space and is really hard to type and hit all the finer points.)

Which I bring up those finer points because one of the things you will need to do with all that XML is change one of the attribute in the jsp:directive.page tag near the top.  You will need to change the "session" attribute from false to true.  What this tells the JSP compiler is that the JSP plans to use sessions and that all the needed stuff to make that happen needs to be created.  To save on overhead, some JSPs can be written so that they don't take part of sessions, however, we are going to need to use sessions in order to remember values every time we click the "Submit" button.

Okay so you see the jsp:useBean tag, which shouldn't be new here, but notice that the scope is now set to session as oppose to page.  The reason being is that the bean will need to exist in the session as oppose to a new bean being created for every time you view the page.  This is also why the JSP needs to take part in sessions.  By putting the bean in the session scope, it will remember the values in the bean between page views.

The next tag is a new one.  jsp:setProperty.  This is much like the jsp:getProperty, but instead uses the setters.  Notice that I've set the "property" attribute to "*".  This is a special token for this attribute.  The "*" means that it will do it's best to try to match names to fields.  This can save you a lot of time and can also cause you a lot of headache.  It's one of those double edge sword things.

Moving on down, you see the EL for outputting the name in the paragraph tag.  Nothing new here.  The next part is pretty much your standard HTML input form.  You'll notice that the name attributes for the text inputs has been set to my field names.  The jsp:setProperty tag should take care of the matching up here.  The submit button is your run of the mill HTML submit button that will redirect you to the page that you're currently on, so you really don't go anywhere when you click the "Submit" button.

When you do click the "Submit" button, the jsp:setProperty tag goes to work.  It finds the HTML form and searches inside of it for field name match ups, if it finds a match, it calls the matching setter method.  Once the jsp:setProperty tag is all done with it's work, the web container moves to the page given in the action attribute.  Because the bean is session scope, the values that were pushed to the bean by the jsp:setProperty remain.  The page comes back with the new first and last names now!

Ta-Da!

Like I said this was going to be a real quickie.  I hope this has shown you a bit about read-write beans.  We'll get a little more advance on the next round.

Cheers!