I was recently asked how to use the JDBC-ODBC bridge. I told the person asking that "normally" you would want to use JDBC, and that the Sun developed bridge is not really for production use. I was reminded that there are some old databases out there which only support ODBC connections from Windows.
I wrote a quick example of how to use it which I thought I would share. I had to think about how to do it since it has been so long since I did such a thing. There are two examples of how to connect: one example is a "standard" JDBC connection, and the other takes advantage of the DataSource abstraction.
Note: I created an ODBC connection in Windows to the database called JDBCODBC for this example to work.
Here is the NetBeans code for the project: JavaJDBCODBC.zip
Showing posts with label JDBC. Show all posts
Showing posts with label JDBC. Show all posts
Monday, April 02, 2012
Tuesday, June 24, 2008
Sample QuartzScheduler Job connecting to HSQLDB
I was cleaning up my system and looking at code samples from over the years. I came across an example Job using the Quartz Scheduler to connect to an HSQLDB database and reading the information about the session. I thought I would update it a little and post it.
Requirements:
You must have an HSQLDB database running in server mode.
The Netbeans 6.1 project is located here: HSQLDBQuartzExample.zip
Requirements:
You must have an HSQLDB database running in server mode.
package com.bluelotussoftware.quartz.example;
/*
* HSQLJob.java
*
*/
/*
* Copyright (C) 2008 Blue Lotus Software. 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 SOFTWARE, 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 SOFTWARE, 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 SOFTWARE, 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 2008 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.
*/
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
*
* @author John Yeary
* @version 1.0
*/
public class HSQLJob implements Job {
Connection con;
Statement s;
ResultSet rs;
ResultSetMetaData rsmd;
/** Creates a new instance of HSQLJob */
public HSQLJob() {
}
public void execute(JobExecutionContext context)
throws JobExecutionException {
try {
Class.forName("org.hsqldb.jdbcDriver");
} catch (Exception e) {
System.err.println("ERROR: failed to load HSQLDB JDBC driver.");
e.printStackTrace(System.err);
throw new JobExecutionException("Job Could not continue bacause driver failed to load");
}
System.out.println("Connecting to database...");
try {
// This may need to be changed to match the actual database name
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/glassfish", "sa", "");
} catch (SQLException e) {
throw new JobExecutionException("Failed to connect to HSQLDB Server");
}
try {
String sql = "SELECT * FROM INFORMATION_SCHEMA.SYSTEM_SESSIONINFO";
s = con.createStatement();
rs = s.executeQuery(sql);
rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rsmd.getColumnName(i) + "\t");
}
System.out.println();
while (rs.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rs.getString(i) + "\t");
}
System.out.println();
}
// Clean up the connection
rs.close();
s.close();
con.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
while (e.getNextException() != null) {
System.err.println(e.getMessage());
}
}
}
}
package com.bluelotussoftware.quartz.example;
/*
* QrtzScheduler.java
*
*/
/*
* Copyright (C) 2008 Blue Lotus Software. 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 SOFTWARE, 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 SOFTWARE, 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 SOFTWARE, 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 2008 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.
*/
import java.text.ParseException;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
public class QrtzScheduler {
public static void main(String[] args) {
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler;
try {
scheduler = schedulerFactory.getScheduler();
scheduler.start();
JobDetail job = new JobDetail("hsqldb_example",
scheduler.DEFAULT_GROUP, HSQLJob.class);
CronTrigger cron = new CronTrigger("cron",
scheduler.DEFAULT_GROUP, "0/10 * * * * ?");
scheduler.scheduleJob(job, cron);
} catch (SchedulerException e) {
} catch (ParseException e) {
}
}
}
The Netbeans 6.1 project is located here: HSQLDBQuartzExample.zip
Sunday, February 10, 2008
Book Review: Java EE 5 Development using GlassFish Application Server
Let me start by saying that I am glad that Kshipra Singh, Packt Publishing, contacted me to see if I would review the book. I would also like to note that I am glad that David R. Heffelfinger wrote the book. We need more books on projects like GlassFish.
My overall opinion of the book is good. The book is very well written, and the code examples in the book work. Working code examples are the number one criteria for me. The code examples start with some examples in Chapter 2 that are used throughout the remainder of the book. This provides a coherent flow through the book. You may also download the code examples from the Packt Publishing support site.
I would recommend it as a book to have on your development bookshelf (3/5 stars).
The book claims to be the complete guide to installing and configuring GlassFish. I would not give it that much credit. There is room for more extensive books on GlassFish. There are a number of topics that are very general and have nothing to do with the actual configuration of the server. A better book summary would be a guide to installing, configuring, and developing applications for the Glassfish server. It is really a Java EE 5 tutorial which features Glassfish.
As a book on GlassFish, it is very light in its coverage. As a tutorial for developers acquainting themselves with Java EE 5 and deployment on Glassfish it is very good. In my opinion it is targeted at developers familiar with J2EE who want to switch to JEE5, or junior developers trying to get a better comprehension of the EE environment. It is not for novice programmers.
Chapter 1
Getting Started with GlassFish
This chapter covers getting and installing GlassFish. It is very basic, but will get you up and running. It also includes how to set up your JNDI database connections. The majority of this information can be readily found on the GlassFish site on Java.net. There is a good example of how to set up multiple domains on GlassFish which is not easily gleaned from the site. There is a chart which shows how the --portbase command line option is used to set the ports on which GlassFish services connections. This provides the best explanation for this command line option and graphically depicts what the results are.
Chapter 2
Servlet Development and Deployment
This chapter is a very basic tutorial on servlet technology. It includes writing a simple servlets, web.xml files, and deployment file layout (war files). It includes some examples on html forms, request forwarding and response re-direction. There is nothing GlassFish specific and the files will just as easily deploy on Apache Tomcat unaltered. There is one item of note which is sun-web.xml related which has to do with how to change the context root. This is used if you do not want the default deployment context to match the name of the war file.
Chapter 3
JavaServer Pages
This chapter again has a basic tutorial on JSP technologies. There is a really good example of creating custom JSP tags and how to use them. Again, there is nothing that would prevent the war files from being deployed on Apache Tomcat. I wish that the author would have covered Unified Expression Language (EL) in more detail. It is more central to this technology on JEE5 platforms.
Chapter 4
Database Connectivity
This is the first chapter which covers a really important topic in the enhanced JEE5 database access functionality, new Java Persistence API (JPA), and its reference application server (GlassFish). The first example shows a servlet and how to connect to a database using the old form of JNDI lookup without resource injection. The next example shows the simplified version using resource injection of the DataSource. This removes all the plumbing of fetching our data source.
The next section covers Java Persistence API (JPA) and provides an in-depth tutorial. This is a key concept in JEE5. It introduces the Entity annotation on a POJO to convert it to a persistable object. The simple example that follows it demonstrates correctly how to to use JPA in a non-thread safe environment of a servlet using a UserTransaction. It also covers the persistence.xml file.
This chapter is a must for anyone who wants to learn JPA. The sections on entity relationships, and composite primary keys are done extremely well.
This chapter concludes on Java Persistence Query Language (JPQL) which is the follow-on from EJB QL.It is very light. I wish the author would have covered this very important topic in more detail. That being stated, the code sample is a perfect example.
The book is worth purchasing for this chapter alone.
Chapter 5
JSP Standard Tag Library
This chapter is a basic tutorial on the JSTL. I found a number of syntax mistakes, which were submitted back to Packt. The SQL JST Tag Library is covered. It was very simple. There is one note on No Suitable Driver SQL Exception which is often a hard thing to track down.There is nothing substantive about this chapter.
Chapter 6
JavaServer Faces
This is another JEE5 technology that needs more coverage in general. This chapter provides a good foundation on the reference JSF implementation. It is very well written. I am a big advocate of JSF and thoroughly examined this chapter.
The introductory examples are well done and give a good overview of the technology. The example Customer bean is the same bean that is used in JPA in chapter 4. This shows the consistency and flow between chapters. In this case we use the bean as a managed bean in the JSF context.
The chapter also explains the changes needed in the web.xml file for JSF.
The section on validators is very well done. It includes an example using the Apache Commons Validator framework. The point is to show that you should look for good validators rather than creating your own. Roll your own for domain specific requirements. It also covers validator methods in some detail. It also covers another useful utility from the Apache Commons Language Library.
There is a section on customizing messages that provide feedback to the user on various validation errors. It contains a section on how to modify the default messages on GlassFish. It is nice to know how to do this, but I would encourage users NOT to do it. You can Google for the default messages to see what they mean. If you change them, that option no longer exists. Also it is not intuitively obvious where the message is coming from. There is another example using a message bundle for your customized messages. I would HIGHLY recommend using this method.
There is a wonderful section on integrating JPA and JSF. This is a must read, and covers the practical side of JSF and JPA. It uses a model-view-controller paradigm. It shows how to use the JPA as a managed bean that gets set from the JSF page and saved/modified from the controller servlet. This is an excellent example of how to do it.
Finally, the chapter closes with a reference to the JSF Core components. I personally believe that this should have been an appendix. It really does not contribute to the flow of the book, or chapter. I went through the reference with a fine-toothed comb. The examples are really clean. I submitted some errata for the section, but it was done very well.
This is another chapter that makes the book worth purchasing.
Chapter 7
Java Messaging Service
This is a chapter that has a very specific setup for GlassFish. Most of the previous chapters were general enough on the specific technologies that they could be used on Apache Tomcat. The JMS server setup which is covered for GlassFish is very specific to the server.
The first part of the chapter covers how to set up the JMS connection factory, and JMS destination resources (Queue and Topic).
The examples that follow are very well done on how to use the various topics and queues.
I was really impressed with the authors examples. They were clean. I questioned one of the examples on durable topics, only to discover that the author was correct.
Chapter 8
Security
This chapter seems out of sequence. The Enterprise Java Beans (EJB) and Web Services chapters follow it. I would have recommended it to follow those two chapters. The author does cover securing EJBs and web services which require a security pre-cursor, but it seems to disrupt the flow of the book.
This chapter was a big disappointment. The topic is covered in minimal detail. This chapter is so important that it needs more coverage.
Here are some of the major omissions:
The JDBC realm is complex. I understand that setting up a JDBC realm requires more work, but I am not sure how many people would use this type of realm.
The file realm coverage is detailed, but I am not sure that any enterprise would use this arrangement. It is not scalable.
The example login form using j_security_check is very useful, as well as, the example LogoutServlet.
The certificate realm is covered in fine detail. It is one of the best examples of how to configure this setup.
The LDAP and Solaris realms are weak. There is nothing here but a placeholder explanation. I can imagine that most enterprise users will have an LDAP domain that they will connect to. This topic could have included an example using OpenLDAP with its configuration in an appendix, or using openDS.
The JDBC realm setup has a number of serious errors which were reported as errata.
The section on defining custom realms is ok. It glosses a topic which requires more detail. I would HIGHLY recommend using a pre-defined realm instead of defining your own.
Chapter 9
Enterprise JavaBeans
This chapter provides a good tutorial on the JEE5 EJB 3.0 technologies. It covers the use of the new @Stateless, @Stateful, and @MessageDriven bean annotations.
There is an excellent example of using a stateless session bean as the Data Access Object (DAO) controller for JPA. It is well done. This is followed by another excellent example of how to use DAO EJB in a web application using resource injection.
Transactions are covered in very good detail. There is an excellent table which explains the various types of container managed transactions, and the @TransactionAttribute annotation.
The real jewel of this chapter, in my opinion, is the section on Bean-Managed Transactions which includes an excellent example with all of the correct annotations.
There is a section on the new EJB Timer service. I wish they would have included a practical example, but the included example gives you a feel on how it works.
EJB Security is covered lightly. There is a great note about automatically matching Roles to Security Groups on GlassFish. It is a very well hidden feature, and one which I was not aware of. This simplifies some of the security mapping and is a great time saver.
This is another good chapter.
Chapter 10
Web Services
This chapter provides a good tutorial on Java API for XML for Web Services (JAX-WS). It has some simple examples, and demonstrates the great GlassFish web service testing facility built into the platform. The tester is a web based page which allows you to enter values and see the results, as well as, the SOAP messages (Request and Response). This is a real time saver and can help a developer check the expected messages quickly.
The chapter includes a section on how to include attachments and expose EJBs as web services.
The chapter concludes on a light coverage of web service security.
Chapter 11
Beyond Java EE
This chapter covers some alternative and complementary technologies for JSF like Facelets, Facelets Templating, Ajax4jsf (providing AJAX functionality to JSF applications), and Seam. The chapter includes some sample applications and how to install and set up these technologies.
Appendices
The appendices include coverage of using JavaMail and integrating GlassFish into various IDEs.
Again, I would recommend this book for anyone who wants to learn the basics of JEE5 programming with GlassFish.
My overall opinion of the book is good. The book is very well written, and the code examples in the book work. Working code examples are the number one criteria for me. The code examples start with some examples in Chapter 2 that are used throughout the remainder of the book. This provides a coherent flow through the book. You may also download the code examples from the Packt Publishing support site.
I would recommend it as a book to have on your development bookshelf (3/5 stars).
The book claims to be the complete guide to installing and configuring GlassFish. I would not give it that much credit. There is room for more extensive books on GlassFish. There are a number of topics that are very general and have nothing to do with the actual configuration of the server. A better book summary would be a guide to installing, configuring, and developing applications for the Glassfish server. It is really a Java EE 5 tutorial which features Glassfish.
As a book on GlassFish, it is very light in its coverage. As a tutorial for developers acquainting themselves with Java EE 5 and deployment on Glassfish it is very good. In my opinion it is targeted at developers familiar with J2EE who want to switch to JEE5, or junior developers trying to get a better comprehension of the EE environment. It is not for novice programmers.
Chapter 1
Getting Started with GlassFish
This chapter covers getting and installing GlassFish. It is very basic, but will get you up and running. It also includes how to set up your JNDI database connections. The majority of this information can be readily found on the GlassFish site on Java.net. There is a good example of how to set up multiple domains on GlassFish which is not easily gleaned from the site. There is a chart which shows how the --portbase command line option is used to set the ports on which GlassFish services connections. This provides the best explanation for this command line option and graphically depicts what the results are.
Chapter 2
Servlet Development and Deployment
This chapter is a very basic tutorial on servlet technology. It includes writing a simple servlets, web.xml files, and deployment file layout (war files). It includes some examples on html forms, request forwarding and response re-direction. There is nothing GlassFish specific and the files will just as easily deploy on Apache Tomcat unaltered. There is one item of note which is sun-web.xml related which has to do with how to change the context root. This is used if you do not want the default deployment context to match the name of the war file.
Chapter 3
JavaServer Pages
This chapter again has a basic tutorial on JSP technologies. There is a really good example of creating custom JSP tags and how to use them. Again, there is nothing that would prevent the war files from being deployed on Apache Tomcat. I wish that the author would have covered Unified Expression Language (EL) in more detail. It is more central to this technology on JEE5 platforms.
Chapter 4
Database Connectivity
This is the first chapter which covers a really important topic in the enhanced JEE5 database access functionality, new Java Persistence API (JPA), and its reference application server (GlassFish). The first example shows a servlet and how to connect to a database using the old form of JNDI lookup without resource injection. The next example shows the simplified version using resource injection of the DataSource. This removes all the plumbing of fetching our data source.
The next section covers Java Persistence API (JPA) and provides an in-depth tutorial. This is a key concept in JEE5. It introduces the Entity annotation on a POJO to convert it to a persistable object. The simple example that follows it demonstrates correctly how to to use JPA in a non-thread safe environment of a servlet using a UserTransaction. It also covers the persistence.xml file.
This chapter is a must for anyone who wants to learn JPA. The sections on entity relationships, and composite primary keys are done extremely well.
This chapter concludes on Java Persistence Query Language (JPQL) which is the follow-on from EJB QL.It is very light. I wish the author would have covered this very important topic in more detail. That being stated, the code sample is a perfect example.
The book is worth purchasing for this chapter alone.
Chapter 5
JSP Standard Tag Library
This chapter is a basic tutorial on the JSTL. I found a number of syntax mistakes, which were submitted back to Packt. The SQL JST Tag Library is covered. It was very simple. There is one note on No Suitable Driver SQL Exception which is often a hard thing to track down.There is nothing substantive about this chapter.
Chapter 6
JavaServer Faces
This is another JEE5 technology that needs more coverage in general. This chapter provides a good foundation on the reference JSF implementation. It is very well written. I am a big advocate of JSF and thoroughly examined this chapter.
The introductory examples are well done and give a good overview of the technology. The example Customer bean is the same bean that is used in JPA in chapter 4. This shows the consistency and flow between chapters. In this case we use the bean as a managed bean in the JSF context.
The chapter also explains the changes needed in the web.xml file for JSF.
The section on validators is very well done. It includes an example using the Apache Commons Validator framework. The point is to show that you should look for good validators rather than creating your own. Roll your own for domain specific requirements. It also covers validator methods in some detail. It also covers another useful utility from the Apache Commons Language Library.
There is a section on customizing messages that provide feedback to the user on various validation errors. It contains a section on how to modify the default messages on GlassFish. It is nice to know how to do this, but I would encourage users NOT to do it. You can Google for the default messages to see what they mean. If you change them, that option no longer exists. Also it is not intuitively obvious where the message is coming from. There is another example using a message bundle for your customized messages. I would HIGHLY recommend using this method.
There is a wonderful section on integrating JPA and JSF. This is a must read, and covers the practical side of JSF and JPA. It uses a model-view-controller paradigm. It shows how to use the JPA as a managed bean that gets set from the JSF page and saved/modified from the controller servlet. This is an excellent example of how to do it.
Finally, the chapter closes with a reference to the JSF Core components. I personally believe that this should have been an appendix. It really does not contribute to the flow of the book, or chapter. I went through the reference with a fine-toothed comb. The examples are really clean. I submitted some errata for the section, but it was done very well.
This is another chapter that makes the book worth purchasing.
Chapter 7
Java Messaging Service
This is a chapter that has a very specific setup for GlassFish. Most of the previous chapters were general enough on the specific technologies that they could be used on Apache Tomcat. The JMS server setup which is covered for GlassFish is very specific to the server.
The first part of the chapter covers how to set up the JMS connection factory, and JMS destination resources (Queue and Topic).
The examples that follow are very well done on how to use the various topics and queues.
I was really impressed with the authors examples. They were clean. I questioned one of the examples on durable topics, only to discover that the author was correct.
Chapter 8
Security
This chapter seems out of sequence. The Enterprise Java Beans (EJB) and Web Services chapters follow it. I would have recommended it to follow those two chapters. The author does cover securing EJBs and web services which require a security pre-cursor, but it seems to disrupt the flow of the book.
This chapter was a big disappointment. The topic is covered in minimal detail. This chapter is so important that it needs more coverage.
Here are some of the major omissions:
- Setting up a SSL/TLS connection using a self-signed certificate, or CA certificate
- Setting up an LDAP realm
- Optional attributes for the various realms
The JDBC realm is complex. I understand that setting up a JDBC realm requires more work, but I am not sure how many people would use this type of realm.
The file realm coverage is detailed, but I am not sure that any enterprise would use this arrangement. It is not scalable.
The example login form using j_security_check is very useful, as well as, the example LogoutServlet.
The certificate realm is covered in fine detail. It is one of the best examples of how to configure this setup.
The LDAP and Solaris realms are weak. There is nothing here but a placeholder explanation. I can imagine that most enterprise users will have an LDAP domain that they will connect to. This topic could have included an example using OpenLDAP with its configuration in an appendix, or using openDS.
The JDBC realm setup has a number of serious errors which were reported as errata.
The section on defining custom realms is ok. It glosses a topic which requires more detail. I would HIGHLY recommend using a pre-defined realm instead of defining your own.
Chapter 9
Enterprise JavaBeans
This chapter provides a good tutorial on the JEE5 EJB 3.0 technologies. It covers the use of the new @Stateless, @Stateful, and @MessageDriven bean annotations.
There is an excellent example of using a stateless session bean as the Data Access Object (DAO) controller for JPA. It is well done. This is followed by another excellent example of how to use DAO EJB in a web application using resource injection.
Transactions are covered in very good detail. There is an excellent table which explains the various types of container managed transactions, and the @TransactionAttribute annotation.
The real jewel of this chapter, in my opinion, is the section on Bean-Managed Transactions which includes an excellent example with all of the correct annotations.
There is a section on the new EJB Timer service. I wish they would have included a practical example, but the included example gives you a feel on how it works.
EJB Security is covered lightly. There is a great note about automatically matching Roles to Security Groups on GlassFish. It is a very well hidden feature, and one which I was not aware of. This simplifies some of the security mapping and is a great time saver.
This is another good chapter.
Chapter 10
Web Services
This chapter provides a good tutorial on Java API for XML for Web Services (JAX-WS). It has some simple examples, and demonstrates the great GlassFish web service testing facility built into the platform. The tester is a web based page which allows you to enter values and see the results, as well as, the SOAP messages (Request and Response). This is a real time saver and can help a developer check the expected messages quickly.
The chapter includes a section on how to include attachments and expose EJBs as web services.
The chapter concludes on a light coverage of web service security.
Chapter 11
Beyond Java EE
This chapter covers some alternative and complementary technologies for JSF like Facelets, Facelets Templating, Ajax4jsf (providing AJAX functionality to JSF applications), and Seam. The chapter includes some sample applications and how to install and set up these technologies.
Appendices
The appendices include coverage of using JavaMail and integrating GlassFish into various IDEs.
Again, I would recommend this book for anyone who wants to learn the basics of JEE5 programming with GlassFish.
Labels:
books
,
glassfish
,
JDBC
,
JEE5
,
JNDI
,
JSF
,
Persistence
,
Programming
,
SJSAS
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)
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)
Labels:
Apache Derby
,
books
,
Java
,
JavaDB
,
JDBC
,
JSE6
,
Programming
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.");
}
...
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.");
}
...
Labels:
JDBC
,
Programming
Subscribe to:
Comments
(
Atom
)
Popular Posts
-
Introduction This article is not another diatribe to tell you the importance of unit testing. I think we can all agree that it is important...
-
A friend of mine asked me if there was a list of reserved words in EL and JSF. He had previously looked for it, and after some Google search...
-
I saw a question posed on stackoverflow called Trouble with Primefaces 3.0.M2 SelectOneMenu Ajax behavior and I had just done an example a...
-
I was working on a couple of SSL based issues when I made a couple of observations. The default self-signed key generation in Java does not ...
-
This is an example on how to make a system call to the local operating system to execute external programs. This example was written to work...
-
We have been doing a lot of work lately with PrimeFaces. A common set of questions comes up about displaying <p:dialog/> boxes on a pa...
-
I was asked earlier today how to reset fields in a JSF application, if the validation fails. In his case, he had a Richfaces table which had...
-
Previously, I posted an example of how to use JSF 1.2 with form based authentication (j_security_check). In this example, I use JSF 2.x to...
-
Image by quasarkitten via Flickr The basics for creating a Maven archetype can be found in the Maven - Guide to Creating Archetypes . The ...
-
Abstract A common use case is to iterate over a collection of elements, and display them on a page. In the world of JSP, we would use a Ja...