Sunday, 9 August 2009

Create and use an oracle connection pool in Tomcat 6.xx

NOTE: this post is in fact a translation and a shorter version of post that I wrote on my other blog ( www.baze-podataka.net ). It is translated using Google translate tool and than slightly modified by me. So, if you have any complaints, please complain to Google ;-)

Creating a connection pool is a very good practice when developing applications that often connect to the database because it is much "cheaper" to use one of the already created connections, then to repeat the entire process of Connecting to the database every time we need a connection.
It’s such a good practice that many application servers already have their own implementation of connection pooling.

Such server is Tomcat.

All that is left for us to do, of course, is to set all the properties of server that we need to use, and to provide the appropriate drivers that work with a specific database.
Then, if necessary, just take the connection from the pool, and use it, but take care of their proper use.

In this post, I will set Tomcat 6.0.18.
A database for which I’ll create a connection pool is Oracle 10g.

There’s a lot of tutorials, texts and examples about this on the Internet, but very often related to older versions of Tomcat (ver. 4, 5, 5.5).
Unfortunately, for all of these earlier versions of Tomcat many specifications and settings are different, so it probably won’t work with version 6.xx. At least that was the case with me.

So, let’s create an oracle connection pool!

Prerequisites:
First thing you need to have is , of course, Tomcat.
You can download it following this link.
If you use NetBeans to write a code, as I do, you can use Tomcat that comes bundled with the installation of the IDE itself.

Next, we need the appropriate JDBC drivers for Oracle 10g. This means you need an ojdbc14.jar file that comes within the Oracle itself.

Copy this file to <Tomcat home dir>/lib/ folder.

And, of course, we need a database installed too.
Check whether the database you wish to use is available and whether you can connect to it.

create a connection pool

Creating the pool is a quite fast and easy job.
For example, if your application context path is /myapp , it is necessary for you to:

1. Edit the context.xml file, which is located within the META-INF folder of your project like this:

<?xml version=”1.0? encoding=”UTF-8??>
<Context path=”/myapp” docBase=”myapp” reloadable=”false”>
<Resource name=”jdbc/oracleconnection” auth=”Container”
type=”javax.sql.DataSource” username=”existing_username” password=”user_password”
driverClassName=”oracle.jdbc.driver.OracleDriver” url=”jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521:sid”
maxActive=”10? maxIdle=”5?/>
</Context>


By setting these parameters you determine how this pool will “look” like.
Visit Tomcat’s website for a list of all available parameters.

2. In the web.xml file of your application, you need to insert:

<resource-ref>
<res-ref-name>jdbc/oracleconnection</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
inside tags <web-app> and </web-app>

And that's it!
Of course, this is not the only way to create connection pool in Tomcat-6, but it is quite simple, don't you think?

Hot to use connections within our web applications

Using connection pool’s connections within our web applications is as easy as creating the pool itself.

In Java EE, DataSource objects are obtained using the JNDI lookup mechanism.
All you need to do to get a connection is something like this:

Connection connection = null;
InitCtx context = new InitialContext ();
EnvCtx context = (Context) initCtx.lookup ( "java:comp/ENV");
DataSource ds = (DataSource) envCtx.lookup ("JDBC/oracleconnection");
connection = ds.getConnection ();

and that’s it.

If you are interested in learning more about connection pool, and the best ways of using it, I suggest you to visit my earlier post , and read the 11th chapter of the book I wrote about...

Wednesday, 29 July 2009

Eclipse Galileo and Struts2

I was quite surprised with how many people came to my blog and read my earlier post on how to create a blank Struts2 project and start using this framework in NetBeans 6.5

With a release of new Eclipse, I thought it would be interesting to do the same thing, but now in this IDE.
As you probably already know, Eclipse is one of the famous and certainly one of the best Java IDEs.
Well, about a month ago people from Eclipse foundation released a 3.5 version of Eclipse, called Galileo.

I develop almost all my project using NetBeans, and have never done any Struts2 programming using Eclipse.
That is why I decided to write a post on how to create a Struts2 example in new Eclipse release: Galileo. That's quite fun because that way I (we) get to learn on how to use Struts2 in Eclipse, and get to see Galileo in action a little bit closer…

Note: In this post, I’ll use much of the text , entire source code and application logic from my previous post and concetrate only on the differences between these two IDEs.


So, let’s get started:

First of all we need Eclipse Galileo. Go to the http://www.eclipse.org/downloads/ and download Eclipse IDE for Java EE Developers.

Next thing we need is Struts2 itself. Go to http://struts.apache.org/2.x/index.html and download the latest version of Struts2.
I downloaded struts-2.1.6-all.zip
You won't be needing all the libraries in it. Just 6 of them. Because of this, you can download essential dependencies only.

When you download one of these archives, extract it to some location, for example: c:\Struts2

It is now time to start a new project. Start Eclipse Galileo.


Click file --> new --> Dynamic web project



Let’s call this project GalileoStruts2Example
I’ll use Tomcat 6 . You can use some other server that you have available , it is completely up to you.






Click Finish.

Your project tree will look like this:







Now, in order to use Struts2 libraries, let's add those essential dependencies to project:

Right-click on the project --> properties --> Java Build Path , select Libraries tab and click on the “Add External JARs” button.

Go to folder where you extracted Struts2 libraries and select ( add to project ) following files:

- struts2-core-2.1.6.jar
- freemarker-2.3.13.jar
- ognl-2.6.11.jar
- commons-fileupload-1.2.1.jar
- commons-logging-1.0.4.jar
- xwork-2.1.2.jar


Most of the tutorials on the web are written for older version of struts2, at the time when commons-fileupload-1.2.1.jar was not mandatory, so even when following all the steps in tutorial , you just couldn't get your project to work ( with newer version of Struts2 ) !

Now, your project will look like this:



Now, copy these six JARs into the “lib” folder located in the root of WEB-INF folder.






These files will be uploaded to App Server , and a deployed application will use it.
We could put this files into main lib folder of application server, but it is most probably better this way...

We need to create one more folder in the root of the WEB-INF , and name it "classes".
This is where you will create struts.xml, and if needed - a struts.properties file.

I'll put all my JSP's into new folder, "jsp" , which I will create in the root of "WebContent" folder.

All Java code that we write, we will place into some package in the "Java Resources: src" folder.
I'll create one now, called "struts2Example" and a "Hello" Class in it.
If you use validaton, put all Validation XMLs inside class's package too...






This is how, at minimum, your Struts2 project structure should look like.


I'll create one small Struts2 application now. Nothing complicated.
User will enter his name, and press "submit" and other page will open , saying Hello to this user.

So, let's first create a Java class extending ActionSupport class , named Hello, inside Struts2Example package.
Let's make it to look something like this:

package struts2Example;
import com.opensymphony.xwork2.ActionSupport;


public class Hello extends ActionSupport
{
private String name, message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return "Hello " + getName();
}
public void setMessage(String message) {
this.message = message;
}
}

We now need two JSPs, for example "nameinput.jsp" and a "response.jsp"
Each JSP needs to contain this line, in order to use struts2 custom tags in it:

<%@ taglib prefix="s" uri="/struts-tags" %>

nameinput.jsp:


response.jsp:



Let's create an XML validation file for Hello class, and make a name property mandatory.

Hello-validation.xml:

<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
<field name="name">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>Please enter name</message>
</field-validator>
</field>
</validators>


Let’s see how our project tree looks at this stage:



There's only 2 things left for us to do:

Edit struts.xml, and web.xml:

struts.xml must be located in “classes” folder located in the root of WEB-INF folder:






This is where place a file struts.properties if we need to use it, as well…

web.xml:






And if we press “Run” button, and choose a server on which it is supposed to run




we’ll get something looking like this:




But don't worry. Everything is OK, we just didin't handle default page...
If we append entername.action on the URL , our new application will open:


If we do not enter name and press “submit”:



but if we do enter name and press “Submit”:



So, I hope I helped you to understand how to create an empty struts2 project in Eclipse Galileo.

At the end, our project looked like this:





A small conclusion of mine: great thing about Eclipse is that you can do just about everything with it , with just a little few extra settings and installations...
Unfortunately, for me - many things and options remained a little bit more complicated and unintuitive regarding to some other IDEs. That is such a shame!
Nevertheless , for me , Eclipse continues to be one of the best choices!.

Enjoy Struts2 and Galileo!


Thursday, 9 July 2009

How to create Struts2 project in NetBeans

If you decide to start learning and using struts2, probably one of the first things you think about is which IDE to use, and what you need in order to create and run a Struts2 project...

If you search the web , you'll find many tutorials on how to create a struts2 project, and start developing.
This is what I did when I was starting, and soon find out that nothing I found on the web worked for me in proper manner...

So, I decided to create a small tutorial on how to create an empty struts2 project , in order to help others, and save their time.
Not to teach you Struts2, but to help you create a working Struts2 project!

Ok, I will use NetBeans 6.5, and a Tomcat 6 that comes with it...

First of all, go to http://struts.apache.org/2.x/index.html and download the latest version of Struts2.
I downloaded struts-2.1.6-all.zip
You won't be needing all the libraries in it. Just 6 of them. Because of this, you can download essential dependencies only.

When you download one of these files, extract it to some location, for example: c:\Struts2
It is now time to start a new project. Start NetBeans.

Click File -> New project -> Java web -> Web application



Let's name our project "Struts2Example". Click "next".
Choose which server you wish to use ( I selected Tomcat 6 ), set JavaEE to version 5, and leave ContextPath to be /Struts2Example

You can click "finish" now.
If you click "next" DO NOT, I repeat DO NOT choose available ( older version ) of struts under "frameworks".

Your project tree will look this:




Now, in order to use Struts2 libraries, let's add those essential dependencies to project:

Right click on "Libraries" folder and then click "Add JAR/folder". A dialog will open.
Go to folder where you extracted Struts2 libraries and select ( add to project ) following files:

- struts2-core-2.1.6.jar
- freemarker-2.3.13.jar
- ognl-2.6.11.jar
- commons-fileupload-1.2.1.jar
- commons-logging-1.0.4.jar
- xwork-2.1.2.jar


Most of the tutorials on the web are written for older version of struts2, at the time when commons-fileupload-1.2.1.jar was not mandatory, so even when following all the steps in tutorial , you just couldn't get your project to work ( with newer version of Struts2 ) !

Now, your project will loke like this:



Now, in the root of WEB-INF folder create a new folder , and name it "lib".
Copy these six JARs into this new folder.




These files will be uploaded to App Server , and a deployed application will use it.
We could put this files into main lib folder of application server, but it is most probably better this way...

We need to create one more folder in the root of the WEB-INF , and name it "classes".
This is where you will create struts.xml, and if needed - a struts.properties file.




I'll put all my JSP's into new folder, "jsp" , which I will create in the root of "Web Pages" folder.

All Java code that we write, we will place into some package in the "Source Packages" folder.
I'll create one now, called "Struts2Example" and a "Hello" Class in it.
If you use validaton, put all Validation XMLs inside class's package too...




This is how, at minimum, your Struts2 project structure should look like.


I'll create one small Struts2 application now. Nothing complicated.
User will enter his name, and press "submit" and other page will open , saying Hello to this user.

So, let's first create a Java class extending ActionSupport class , named hello, inside Struts2Example package.
Let's make it to look something like this:

package Struts2Example;

import com.opensymphony.xwork2.ActionSupport;

/**
*
* @author Darko
*/
public class Hello extends ActionSupport
{
private String name, message;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getMessage() {
return "Hello " + getName();
}

public void setMessage(String message) {
this.message = message;
}

}

We now need two JSPs, for example "nameinput.jsp" and a "response.jsp"
Each JSP needs to contain this line, in order to use struts2 custom tags in it:

<%@ taglib prefix="s" uri="/struts-tags" %>

nameinput.jsp:



response.jsp:



Let's create an XML validation file for Hello class, and make a name property mandatory.
Hello-validation.xml:

<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
<field name="name">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>Please enter name</message>
</field-validator>
</field>
</validators>

There's only 2 things left for us to do:

Edit struts.xml, and web.xml:


struts.xml:


web.xml:


and if you deploy this project to server, and open
http://localhost:8084/Struts2Example/entername.action , you'll get something like this:



If we do not enter name:



and if we do:



So, I hope I helped you to understand how to create an empty struts2 project in NetBeans.
At the end, our project looked like this:





There's more to it. For example, if you wish to override some theme's behaviour ( for example "simple" ) you create folders
template/theme_name ( for example template/simple ) and it you copy all the original files from this theme ( from struts2-core-X.X.X.jar ) and edit them in this folder...



But, some other time about that and some other usefull things...

Enjoy Struts2!

Tuesday, 30 June 2009

Od sada i na baze-podataka.net

Od prije malo više od nedjelju dana, moje tekstove možete pratiti i na www.baze-podataka.net

Radi se o jednom od mojih omiljenih sajtova koji svakodnevno posjećujem gotovo još od njegovog osnivanja, i lično - smatram da se radi o najkvalitetnijem domaćem sajtu na temu baza podataka, zbog čega mi je bila velika čast prihvatiti poziv Dejana Topalovića da budem jedan od autora.

Nažalost, sve se desilo u periodu kada sam jako opterećen obavezama na poslu, pa za sada novih postova od mene nema, već sam samo, na Dejanov predlog, prenio jedan od tekstova sa devtalks.blogspot.com



O sajtu

Ko nije upoznat, baze-podataka.net je blog posvećen temama o bazama podataka , kako sa administratorske tako i sa programerske strane.
Smatram da bi svako ko se bavi pomenutim poslom trebao ovaj sajt sačuvati pod svoje bookmarks-e , jer će sigurno uživati u tekstovima i naučiti nešto novo.



Radujem se našem budućem druženju (i) na baze-podataka.net !

Wednesday, 17 June 2009

Struts 2 Design and Programming: A Tutorial ( Book recommendation )

There's one more book that I would like to recommend to you.
It is called, well I assume you've already guessed, Struts 2 Design and Programming: A Tutorial.



If you'd like to learn Struts2 framework, then I think this is a good place for you to start!

It is written for beginners who'd like to learn Struts2, but pros could also use it to refresh their memory on how some things could and should be done.

What thrilled me most when reading this book was the fact it was written exactly as I would like it to be...

Everything is explained very well, and there are a lot of useful examples...


You'll learn about MVC design pattern, struts2 tags, interceptors, input validations , type conversions, ajax in struts2 , tiles ,  some Tomcat settings, DAO design patterns and alot more...

I really enjoyed reading it.

Blackboard designer :-)

Ovaj tekst niti je interesantan, niti će iko išta naučiti iz njega ili mu biti koristan, već sam ga napisao da bih ispravio sam sebe.

Neki dan sam počeo sa dizajnom novog modula koji bi koristio bazu podataka, te uzeh da nacrtam ER dijagram kako bi baza za njega izgledala...

U sred crtanja dijagrama za novu bazu sam se sjetio teme koja je nedavno pokrenuta na www.baze-podataka.net o tome u čemu crtamo ER dijagrame.

Tada sam napisao da koristim Oracle designer.

Ne bi ni meni bio ništa interesatno, da sebe nisam uhvatio kako sam za crtanje dijagrama ipak prvo koristio dobri stari Blackboard designer, kojeg sam zaboravio navesti :-)

Dobro, kada završim dijagram ipak ću sve prenijeti u Oracle designer jer je malo teže iz Blackboard designer-a izgenerisati bazu, a nigdje nisam ni na internetu našao kako ovo uraditi automatizovano :-)

Monday, 25 May 2009

SQL Developer , nebrušeni dijamant

Obožavam maj.
To je mjesec kada se u Crnoj Gori najviše praznuje.
Prvo dođe 1. maj pa onda i 21. maj , prije toga u aprilu i uskrs
i ako se “poklopi” da ovi dani padaju u četvrtak – petak , tu ukupno bude fin broj dana za odmaranje.

To je razlog što me dugo nije bilo sa novim tekstom. Praznovalo se, što ću :-)

Ako se ovome doda da sam u maju bio još i na ( zasluženom ) odmoru od ogromnog i iscrpljujućeg projekta – mogu reći da mi je ovaj maj bio poseban... :-)

Međutim, majski praznični dani su u Crnoj Gori, na žalost, završeni :-(
Ali nije ni to loše. Ja sam jedan od onih koji obožavaju svoj posao.
A tu su i novi tekstovi na devtalks-u …

Prije neki dan mi pade na pamet jedan duži tekst koji sam posvetio recenziji IDE-ova za rad sa Oracle-om, pisanju koda u PL/SQL-u, upita u SQL-u i slično, a koji nikada nisam objavio.
Dakle, o alatima koji su u ponudi na tržištu, i moje impresije o istima.
Konkretno – radi se o “PLSQL Developer”-u , “Toad”-u , “SQL Developer”-u i “SQL Manager 2007 Lite for Oracle”.
Ja u principu nisam baš totalno zadovoljan alatima ove vrste za rad sa Oracle-om i ovo je upravo jedna kategorija IDE-a koje sam vrlo često mjenjao tokom rada sa pomenutom bazom ne bih li našao nešto što mi u potpunosti odgovara.

Ovdje ću prenijeti samo dio teksta, i to onaj koji je posvećen Oracle-ovom SQLDeveloper-u.

Dakle, ovako sam tada opisao ovaj alat:


SQL Developer



Ako pričamo o konkurenciji Toad-u, onda moramo na prvo mjesto staviti program koji nam dolazi pravo iz Oracle-a a koji je ranije bio poznat pod nazivom Raptor: SQL Developer.
Zaista svjetlo na kraju tunela, i pravo osvježenje!



Ovo je nešto što, po meni, najviše liči na jedan pravi alat za rad sa bazom podataka i razvoj aplikacija, kada je u pitanju Oracle.
To što je pisan u Javi je u jednoj mjeri dobra stvar, a u najvećoj mjeri jako loša.
Upravo je moja najveća zamjerka kod ovog programa uperena ka njegovoj brzini. Ustvari ne ka brzini izvršavanja naredbi toliko - koliko na brzinu renderovanja njegovog izgleda i brzinu jave u domenu GUI-ja inače.
Znamo da Java baš i nije svjetski prvak u brzini kreiranja GUI objekata. E , tu ova mana dolazi do izražaja.
Mislim da su momci iz Oracle-a mogli ovaj aspekt malo bolje uraditi. Pravi primjer brzog IDE-a pisanog u Javi kod kojeg nikada nemamo ovaj problem je npr. NetBeans ili Eclipse.
Često mi se desi da nakon dugog rada u nekom drugom programu, kliknem da se vratim na SQL Developer, a onda moram da sačekam ko zna koliko ( dragocjenog ) vremena da mi se prikaže program sa svim elementima i trenutnim stanjem.
Inače, ovo je možda jedina ozbiljnija zamjerka na ovaj program.
Program ima veoma dobar code completion , ima podršku za CVS i subversion, stablo je veoma lijepo urađeno, pregledno je i brzo.
Ima skoro sve elemente koje editor jednog savremenog IDE-a treba da ima.

Pristup tabelama je veoma jednostavan i brz:
Jednim klikom na neku tabelu nam se odmah otvara novi prozor sa svim informacijama po tabovima za odabranu tabelu.

Tabela za prikaz podataka bi mogla biti puno ljepša , a njene ćelije malo većih dimenzija.

Još jedna dobra stvar kod ovog programa je ta da ne moramo imati instaliran nikakav Oracle client kod sebe, jer za konekciju ne koristi tnsnames.ora već JDBC drajvere.

SQL Developer sada zaista zaslužuje da mu se da šansa.

Savjet:
Svim korisnicima savjetujem da prije početka obavezno urade sljedeće:

Tools -> Preferences -> Database -> Object viewer Parameters i štrikirajte “Automatically freeze object viewer windows” jer će se u protivnom svaka tabela na koju kliknemo jednom otvarati uvijek u jednom istom prozoru. Sada će se svaka tabela otvarati u posebnom prozoru.


Da , to je nešto što bih ranije rekao za ovaj alat, nakon nekoliko nedjelja rada u njemu i to u NE kritičnim situacijama, kada se mogu tolerisati određene gluposti koje IDE može izazvati.
Tada mi je ovaj program zaista bio pravo osvježenje jer je izgledao oprilike onako kako sam ja zamišljao da bi jedan IDE za rad sa Oracle-om ( za developere, naravno ) i trebao izgledati.
Ono što bih sada rekao za ovaj IDE je da ga se bar još neko vrijeme zaobilazi u širokom luku!
On je OK da se kući koristi i za učenje, ali ako se odlučite za njega na nekom ozbiljnijem projekrtu - uvijek treba imati pored sebe i jedan od dokazanih alata.

Zašto sam promjenio mišljenje? Pa kao prvo zato što sa ovim alatom nikada ne znaš na čemu si. Recimo da smo prepravili neku funkciju, paket, proceduru...
Nakon kompajliranja istih uopšte nećemo znati da li je kompajliranje uspješno obavljeno, da li je novi objekat validan , u čemu je problem ako problem postoji ( ne prikaže se lijepo poruka kao u npr. Toad-u )…

Evo još jedan primjer: Dešavaće vam se nekada da će program sam od sebe početi prikazivati neki view sa uduplanim kolonama, dok je u drugim alatima taj pogled sasvim OK. A onda ti ako nemaš na produkcionoj lokaciji još neki alat nećeš moći ništa dalje raditi oko pomenutog pogleda...

Ako program ( kojem inače ne treba instalacija ) iskopiramo na neki drugi računar i pokušamo ga pokrenuti – tu nastaju tek posebne situacije i blokiranja računara...
O fantomskom brisanju ili dodavanju znaka tačka-zarez ( ; ) na kraju kodova koje želimo iskompajlirati – ni da ne pričam!

Sve u svemu – SQL Developer je zaista alat kojeg jedna tanka linija dijeli od odličnog alata i vjerovatno će to uskoro i postati, kada se isprave određene nebuloze koje postoje u njemu. Zaista je sjajno zamišljen.
Mislim da Oracle mora sebi priuštiti jedan ovakav, ali bug-free i price-free alat po svaku cijenu.

E, da , za kraj: jedva čekam maj 2010-e. :-)