Wednesday, March 30, 2011

Accessing a PostgreSQL table using Hibernate

I was goofing around with PostgreSQL, and I wanted to give it a try, so I decided to replicate my Payment table from HSQLDB to PostgreSQL and I got something like this
CREATE TABLE "PAYMENTS"
(
  id_order integer NOT NULL,
  id_customer integer NOT NULL,
  total_amount_transaction double precision,
  transaction_number character varying(50),
  creation_ts timestamp with time zone,
  CONSTRAINT pk_payments PRIMARY KEY (id_order, id_customer)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "PAYMENTS" OWNER TO payments;
As you well know with Hibernate the switch should be not very painful, and it won't have any impact on existing code!
But...Surprise!

The impact is not a huge impact but it's something really specific, and that's why I'm creating this post.

The usual steps to chnage from one DB to another DB is Hibernate is really simple:
This is my previous DataSource - Because, to accelerate the process I did the change locally before deploying this to my app server, so I can test locally using my existing JUnit test cases
And this is my new DataSource for PostgreSQL
Important: Remove the "defaultAutoCommit" attribute and add "defaultCatalog" attribute
This is my new Dialect

And this is the second Important detail:
Add double quotes to your table name!, just like this
My original code used to be
@Table(name = "PAYMENTS")


This is my new Payments DB :)

Hibernate did't again!

Wednesday, March 23, 2011

Integration reCaptcha with Spring MVC

When I was explaining about reCaptcha on my previous entry, I made reference to my little-store example app, which basically has a bunch of frameworks (the idea is implement those technologies that I want to learn or just practice).

What I did is really simple, the first step was adding my new dependency to my POM
Then add to my webApplicationContext.xml my new reCaptcha bean
You must get the keys from the official website by adding your site. On my case I put the keys in a properties file, and then by using spring I loaded that file


Next in my Controller I used my ReCaptcha bean, like this
As you could see, this code populates a variable (reCaptcha) which I'm going to display on my JSP using JSTL:
${requestScope.reCaptcha}
Inside of a HTML FORM

Finally, this is how I validated the confirmation text (you must be expecting these 2 params: recaptcha_challenge_field and recaptcha_response_field)

The only problem I faced was related to my flow (which screen should I display), but besides that the implementation is really straight forward, simple!

Sunday, March 20, 2011

reCaptcha - FREE anti-bot service that helps digitize books

Did you remember one of my entries where I implemented jCaptcha???
If you don't know what I'm talking about this is the entry

Now that we understand each other, just for things of the destiny (¬¬ yeah of course!), I found something about "Digitizing Books One Word at a Time" from Google and how many times you've seen this Captcha.


Actually, you can implement it on the same way with jCaptcha, but you need more customization, at the end it has Pros and Cons both solutions, but as an Architect, I take in consideration 2 main factors:
  • Is your App going to be in a closed environment?? Is it going to have access to Internet?? (One thing is that you can access your app through web and something else is that your Network and Server configuration doesn't allow your app to interact with other websites)
  • Do you want to have full control of your App?? Then you don't want to share anything about your app with any external entity, you don't need external Black Boxes (you can re-invent the wheel for you, can't you?)
For this particular situation, I'd prefer to share something with the world, I mean I don't care if Google knows that I'm using its service, My App can share and cooperate with the rest of the world, because I'm not using critical information (for my purposes: Educational)

Then let's begin...
.
What is reCAPTCHA?
reCAPTCHA is a free CAPTCHA service that protects your site against spam, malicious registrations and other forms of attacks where computers try to disguise themselves as a human; a CAPTCHA is a Completely Automated Public Turing test to tell Computers and Human Apart. reCAPTCHA comes in the form of a widget that you can easily add to your blog, forum, registration form, etc.


In my next entry I'll be implementing this reCaptcha in my little-store app :)
So I'll see how it works and how hard is to implement it (obviously I'll need to install the library on my local Maven Repo) and use Scriptlets "duh!"
But as people say, if life gives you lemons, make lemonade and that's what I'm going to do

Tuesday, March 15, 2011

Pass parameters from one page to another

This is the issue, I have a JSP which helps me to generate a URL to change the Locale, to switch between Spanish and English, but I have a JSP (maybe more) which is displayed based on a Parameter, because shows the details for an Object based on idObject.
This is my original JSP (So each time I clicked the link, the page was refreshed, but missing the param, obviously the content was never displayed - duh!)

The fix is really simple, just add more params to each URL, by using JSTL :) Like this (creating dynamically my params)

Sunday, March 13, 2011

Spring MVC and Tiles 2

I still remember how cool it was to use Tiles with Struts, back in Mexico and a couple of times here, but since I've migrated my efforts on Spring MVC;
At the very beginning I couldn't implement Tiles successfully (I just tried 2 times :P - 1 really important and another one just for fun)
But when Tiles became an independent project: Apache Tiles 2 things changed a little bit, and now that everything could be delegated to Spring, let's give it a shot!
I didn't have to change too many things, because let's start from an existing App using Spring MVC, Spring Core, Hibernate, Apache CXF, DisplayTag, jCaptcha, etc.

This is my Application layout (yes! I <3 Maven 2!)
 

This is one of my Controllers (something really common)
On the return statement I'm just displaying the file: /jsp/start/landing_page.jsp
This is my previous webApplicationContext.xml (look at the InternalResourceViewResolver - it maps the JSP's to the return statements on my Controllers)

Let's start by integrating Tiles


Add new dependencies in your pom.xml
Update your webApplicationContext.xml (don't forget to take out the existing InternalResourceViewResolver - we're going to replace it with a Tiles View Resolver) by adding these entries
Put more attention to this portion (the rest is a nice to have)
Then according to this tilesConfigurer, I have to add a new file on each JSP folder (views.xml) and my layouts, like this
 

layouts.xml
default.jsp
footer.jsp. Look at the links, because this is the key to make this APP Multilanguage (besides the entries on webApplicationContext.xml and obviously the *.properties files)
 

views.xml on /jsp/start/ folder
This portion makes the magic (
without touching any single line of code!!! )
Where else have you seen "start/landing_page" before? If you don't remember, in my controller (return statement: return "start/landing_page";//show jsp)

And now you're ready to rock!

Friday, March 11, 2011

Applications Multilanguage - Issue with Ñ and Accents

It's been a while since I worked with an Application in Spanish.
Always English!

This time, testing that my messages properties were used properly (I was just testing that I didn't miss any message), I saw something really weird:

After thinking about what happened in Japan and reading the news, I came back to this issue.

Then, I realized I was using the wrong META TAG (Charset)
After updating my Charset to "ISO-8859-1", everything look as I expected, hopefully I won't have to face any issue like this one with another language (like Russian, Hindi or Japanese) because as I know all of them have a different CharSet different from English and Spanish :)

Wednesday, March 9, 2011

JCaptcha & Spring MVC

Have you ever heard about Captcha.
Is this familiar?

Now that you remember what I'm talking about, let's begin.
I chose JCaptcha, because I used before with Struts back in Mexico for one of my projects when I was working in Government (SICOSIEM) and it was really useful (but I used a servlet)
Now the idea will be implementing the same project on an existing Spring MVC App, which is really simple :)
First things first!. Get JCaptcha and install it in your Local MVN Repo (version 1.0-all), because if you add as dependency version 1.0, it will not work, due to the lack of some jars on Maven Central Repo.
My Controller which will behave like my old servlet (I just have to create an IMG tag with src="/myAppContext/captcha/captcha.htm")
This is how you have to use it (on my previous jsp I have an input text called "captchaText" which holds the value entered by the user)
This is a minimal configuration (I have the bad habit of splitting all my configurations to make my life easier, on this case I'll call this configuration file "jcaptcha.xml"), if you want to dig deeper, you can explore the official web site and play around with other classes (just look into this package: com.octo.captcha.engine.image.gimpy)
FYI: This is the captcha service I'm injecting in my Controllers
Don't forget adding your new configuration file for JCaptcha in your Spring App Context (this is my web.xml)
If you want to see a more complex ("customized") configuration, you can use see this one (It took me a while to create it - but I used as reference what is on JCaptcha WebSite)

Monday, March 7, 2011

Mapping 2 or more URL patterns with same servlet

We have a simple Spring MVC servlet (as usual), nothing out of normal.
With its respective mapping
This is the tricky part, I want to map some weird request mappings like: *.htm or *.jspx (besides *.do)
  • registerCustomer.do
  • registerCustomer.htm
  • registerCustomer.jspx

The solution is simple, just add another entry to your servlet-mapping: The only restriction is to use web-app version=2.4 or 2.5
I always use 2.4 and I didn't have anything else to do. But for educational purposes I updated my web.xml (web app descriptor) for my future developments.

Sunday, March 6, 2011

Round-Robin

"Round-robin" describes a method of choosing a resource for a task from a list of available ones, usually for the purposes of load balancing. Such may be distribution of incoming requests to a number of processors, worker threads or servers. As the basic algorithm, the scheduler selects a resource pointed to by a counter from a list, after which the counter is incremented and if the end is reached, returned to the beginning of the list. Round-robin selection has a positive characteristic of preventing starvation, as every resource will be eventually chosen by the scheduler, but may be unsuitable for some applications where affinity is desirable, for example when assigning a process to a CPU or in link aggregation.


I had to implement the same thing for an external call, we need to balance the load to a set of servers equally, so I had to create a CircularQueue (It's just a wrapper for a List)
All my items are located in an XML, and I just load them in an existing method, I only added a new block of code

Wednesday, March 2, 2011

JUnit using only annotations

To be honest I tried annotations with JUnit recently, but the first time I tried, it didn't go well, so I procrastinate it.
But for this "experimento", I'd to retake it with excellent results
, and this is one of test cases [I had to create a base TestCase class - you know how lazy I'm:) to avoid the process of loading my context and Log4J]
Don't forget my "golden rule", use Maven!!! I'm using JUnit 4.8
As you can see, there isn't too much to explain. Only we're using "SpringJUnit4ClassRunner.class", because to do my tests I need my Spring App Context (with all my beans)

This is a portion of my test case I haven't used much the annotations Before and After, but some day I'll find them an application.

Something really cool is the part where we can define if my test method will be Transactional, if we want to Repeat it or if after test is executed we want to Rollback the Tx.
Because, for a regular Test, just with the annotation @Test will be enough.
I felt in love with these annotations, because finally I don't have to load the a test Database and Clean it after my testing is done (I know, you still have to re initiate the sequences, but who cares, they're UNIQUE), I can reuse my existing initial DB and play with it, and nobody will see my garbage/testing data; unless I want it
 
@Transactional  --> There is a Tx involved on this test
@Rollback  --> When is done (rollback Tx)
@Repeat(2)  --> Repeat 2 Times this execution
That's what I'm talking about!!!
¡JUnit Rules!