04 March 2016

Why logging frameworks did not make use of Java 8 like JUL did

1)
In scala the language, there's three types of value definition; regular variables that are initialized once reached by the execution environment like:

val x: Int = getXValueFromDatabase()

the function getXValueFromDatabase()will be executed once this line is reached.

The second type is lazy variables, the will not be evaluated until the variable is used, and the syntax like:

lazy val x: Int = getXValueFromDatabase()

The third type is defined like functions (actually there are functions) and defined using the function definition syntax like:

def x: Int = getXValueFromDatabase()

and will be evaluated each time the symbol x is referred.
see this SO question: http://stackoverflow.com/q/9449474

2)
In the java world, there's variables like the first type in scala and methods like the third type in scala, and also there's Initialization-on-demand holder idiom

The most common used is the variables and methods.

So, how can we use it in Logging?

Look to the javadoc from sfl4j
void info(String format,
        Object... arguments)
Log a message at the INFO level according to the specified format and arguments.
This form avoids superfluous string concatenation when the logger is disabled for the INFO level. 
What it can do for you is that it defers the string concatenation until the framework do a check like the following:

 if (!isLoggable(level)) {
     return;
 }

but this is not enough, calling external service/resource to get the information to log is resource wasting when the log level is higher than the one specified in the application.

So, can we make use of lazy or even function calls here, where the logging peace of data is not calculated until the check of (isLoggable) is done?

Yes, JUL did it, using Java8 Supplier interface

Look to this example:

package test;

import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LoggingExample {

    public static void main(String[] args) throws Exception {
        Logger logger = Logger.getGlobal();
        logger.addHandler(new FileHandler(System.getenv("HOME") + "/logging_example.log"));

        logger.setLevel(Level.INFO);

        logger.fine(() -> String.format("V1 - the value of the expensive resource is \"%s\"",
                getSomeExpensiveResourceListExternalServiceCall("V1")));

        logger.fine(String.format("V2 - the value of the expensive resource is \"%s\"",
                getSomeExpensiveResourceListExternalServiceCall("V2")));

        logger.info(() -> String.format("V3 - the value of the expensive resource is \"%s\"",
                getSomeExpensiveResourceListExternalServiceCall("V3")));

        logger.info(String.format("V4 - the value of the expensive resource is \"%s\"",
                getSomeExpensiveResourceListExternalServiceCall("V4")));
    }

    private static Object getSomeExpensiveResourceListExternalServiceCall(String version) {
        System.out.println(version + " - GETTING THE EXPENSIVE RESOURCE");
        return "some expensive resource";
    }
}

I run this example with setting the logger level to info (as shown) and here's the std out:

V2 - GETTING THE EXPENSIVE RESOURCE
V3 - GETTING THE EXPENSIVE RESOURCE
V4 - GETTING THE EXPENSIVE RESOURCE

Not that, V1 does not call the getSomeExpensiveResourceListExternalServiceCall at all.
This is because the supplier will never be executed until the following check is done:

 if (!isLoggable(level)) {
     return;
 }

This is a good usage of Java 8, and every single logging framework should make use of it.

29 February 2016

Scala or Kotlin

JVM has many language based on it, many of them are famous like Groovy, Scala, Koltin and others.

In the past I've played with Scala, now I try to post the same code snippet in Scala and in Koltin (actually koltin looks like scala in many ways):

Scala Code:

// scala

object Main {
  def main(args: Array[String]): Unit = {

    val a = 10
    val b = 50
    println(apply(a, b, { (x, y) => x * y }))
    println(apply(a, b, sum))

    val l = List(1, 3, 5)
    l map { _ * 2 } filter { _ > 4 } foreach { println(_) }
  }

  def sum(a: Int, b: Int): Int = a + b

  def apply(x: Int, y: Int, f: (Int, Int) => Int) = f(x, y)
}

Koltin Code:
// kotlin

fun main(args: Array<String>): Unit {

    val a = 10
    val b = 50
    println(apply(a, b, {x, y -> x * y}))
    println(apply(a, b, ::sum))

    val l = listOf(1, 3, 5)
    l.map { it * 2 } .filter { it > 4 } .forEach { println( it ) }
}


fun sum(a: Int, b: Int): Int = a + b

fun apply(x: Int, y: Int, f: (Int, Int)-> Int) = f(x, y)


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 {

@Override
public void destroy() {

}

@Override
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));
return;
}
}

chain.doFilter(req, res);
}

@Override
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:

http
.httpBasic()
.and().authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.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)

Test


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


Conclusion

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

Introduction:

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)

Note:

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)


Update:

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"/>

references: 

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()){
           out.println(p.getUrl());
     }
}

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