Thursday, December 29, 2011

Unit Test on Spring via Maven - configuration tips



 This post is for newbies who set their project to run Spring powered Unit Tests via Maven.

There are many blogs who mention how to do it.
I would recommend to install STS IDE and create new Spring Template project.
It usually comes with built in Test package. The test package can be executed via JUnit.

The tricky part comes when you want to run the tests via Maven and set the Spring configuration xml file in your custom folder.

Using default setting, Maven might raise an exception complaining the Spring xml configuration file could not be found or Tests could not be found.

So, my two cents are:
cent 1: Make sure your test classes ends with Test (and not ending with Tests, for example, as it comes with the Spring default project)
cent 2: configuration can be resolved while defining the spring configuration path.
 The trick is to use the relative location as it is in the source folder, and not in the target compilation folder. Also note to use backslash as folder separation and not dots.

Configuration using classpath relative path:

@ContextConfiguration (value = "classpath:/com/company/app/OrderPersistenceTests-context.xml")

 @RunWith(SpringJUnit4ClassRunner.class)

public class OrderPersistenceTest {

...

}

or

Configuration using project relative path:

@ContextConfiguration (value = "file:src/test/resources/com/company/app/OrderPersistenceTests-context.xml ") 
@RunWith(SpringJUnit4ClassRunner.class)
public class OrderPersistenceTest {



...

} 


Run tests using maven:
If pom.xml has the skipTest tag with true as value, e.g.:

       

            

                org.apache.maven.plugins

                maven-surefire-plugin

                2.6

                 

                1.5

                1.7

               true

            

            

...


...

Then no test will be executed, even when explicitly executing maven with test goal


Good luck !

Friday, November 25, 2011

How to install (Go Daddy) certificate on Tomcat/Ubunto

Recently I spent a lot of time installing new certificate I bought from GoDaddy on my Tomcat server.
Although this process should be common, I could not create certificate chain via java keytool.
At the end I found that the GoDaddy documentation was lacking some basic info and I needed to find it my self.

So, for any of you who bought certificate via GoDaddy and need to deploy it into tomcat, here is the complete guide:

1. Create new public/private key (key pair) via keytool
Notes:
- It is important to provide complete path to keytool. Verify it located in the same JRE folder tomcat use.
- Mind the alias name, we need to keep consistency with the next steps.
script:
/complete/path/to/keytool -keysize 2048 -genkey -alias tomcat -keyalg RSA -keystore /path/cer/tomcat.jks

2. Create server csr file.
Needed to issue certificates from your CA (e.g. GoDaddy).
Notes:
- Use RSA as key algorithm
- Use same alias as you used in previous step
script:
/complete/path/to/keytool -certreq -keyalg RSA -alias tomcat -file /path/cer/tomcat.csr -keystore /path/cer/tomcat.jks

At the end of this step, go to your CA certificate management panel and re-key the certificate using the tomcat.csr file content.
Save the (extracted) files on your sever (in our example /path/cer/)

3. Get your server private key.
This step needed, since the private key required for the certification chain creation. The keystore file we created contains both public and private key.
Since keytool can not get the private key, we need to use additional tool.
For me KeyTool-IUI did the trick. You can use this link too.
The relevant menu item is specified in the image below:

The private key file should be in the format specified in the image below:


4. Create the certificate chain:
Notes:
- You can replace gd_bundle.crt with any root certificate given by your CA.
- Make sure the "-name" variable is the same as alias given in step #1.
script:
openssl pkcs12 -export -chain -CAfile /path/cert/gd_bundle.crt -in /path/cert/your_domain.crt -inkey /path/cert/tomcat.pem -out /path/cert/keystore.tomcat -name tomcat -passout pass:YOUR_PASSWORD

5. Update Tomcat server.xml file:
<Connector executor="tomcatThreadPool" protocol="org.apache.coyote.http11.Http11Protocol"
        URIEncoding="UTF-8"
        port="443"
        acceptCount="100"
        enableLookups="true" disableUploadTimeout="true"
        acceptorThreadCount="2"
        scheme="https" secure="true" SSLEnabled="true"
        keystoreFile="/path/cert/keystore.tomcat"
        keystorePass="YOUR_PASSWORD"
        keyAlias="tomcat" keystoreType="PKCS12"
        clientAuth="false" sslProtocol="TLS"
/>

Restart Tomcat and you are ready to go!

If this post saved you time, kindly share it with others.

Thursday, November 24, 2011

Convert PDF to image via PDFbox

Recently I have been asked to generate an image from a PDF file.

In this post I'll use the Apache project pdfbox as the ImageToPDF converter.

Convert PDF page into image
I'll specify two samples, however full complete documentation about  possible options and default values could be found here.

String pdfPath = "/path/to/file.pdf";
//config option 1:convert all document to image
String [] args_1 =  new String[3];
args_1[0]  = "-outputPrefix";
args_1[1]  = "my_image_1";
args_1[2]  = pdfPath;

//config option 2:convert page 1 in pdf to image
String [] args_2 =  new String[7];
args_2[0] = "-startPage";
args_2[1] = "1"
args_2[2] = "-endPage";
args_2[3] = "1";
args_2[4] = "-outputPrefix"
args_2[5] = "my_image_2";
args_2[6] = pdfPath;

try {
// will output "my_image_1.jpg"
        PDFToImage.main(args_1); 
// will output "my_image_2.jpg" 
   PDFToImage.main(args_2); 
      } catch (Exception e) { logger.error(e.getMessage(),e); }
and that's it. As simple s that.
The output image is very good and include also text that was created in JavaScript in the PDF.

Tuesday, November 8, 2011

Have you used bitly/TinyURL? Check out the following cool site

CatchyLink.com is a new site targeting anyone who seek to shorten a URL.
The differentiation from common URL shortening services in the web (such as bitly and TinyURL) is that CatchyLink generate ....hmmm.... catchy links :-) .

Other sites generates short url that is a collection of hashed letters, no human can remember it or tell it our loud, such as http://tinyurl.com/cvt4cpfaDff.

CatchyLink creates URL that not only is short but also one that humans can pronounce and remember.
Such as:  http://catchyLink.com/BigBlueOcean 
Catchy, right?



This is very useful if you need to tell someone else the link or you simply need a link that no one will forget. In our case you can tell your audience to enter the BigBlueOcean. Cool right?

CatchyLink also allows you to regenerate the Catchy Link, in case you did not like the suggested URL.   It actually quite funny & addictive ...  try it and see what I mean ... !

Storing long strings in Google App Engine

Recently I am experimenting with Google App Engine development for a small cool project I involved in.
(p.s. GAE has been recently got out of preview mode into release mode)

As you probably know,  the data is persist in NoSQL type storage.
This has some implications on the state of mind one need to model and access its data.

I was surprised to learn the concept and constraint this model brings ( such as that queries will use only AND no OR..).

Once interesting issue that I faced was the fact that String field is limited to 500 characters.

Since I needed to store longer strings, I immediately turned into the next data type which contains higher amount of characters - Text.
However, following that change I faced another problem - I could not do any queries on that field, since it could not be indexed.

Therefore I sought another solution.
I decided to split the long string into smaller chunks (500 long each) and store it in StringList type.
That provided me a way to keep the string length and have queries by this field (Google Query Language allows to do queries on list).

So my question is - do you have any other solution for storing long Strings given the fact that the field required to be searchable?

p.s.
The project was written in python.... grrrr... I have nothing further to say.

Saturday, October 15, 2011

Application Context constantly being destroyed and reloaded

This post should help those who face the situation where their Application Context constantly being destroyed and then reloaded. The issue also might follow with these log messages:
- INFO: Additional JARs have been added : 'someJar.jar'
- org.apache.catalina.loader.WebappClassLoader modified

I know this issue has been address over the web, but if I would be able to save even one developer few hours then it is worth the time I spend writing it.

To make a long story short - this issue is caused due to a corrupted jar being deployed in your application.
The INFO message indicates which jar caused the problem exactly.

Please notice that sometimes, modifying the jar in the application might not be enough. One might need to seek and destroy the corrupted jar in the deployed application.

Some solutions on the web discussing seeking the jar in Maven (like here), but in my case it was a simple copy & paste into the project WEB-INF/lib folder.

If you use Eclipse (STS) and Tomcat and the server is configured to "use workspace metadata (do not modify Tomcat installation)"  , then going into the Tomcat webapp folder will not help
You can find the mentioned jar by right click on the Tomcat instance (in the Server tab) and choose open.
Then click on "open launch configuration". In the VM arguments inner window, you will find the full path in the variable:  -Dwtp.deploy .

Saturday, October 8, 2011

Please stop defaulting your startup with freemium


Recently it seems that the Freemium model is dominating almost every SaaS startup.

I guess that the motivation for this model, from the startup point of view, is to try to solicit as many customers as possible to use the product (Hey, its free!) and then they assume that after the customer have used the basic stuff, it will be easy to convert them to more advanced paid version.

But is it really what the customer needs? Is this model ideal for paying customers?

Please read on.

What's wrong with freemium ?
For the selling companies there are evidences that the conversion rate to actual paid user is very low (~3%).
So the problem is double - not only the company which offer the service has low paying customers, but it also has tons of unpaid customers, which cause them overhead for nothing.
Moreover, for very heavy usage (for paying customers) the selling company also looses for extensive use of resources, since the plans are often for the amount of features used and not the frequency.

For the customer, this model is also problematic, since usually freemium:
  • Bundles plan with features - So free users don't actually have access to the full set of features. This might cause them not to use the product in the first place.
  • Bundles plan with amount of use - So customers who need the advanced mode, but have low traffic, are in a problem.

So the question is why binding the product possible set of features to the traffic amount?


Pay per usage (as you go)
Pay as you go
I think the customer will be much happier if he will be exposed to the complete feature set. It will help him evaluate the product better, examine the added value and potential fit.
The differentiation between customers should be the amount of usage (e.g. Amazon cloud pricing)-
Paying very few is almost like a free product, so it will not set any high entry bar. If any, it will push away one with no real interest and leave in only those who really need it (and might be willing to pay more in the future).

Moreover, paying per usage will be fair for the customer, assuming, that if his usage volume increases he benefit more and could afford to pay more.
It will also be a better approach for customers who have seasonal demand for their product, so they pay exactly as their business consume.


Pay per usage with a twist
Naturally one can improve this model by fine tune it for certain needs:
- Support aggressive/Freemium like marketing: Declare no charge policy until the cost will be aggregated to certain minimum threshold  (e.g. 5$). This will offer many potential customers room for experiment, with the difference that there is no migration needed for paying mode. It's already on.
- Support suspicious & skeptical customers by providing billing limitation (e.g. Block activity once billing account will reach 10$)
- Support enterprise customers by providing major transaction discount on large usage volume or maximum payment.

Successful use cases for the mentioned model

 A good use-case for successful pay per usage model with fine adjustment is the city bike rental program like http://www.velov.grandlyon.com/. -  users first need to pay a low rate subscription fee (so payment means are already in the system), then users would pay per usage time. The adjustment in this case is that there is no payment for the first 30 minutes. This is done since the company/city want to support short distance rides.
So this is a good example how to provide a free use but with a protection for the business against over use and with minimum income guaranteed (the subscription).


Use case where freemium model is bad
kampyle is an online feedback tool with sophisticated data analysis. Their free plan has almost no significant features, and is limited to very low feedbacks number. The downside is that free users will not be exposed to the advanced features which make this product great. Moreover, in order to enjoy the advance reporting users must buy the Silver plan (249$), even if they have no significant traffic. Why bind features to traffic ?
Other excellent products who these bindings approach are UserVoice (feedback tool) and SurveyMonkey (online Survey services).


Use case where freemium model done right
A good use case where freemium model is done right is Animoto.
I don't have any conversion rate number (from freemium to paying) expect the fact that they are quite successful, so I guess it is more then average.
The difference in this case is that the nature of the product usage (e.g. for special events, once in a while..) make it a must to buy one of the plans. No one would like to produce his child birthday movie (i.e. a rare occasion with high sentimental value) with resolution he can't utilize in wide screen TV to present the party guests.
In that case, providing a taste of the product, just for the customer to see if this is the right choice is correct.
Users are unlikely to use that product on a daily basis, therefore no fear for abuse.

*****************
So my wish is - please - be creative!
Think carefully what your clients truly need and how to address them in a win-win way.
Think how your product is being used and target for it!

Please don't use the Freemium approach as default.







Wednesday, September 21, 2011

Web Application Security Testing - beyond black box testing

In the recent OWASP convention which conducted Israel, I was exposed to an additional approach in Web Application Security testing - Glass Box testing.

Till now I was mostly familiar with black box security testing and white box security testing.
As an example for each, the black box security testing focus on changing values which are known to the browser, or exposed via web service.
e.g. changing URL parameter -
From: http://www.google.com/search?q=text_to_search&ie=utf-8   
To: http://www.google.com/search?q=SOME_HACKED_CODE&ie=utf-8

Obviously this approach is often limited to modification of data which exposed to the client.
 
The white box testing focuses on founding vulnerabilities on code level, sometimes - regardless the fact whether it is reachable by the UI or not (e.g. static code analysis).
This approach often finds vulnerabilities which would be hard to detect in black-box testing, since the entire code flow is exposed and not only the external interface.

The glass testing approach is actually empowerment of black-box testing with white-box testing detection power.

Imaging a black box testing agent that receive hints from internal agent (in the server) about possible parameters and values it should use in order to penetrate the system.
The black-box agent with the internal information then performs those tests and reports for any findings.

Further reading including examples and references could be found in Omri Weisman's (IBM) presentation.

Tuesday, September 6, 2011

Recommended reading book list


Most of the information I gain is being consumed from the internet.
There is no need to specify why the Internet is one of the best inventions ever, however, there is one drawback for it: It tend to make people less patience (in a sense of time, not tolerance toward each other..). It seems that the Internet reduces the amount of words people are willing to read.
If the article haven't reached its point in less then 2 minutes - than of we go to the next one..

I think it a common fact that all of the popular content platforms (forums, blogs, web sites,...) are not suited for long content. It's just not comfortable to read too much content via these platforms.

Therefore one can rarely see any long blog posts or articles.  If a certain topic requires in-depth content, then the content will often be migrated to other media type such as ppt or pdf files.



Having said that, I enjoy a good technical book where I can expend my knowledge beyond the 5 minute post with example.
Since I don't have much spare time I always consider cost-benefit tradeoff - whether a book will give me the benefits I expect in aspect to the time I will spend reading it.

The following list contains books which successfully pass the cost-benefit tradeoff test... I'll try to update it from time to time.



Burn Your Business Plan!: What Investors Really Want from Entrepreneurs, by David E. Gumpert - This book encourages out-of-the box not conventional thinking.
Highly recommended for new startups who want to focus on getting things done.

(amazon link)


Spring Security 3, by Peter Mularien - Very good step-by-step books regarding Spring Security 3

(amazon link)

Getting Real by 37signals - 16 chapters and 91 essays that highlight the 37Signal's philosophy about the way entrepreneurs, developers & designers should get the work done.


Rework , by Jason Fried & David Heinemeier Hansson - An agile approach for how business should run. Practical and also philosophical.

Tuesday, August 16, 2011

DAO layer - Generics to the rescue

Generics can be a powerful tool to create reusable code with the power of compile time verification (type safety..).
Unfortunately I feel the main stream developers still afraid of it.
However, in analogy to Hagrid's spiders I would say that Generics are seriously misunderstood creatures... :-)

I hope the following example will demonstrate how useful they can be.

The Problem - DAO (Data Access Objects) classes have common methods such as save, update, delete, loadAll.. which are required in every DAO class.
Writing a base class with these common methods and making every DAO object extend it, is simply not enough since each DAO class represents a different domain class and therefore the type used in the common methods' signature is different (although implementation is similar), for example:
class OrderDAO {
//save method receive an Order
public void save(Order order){....}
//getAll method return Orders List
public List<Order> getAll(){...} 
}

class UserDAO{
//save method receive an User
public void save(User user){....}
//getAll method return Users List
public List<User> getAll(){...}
}


How Generics can help us create a base class with a common implementation and yet, keep method signature type-safety?
First, we need to define an interface with the common methods:
/**
 * Base interface for CRUD operations and common queries
 */
public interface IDaoBase<T> {
	
	public List<T> loadAll();
	
	public void save(T domain);
		
	public void update(T domain);
		
	public void delete(T domain);
	
	public T get(Serializable id);
	
	/**
	 * Get list by criteria
	 * @param detachedCriteria the domain query criteria, include condition and the orders.
	 * @return
	 * 
	 */
	public List<T> getListByCriteria(DetachedCriteria detachedCriteria);
	
	public List<T> getListByCriteria(DetachedCriteria detachedCriteria, int offset, int size);	
}

Please note that we utilize generics so each method signature has a type T, which in the implemented DAO classes, will be a concrete type, per domain.

The second step is to create an abstract class which implements the common functionality:

public abstract class DaoBase<T> extends HibernateDaoSupport implements IDaoBase<T> {
	private Class<T> entityClass;
	
	@Autowired
	public void setSession(SessionFactory sessionFactory){
		this.setSessionFactory(sessionFactory);
	}
		
	public DaoBase() {
		
		entityClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

        public List<T> loadAll(){
		return getHibernateTemplate().loadAll(entityClass);
	}

	public void delete(T domain) {
		getHibernateTemplate().delete(domain);
	}

	public void save(T domain) {
		getHibernateTemplate().saveOrUpdate(domain);
		
	}

	public void update(T domain) {
		getHibernateTemplate().merge(domain);
	}
	
	
        public T get(Serializable id) {
		T o = (T) getHibernateTemplate().get(entityClass, id);
		return o;
	}

	public List<T> getListByCriteria(DetachedCriteria detachedCriteria,
			int offset, int size) {
		return getHibernateTemplate().findByCriteria(detachedCriteria, offset, size);
	}
	
	public List<T> getListByCriteria(DetachedCriteria detachedCriteria) {
		return getHibernateTemplate().findByCriteria(detachedCriteria);
	}
}

And that's it !
Take a minute or two to inspect how the base object implements a generic functionality with a type-safety manner.

All we have to do when implementing a new DAO is:
1. Interface to extend the IDaoBase with a concrete type
public interface DaoUser extends IDaoBase<User> {//<=Notice the User typing
	//Add any additional custom methods..
	public User getbyUsername(String username);
        public User getbyEmail(String email);
}

2. Implementation to extend the DaoBase with a concrete type

//This class has all the common methods, which are type safe for the User class
@Repository("daoUser")
public class DaoUserImpl extends DaoBase<User> implements DaoUser { //<=Notice the User typing

	public User getbyUsername(String username) {
// concrete implmentation		...
	}

So now you see how powerful it is to use generics. Hope it is now a bit less scary and more understood...

Please post me if you have further cool tricks utilizing generics for ease development.

Moreover, if you think any of the above can be improved, I'll be happy to hear about it.

Sunday, August 7, 2011

Spring security 3 Ajax login - accessing protected resources

I have seen some blogs about Spring Security 3 Ajax login, however I could not find any that tackles how to invoke Ajax based login, where a protected resource is being accessed in Ajax by an anonymous user.

The problem - The web application enables anonymous access to certain parts and certain parts are protected resources which require the user to login.
When an anonymous user accesses protected resources (via Http Get / Post), Spring Security automatically invokes the login page and after a successful authentication, redirects to the required resource/page.
However, if the protected resource is being accessed in Ajax, the login page will not appear correctly (will be set on part of the page). The 302 code (redirect to login page) will not function as expected in Ajax.
Please note that this is NOT the same as initiating an Ajax login screen (e.g. when user press on the login button and a popup with user/password fields is being invoked).
So - how can we have Spring Security 3 handle access to protected resources both with "regular" HTTP Post(FORM based authentication) AND Ajax calls, including a redirect to the required resource after successful authentication?

So, this blog post has two protection layers/parts:
1. Spring Security 3 standard FORM based authentication
2. Configure/extends Spring Security 3 and the app to support also Ajax access to protected resources.

Regarding part 1 - there are many references about the issue. No need to elaborate.
Regarding part 2 - Requires the following:
   1. Configure Spring Security 3 to enable Ajax based login.
   2. Configure client Ajax calls to protected resources to handle request for authentication.
   3. Re-execution of functions to simulate the automatic user original method invocation after successful login (as it happens in the FORM based login)

The below diagram describes a detailed flow and should help follow the client/sever communication.

Handling protected resource access via Ajax





Lets discuss the diagram:

The flow starts with an anonymous user Ajax request to a protected resource (1). In this case the user wants to add an item to the shopping cart.

The addItem method is a protected resource, which is protected via Spring Security (@pre_authorize("SOME_ROLE")) (2).  This causes the Spring Secutiry filter (3) to send the login FORM with HTTP code 302 (i.e. redirect to that page).

Now, since this is an Ajax call, it will not handle the request well, so here comes the part that takes the login FORM, put it aside, and invoke Ajax based login instead (4):

The client Ajax method (which invoked the Ajax addItem method) checks whether it is a form based login or any other reply. If it is a FORM based login, it will call a dialog modal (5) that will try to login in Ajax. Spring will handle the Ajax login authentication (6) and return an appropriate message to the client. The client, if the message was successful, will re-execute the original function, which tried to access the protected resource (e.g. addItem in our example).

Let us see how it all fits in our code:
Steps #1, #4 - Client side which accesses protected resources and checks if a login is required
//JavaScript method - Ajax call to protected resource (#1 in flow diagram)
function addItem(itemId) {    
    $.ajax({
        url: '/my_url/order/addItem',
        type: 'POST',
        data: ({orderItemId : itemId,...}),               
        success: function(data) {

           //construct a callback string if user is not logged in.
           var cllbck = 'addItem('+itemId +')';

           //Client check if login required
           //(#4 in flow diagram)
           if (verifyAuthentication(data,cllbck)){
               // in here => access to protected resource was ok
               // show message to user, "item has been added..."
           }
      });
    }

Steps #2, #3 - is a regular Spring Security configuration. Plenty of resources out there.
Step #4 - Client checks if login is required:
function verifyAuthentication(data, cllBackString){
   //naive check - I put a string in the login form, so I check for existance
   if (isNaN(data) && (data.indexOf("login_hidden_for_ajax")!= -1)){
      //if got here then data is a loginform => login required
      
      //set callback in ajax login form hidden input		
      $("#my_callback").val(cllBackString);	
 
      //show ajax login
      //Get the window height and width
      var winH = $(window).height();
      var winW = $(window).width();
              
      //Set the popup window to center
      $("#ajaxLogin").css('top',  winH/2-$("#ajaxLogin").height()/2);
      $("#ajaxLogin").css('left', winW/2-$("#ajaxLogin").width()/2);
      $("#ajaxLogin").fadeIn(2000); 
      return false;
      }	
    // data is not a login form => return true to continue with function processing
    return true;	
}
Step #5, #7 - the Ajax login FORM utilizes the following Ajax login:

function ajaxLogin(form, suffix){
	
	var my_callback = form.my_callback.value; // The original function which accessed the protected resource
	var user_pass = form.j_ajax_password.value;
	var user_name = form.j_ajax_username.value; 

//Ajax login - we send credentials to j_spring_security_check (as in form based login
	$.ajax({
          url: "/myContextURL/j_spring_security_check",    
          data: { j_username: user_name , j_password: user_pass }, 
          type: "POST",
          beforeSend: function (xhr) {
             xhr.setRequestHeader("X-Ajax-call", "true");
          },
          success: function(result) {    	
          //if login is success, hide the login modal and
          //re-execute the function which called the protected resource
          //(#7 in the diagram flow)
    	  if (result == "ok") {
 
            $("#ajax_login_error_"+ suffix).html("");            
    	    $('#ajaxLogin').hide();
    	    if (my_callback!=null && my_callback!='undefined' && my_callback!=''){
    		eval(my_callback.replace(/_/g,'"'));
    	    }
    	    
            return true;
          }else {       	
        	
        	$("#ajax_login_error_"+ suffix).html('<span  class="alert display_b clear_b centeralign">Bad user/password</span>') ;
        	return false;        	
        }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
    	$("#ajax_login_error_"+ suffix).html("Bad user/password") ;
    	return false; 
    }
});
}

We need to set Spring to support Ajax login (#6):
Set Spring Security xml configuration:


   
    
        
        
		
		
        	
        
                    
        

    
	
	...

Define a handler for login success:
@Component("ajaxAuthenticationSuccessHandler")
public class AjaxAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {	
	   
    public AjaxAuthenticationSuccessHandler() {    
    }

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {	
		
		HttpSession session = request.getSession();		
		DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) session.getAttribute(WebAttributes.SAVED_REQUEST);
		//check if login is originated from ajax call
		if ("true".equals(request.getHeader("X-Ajax-call"))) {
	        try {
	        	response.getWriter().print("ok");//return "ok" string
	        	response.getWriter().flush();
		} catch (IOException e) {				
		   //handle exception...
		}
	    } else {	    	
	    	setAlwaysUseDefaultTargetUrl(false);		
		...
	    }
	}
}
Define a handler for login failure - the same as success, but the string is "not-ok".

I know some of the code here is not the best practice so I would like to hear what you think.
Please post me if you can see a way to improve the process or make it more generic.

Acknowledgment -
Diagram was done via gliffy - online diagram tool

Thursday, August 4, 2011

Development stack

On the previous post I wrote a bit about commonly used web development tools.


I now want to focus about my favorite development stack for Java web applications development -

Application server : Tomcat - currently using version 6, but will upgrade to 7 soon. Works great both in Win and Ubuntu. Easy to setup and scalable.
Application framework : Spring - highly stable, robust and now with version 3+ more simple.
Still using different Spring modules can make one fall into maven hell, but I believe it will get better and that the pros are much higher then the cons.
DB : MySQL   / Neo4J - I recently started to think about integration between Graph DB and Relational DB. Recent trends makes us transforming the conventions we know and use. For me - I start thinking that maybe a Graph DB is the "standard" / "natural" choice and relational DB should be chosen per case and for good reason. See Neo4J presentations about how the world should be modeled via the eye of graphs (Try to look for "Thinking in Graphs" article).
ORM : Hibernate/ Spring data-  spring data graph now provides more conservative use and aligned with the current JPA conventions.
UI framework : JQuery + JQuery UI - I also prefer to use plugin/extensions that are theme roller ready.

Monday, August 1, 2011

Toolkit for web development

Following the interesting startup survey infographic about The Web & Business Tools Startups Use Most, I would like to state my toolkit when it comes to web development.

Mocking and wireframe:
Balsamiq - not doubt about this one. I have tried several mocking tools including one which plugs into FF, however Balsamiq is the most simple, extensible, configurable tool for wireframe. Great for agile development since it makes you focus on functionality.
Gliffy - Online diagram tool that support UML. Very easy to start with, very clean and clear outcome.

Project documents sharing: DropBox - enable you to seemlessly share documents cross computers and cross team members.

Page design:  crocodoc - Great tool to provide feedback ( inputs... :) - internal joke... ) for designer. You can post feedbacks in certain places on the design page (like sticky notes - but better) and have offline review. Really cool.

Assembla - Manage your code repository (I use SVN) and support development activities such as planning tasks (tickets), daily meetings, wiki, code diff and much more. Installing and Configuring SVN always seemed to be an exhausting task which even was a highly important development infrastructure tool, does not bring added value to the customer and not the core of application development, therefore an ideal candidate to outsource.

IDE: Eclipse / STS - In not so far past, STS was very slow, but now it is much faster and all the bundled apps make it an easy choice for Java development.
IDE plugins:
ResourceBundle Editor: Useful to track and edit multiple i18n files in Java. (extract it and drag the folder into the eclipse/plugins folder)

Gimp - I don't want to encourage developers to handle UI design themselves (so this would be under the section of productivity killer..)

Testing - BadBoy UI recording tool, most intuitive recording and testing tool I know. Provide also an advanced mode, if required, for testing and verification.

Web pages usability - crazyEgg - demonstrate and visualize where in the page users click.
A very good tool to identify design pitfalls. Helped me see what users think and actually identify that users tried to click on a section which wasn't clickable.

Development OS : Windows
Deployment OS: Ubuntu Server
I found it very useful to use windows to boost development productivity and then deploy it on the Ubuntu server, via remote access. This portability forces me to write better code.

Remote access:
Remote command line control: SSH
Transfer files to server: FileZila

General productivity tools:
Firefox - For me, still the ideal browser for development.
Firebug - The ultimate FF plugin and the reason I don't use Chrome (I know Chrome has alternative, but still..) . No additional word is needed.
ReloadEvery - FF plugin that enable reload of pages automatically. Useful for load test or profiling.
JSONView - FF plugin to view json in clear way.
Cookie manager - Manage cookies (edit, clear, view..)
RoboForm - password management tool, also came in the flavor as a FF plugin. Enable you to have (different) strong password for each site. If you are still using your single "strong" password cross sites, then give it a try, you will be able to sleep better. I have the paid version. Worth every cent.
Notepad++ - Great for adhock file editing.
jsfiddle - Test small scripts / css online
skitch - similar to snagit.
I'll keep updating this list if I will come across further interesting tools.