Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Saturday, June 24, 2017

Setup Lombok with STS/Eclipse based IDE

For those of you who haven't heard about boilerplate code, you can check this link
Now that you already know what's that we found this little library

You can add it to your Maven projects easily, however adding it to your Eclipse is a challenge, especially if you are not using barebones Eclipse like me, who happens to use STS and initially it didn't work:


Why it doesn’t generate getter and setter like in the video? I already installed that thing like 3 times and nothing :(

Well, the solution for me was this:

Paste the JAR manually into MacOS folder

Add the option
to the file STS.ini

Finally you NEED to close the STS/eclipse and start again. (Restart doesn’t take effect)

Once you’ve done close and start STS. You’ll see the getter and setter is autogenerated.
In case you see any compilation errors, just clean and build your project.


Voila!

Tuesday, March 4, 2014

Add Token Based Authentication on Spring Security

Problem I have an application which has already implemented Basic Authentication using Spring Security.
Now as part of a new requirement I have to enable a Token based authentication as well.
My first task was to updgrade to Spring 3.0.7 and to Spring Security 3.1.3 among other dependicies that needed an update as well.
After that, let's go to the meaty part of this implementation :)
While researching I couldn't find any example, only pieces, that's why I'm publishing and sharing my findings with all the community:

At least I knew that I had to implement another Authentication Provider (that's why I needed to Upgrade my App) and something to catch the event of login and tell Spring to perform another authentication (like a Filter, maybe?)

This is my implementation: Spring's config
PingIdentityTokenValidatorImpl (Validates Given token)
KaplanOAuth2UserDetailsService (Performs Authentication, generates user following spring security standards)
KaplanCustomOncePerRequestFilterFilter (This filter does the trick) Just add it to your security configuration in the right place of the chain of execution and you're set Although, my original approach was to extend from AbstractAuthenticationProcessingFilter, however I saw it being invoked multiple times per request (it didn't bother me), but that wasn't good enough for me, also it was more complex :P

Friday, February 14, 2014

Previously initiated loading for a different type with name "javax/management/MBeanServer"

When I was doing a migration / upgrade to Spring 3.1, I faced a really weird Error.

My App was using Jetty to run deploy my WAR file.


Short story / Long Story

Although I was not using MX4J library in my project, I remembered that:
"Jetty defaults to overriding the normal J2SE class loader delegation model  (which calls for delegating to the parent)."

Therefore, this could be fixed by using this System Property:


-Dorg.mortbay.jetty.webapp.parentLoaderPriority=true



This is how you should do it in your pom:


And that error will go away.


Friday, January 3, 2014

JSONProvider builds wrong String

Looking at my backlog I found a very interesting ticket:

As a consumer of JSON web services, I would like the services to render fields with consistent types regardless of the content. When postal codes begin with zero, they are rendered as strings. When they begin with a non-zero character, they are rendered as numbers. This makes handling the JSON responses very cumbersome and causes hard to track down bugs in our code. 

It would be better if the conversion checked the type in the xsd (in the case of postal codes, string) and rendered it accordingly. 


Weird, isn't it? Then I realize, I wasn't the only one with this issue, a found a few other clueless developers with the same problem (look here and here), so that, I wasn't alone.

But so far no one had an answer, until I checked the code of my JSONProvider, this one: org.apache.cxf.jaxrs.provider.JSONProvider

My conclusion was simple, depending on the value of the string passed to the Converter, it will be casted to Boolean, String or Number.

There are 2 choices: Create my own custom JSONProvider extending from the original (and try to fix the world) or implement another which really worked as expected.

In a few words, I chose JacksonJsonProvider, however I had to customize it a little bit, because I needed to fix the issue and not create a new one (i needed the same output), and so far this is the result:

This is the original output

This is my implementation
And my new output I still have something to fix-customize because that "ArrayList" looks ugly though, but code and areCode now make sense, because they match my XSD and Pojo as well.

Friday, July 15, 2011

Updating Logging Level in Runtime using Spring

As you know, there is one way to achieve this easily by writing Java code, catch the logger and update the logging level. This is what I called: Programmatically!

But there is another way, when you already have Log4J in your WebApp, just like this:
Just add one additional param to your web.xml, besides log4jConfigLocation By doing this, the Listener will refresh the Log4J configuration each 2 seconds.

Thursday, June 23, 2011

mvc:view-controller

This tag is a shortcut for defining a ParameterizableViewController that immediately forwards to a view when invoked. Use it in static cases when there is no Java Controller logic to execute before the view generates the response.

An example of view-controller that forwards to a home page is shown below:
Source: http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html

Thursday, June 9, 2011

Using @PathVariable

Let's say that you are creating an user account-based web application in Spring 3.0. You would like to create a controller that would allow users to see each other's profile by using a URL such as
http://myapp/profile/username.

For example:
http://myapp/profile/Juan would show user Juan's profile.
http://myapp/profile/Gaby would show user Gaby's profile.


Spring 3.0's annotated controllers make this kind of mapping easy with the new @PathVariable mapping. As you can see, the RequestMapping for the showProfile method has something a bit unusual: {username}
This is a PathVariable, and it means that this method will serve any request of the format "/profile/someUserName"

We capture the actual username in the next line using the @PathVariable annotation and store it in the variable
final String username
Now we can use it however we want!
Viva Spring framework!!!

Sunday, May 22, 2011

Load Properties in Spring MVC

This is a really trivial case, but I have to cover it, because you never know when you'll need it.

We have our application and we need to load a Properties file and use it, specifically in one of your Controllers, just like this...

I know! When we say spring + properties files, everybody think on this case (don't you?):
But this is not the case I want to cover right now, because the one I want to cover is this one:
String value = (String)properties.get(key);


Ahhhh! That's what I meant :D

How can I do that? Simple, trust in Spring! (may the Spring be with you :P ) By using Util Schema

Piece of cake
Pan comido

Wednesday, May 18, 2011

Log4jConfigListener Deployment Issue on WebLogic

It looks like Spring framework's Log4jConfigListener is having an issue when webapp is deployed as WAR.
Log4jConfigListener is defined in web.xml. I got the below error while deploying the application in weblogic 10.3:

 
weblogic.management.DeploymentException: Cannot set web app root system property when WAR file is not expanded - with nested exception:  [java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded].

The solution is deploy the WAR as exploded or don't use Log4jConfigListener. The spring framework documentation also says the WAR should be exploded.

But... there is a solution available to this without any code change. We just need to set "Archived Real Path Enabled" option checked, just like this:


1. Go to server admin console->Domain-> Web applications. Click the checkbox of Archived Real Path Enabled. This should make an entry into domain config.xml as below. 2. Second option is at webapp level by updating weblogic.xml as below: true The value of set in the web app has precedence over the value set at the domain level. The default value of this property is false.

This is my example:

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 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!

Wednesday, September 8, 2010

@Autowired and @Qualifier

"Your best friends could be @Autowired and @Qualifier"
I have to migrate data from DB2 to Oracle, both databases have the same structure, well, my Oracle has better design, but I'm reusing the some objects, like POJO's and DAO's, the only thing I changed were my mappings, because I have to keep my mappings for DB2 and for Oracle.
If I have the same DAO for both databases, what can I do?
daoApplicationContext.xml
As you can see, I have 2 different DAO's sharing the same Interface & Implementation, but each one belongs to a different "sessionFactory" serviceApplicationContext.xml
Nothing special, right? But now here it comes the interesting part, because @Autowired by itself it will inject the given bean in your ServiceImpl, but you must have only one bean of that type. In my case I have more than 1, so @Autowired will throw an error when loading the context.
Then it comes @Qualifier which will match based on the given name, and problem solved chavos!!!

Notes: I used org.springframework.beans.BeanUtils to create a copy of my bean (pojo) returned from DB2 into a non-persistent Pojo which I'll manipulate before inserting into Oracle (DB2 completes each column value with spaces to achieve the given size of that column, so each time you query a DB2 column you'll get a lot of extra spaces)

Friday, August 13, 2010

Spring MVC - Binding VO to a Form

Problema:
I have a VO and I wanted to populate it on my JSP and on my controller just process the VO already populated.

Solution:

On my POST method I'll handle my VO already populated.
This entry will do 50% of the job @ModelAttribute(value="LoggerVO") LoggerVO loggerVO
On my JSP I'll map using spring's tag library
By doing this modelAttribute="LoggerVO" commandName="LoggerVO"
I'm matching what I have on my form and what I have on my Controller
I hope this will help you!
Salu2

Monday, August 9, 2010

Adding Spring Web MVC part 2

Now I'll show you a couple of examples how it looks like a Controller & a JSP using Spring MVC.

From my personal perspective Defining a controller gives you a lot of power, because you can define a method to handle RequestMethod.GET, just to show a Form, and another method to handle the RequestMethod.POST to handle the "submit", cool isn't it?

By adding @Controller you already told Spring, "hey this dude is going to be a Controller".

@RequestMapping(value="/configuration/*") means: "If my URL is WebContext/configuration/ this Controller is going to handle the Request"

Then on each method I can define my path below /configuration/ @RequestMapping(value = "showConsumersConfiguration.do"), something like this WebContext/configuration/showConsumersConfiguration.do

I almost forgot @Autowired which is for inject implementation of that Bean


If you want to handle an object like a form (bind an object to a form), check this out

Important, include these tag libraries!

By using this attribute modelAttribute="UserVO" of form:form tag, I'm binding this line of my controller: modelMap.put("UserVO", userVO); with my form

If you see carefully, each attribute of my VO, has a reference on my JSP, at least as hidden field, but all of them are there

Now my form has been binded to my VO @ModelAttribute UserVO paramUserVO

Now you're ready to play around with this thing!!!

Always go to the official documentation to get more details!!!

Sunday, June 27, 2010

WebServices with CXF - Configuration files - web.xml

Saturday, June 26, 2010

WebServices with CXF - Testing using JUnit

As you know JUnit is for Testing, so basically I'm going to test my running/deployed WebApplication by declaring this Test Cases:

This one is just a TestCase which tests my Spring Bean Service
And this fellow tests our WebService

As you can see, we need to link using our Service Interface (LibraryService.class) to this JaxWsProxyFactoryBean instance

That was easy! Isn't it???

Sunday, June 13, 2010

WebServices with CXF - Configuration files II

I'll just include my Spring configuration files.
Why files? -I though Spring only needs an applicationConext??? Well... Because I prefer to split configuration files according to it's purpose:

  • One will have everything related to the Persistence layer
  • and the second one will have all my Business layer -services
Following this logic I should have another one for my Web layer

daoApplicationContext

serviceApplicationContext

When I met Annotations, I just felt in love with them, because one of the main advantages you gain is small configuration files.

On my next entry I'll cover my Apache CXF configuration file and how it fits.

Don't forget to add @Autowired, in case that you want to use this feature by

WebServices with CXF - Configuration files I

I'll show 2 basic configuration files: web.xml & my hibernate configuration file (mapping.cfg.xml)


As you noticed I'm using Spring MVC (see webApplicationServlet), but for now let's focus on Spring and CXF:

My 3 main configuration files are listed here, where the 3rd one is for CXF (really obvious file name) and to enable Apache CXF is so simple, Did you remember XFire?

This is not rocket science! So simple :)


Now let's see my (small) Hibernate configuration file (which I just called mapping.cfg.xml) Instead of using resource=, I'm using class=, because I don't have any hbm.xml file. I'm mapping directly to the class (due to Java Annotations, my mapping it was declared on each POJO).

Now what do you think? Is not as complex as looks like.

WebServices with CXF - Integrating with CXF II

This is going to be a really small entry, because we're going to finish with my ServiceImplementation.
On the next entries we'll discuss configuration files & finally we'll see everything working (Obviously I'll need to test it).

But before that, let's analyze my implementation:

As I've been doing I'm using a lot of WebServices Annotations

What I did???

  • Define service name of the Web Service
  • Declare the complete name of the service endpoint interface defining the service's abstract Web Service contract (My Interface)
  • And set my targetNamespace: the targetNamespace is used for the namespace for the wsdl:portType (and associated XML elements)

WebServices with CXF - Integrating with CXF I

As I said before on Service Interface & Implementation, somehow we'll have to retake that code to implement CXF, and that's what we're going to do.
I want to expose as WebService my LibraryService and as WebMethods these methods:

  • public List getAllAuthors()
  • public List getAllBooks()
  • public List getAllEditors()
  • public List getAllOnlyEditors()
  • public BookDTO getBook(Integer bookId)
Ok, everything looks nice, but what happens if my client is asking for a "subService" (WebMethod) which returns AllAuthors, but he/she doesn't expect a WebMethod called getAuthors, retrieveAuthors or returnAuthors.
What can we do??? -We're done with our coding and that method (getAllAuthors) is being used in many places in our App.
Are you going to rename your code just because your client doesn't like your naming convention???. Later you'll see my answer.

Let's modify my code, first, Interface then Implementation;
By adding Java WebServices API Annotations And don't forget for every method we must declare it like a WebMethod In this case I'm declaring a couple of additional attributes, which basically let me give another name to WebMethod, a different name to my original Java Method - this will be the name available on my WebService/WebMethod (this is the second option for my client)

And finally, what can I do if have logic on this interface that I don't want to make it public (available as WebMethod)???
This is the answer: "Just exclude it"