16 January 2016

Html5Mode in angular js for Java

Here's a sample Servlet filter implementation to allow return pages from the server with the / pattern.

Note: I've marked angularjs requests with "source" header set to "ng".

@WebFilter(urlPatterns = { "/*" })
public class Html5ModeFilter implements Filter {

public void destroy() {


public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {

HttpServletRequest request = ((HttpServletRequest) req);
boolean notNgRequest = !"ng".equalsIgnoreCase(request.getHeader("source"));
String servletPath = request.getServletPath();

if (notNgRequest && !servletPath.contains(".")) { // skip .js, .css,
// .png, etc...
if (!"/".equalsIgnoreCase(servletPath)) {
((HttpServletResponse) res).sendRedirect("/?next=" + servletPath.substring(1));

chain.doFilter(req, res);

public void init(FilterConfig arg0) throws ServletException {



15 January 2016

spring security java config for REST service

I am trying to setup spring security for REST service in spring.

All worked fine, but when I tried to do logout, I find that instead of session being invalidated; some redirect happens to /login url (which is not exists).

The solution is to tell the logout configuration to only send 200 stauts code and not to redirect to the login page (hence this is a rest app and there's no login page - the client can be mobile app, js client like angular, etc..)

Here's the configurations:

.and().logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())

.and().csrf().disable(); // for development only

02 July 2015

Tail Recursion

Tail recursion is special case of recursion where the function calls itself as the last statement in the method.

From wikipedia:

Tail calls can be implemented without adding a new stack frame to the call stack. 

Here's an example of Sum of Ints function that sum Integers between a and b

so when call sumOfInts(1, 4) would equals 1 + 2 + 3 + 4 = 10

First implementation using non-Tail recursion:

def sumOfInt(a: Int, b: Int): Int =
        if (a > b) 0 else a + sumOfInt(a + 1, b) // last stmt is a call to the same function and then add some value to it (non tail recursion)

The second implementation using a Tail recursion function:

def sumOfInt2(a: Int, b: Int): Int =
        sumOfAllInts(a, b, 0)                    

def sumOfAllInts(a: Int, b: Int, t: Int): Int =
        if (a > b) t else sumOfAllInts(a + 1, b, t + a)  // last stem is a call to the same function only (tail recursion)


sumOfInt(1, 100000000)                        //> java.lang.StackOverflowError
sumOfInt2(1, 100000000)                       //> res2: Int = 987459712


The Tail recursion version using the same stack frame on each call (vs the non-tail recursion which  will use a new stack frame for each call for the reclusive method)

See this question and read the answer to understand about Tail Recursion: http://cs.stackexchange.com/questions/6230/what-is-tail-recursion

29 May 2015

Configure tomcat (on HTTP) to work with HTTPS Load Balancer/Reverse Proxy


The following pattern is common when deploying java webapps on tomcat.

(HTTPS) LB/Reverse Proxy <--> (HTTP)Tomcat <--> Webapp

Usually, the HTTPS certificate is being installed on the Load Balancer/Reverse Proxy, then the LB/RP will communicate with internal tomcat on HTTP/AJP. (see References)


The following configurations is required only if LB/RP to connect to tomcat on HTTP.

If the communication done on AJP, then no configuration is required to pass HTTPS information to tomcat.

As one of the design goals of AJP is :
"Adding support for SSL, so that isSecure() and getScheme() will function correctly within the servlet container. The client certificates and cipher suite will be available to servlets as request attributes
(quote from https://tomcat.apache.org/connectors-doc/ajp/ajpv13a.html)


If you use HTTP connector, still the below configuration is not required, just tell tomcat (thought the connector configurations), on which scheme the response should be returned by using:

<Connector protocol="HTTP/1.1" port="8081" proxyName="linux-server" proxyPort="443" scheme="https" secure="true"/>


There are 2 steps required in case of the communication done on HTTP:

1. On the LB/RP you need to configure it to send its http scheme (in this case https) as a request header to the tomcat servers.

In apache2, you may need to use the following line in apache2.conf (depends on your LB/RP)

RequestHeader add x-forwarded-proto “https”
2. On tomcat side, you need to tell it to use the protocol scheme of the LB/RP that is being sent in the headers.

To do so, you need to add the following valve to conf/server.xml

10 April 2015

About web security (1)

We usually implement web security with Roles and Permissions.

a Database Table for users and one for Roles which users belongs and one for Permission for the roles which the users a role should have.

[Users Table]    <- Many-to-one -> [Roles Table] <-  One-to-many -> [Permissions Table]

The above model is the basic, but we can add extra relation between the Users and the Permissions to allow direct permission on the table regarding the role in which the user belongs.

The Authentication does from the Users table.. the user is there and not disabled.

The Authorization is all about answering the question of "Is the user has access to this restricted object?"

How Authorization done?

In Web - where the restricted object is all about URL resources - the autorization is done as follows:

  • Every resource (a pattern for resources) in the system (should) have a list of permissions associated (usually only one) with it.
    Usually defined in the Permissions table as URL -> PERMISSION mapping. (or in XML as of spring-security)
    ex: '/editMyProfile.html' url mapped to CAN_EDIT_PROFILE permission.
  • When the user successfully login, a list of all permission is attached to him (either role permissions or user permission as discussed before)
  • Then when the user requests some URL, The system checks if the user has some attached permission that in the list of permissions that is associated with the url. If yes then the system allows the user to access the page, otherwise HTTP 403 is returned to the user.

How to draw the menu:

First you have your structure of menu (tree menu, list menu or whatever).
Initially, get all urls from Permissions table of the database and draw this permissions as following:

for (Permission p: permissions){
     if (userHavePermission(p.getPermissionName()){

the above is very simple code example.
Also you can consider nesting the menus by having a self-referential relationship in the Permissions table.

22 January 2015

Two notes about Java Generic Types (Type Covariance and Type erasure)

Java Generics have two characteristics that are important when working with generics of Java.

The first one is the most important and most well-known than the other, the second is less known.

1. Generics types are not Covariant:

All of us knows that List<String> cannot substitute List<Object>; however String[] can substitute Object[]

This prevent error in Generics that happens in case of arrays.

String[] sArr = new String[] {"Hello"};
Object[] oArr = sArr;
oArr[0] = 10; // << Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer

However in case of Generic types, such error is being caught  at compile time, and this is because Type Parameters (Generics) doesn't allow type covariance.


List<String> sList = new ArrayList<>();
List<Object> oList = sList; // Type mismatch: cannot convert from List<String> to List<Object>


2.  Type parameters is being removed in generated byte code (Called Type erasure).

This is why you cannot say: T.class

When you compile some code against a generic type or method, the compiler works out what you really mean (i.e. what the type argument for T is) and verifies at compile time that you're doing the right thing, but the emitted code again just talks in terms of java.lang.Object - the compiler generates extra casts where necessary. At execution time, a List<String> and a List<Date>are exactly the same; the extra type information has been erased by the compiler.