Friday, December 28, 2007

How to set the License for a project in Netbeans 6.0

To set the project license on a per project basis, you need to set a property called project.license to the value of the license you want to use. For example: If I want to use the Apache 2.0 license, I need to set the property to project.license=apache20. This is accomplished by opening the project files and going to the nbproject directory. You will see a file called project.properties, double click on it to edit it.

You then add the line to the of the properties and save. Any java source files created now will contain the Apache 2.0 license.

/*
* Copyright 2007 John Yeary.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the License for the specific language governing
* permissions and limitations under the License.
* under the License.
*/

How to set the Default License in Netbeans 6.0

To set the default license on Netbeans 6.0 for ALL projects go to Tools --> Templates and expand the Licenses tree. Select the Default License and Open in Editor.


You may then modify the default license to meet your needs.

<#if licenseFirst??>
${licenseFirst}

${licensePrefix}To change this template, choose Tools | Templates
${licensePrefix}and open the template in the editor.
<#if licenseLast??>
${licenseLast}

Note: You must add ${licensePrefix} to each line you wish to add.

<#if licenseFirst??>
${licenseFirst}

${licensePrefix} Copyright ${date?date?string("yyyy")} ${user}.
<#if licenseLast??>
${licenseLast}

This version sets the copyright to the current date and the name to the ${user} property. If you need to modify the ${user} property please see How to set @author or ${user} properties in Netbeans 6.0 templates

How to set @author or ${user} properties in Netbeans 6.0 templates

This is a simple task in Netbeans 5.5, but not obvious in Netbeans 6.0. To set the ${user} variable in templates in Netbeans 6.0, you must go to Tools --> Templates. This will bring up the Template Manager screen. Scroll to the section called User Configuration Properties and expand it. You will see a template called User.properties.


Select the User.properties and Open in Editor. Uncomment the line user and set it to the appropriate value and then save the file.


Now when you create a new Java source file, the javadoc @author will be set to the new property. This same method is used to set other properties in your templates as well.

Thursday, December 20, 2007

Pragmatic Logging

After reading the book Release It! I decided to write a quick extension to the Java Logging framework from the JDK. I called it PragmaticLogging. It is a Netbeans 6.0 project. I have released it under the Apache 2.0 License.

The idea was to provide a simple extension to the JDK which would make logging easier for developers and administrators.

There is another zipped Netbeans project called PragmaticLoggingExample which will use the Pragmatic Logging framework to generate some example logging output.

The project is completely documented (If you see something missing... leave a comment).

If you have any suggestions/enhancements please post a comment and I will see about updating the framework.

Saturday, December 15, 2007

Release It! Review

I just completed reading Release It! by Michael T. Nyggard (Pragmatic Bookshelf 2007). It is part of The Pragmatic Programmers series. I have read the book cover to cover twice. At first, I thought that the book was just another book on how to manage projects. So What! The ideas presented in the book were common sense. I have been doing these same things for many years.

Then one day I was working on a project, and was trying to figure out how to handle a problem. I remembered what I read in Release It! about the topic. I grabbed the book off the bookshelf and looked it up; logging. The ideas presented are common sense, but how often have we missed to boat. The ideas presented in the book I implemented much to my own joy. The result was a customized deployment of the Java Logging system which is simple to maintain and does not require external libraries.

It was at that point I realized the brilliance of the book and the pragmatic side of things. I re-read the book. As an architect, project manager, developer, and maintainer of complex software ecosystems, the ideas in the book provide a "pragmatic" common sense approach to handling situations. The book is a learning tool, one person's personal perspective on software design and deployment, and a reference. It is an all-in-one book.

This book provides a great tutorial on how to manage complex projects for the novice, and a gentle practical reminder to the seasoned architect/project manager.

The book is divided into 4 major sections: Stability, Capacity, General Design Issues, and Operations. The first two sections provide the basis for the remainder of the book. The Stability and Capacity sections have divided the topic into an explanation, followed by general design patterns and anti-patterns. It explains in enough detail how to implement good patterns and recognize bad ones.

The section on General Design covers items like Administration and Security. There is nothing earth shattering in these sections, but they do provide a basis for a "check list" of items to make sure you consider in your designs.

The final section on Operations is the one where you will make friends with your administrators and keep your sanity. The portions on designing for monitoring including logging will be your savior at 2:00 AM in the middle of a blizzard. The discussion on designing for the future does not get enough attention in our modern get it out the door now world. This may be the push you need to think about it.

This is a book to have on your bookshelf. Mine is full of tabs and post-it notes.

Sunday, November 11, 2007

IntelliJ IDEA 7.0

I had a chance to give IntelliJ IDEA 7.0.1 on my Mac. The latest version of IntelliJ has a wonderful set of new features. I really am enamored with its web services development tools. The support for Apache Axis is a wonderful thing. As a Netbeans user, I have issues around using Axis. It is nice to find first class support.

The support for various frameworks is quite impressive too: GWT, Apache Struts (1.2 and 1.3.x), Spring (1.2.9 and 2.0.7), and Hibernate are great.

Alternative language support has also been added for Ruby and Groovy. They also have the best Javascript editor in an IDE have seen.

One of the biggest strong points for IDEA has always been refactoring. The latest version does not disappoint. There have also been a number of improvements to its code analysis tools. They help the novice to experienced programmer to avoid common mistakes.

One of the nice features that I came across which was not mentioned in the marketing glossies and notes are: JAXB code and schema auto generation. The other one was XmlBeans code auto generation from a schema. Very cool!

My chief complaint about IntelliJ IDEA 7.0.1 is the lack of visual development of JSF. The Netbeans IDE has the best visual JSF tools.

The only other complaint is lack of import/project support for Netbeans projects. Eclipse support is available, but I need the Netbeans support.

My overall impression is great. It provides the Java developer with a great IDE with a number of powerful features/tools. It is definitely worth having in your toolbox.

Friday, November 09, 2007

Building Maps into Your Swing Application with the JXMapViewer



I just read a great tutorial by Joshua Marinacci on using the new Swing Labs JXMapViewer component. His tutorial is on java.net. It took me 15 minutes start to finish to do the tutorial. At the end, I had a wonderful proof of concept for using mapping in a Swing application.

This is a tutorial that should not be missed. It is so well written with plenty of images to demonstrate the steps. BZ to Josh.



I have added a copy of my example application which includes the screenshots above here
You will need to fix the dependencies and point them to the jar files found in the root of the project directory

Wednesday, November 07, 2007

JavaOne 2008 Tools and Languages Review Team

I have been given quite an honor this year to help as an external reviewer for papers submitted for JavaOne 2008. The review team consisted of a number of great folks from the world of Java. The team included the Java Posse: Dick Wall, Tor Norbye, Carl Quinn, and Joe Nuxoll, Cay Horstmann, Fabiane Nardon, Adam Myatt, John Brock, Sharat Chander, David Folk, Gregg Sporar, and Petr Suchomel. It was quite an honor to be among such a terrific cast of reviwers.

We completed the task in a timely manner, and I am very pleased with the great submissions for this year at JavaOne. There was a lot of thought and consideration given to the proposals. We had over 300+ submissions to examine for merit. In the end, our whole team felt that we had a banner year for submissions. I hope all of the folks at JavaOne appreciate the selections.

Java SE 6 for OS X 10.5 (Leopard) 13949712720901ForOSX

Please help support the cause to get Apple to provide Java SE 6 to the OS X community. The latest version of OS X Leopard has only Java SE 5.
13949712720901ForOSX

The first part of the string is the decimal notation for 0xCAFEBABE [1], the magic cookie for JavaClass files (thanks David for the number and the pointer to Fredericiana's photo). Then post similar instructions on your blog or point people here. Let's see how far this gets us! [2]

We should then be able to use any search engine, Google is a good choice, to search for this string [3], and hopefully motivate the managers at Apple to invest more time on Java and be more open about their plans with the community.

Your vote may also be an energizer to those groups that are starting to port the OpenJDK to OSX (via the mac java community).

2008 JavaOne Call-for-Papers is LIVE

JavaOne Conference
Call for Papers is OPEN
Submit your proposal today - Deadline is November 16, 2007
JavaOne, Sun's 2008 Worldwide Developer Conference, is seeking proposals for technical sessions and Birds-of-a-Feather (BOFs) sessions for this year's Conference.
Attracting over 15,000 developers and leaders in the developer community - from industry leaders, to experienced developers to developers starting out - this conference is one that brings together some of the industry's best and brightest.
The JavaOne conference is your opportunity to reach this specialized community by educating and sharing your experience and expertise with the developer community.
Additional information on the program can be found at:

Sunday, October 21, 2007

Murach's Java SE 6

There have been a number of books and tutorials written about Java. The gold standard for me has always been "Learning Java" by Patrick Niemeyer and Johnathan Knudsen (O'Reilly & Associates). I have had a number of new programmers, enthusiasts, and members of the JUG tell me it is information overload. The book does contain a lot of information in its 828 page heft. As a result, I have been looking for a book just for beginners. I have found it.

I just completed reviewing Murach's Java SE 6. It is a very good resource for learning Java. This book does an excellent job of providing a firm basis for understanding the technology. The book is clearly and concisely written. The book is divided into 5 major sections which cover the essential Java skills to advanced topics on data access programming using XML and JDBC.

The teaching style is very clever. It typically takes the form of a page of information with facing page with examples. I found this to be very important in getting sometimes difficult points across. I typically take the "Show me the code" philosophy, and this style works for me.

The other technique that used is to convey a purpose for learning Java. This is done by using the various topics as building blocks to create an application. The final result is a completed application at the end of the book. It encompasses the lessons learned, and gives the new programmer a sense of accomplishment with a completed functional application at the end of the book. I love it.

I have found that people learn better with functional code examples. This book is replete with them. One of my greatest annoyances is to have code samples which do not work. This clouds the ability to learn because it forces the beginning programmer to question their abilities. The shroud of uncertainty should not be because the gold standard code is incorrect. I am pleased to note that I tried a number of code examples and they all worked.

My favorite section is Data access programming with Java. Chapter 20 covers working with XML. This is a must for any programmer. XML is the new black, and anything that can help you learn this important technology is a must. In chapter 20, the topic of StAX is covered. This is the best simplified example of using StAX I have seen. After reading the information, and performing the examples, I felt I had a better understanding of this technology.

I only have a few minor negative points to mention: the title is a little misleading. The majority of the information in the book really details Java SE 5 enhancements with two notable exceptions: StAX and an introduction to Derby (Java DB). The water is chummed in Chapter 1 where he mentions that C# runs faster than Java. This is a point that needs to be proven. Java 6 SE is almost as fast as C/C++ on bare metal. I have not heard anything like this for C#. I will forgive this remark though since the rest of the book is so well written.

My overall impression is that the book is an outstanding resource for new and seasoned programmers. This is a great book to add to the reference shelf.

The publisher has a number of code samples, student workbooks, and tutorials:

Student and Trainer Resources (Publisher)

Saturday, October 20, 2007

Quartz Job Scheduler on Glassfish

I have discovered that get a Quartz Job Scheduler to run in glassfish, you need to change the server.policy file to add the following information:

///////////////////////////////////////////////////////////////////////////////////////////////
// Quartz Scheduler
///////////////////////////////////////////////////////////////////////////////////////////////
grant codeBase "file:${com.sun.aas.instanceRoot}/applications/j2ee-modules/QuartzScheduler/-" {
permission java.lang.RuntimePermission "getClassLoader";
// Required for ShutdownHookPlugin
permission java.lang.RuntimePermission "shutdownHooks";
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
permission javax.management.MBeanPermission "com.sun.enterprise.admin.runtime.BaseRuntimeMBean#", "registerMBean";
permission javax.management.MBeanServerPermission "findMBeanServer";
};

Thursday, August 02, 2007

Running Woodstock 4.1 on Apache Tomcat 6.x

This is part of a comment I posted previously, but I thought it might worth mentioning with some details

To get the components to work with Apache you will need to download the Sun JSF 1.2 RI and install it in the lib directory. You will also need the Java Standard Tag Library (JSTL) implementation. The Apache JSTL 1.1 implementation needs to be installed in the lib directory.

Once these libraries are installed, you may check that the Woodstock libraries will run by installing the Woodstock examples.

Once these steps are completed and you run the examples you should see this this page

Monday, July 02, 2007

VWP (Woodstock) JSF MessageGroup Tip

It is funny how often we as programmers do things that later cause us extra work.

How many of you while developing a JSF Page use a MessageGroup to display debugging information? I bet your intent was to delete, or not to display (visibility/render) it later...

Here is a tip that will make your life easier....

1. In your web.xml file add an environment entry called displayMessageGroups like below.


2. We will use this to inject a resource into our Application Bean to set it for the whole project.

3. Open the Application Bean (usually ApplicationBean1) and add the following:
@Resource(name = "displayMessageGroups")
private boolean displayMessageGroups;

public boolean isDisplayMessageGroups() {
return displayMessageGroups;
}
This will allow us to change the value from true/false by simply changing the web.xml file if we need to turn on the messages for debugging.

NOTE: I am using auto-boxing on the Boolean --> boolean conversions.

4. Now bind the component by using the properties for the MessageGroup components in your project.

NOTE: You will want to bind the render property and not the visible property. We do not want to add additional downloaded components to the page if we are not planning on using them. This is good style.





This will save you a lot of time later and make debugging easier if you need it.

Sunday, June 24, 2007

How to determine Project Woodstock components version in Netbeans

This is just a simple explanation of how to determine which version of Project Woodstock components you are using in Netbeans. This question often comes up when you are posting to the Project Woodstock or netbeans forums. The Woodstock components are organized into jar files which have a MANIFEST.MF file inside. The MANIFEST.MF contains all of the details:

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.0
Created-By: Sun Microsystems Inc.
Implementation-Title: Woodstock 4.1
Implementation-Version: 4.1
Implementation-Vendor: Sun Microsystems Inc.
Implementation-Vendor-Id: com.sun
Specification-Title: Woodstock
Specification-Version: 4.1
Specification-Vendor: Sun Microsystems Inc.

Name: com/sun/webui/jsf/
X-SJWUIC-SWAED-Version: 4.0
X-SJWUIC-Components-Version: 4.1
X-SJWUIC-Components-Timestamp: 200706221216
X-SJWUIC-Theme-Version-Required: 4.1
X-SJWUIC-JSF-Version: 1.2
X-SJWUIC-Dependencies: dataprovider.jar/1.0, jhall.jar/2.0
X-SJWUIC-Dependencies-FileUpload: commons-fileupload.jar/1.0

This example is taken from Netbeans 6.0 Daily Build 200706230000. The Library is called Web UI Components and the specific jar file is webui-jsf.jar. The two items usually asked for are version and the component timestamp. The timestamp indicates which build you are using of the particular components.

Thursday, May 24, 2007

Java EE5 Persistence and Generics

The new Java EE5 Persistence provides some really cool functionality. It was designed with backwards compatibility in mind. This has resulted in some interesting issues. For example if you perform a Query which returns more than one object, the objects are returned as a List. The List is a very generic Object List. Generally we know that if we perform a query that it should return specific types back to us. For example we expect it to return a collection of the entity itself. If we accept the default which is to return a List, the compiler will report an unchecked warning. If you use the -Xlint:unchecked option, it will point out that we are getting a generic Object List and it can not verify the type of the Object.

The Solution... is simple...

When you get the List back cast it into a specific type. For example:

Query q = em.createQuery("SELECT OBJECT(p) FROM PuzzleBox p");
List puzzles = q.getResultList();
A rather elegent solution... alternatively you can have a more complex version such as

ArrayList puzzles = new ArrayList(q.getResultList);

This works because an ArrayList can accept a Collection as noted in the Javadocs:

ArrayList(Collection<? extends E> c)


The last and most inelegent solution is to annotate the methods which use the generic List of Objects to suppress the complier warnings with a @SuppressWarnings("unchecked") annotation.

Java EE5 Persistence Annotations for Web Applications

I am taking the time to create some cliff notes from a wonderful presentation at JavaOne TS-4593 "Guidelines, Tips, and Tricks for Using Java EE5 from Java Blueprints" (Inderjeet Singh, Marina Vatkina, et.al.) and an article in JavaOne Today by Rick Palkovic. When the technical sessions are released to the general public, it would be a good read for any Java EE5 developer.

The problem has to do with thread safety on web applications. If you are using servlets, or a technology based on servlets like JSF, you must consider thread safety for persistence. A common injection is to use the container managed persistence context. This usually takes the following form

@PersistenceContext(unitName="myContext")
private EntityManager em;

The problem is this is NOT thread safe if used in a servlet. A servlet processes many requests and the container handles many requests. Even if you use an injection to get a UserTransaction, it lulls the programmer into a false sense of safety.

In their talk, they mentioned four methods to ensure thread safety on servlet based technologies
  • Use a request-scoped bean Java Server Faces. The life of the bean is a single transaction.
  • Use class level annotations with JNDI lookups
  • Use a @Resource annotation
  • Use the "old style" JNDI InitialContext lookup method
Here is an example of the "old-style" method:

public EntityManager getEntityManager() throws NamingException {
Context ic = new InitialContext();
return (EntityManager) ic.lookup("java:comp/env/EM");
}
Another alternative is to use the @PersistenceUnit annotation to get an EntityManagerFactory. The EntityManagerFactory is a thread-safe object. From the factory we create the EntityManager. This is also thread-safe since it creates a new EntityManager per call.

@PersistenceUnit(unitName="myContextPU")
private EntityManagerFactory emf;

public EntityManager getEntityManager() {
return emf.createEntityManager();
}
These methods should help the developer maintain thread-safety.

Wednesday, May 23, 2007

Netbeans 6.0 Visual Web Pack (Woodstock) - Common Tasks Component

There are some really cool new woodstock components available in the new VWP and from the java.net site. Woodstock is the original code name for the components which are used in VWP. These new components provide a new level of reusable web components which were not available before. One of the new components which is used extensively in project glassfish on the administrative console is the common tasks component.

This component provides a number of visual queues to what a user can do with the component. The component looks like this currently in Netbeans 6.0 M8. The component is not on the visual palette in 6.0 M9 Preview. The component does not necessarily look appealing in the current form on the palette, but renders perfectly.





As you can see from the images this is a really cool idea. The info button "i" allows you to provide additional information about what the task does. You can add a URL for additional information and a separate title for the info that is displayed. Here is an example from project glassfish where you can see another example of its use.



This shows you some of the capabilities.

The trick is how do you use it?

On project glassfish, when you click on the task it directs you to the appropriate category you selected. The details are scarce. So let me give you one solution. Use the actionExpression tag to set an action for the component. Here is mine for the example I showed above

<webuijsf:commontask
actionExpression="#{CommonTasksExample.masterDetailTaskAction}"
binding="#{CommonTasksExample.commonTask1}"
id="commonTask1" infoLinkUrl="/faces/Page3.jsp"
infoText="This example shows how to use a DropDown component to set values in a table" infoTitle="Master-Detail Example"
style="height: 48px; width: 250px" target="_self" text="Master Detail Example"/>

The actionExpression is bound to a method which uses a navigation handler to navigate to the appropriate page.

public String masterDetailTaskAction() {
getApplication().getNavigationHandler().
handleNavigation(FacesContext.getCurrentInstance(), null, "MasterDetail");
return null;
}

This allows me to navigate as required. I hope this example will inspire you to try out the new components. They will add a level of professionalism to your web pages and make your users have a better experience on your site. Implemented fully, it may even avoid a call to the help desk, or you to figure out what a task is supposed to do.

Thursday, March 29, 2007

HSQLDB Database Locking and Shutdown

I have had a number of questions on how to shutdown multiple HSQLDB databases running on one JVM. I have written an example application which will shutdown all of the databases attached to a single database engine in a JVM. The application uses only one test database, but the principal applies to multiple databases.

The software is released under the Apache 2.0 license. The project was developed in Netbeans 5.5

Here is the software: HSQLDBLocking.zip

Here is the source code if you prefer to see it instead of downloading the project:

/*
* TestHSQLDB.java
*
* Created on February 9, 2007, 10:04 PM
*
* $Id: TestHSQLDB.java 12 2007-03-29 21:19:48Z jyeary $
*
*/
/*
* Copyright (C) 2007 Blue Lotus Holdings, LLC. All Rights Reserved.
* Copyright (C) 2007 Blue Lotus Software. All Rights Reserved.
* Copyright (C) 2007 White Lotus Software. All Rights Reserved.
* Copyright (C) 2007 John Yeary. All Rights Reserved.
*
* THIS SOFTWARE IS PROVIDED "AS IS," WITHOUT A WARRANTY OF ANY KIND.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. BLUE LOTUS HOLDINGS, LLC
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
* SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION
* OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
* BLUE LOTUS HOLDINGS, LLC OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE,
* PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE
* THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE,
* EVEN IF BLUE LOTUS HOLDINGS, LLC HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*
* Copyright 2007 John Yeary
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bluelotussoftware.db.hsqldb;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Vector;
import org.hsqldb.DatabaseManager;

/**
*
* @author John Yeary
* @version $Revision: 12 $
*/
public class TestHSQLDB {

/** Creates a new instance of TestHSQLDB */
public TestHSQLDB() {
}

/**
* @param args the command line arguments
*/

public static void main(String args[]) throws Exception {

// Use the class loader to load the JDBC driver
Class.forName("org.hsqldb.jdbcDriver");
Connection connection = DriverManager.getConnection("jdbc:hsqldb:file:test", "sa", "");

// Fetch all of the known database URIs and display them
Vector v = DatabaseManager.getDatabaseURIs();

for (Object o : v) {
System.out.println(((String) o));
}

ResultSet r = connection.createStatement().executeQuery("SELECT * FROM INFORMATION_SCHEMA.SYSTEM_USERS");
r.next();
System.out.println(r.getString(1));

// Shutdown the database normally (0), or shutdown and script out using (2)
DatabaseManager.closeDatabases(0);

connection.close();
}
}

Wednesday, March 28, 2007

JDBC Tips and Tricks

Tip #1

A ResultSet is ALWAYS returned from an executeQuery() method. This often causes issues since developers often try to check to see if the result was null, and it will always return false.

For example:
...
Statement stmt = connection.createStatement();

ResultSet rs = stmt.exeuteQuery("SELECT * FROM X.Y");

// Check for null will be false
If(rs == null) {
//Do something
}
...

To check for results use next(). This will allow you to determine if there are results.

if(rs.next()) {
//Do something
}

Tip #2

Please note that generally a cursor returned by a query only moves forward through the ResultSet unless it is set explicitly. Some databases do not support anything other than forward only cursors. You need to set the cursor explicitly before executing a query.

To set the cursor to a read-only concurrency and scroll insensitive use the following:
...
Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
...

Tip #3

To see native database errors try using Connection.nativeSQL("your query here") in the error messages. This will show you what the database thinks you are asking for.

try {
...
} catch (SQLException e ) {
info("An SQLException occurred. This is the native query sent to the database\n: "
+ con.nativeSQL("SELECT TRUNC(SYSDATE) DATE FROM DUAL"));
}
...

Tip #4

If you use a counter inside your next() method loop you can see how many results were processed, or report if nothing was processed.

...
int counter = 0;
while(rs.next()) {
//Do something
counter++;
}

if (counter == 0) {
System.out.println("No records processed.");
} else {
System.out.println(counter + " records processed.");
}
...

Sunday, March 25, 2007

Sun Java System Application Server 9.x (glassfish) External JNDI LDAP Resource Part III

I have had a question posed to me about how to use this resource once it is setup. Indeed it would be quite limiting without an example. I have created a stateless session bean (SSB) using JEE5 resource injection to show how to use it. It also has @WebService capabilities for testing. Keep in mind that the application has NO security and is merely provided as an example.

Prerequisites:
  • LDAP Server installed and configured
  • Sun Java System Application Server (glassfish) 9.x
  • External JNDI LDAP resource configured

License: Apache 2.0
Package: EJBLDAPModule.zip

This is a Netbeans 6 project.

Thursday, March 15, 2007

Sun Java System Application Server 9.x (glassfish) External JNDI LDAP Resource Part II

In my recent blog entry on configuring an external JNDI LDAP entry, I showed how to connect to an LDAP server as a JNDI reference. This assumes that the LDAP server is on the local machine and that it allows anonymous authentication. Usually this is not the case. I will cover how to use a login to an LDAP server which requires a little more configuration.

Prerequisites:
  • A working LDAP server
  • A login which can browse the directory tree
Instructions:

Please follow the directions in my previous blog entry to set up the basic external JNDI resource. The Sun Java System Application Server 9.1 Administration Guide is incorrect on how to set the properties. It refers to using some properties that are defined for LDAP like PROVIDER-URL. Unfortunately, to use them you would need to prefix them with the appropriate class. So we will use an alternate tack and use them by their fully qualified names. Add the following properties to the entry.

PROVIDER-URL:
java.naming.provider.url

SECURITY_PRINCIPAL:
java.naming.security.principal

SECURITY_AUTHENTICATION:

java.naming.security.authentication

SECURITY_CREDENTIALS:

java.naming.security.credentials

Since we have the fully qualified names, we can use them to set the properties for our external JNDI resource. See the image below.


Once you have the properties set and saved, you will have a complete external JNDI LDAP connection.

Congratulations!

Tuesday, March 06, 2007

Sun Java System Application Server 9.x (glassfish) External JNDI LDAP Resource Part I

I read the SJSAS Administration Guide to determine how to set up an external JNDI Resource. In my case, I wanted to simply provide another method to talk to LDAP outside of the security context. The Administration Guide is helpful...but incorrect. I have included the steps required to connect to an external LDAP server below. This works with OpenLDAP and SunONE Directory Server 5.2. The syntax should be similar on other systems.

Prerequisites:
  • An LDAP server. I use both OpenLDAP and SunONE Directory Server
  • Sun Java System Application Server 9.x (Project Glassfish). I am using Glassfish V2 Build 37
Instructions:

1. Log into the glassfish administration console.
2. Navigate to the Resources --> JNDI --> External Resources tree.


3. Create a new JNDI External Resource (see image below)
  • JNDI Name: pick a unique name for the resource. I prefix mine with ldap e.g. ldap/myldap
  • Resource Type: javax.naming.ldap.LdapContext
  • Factory Class: com.sun.jndi.ldap.LdapCtxFactory
  • JNDI Lookup: this would be your BaseDN e.g. dc=bluelotusholdings,dc=com


4. Check to make sure that the resource was created correctly and that it appears in the server JNDI Browser. If it does, you have configured it correctly. To find the JNDI Browser go to Application Server --> JNDI Browsing.


5. You should see something that looks like the image below. Please note the organizationalUnit (ou) ou=people and ou=groups are displayed as nodes in the BaseDN.


Success!

Sunday, January 28, 2007

LDAP Authentication with Apache Derby (Java DB)

It has come to my attention that there is not a really good tutorial on how to use Apache Derby and LDAP without combining a lot of different sources. Hopefully this will simplify the work for everyone wanting to use LDAP authentication with Apache Derby.

Assumptions:


Procedures:

Global:

If you want to have the configuration set on a global level add the following to a file called derby.properties in the installation directory. You will need to modify it to match your environment.

derby.connection.requireAuthentication=true
derby.authentication.provider=LDAP
derby.authentication.server=ldap://localhost:389
derby.authentication.ldap.searchBase=ou=people,dc=bluelotusholdings,dc=com
derby.database.defaultAccessMode=fullAccess

Database:

You can set the database properties on a database basis. This is accomplished by setting the parameters (database properties) in the database using SQL. The script is located below. This must be modified to accommodate your environment. Place the jndi and ldap files in the directory containing the database (see below). The database in my example is called ldaptest.




/* Apache Derby 10.x */


/*
* This file is used to set the database-wide LDAP configuration. Rebooting the service is
* required for the changes to take effect.
*/

/* Set the authentication provider to LDAP */


CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(
'derby.authentication.provider',
'LDAP')

/* Set the LDAP server */

CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(
'derby.authentication.server',
'banyan:389')

/* Set the BaseDN to search */

CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(
'derby.authentication.ldap.searchBase',
'ou=people,dc=bluelotusholdings,dc=com')

/* Create a cached entry for a user */

CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(
'derby.user.jyeary',
'uid=jyeary,ou=people,dc=bluelotusholdings,dc=com')
Once you have executed the script above, you will need to restart the database. I used my Aqua Studio application to connect to the database.


All Done!

Notes:

  • If LDAP is not available you can not connect to the database.

The Problem of Offline Web Applications - Technology Choices

I have been trying to develop a new application for doing timesheets. We currently use a system which was developed using MS Access and MS Excel combined with access to an Oracle database and a local hsqldb. Needless to say it is messy solution. It was something that was started by a wonderful field engineer that works for my company. As these kinds of projects take on a life of their own, the problems of updating them and ensuring that everyone is using the latest version come up.

Here are some of the issues:
  • Non-object oriented (OO) design
  • No source control
  • No version control
  • No defect management
  • No mechanism to control enhancements
  • MS Access and Excel are binary applications, so there is no clear way to implement source control
  • No clear interfaces
  • Client interaction directly with Oracle
  • On/Off line modes are user controlled
  • Can not move database back end without updating all clients
So I am examining some ideas to make the timesheet application a better design. There are really two options to consider: a web based application, and a standalone Web Start application.

The web based application I have in mind could take form using either a completely server side version using JSF. The other option is to use an embedded database like Java DB in a browser, and submit the final results to a application server. The latter does not have a clearly defined method of updating the application. The idea is based on the demo of Java DB called Java DB-in-a-Browser Demo

The demo is impressive from a number of ways. It shows how to use Java DB, AJAX, Live Connect technology (been around since the days of Netscape and Java integration), applet technologies, and simple HTML. It is truly an enlightening demonstration.

The alternative is to create a rich Swing based application using Java Web Start. These technologies have really matured and combined with the Sun Java System Application Server make a great tool set for any Java developer. The application client using being dispensed from the application server solves a number of problems including simplification of the client. A majority of the business methods are implemented on the server. This leaves the presentation and validation to the client. This combined with Java DB packs a potent punch. It also solves two problems mentioned above: offine use with a mechanism for interaction when a network connection is detected (automatic), and removal of direct interaction with database.

You may believe that I am inclined to use the Swing application client, but I really am impressed with JSF. JSF does require online access to work which may hamper its implementation.

Some technologies to consider:


Here are some interesting articles in the same genre:

Popular Posts