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. :-)

Friday, 27 March 2009

Easy_Logger for Oracle - Log every insert, update or delete for a table , with details

When it comes to client's demands when creating some IS or designing a DB, very often there's a need to have a complete log of all actions on some table containing important data.
I received a few such demands myself...

Something like this isn't so hard to make it yourself.

We could easily write a
before insert or update or delete trigger and iterate through all the columns saving all old and new values into some log table.
But what if we have many tables that needs such log? Writing all of these triggers would take a quite time...
And what happens when we alter some of these tables?

That is why I created "Easy_Logger".
Thanks to Easy_Logger we can easily create and maintain logging triggers.

Easy_logger is a PL/SQL package , so it can be applied only to Oracle.
It is written in Oracle 10g. I didn't test it on any other version...

So, how do we use Easy_Logger?

First of all, you should run this script:

instal_EL_prerequisites.sql

It will create a table called "EL" ( as Easy Logger ) which will contain all of our logs.
It has 6 columns:

EL_ID - autoincrementing ID , primary key
EL_TABLE - Table name for which the log is created
EL_ACTION - Which action was logged ( insert, update or delete )
EL_LOG - The log itself containing all the old and/or new values in a record
EL_USER - User name which commited action
EL_DATE - When was log created

If this script ended without errors, you can now download Easy_Logger package itself and apply it into your database:

Package declaration
Package body


If everything went well, and without errors, you can now start creating a logging trigger for any table you wish.
I will explain now how to do this:

When creating an Easy_logging trigger for some table, you need to specify some parameters , that are part of a record EL_PREFERENCES:

it looks like this:

TYPE EL_PREFERENCES IS RECORD (
table_name varchar2(64),
create_AFTER_trigger BOOLEAN := true,
on_insert BOOLEAN := true,
on_update BOOLEAN := true,
on_delete BOOLEAN := true
);

so, if you want to create an AFTER [{INSERT},{UPDATE},{DELETE}] TRIGGER, you would set "create_AFTER_trigger" variable to TRUE ( else, if you would like to create a BEFORE [{INSERT},{UPDATE},{DELETE}] TRIGGER, you would set "create_AFTER_trigger" variable to FALSE) .
"Table_name" variable holds information about table's name for which you want to create a trigger,
and "on_insert" , "on_update" and "on_delete" simply tells Easy_logger on which action should a trigger fire.
After you set all of this variables, you need to call a procedure called EASY_LOGGER.CREATE_TRIGGER() by sending this PL/SQL record to it...




EXAMPLE:

if we want to make a trigger that fires on after inserting or deleting a record in a table called MY_TABLE, we would execute following code:

declare
preferences EASY_LOGGER.EL_PREFERENCES;
begin
preferences.table_name := 'MY_TABLE';
preferences.create_AFTER_trigger := true;
preferences.on_insert := true;
preferences.on_update := false;
preferences.on_delete := true;
EASY_LOGGER.CREATE_TRIGGER(preferences); <-- this is the procedure for creating a trigger!
end;

or just call

exec EASY_LOGGER.CREATE_TRIGGER('MY_TABLE',true,true,false,true);

(notice that arguments for this procedure are exactly in the same order as variables in EL_PREFERENCES record)

and a code for creating a logging trigger will generate in dbms_output, so don't forget to set serveroutput on!

All that there is left for you to do is to execute generated code, and you'll have your logging trigger for MY_TABLE table created.

For those who need generated code as a returning value, and not as dbms_output output, there is a function called get_trigger_ddl which has no input parameters.
It returns last generated trigger's  DDL .

You can call it like this:

declare
your_variable clob;
begin
EASY_LOGGER.CREATE_TRIGGER('MY_TABLE',true,true,true,true);
your_variable := EASY_LOGGER.get_trigger_ddl();
...  -- do whatever you like with generated code...
end;

That's it!
Every action specified when creating logging trigger will be logged in EL table.
I hope you'll like it...
You are free to report any bug, or suggest any good idea for me to implement in order to make Easy_logger better...