Coffee to go

Icon

var thisBlog = getGlobalContext().buildFromTemplate(PERSONAL | PROGRAMMING | RANDOM_THOUGHTS);

Dynamic authentication success and failure url using Spring 3 MVC & Security

If you have used spring’s form-login security before then following (part of) configuration will look familiar to you:

<security:form-login login-page="/login"</pre>
 authentication-failure-url="/login/failure"
 default-target-url="/"/>

What it says is: where the login page resides (login-page), after logging in redirect user to “/” (default-target-url) given that user wasn’t landed here while trying to access any page that required authentication and what page to serve in case of failed login attept (authentication-failure-url).

OK, it’s pretty straight forward but what if instead of using values specified in config one has to specify these values dynamically – with dynamically I mean on authentication failure instead of redirecting to “/login/failure” (value of authentication-failure-url), redirect to /signup or some other url depending on some checks/conditions?

Luckily for this spring has:

Interface / Class Description
AuthenticationSuccessHandler Strategy used to handle a successful user authentication.
   
SimpleUrlAuthenticationSuccessHandler Simple implementation of AuthenticationSuccessHandler interface which by default uses the default-target-url value to redirect to user on successful authentication
   
AuthenticationFailureHandler Strategy used to handle a failed user authentication.
   
SimpleUrlAuthenticationFailureHandler Similarly, this class is simple implementation of AuthenticationFailureHandler interface and it by default redirect the user to value of authentication-failure-url
   
RedirectStrategy Encapsulate the redirection strategy

If you haven’t noticed yet RedirectStrategy is the interface we are most interested in, since it’s the one that will be one incorporating the strategy of forward requests. So for this we simply need to write a custom class that implements RedirectStrategy and override sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) method.

Let’s show you what I mean:

//Custom redirection strategy for handling successful handling
public class CustomSuccessRedirection implements RedirectStrategy {

	@Override
	public void sendRedirect(HttpServletRequest request, HttpServletResponse response,
			String url) throws IOException {

		//redirect based on some condition
		if(someCondition) {
			response.sendRedirect("/home/a");
		} else {
			response.sendRedirect("/home/b");
		}
	}
}

Similarly a strategy for failed authentication can also be written in the same way.

Now to override the default url redirection strategy we need to add following to config:

<!-- Custom Redirection Strategy bean -->
<bean id="customSuccessRedirStrategy" class="net.waqassiddiqi.spring.CustomSuccessRedirection" />
<bean id="customFailedRedirStrategy" class="net.waqassiddiqi.spring.CustomFailedRedirection" />

<bean id="customRedirSuccessHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
	<property name="redirectStrategy" ref="customSuccessRedirStrategy" />
</bean>

<bean id="customRedirFailedHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
	<property name="defaultFailureUrl" value="/login/failure" />
	<property name="redirectStrategy" ref="customFailedRedirStrategy" />
</bean>




Share on Twitter

And java guys say c# is bad!

Its not like I don’t like or enjoy to work with Java, it’s just the fact that it takes more time as compare to C# to perform some trivial tasks; Like ‘calculating the time duration (in hours/minutes/seconds) between two date times’ – doing this Java way (as pasted below, I really missed the days working with C#)

...
Calendar startDate = getStartDate();
Calendar endDate = getEndDate();

//Calculate time elapsed in HH:MM:SS
long totalMilliSec = endDate.getTimeInMillis() - startDate.getTimeInMillis();
int seconds = (int) (totalMilliSec / 1000) % 60;
int minutes =  ((int)(totalMilliSec / 1000) / 60) % 60;
int hours = (int)(totalMilliSec / 1000) / 3600;

System.out.format("%02d:%02d:%02d", hours, minutes, seconds);
....
Sample output will be something like: 24:01:34
....

For comparison find below the C# code which does exact the same:

DateTime dtStart = getStartDate();
DateTime dtEnd = getEndDate();

TimeSpan ts = dtEnd.Subtract(dtStart);
Console.WriteLine("{0}:{1}:{2}", ts.Hours.ToString("D2"),
      ts.Minutes.ToString("D2"), ts.Seconds.ToString("D2"));
.....
Sample output will be something like: 24:01:34
.....

Between, for java, there exists an easy to use library to work with date time ‘Joda Time’. One can say that it provide almost all the functionality C#’s DateTime provide. Here you can find more: http://joda-time.sourceforge.net/

Share on Twitter

java – ResultSet.getTimestamp() = Date + Time

Fall into this again, now not to forget this again I am posting it here.

ResultSet.getDate() returns date without time i.e. If table column has date time value say 2011-01-01 12:05:01 then the output of ResultSet.getDate() will be 2011-01-01.

And if in case complete date time value is required use ResultSet.getTimestamp() instead. The output will be complete date with time 2011-01-01 12:05:01

ResultSet rs = ...;
rs.getDate("columnName"); //value will be date without time
rs.getTimestamp("columnName"); //value will be date *with* time
Share on Twitter

Changing field name before serialized json output using flexjson & java

Today I was working on a Web API integration project when I ran into this problem. All data being sent and received from this Web API is in JSON format and for which we are flexjson, which works good for serializing and deserializing POJO to/from json.

By default flexjson uses the POJO property names as the field name in serialized json output, so the output of this POJO:

//Person.java
public class Person {
	String firstName;

    public String getName() { return firstName;}
    public void setName(String firstName) { this.firstName = firstName; }
}

will be:

{"firstName":"Abdul Kareem"}

But what if I can’t change POJOs but still would like the serialized output to be something like this:

{"first_name":"Abdul Kareem"}

This was the problem which I ran into today, overriding the default flexjson behaviour and provide the field names manually. It wasn’t that difficult as I thought, few minutes into mailing list search led me to official flexjson tutorial page on sourceforge. There they have written about using Custom Transformer in great detail using example.

So in short, in order to play with field name’s during serialization flexjson has provided an abstract class AbstractTransformer, writting custom transformer is as easy as extending this class and overriding void transform(Object object) method.

Pasted below is the code of FieldNameTransformer class which I wrote for solving the problem I mentioned earlier. It allows user to specify the field name rather then using default POJO property names in json serialized output.

public class FieldNameTransformer extends AbstractTransformer {
	private String transformedFieldName;

	public FieldNameTransformer(String transformedFieldName) {
		this.transformedFieldName = transformedFieldName;
	}

	/***
	 * Use this method to override the default functionality
	 * of handling field names and their values
	 */
	public void transform(Object object) {
		boolean setContext = false;

		TypeContext typeContext = getContext().peekTypeContext();

		//Write comma before starting to write field name if this
		//isn't first property that is being transformed
		if (!typeContext.isFirst())
			getContext().writeComma();

		typeContext.setFirst(false);

		getContext().writeName(getTransformedFieldName());
		getContext().writeQuoted((String) object);

		if (setContext) {
            getContext().writeCloseObject();
        }
	}

	/***
	 * TRUE tells the JSONContext that this class will be handling
	 * the writing of our property name by itself.
	 */
	@Override
    public Boolean isInline() {
        return Boolean.TRUE;
    }

	public String getTransformedFieldName() {
		return this.transformedFieldName;
	}
}

And this is how to use it:

Person person = new Person();
person.setFirstName("Abdul Kareem");

JSONSerializer serializer = new JSONSerializer().exclude("class")
                .transform(new StringTransformer("first_name"), "firstName");
String jsonString = serializer.serialize(person);

And here is the desired output:

{"first_name":"Abdul Kareem"}
Share on Twitter

I know how to transform an idea into product but Business Model?

The other day as a part of knowladge sharing session in office we had a presentation on ‘Business Model Generation’ by Basit (@syedabdulbasit).

This presentation covered following questions:

  1. What really Business Model Generation means?
  2. How to turn your idea (here idea could be an android application, a new VAS service or even selling cattles) into a presentable business model?
    &
  3. Why is it important after all?

Overall it was a great presentation, very informative and presented in a very interesting manner but what I really liked was a small ‘activity’. Before presentation all of the attendee were given a task to come up with some product or service idea and make a ‘business model’ (with what ever knowladge they have on this topic) so to present in front of upper management and convince them ‘why and how it’s a good idea to invest in your idea’.

Being a technical person I treated this ‘model’ like any other flow diagram and below is what I came up with for ‘A Campus Guide’ Android Application idea:

hmm does this looks like a business model to you? With this model will you be convinced if I say

‘I have a brilliant Idea for our XYZ Client, to convert this idea into to product we need following resources which will cost us. But no worry, not only this product will full fill the our client’s need but also result in revenue for both of us’.

I am sure you won’t and probably you will respond with something below:

‘OK, I understand you idea but what is the value of this product to us, client and  most importantly to prospective users? What precisely be the required resources? And most important what will be the revenue streams?
Your model doesn’t say anything about these?

This is exactly what I thought of my model when Basit played this video:

A video about ‘Business Model Canvas’, a tool for describing, designing, challenging, inventing, and pivoting a business model.

The video & presentation quickly made me realize ‘why my model is not even a business model’, ‘what a good business model should cover’ and most important to me ‘How to turn an idea into a presentable business model’

Using the proposed business model canvas, see how easy it was (even for me) to made a presentable model:

Now this final business mode of mine has every thing:
1. The value our idea proposes to us, client and prospective users
2. Potential market
3. Ways to access this market
4. Required cost for operating this business model
5. And, the revenue streams i.e. the ways this idea can generate revenue

Share on Twitter