Wednesday November 30, 2005
Paradise for Web Framework Developers...
While preparing the abstract of a session for JavaOne 2006, Petr Pisl—senior developer in the NetBeans J2EE team—introduced me to the WebFrameworkProvider class of the NetBeans APIs. (The NetBeans APIs enable you to extend the IDE. Plus, they enable you to build completely non-IDE related applications on top of the NetBeans core.) This class is really cool—it's really all you need for implementing the basics of a web framework in NetBeans IDE. My implementation doesn't do anything yet—but it already looks impressive. Here you can see that, in addition to the standard IDE 5.0 support for JSF and Struts, I've begun building support for Wicket and Tapestry (the dialog box below is what the user of NetBeans IDE sees when creating a web application, enabling him/her to add support for one or more web frameworks):
It's not much yet, but you can see that if I continue this way (by enabling the addition of framework libraries, configuration files, deployment descriptor information, code completion, hyperlinking, samples, and so on), any web framework can be supported without very much sweat.
Currently, in addition to learning about adding libraries and files for frameworks, I'm trying to get my head around code folding (and after that hyperlinking). The NetBeans APIs, once you have entry points to them (partly via the tutorials that are being put together), are really interesting and robust—you can very quickly throw far more together than you ever thought possible.
Nov 30 2005, 12:14:08 PM PST Permalink
Shadowing and Hiding in Layer XML Files in NetBeans IDE
In the IDE, when you go to Tools > Palette Manager, you get two menu items—Swing/AWT Components and HTML/JSP Code Clips. Here's what the HTML/JSP Code Clips Palette Manager looks like:
Now, let's say you've created your own palette (as I've done for the jboss-web.xml file and the Manifest.mf file, as shown in the previous few blog entries). How would you add the code snippets in your palette to the Palette Manager? At first I didn't understand it, then I looked in the layer.xml files (plural)—because two layer.xml files are involved here. The first is the layer.xml file provided by the HTML module; the second is the layer.xml file provided by the JSP module. Together, the two layer.xml files specify that the code snippets defined by their modules belong to the same Palette Manager. How is this done? It's quite funny, if you like this kind of humour... The place to start is to realize that the IDE makes use of something called shadow files. (Read here for details.) A shadow file is a link that points to an original file. It is useful in the layer.xml file, because often you need multiple instances of the same file. Instead of forcing the IDE to instantiate the same file multiple times, you create a shadow file that links to the original. As a result, the IDE creates the instance once only—and the related shadow files all say: "Hey, we'd like to use that instance too!" The HTML/JSP Code Clips Palette Manager is a case in point. Here's how its content is represented in the layer.xml file's logical view:
Notice how two of the folders have little squares in brackets? That means that they're shadow files. This means that the instances within the HTML and HTML_Forms folders are declared elsewhere—in fact, they're declared in the HTMLPalette folder (notice that here there are no little squares between brackets):
Now, back in the XML code, this is how the first part of the JSPPalette is declared:
<folder name="JSPPalette">
<folder name="HTML.shadow">
<attr name="SystemFileSystem.localizingBundle"
stringvalue="org.netbeans.modules.web.core.palette.Bundle"/>
<attr name="originalFile" stringvalue="HTMLPalette/HTML"/>
</folder>
<folder name="HTML_Forms.shadow">
<attr name="SystemFileSystem.localizingBundle"
stringvalue="org.netbeans.modules.web.core.palette.Bundle"/>
<attr name="originalFile" stringvalue="HTMLPalette/HTML_Forms"/>
</folder>
<folder name="JSP">
<attr name="SystemFileSystem.localizingBundle"
stringvalue="org.netbeans.modules.web.core.palette.Bundle"/>
<file name="UseBean.xml"
url="nbresloc:/org/netbeans/modules/web/core/palette/items/resources/UseBean.xml" />
<file name="GetProperty.xml"
url="nbresloc:/org/netbeans/modules/web/core/palette/items/resources/GetProperty.xml" />
<file name="SetProperty.xml"
url="nbresloc:/org/netbeans/modules/web/core/palette/items/resources/SetProperty.xml" />
<file name="Choose.xml"
url="nbresloc:/org/netbeans/modules/web/core/palette/items/resources/Choose.xml" />
<file name="If.xml"
url="nbresloc:/org/netbeans/modules/web/core/palette/items/resources/If.xml" />
<file name="ForEach.xml"
url="nbresloc:/org/netbeans/modules/web/core/palette/items/resources/ForEach.xml" />
</folder>
...
...
...
</folder>
If you look at the folders that are in bold above, you see that they're shadow folders that point to original files—they're created somewhere else (in the HTML module) but referenced in the JSP module.
A second technique worth knowing about is that you can hide folders and files that belong to other modules. (An example of that was discussed in an earlier blog entry: How to Become Helpless in 5 Minutes.) By hiding folders and files, you have a lot of control over other modules. So, this is what I did (a technique I learnt by looking in the two layer.xml files mentioned above, one in the JSP module and the other in the HTML module) to add my JBoss code snippets to the JSP/HTML Code Clips Palette Manager:
- Make sure that the menu item named in your Bundle.properties file is the same name as used by the other two modules. So, in my Bundle.properties file, I had this value for the key that defines my menu item, which is the same value for the key used by the HTML module and the JSP module:
ACT_OpenJbossddCustomizer=&HTML/JSP Code Clips
- Hide the other two actions (the action in the HTML module and the JSP module that displays the JSP/HTML Code Clips Palette Manager) and declare an instance of your own in your layer.xml file:
<folder name="Menu"> <folder name="Tools"> <folder name="PaletteManager"> <file name="org-netbeans-modules-jbosswebxml-palette-jbossddPaletteCustomizerAction.instance"/> <file name="org-netbeans-modules-html-palette-HTMLPaletteCustomizerAction.instance_hidden"/> <file name="org-netbeans-modules-web-core-palette-JSPPaletteCustomizerAction.instance_hidden"/> </folder> </folder> </folder>Notice the _hidden flags above? This is how you hide folders and files from other modules. (You can also let the IDE generate the above code for you—right-click a folder or file in the layer.xml file's logical view and choose Delete. That doesn't do anything scary—it just adds tags with _hidden flags to your own module's layer.xml file.)
- Finally, declare the resource declaration XML file for your module's code snippets and then declare all the other ones as shadow files:
<folder name="JBOSSPalette"> <folder name="JBoss"> <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.jbosswebxml.Bundle"/> <file name="ContextRoot.xml" url="ContextRoot.xml"/> <file name="ResourceReference.xml" url="ResourceReference.xml"/> <file name="SecurityDomain.xml" url="SecurityDomain.xml"/> </folder> <folder name="HTML.shadow"> <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.web.core.palette.Bundle"/> <attr name="originalFile" stringvalue="HTMLPalette/HTML"/> </folder> <folder name="HTML_Forms.shadow"> <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.web.core.palette.Bundle"/> <attr name="originalFile" stringvalue="HTMLPalette/HTML_Forms"/> </folder> <folder name="JSP.shadow"> <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.web.core.palette.Bundle"/> <attr name="originalFile" stringvalue="JSPPalette/JSP"/> </folder> <folder name="Database.shadow"> <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.web.core.palette.Bundle"/> <attr name="originalFile" stringvalue="JSPPalette/Database"/> </folder> </folder>By taking the three simple steps above, you can get a very nice result—your new code clips are now integrated in the JSP/HTML Code Clips Palette Manager:
Plus, take a look at what my component palette now looks like, but only for jboss-web.xml files:
And now I'm waiting for someone to respond: "But why would you want your JBoss code clips in the JSP/HTML Code Clip Palette Manager? They don't belong there at all! They don't provide JSP or HTML code clips—they provide you with a bunch of XML code clips instead... And why would you want JSP and HTML code clips in your jboss-web.xml editor?" And my answer is... just for the fun of it.
Nov 29 2005, 10:46:47 AM PST Permalink
Manifest File with Syntax Highlighting and Palette!
My support for Manifest files has expanded a bit—now there is syntax highlighting as well as a Component Palette with some (very basic) code snippets:
The left margin of the screenshot looks a bit odd. That's because I've started working on code folding—so far with little success...
By the way, there's a new tutorial on adding HTML code snippets to the Component Palette. It's very easy to do, as my previous blog entries have shown. Here's the complete tutorial: NetBeans Code Snippet Module Tutorial. (It includes downloadable sample code that you can download and play with in the IDE.) However, the Component Palette is enabled, by default, only for HTML files, JSP files, and Form files. Therefore, more tutorials in this area will be added soon—specifically, there'll be a tutorial on extending support for a new file type by adding a component palette.
Nov 28 2005, 06:58:21 AM PST Permalink
You Too Can Make Drag-And-Drop Component Palettes
Similar to my previous blog entry, but this time with an XML file—it's very easy to use the NetBeans Palette API together with the New File Type wizard. Here you see a palette of drag-and-drop components especially for the jboss-web.xml file:
So, the palette that you see above is only visible when a jboss-web.xml file is open in the NetBeans editor. You too can do this! Firstly, use the New Module wizard to create a NetBeans module project. Secondly, use the New File wizard to generate files for distinguishing jboss-web.xml files from all other files (i.e., via its public namespace). Thirdly, the only part that is slightly tricky (because there isn't a wizard for this yet), implement the NetBeans Palette API and associate the pallete with the new file type by implementing the associatePalette method in the XXXEditorSupport.java file. Finally, register the new component palette in the module's layer.xml file.
And that's it. Once you've done this for one file type, it's very easy to do for any/all others—a little bit of copying and pasting can go a very long way! (However, note that I need to work out how to not disable syntax highlighting when enabling the component palette...)
Postscript: Worked it out! I'm now reusing the XML editor, so I get the syntax highlighting that the XML editor provides. I've done this by making sure that the MIME type everywhere is the same (I had different MIME types in different places, which was a bit stupid) and making sure that the MIME type ends in "+XML". So, my jboss-web.xml MIME type is text/jboss+xml. However, I'm using the MIME resolver to distinguish between this type of XML file and all other XML files:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE MIME-resolver PUBLIC "-//NetBeans//DTD MIME Resolver 1.0//EN" "http://www.netbeans.org/dtds/mime-resolver-1_0.dtd"> <MIME-resolver> <file> <ext name="xml"/> <resolver mime="text/jboss+xml"> <xml-rule> <doctype public-id="-//JBoss//DTD Web Application 2.3//EN"/> </xml-rule> </resolver> </file> </MIME-resolver>And so here is the result:

Nov 27 2005, 05:02:25 AM PST Permalink
Making the Component Palette Work for Other File Types
Today I made the Component Palette work for Manifest files. Below you see the result—I have two code snippets in the Component Palette. I can drag-and-drop them (or double-click them) and then a key is inserted in the Manifest file. Here's what it looks like for me now (the tooltip shows what code will be inserted in the Manifest file):
The key to everything is this method in ManifestEditorSupport.java (especially note the bits in bold):
void associatePalette(ManifestEditorSupport s) { DataObject dataObject = s.getDataObject(); if (dataObject instanceof ManifestDataObject) { try { PaletteController pc = ManifestPaletteFactory.getPalette(); Lookup pcl = Lookups.singleton(pc); Lookup anl = getActivatedNodes()[0].getLookup(); Lookup actionMap = Lookups.singleton(getActionMap()); ProxyLookup l = new ProxyLookup(new Lookup[] { anl, actionMap, pcl }); associateLookup(l); } catch (IOException ioe) { //TODO exception handling ioe.printStackTrace(); } } }So, broadly, what you need to do is the following (this is partly from an e-mail from Libor, the guy who associated the Component Palette with JSP files and HTML files for NetBeans IDE 5.0):
- Implement the palette files, required by the NetBeans Palette API.
- Register the palette in the layer.xml file, as shown in previous blog entries.
- Make sure that the palette initialization is done correctly in the XXXEditor.associatePalette() method, as shown in the code above. The essential part is obtaining PaletteController from XXXPaletteFactory and associating it with the file type's lookup.
When you're working on this, the following are the main Java files (highlighted below) you'll be working with:
Unfortunately, I strongly doubt that it's possible to associate the Component Palette with existing file types. In my case, it was possible, because I had created support for Manifest files myself. I basically had to create the palette files and then modify the ManifestEditorSupport.java class to make them work together. But if, for example, you wanted to associate the Component Palette with Java files, how would you go about modifying the related EditorSupport.java class? I doubt that that is possible. (Correct me if I'm wrong, Libor.) This means that for existing file types (i.e., ones over which you have no control), you'll have to wait for the next release (or an addition to the Update Center). An alternative might be to check out the NetBeans sources, modify the appropriate file, and then rebuild the IDE...
By the way, you might have noticed that there's something odd about the Manifest file shown in the first illustration above—there's no syntax highlighting! Somehow, by associating the Component Palette with Manifest files, I disassociated syntax highlighting... Weird! Once I've sorted out this problem, and cleaned up my code a bit, I will write a tutorial that covers everything there is to know about the Component Palette, especially how to create NetBeans modules containing code snippets. However, there'll be nothing surprising in that tutorial if you've read the last few blog entries in this blog...
Nov 25 2005, 01:09:00 PM PST Permalink
Expanding the NetBeans Component Palette without Creating a NetBeans Module
In a few recent blog entries, I described how to really quickly create a NetBeans module containing code snippets, such as <p> tags (or even more extensive tag combinations). However, not everyone wants to do it that way—maybe all you want to do is add code snippets to the Component Palette, but not share them with anyone else (hmmm, sounds a bit selfish, doesn't it). For example, at the end of Simple Extension of NetBeans Component Palette, Kovica asks:What do you think about adding snippets like this: you edit a file, select a text, right click and select Add to palette. Then a dialog opens asking you into what category to add selected text. I hope you can and will do this. Please.
So, I talked to Libor (the guy who implemented the Component Palette for JSP files and HTML files) and he tried to leave a comment in response to Kovica's question, but the comment thing in this blog didn't work for him. So he sent me an e-mail with instructions for adding code snippets. It's not a perfect solution by any means, and it will be improved in future releases. But here's how you can do it, despite the lack of 'official' support for doing this.
- Open a JSP page. The Component Palette should open automatically. If it doesn't, choose Ctrl-Shift-8.
- Right-click in the Component Palette and choose 'Create New Category'. Create a new category. For example, I called mine "Geertjan's category".
- Right-click an item from one of the other categories, choose Copy, and then paste the item in your new category.
- Now close the IDE.
Whenever you see a set of instructions that tells you to close the IDE, you know that you're about to do something unorthodox... So, here it is:
- Go to the NetBeans user directory.
- Go to this directory within the NetBeans user directory:
config/JSPPalette/[new category]/[clip definition file]
For example, here's the place where mine is found, within the category "Geertjan's category":
- Inside the XML file that you find in the directory above, do the following:
- Completely delete the class tag.
- In the place where the class tag was found, paste the following (if you want to add a code snippet that inserts a <br/> tag):
<body> <![CDATA[ <br/> ]]> </body>
- Save and close the file.
- Restart the IDE. You will now see your code snippet in the Component Palette when you open a JSP file. When you drag and drop it (or double-click it), the tag that you created manually outside the IDE will be inserted at the cursor in the Source Editor.
Unfortunately, the name, tooltip, and icons will remain unchanged, which means that they don't fit with the new tag content. On the other hand, using this round-about approach, you can very quickly add many new code snippets to the Component Palette. Just continue copying that XML file that was generated for you in the NetBeans user directory, and your Component Palette will quickly expand to include a variety of your favorite code snippets.
Nov 24 2005, 11:45:46 AM PST Permalink
Sometimes a Picture Speaks Words...

For further details, see Masoud's and Ruth's Developer Collaboration Module Quickstart.
Nov 23 2005, 02:53:35 AM PST Permalink
Simplifying Web Development via Code Snippets
So I've added some code snippets for two sets of tags that I use a lot while writing help files—the header at the top of the page and the 'See Also' section at the end. Both sets of tags are pretty standard, except that each contains links to various other files. So, in the tooltip I've indicated the things that need to be done in bold—by means of the TBD, as shown below:
When I double-click (or drag) the Header item above, the tags that you see in the tooltip are created. That's really great, because now I'll never need to type those tags again.
The tooltip that you see above is of the same kind as the ones I raved about exactly two months ago, in Tooltips Like Never Seen Before. They're defined in Bundle.properties files, referenced in the XML file that collects all the resources for a tag, which in turn is registered in the layer.xml file. Here's the definition of the above tooltip:
And this is the relevant method in my code snippet definition:
Finally, this is the result of dragging the new code snippet into the page:

Nov 22 2005, 03:36:57 AM PST Permalink
Never Type HTML Line Break Tags Again!
So here's the absolutely no-frills simplest implementation of a new code snippet for NetBeans IDE 5.0. The end result in my Projects window is this (in the screenshot, I've selected the only two Java files I needed to create):
When I install my new module, the result is an additional code snippet in the HTML section of the Component Palette (which is displayed when I create an HTML file or JSP file):
When I double-click the code snippet, a <br> tag is created at the cursor. Alternatively, I can drag-and-drop the code snippet wherever I want in my HTML file or JSP file.
This is the content of the BR.java file (hyperlinks will take you to NetBeans API Javadoc):
package org.netbeans.modules.myfiletype.palette.items; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import org.openide.text.ActiveEditorDrop; public class BR implements ActiveEditorDrop { public BR() { } private String createBody() { String Br = "<br>"; return Br; } public boolean handleTransfer(JTextComponent targetComponent) { String body = createBody(); try { MyfiletypePaletteUtilities.insert(body, targetComponent); } catch (BadLocationException ble) { return false; } return true; } }
Note that, in the createBody() method above, the standard code snippets call a dialog box where you can pre-define the code snippet's values. However, I don't like this. I much prefer just dragging chunks of code into the HTML file or JSP file and then modifying them using code completion. (For me, a better solution than all those dialog boxes would be to implement them in the Options window instead. Then, I'd be able to set my desired values once and then tweak them if necessary, but I wouldn't have to set values every time I define a new code snippet.) And this is the content of the MyfiletypePaletteUtilities.java file:
package org.netbeans.modules.myfiletype.palette.items; import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import org.netbeans.editor.BaseDocument; import org.netbeans.editor.Formatter; public class MyfiletypePaletteUtilities { public static void insert(String s, JTextComponent target) throws BadLocationException { insert(s, target, true); } public static void insert(String s, JTextComponent target, boolean reformat) throws BadLocationException { if (s == null) s = ""; Document doc = target.getDocument(); if (doc == null) return; if (doc instanceof BaseDocument) ((BaseDocument)doc).atomicLock(); int start = insert(s, target, doc); if (reformat && start >= 0 && doc instanceof BaseDocument) { // format the inserted text int end = start + s.length(); Formatter f = ((BaseDocument)doc).getFormatter(); f.reformat((BaseDocument)doc, start, end); } if (doc instanceof BaseDocument) ((BaseDocument)doc).atomicUnlock(); } private static int insert(String s, JTextComponent target, Document doc) throws BadLocationException { int start = -1; try { //at first, find selected text range Caret caret = target.getCaret(); int p0 = Math.min(caret.getDot(), caret.getMark()); int p1 = Math.max(caret.getDot(), caret.getMark()); doc.remove(p0, p1 - p0); //replace selected text by the inserted one start = caret.getDot(); doc.insertString(start, s, null); } catch (BadLocationException ble) {} return start; } }
Next, you need a 16x16 image file and a 32x32 image file. (Because when you right-click on the Component Palette you can choose 'Show Big Icons'.) In the Resources package, I have a Bundle.properties file with this content (i.e., the label and the tooltip):
NAME_html-BR=Line Break HINT_html-BR=\ <html>\ <br>
\ </html>And then a small XML file to reference all your resources, which then gets referenced in the layer.xml file:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE editor_palette_item PUBLIC "-//NetBeans//Editor Palette Item 1.0//EN" "http://www.netbeans.org/dtds/editor-palette-item-1_0.dtd"> <editor_palette_item version="1.0"> <class name="org.netbeans.modules.myfiletype.palette.items.BR" /> <icon16 urlvalue="org/netbeans/modules/myfiletype/palette/items/resources/BR16.gif" /> <icon32 urlvalue="org/netbeans/modules/myfiletype/palette/items/resources/BR32.gif" /> <description localizing-bundle="org.netbeans.modules.myfiletype.palette.items.resources.Bundle" display-name-key="NAME_html-BR" tooltip-key="HINT_html-BR" /> </editor_palette_item>Finally, the layer.xml file registers the new HTML code snippet like this:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.1//EN" "http://www.netbeans.org/dtds/filesystem-1_1.dtd"> <filesystem> <folder name="HTMLPalette"> <folder name="HTML"> <file name="BR.xml" url="resources/BR.xml"/> </folder> </folder> </filesystem>That's the whole story of a very simple code snippet. There's really not very much code at all (especially when you realize that MyfiletypePaletteUtilities.java is shared between all the related code snippets). And, at the end of it, you can drag and drop the snippet and... then... you'll never need to type <br> again!
Nov 21 2005, 05:31:28 AM PST Permalink
Simple Extension of NetBeans Component Palette
A while ago I blogged about the new Component Palette. You can drag and drop various common JSP and HTML items onto a JSP or HTML page. But what if you're missing some items? Are you doomed to wait until the next release? No, not now that it's much easier to create NetBeans modules. Look, I added two very simple items myself today, for those moments where I just can't be bothered to type in paragraph tags and break tags. Now all I need to do is double-click in the Component Palette and the IDE creates the tag for me:
If you'd like to try out my new module (because you're just as lazy as me when it comes to paragraph tags and break tags), click here to download it. (You might have to do a right-click on the link and then choose save.) I'd like to write a tutorial about adding your own code snippets, but the API is really unstable, and I think I should wait a bit before beginning the tutorial.
(I've just noticed that the tags are only available for JSP pages, not HTML pages. I know how to fix that—just a minor tweak in the layer.xml file—but just thought you should know about this current limitation.)
Nov 20 2005, 08:43:01 AM PST Permalink
Struts for the Complete Beginner (Part 4)
In the last instalment, you ended up with data access code in a Struts Action class. This is bad. For example, if you read slide 7 of Sang Shin's Accessing Database in Struts Application (which is part of his fantastic—and free—regular college semester-like on-line J2EE course), you're told that "all the database access code should be encapsulated behind the business API classes (using the DAO pattern)". So today I tried to work out what that pattern is all about. The whole theoretical story is described in the Java BluePrints Core J2EE Patterns - Data Access Object.So, now that it's all working for me, this is what it looks like in the IDE:
These are the files you see listed above:
- ApplicationResource.properties. The standard Struts localization and messaging file.
- Customer.java. A POJO representing the customer's name and city (refactored from 'row.java').
- DAOFactory.java. A factory class that returns PointbaseUserDAO.java:
public class DAOFactory { public static UserDAO createUserDAO(Connection connection){ return new PointbaseUserDAO(connection); } } - PointbaseUserDAO.java. This is a class that implements UserDAO.java. It is also the class where all my data access code is now found. This is the content:
public class PointbaseUserDAO implements UserDAO { private Connection connection; private DataSource dataSource; /** Creates a new instance of PointbaseUserDAO */ public PointbaseUserDAO(Connection connection) { this.connection = connection; } public ArrayList listUsers(){ ArrayList customerList = new ArrayList(); try{ String sqlQuery = "SELECT * FROM CUSTOMER_TBL"; PreparedStatement prpStmt = connection.prepareStatement(sqlQuery); ResultSet rs = prpStmt.executeQuery(); /** Here we put field 4 (the name) and field 7 (the city) in the customerList: */ while (rs.next()) { customerList.add(new Customer(rs.getString(4), rs.getString(7))); } rs.close(); } catch ( SQLException e ) { System.err.println("SQL Exception occured while accessing the table" ); e.printStackTrace(); return null; } catch ( Exception e ) { e.printStackTrace(); return null; } return customerList; } } - SecurityManager.java. A simple file discussed in the first instalment. It forms the basis of what will become a more complex security manager (via a database). Currently, all it does is allow someone called 'Ludwig van Beethoven' to log in with a password 'symphony'.
- UserAuthenticationAction.java. This is a Struts action (refactored from 'NewStrutsAction.java') that authenticates the user, via the security manager. It now also tells the DAOFactory.java to create an instance of PointbaseUserDAO.java. Here's the relevant part of this file (everything that's new here is in bold):
if (SecurityManager.AuthenticateUser(newStrutsActionForm.getName(),newStrutsActionForm.getPassword())){ dataSource = (DataSource)servlet.getServletContext().getAttribute("custTable"); Connection conn = dataSource.getConnection(); UserDAO dao = DAOFactory.createUserDAO(conn); customerList = dao.listUsers(); /** Here we put the customerList in scope, so that we can use it in the JSP page: */ HttpSession session = request.getSession(); if(customerList != null){ session.setAttribute("allMyCustomers" , customerList); } return (mapping.findForward(SUCCESS)); } else { ActionMessages errors = new ActionMessages(); ActionMessage error = new ActionMessage("errors.login.invalid"); errors.add("loginWrong",error); saveErrors(request.getSession(),errors); return mapping.getInputForward(); } - UserDAO.java. This an interface. Currently, it is only implemented by PointbaseUserDAO.java. Theoretically, I could have other implementations—MySQLUserDAO.java, DerbyUserDAO.java, etc. Here's the content (very simple so far):
public interface UserDAO { public ArrayList listUsers(); }
It's all really kind of nice—a pretty good framework for expanding this application. (By the way, the DataSourceConnectionAction.java from part 3 is now completely empty and can be deleted!) However, one thing puzzles me, and I hope someone knows the answer to this. When you look at UserAuthenticationAction.java above, you still see some data access code. I'd like the datasource to not be created in the Struts Action class—because it contains a reference to a Struts datasource that connects to PointBase. Therefore, this is a PointBase-specific piece of code that shouldn't be in the Struts Action class. Is there any way to move that to the PointbaseUserDAO.java as well?
Nov 19 2005, 11:29:14 AM PST Permalink
Creating Neat Borders in NetBeans IDE 5.0
I'm busy working on organizing a tutorial that lets you create Masoud Kalali's Gmail Checker for NetBeans. (By the way, if you listen to this episode of Java Posse, you'll find that Tor Norbye mentions Masoud's module! He says, among other things, "If you want to live in your IDE, this brings you one step closer.")I'm learning quite a lot by writing this tutorial. One thing I've learnt is something I wondered about while writing the NetBeans Options Window Extension Module Tutorial—how to create those cool borders around JPanels. For example, here, in the new Gmail Checker Setting panel, which is part of Masoud's module, you see some cool borders with titles—"General Options", "Advanced Options", and "Proxy Settings" (click to enlarge):
Until I read Masoud's tutorial draft, I didn't know how to make those cool borders. I saw them in the other panels in the Options window, but didn't know how to create them. Now I know—select a JPanel and then select the little "..." button in the JPanel's Border property:
Then you get this dialog box (click to enlarge):
Here you select TitledBorders in the top list and then fill in the title in the bottom list. You'll find that you're also able to create a key in the resource bundle, which generates a reference to that key in the Title field.
Pretty neat. From one dialog box to another and at the end you've created a cool border and a professional looking title within it.
Nov 18 2005, 09:44:31 AM PST Permalink
Readable Log Files in NetBeans IDE 5.0
First, a picture of my log file:
If you want your log files to look like this too (i.e, if you want XML instead of text in your log files), read on. The above screenshot is the result of JULI (java.util.logging) logging in Tomcat 5.5.9, which is bundled with NetBeans IDE 5.0. Before going further, a little bit of background reading on JULI:
- Enlightening thread on nbusers
- Java Logging API and How To Use It
- Logging in Tomcat
- Java Logging APIs
So, this is how to set things up so that the IDE generates JULI log files in XML:
- Make your log files a bit more accessible. Right-click your project node, choose Properties, and then, in the Sources panel, add a new source root that points to Tomcat's logs folder in the NetBeans user directory. Note that the logs folder and its parent is created only when you start the server.
- Set your logging properties. By default, with JULI logging support in Tomcat 5.5.9 in NetBeans IDE 5.0, java.util.logging.Logger file output goes to this file:
$catalina_base/logs/localhost-YYYY-MM-DD.log
Server output goes to this file:
$catalina_base/logs/catalina-YYYY-MM-DD.log
Both of these files open in separate tabs in the Output window when you deploy to Tomcat 5.5.9. (And there are two pop-up menu items on the Tomcat Web Server node in the Runtime window, one is called 'View Server Log' and the other is called 'View Server Output'.) However, you can modify a lot of things in a file that must be called logging.properties, which must be found in the default package:
So now we're going to add key-value pairs to the logging.properties file. We want the Output window (handled by java.util.logging.ConsoleHandler) to contain XML instead of text. And we want the content of the server log file (handled by org.apache.juli.FileHandler) to be reformatted in XML too. Here are my key-value pairs:
#------------------------------------------------------------------------ #- Global Settings #------------------------------------------------------------------------ handlers=org.apache.juli.FileHandler,java.util.logging.ConsoleHandler .level=INFO org.apache.juli.FileHandler.level = FINEST org.apache.juli.FileHandler.directory = ${catalina.base}/logs org.apache.juli.FileHandler.prefix = localhost. org.apache.juli.FileHandler.limit = 5242880 org.apache.juli.FileHandler.count = 5 org.apache.juli.FileHandler.formatter = java.util.logging.XMLFormatter java.util.logging.ConsoleHandler.level = FINEST java.util.logging.ConsoleHandler.formatter = java.util.logging.XMLFormatter #------------------------------------------------------------------------ #- Classes #------------------------------------------------------------------------ mypackage.mysubpackage.level=FINEST
Finally, by adding this line, you change the suffix (i.e., the extension) from .log to .xml, which lets you open the log file in the IDE's XML editor (where you can make use of some of this editor's cool features, such as syntax highlighting and code folding as shown in the screenshot at the start of this blog entry):
org.apache.juli.FileHandler.suffix = .xml
However, note that if you change the suffix, then the server log will not be opened in a separate tab in the Output window anymore, because the only log file that opens in the separate Output window tab (apart from the server output file) is the one that is called localhost-YYYY-MM-DD.log (i.e., with a .log suffix). However, I've found that in this case the server log file outputs to the same tab where the server output is displayed. Therefore, even though one of the two tabs remains empty, the other tab seems to contain the output of both the server output and the log file (in XML). So, finally, this is what my new source root looks like after I deployed my application to Tomcat 5.5.9:
When you're trying it out, here's a scriptlet that you can put in a JSP page:
<% // this goes into the server I/O java.util.logging.Logger log = java.util.logging.Logger.getAnonymousLogger(); log.warning("my warning message"); log.log(java.util.logging.Level.SEVERE, "My NPE", new NullPointerException()); // this goes into the log file log("Standard servlet logging"); %>When you add the above to a new web application's index.jsp, and then deploy the application using the logging.properties file shown above, a localhost-YYYY-MM-DD.xml with the following content will be generated:

Nov 17 2005, 06:08:15 AM PST Permalink
By the way, if you want to create the above application yourself, see the Paint App Tutorial by Tim Boudreau. James, a new colleague of ours in the docs department, is busy updating and formatting Tim's tutorial so that it matches the style of our other tutorials. He's done a really good job and we should have the next revision of Tim's tutorial available soon. In the meantime... why not download NetBeans IDE 5.0 Beta 2 and take it for a spin?
Nov 16 2005, 09:29:06 AM PST Permalink
Pop Quiz for NetBeans and Struts Users
I learnt two small but interesting things today about Struts, Tomcat, and NetBeans IDE 5.0. Both things are really quite small, but both are also really quite significant and interesting—at least to me. So, here are the two problems I had—I will not give you the solutions. Instead, if you know one or more of the solutions, please leave a message at the end of this blog entry (or write me an e-mail). In a few days, I'll leave the answers at the end of this blog entry, if nobody out there has managed to work them out...- Problem 1: Struts. At the end of part 3 of my Struts tutorial, I had a Struts datasource for accessing data from a PointBase database:
However, whenever I refreshed the page, a new call was made to the database, which resulted in the data being displayed again:
Question: What did I do to solve this problem?
- Problem 2: NetBeans IDE. Even though I successfully deployed the application to the bundled Tomcat Web Server, a new node did not appear in the Runtime window:
As a result, I wasn't able to undeploy my application from inside the IDE. I also couldn't start/stop the application or open it in the browser from inside the IDE. All of these actions are present in an application node's pop-up menu, but since I didn't have an application node there, I couldn't use the pop-up menu. When I deployed other applications, there was no problem and the node appeared correctly.
Question: What did I do to solve this problem?
Both these issues are quite small and trivial if you know how to deal with them, but pretty frustrating if you don't. Any guesses out there what the solutions are?
Nov 15 2005, 11:45:05 AM PST Permalink







