Thursday, 18 April 2013

Calling Javascript From Java (Example)

This post explains how to call Javascript from Java. The code example is available at GitHub in the Java-Javascript-Calling directory.

Code Example

We create some small Javascript code in a string. This code dumps "Hello World!" and defines a function called myFunction() adding 3 to the provided value:
public class JavascriptCalling {

    public static final String MY_JS
        = "print(\"Hello world!\\n\");"
        + "var myFunction = function(x) { return x+3; };";

    public static void main(String[] args)
            throws ScriptException, NoSuchMethodException {

        // Retrieving the Javascript engine
        ScriptEngine se = new ScriptEngineManager()
            .getEngineByName("javascript");

        if ( Compilable.class.isAssignableFrom(se.getClass()) ) {

            // We can compile our JS code
            Compilable c = (Compilable) se;
            CompiledScript cs = c.compile(MY_JS);

            System.out.println("From compiled JS:");
            cs.eval();

        } else {

            // We can't compile our JS code
            System.out.println("From interpreted JS:");
            se.eval(MY_JS);

        }

        // Can we invoke myFunction()?
        if ( Invocable.class.isAssignableFrom(se.getClass()) ) {

            Invocable i = (Invocable) se;
            System.out.println("myFunction(2) returns: "
                + i.invokeFunction("myFunction", 2));

        } else {

            System.out.println(
                "Method invocation not supported!");

        }

    }

}
The above starts by retrieving the Javascript engine. Next, if one can compile the Javascript, our code is compiled. The script is executed, which prints "Hello World!". Last, if the engine allows invocation, we call our function defined in our Javascript code.

The result is:

Tuesday, 2 April 2013

Creating A Customized Spring User & Persistence

This post explains how to create a customized Spring user and persistence mechanism for authentication. The code is available at GitHub in the Spring-MVC-Customized-User directory.

Things To Take Into Consideration

Before creating a customized user, we need to remind what a user is in Spring. We know from here that a user is an implementation of the UserDetails interface. Spring security also requires a loading mechanism, as an implementation of the UserDetailsService interface. To keep this example simple, we are not going to implement login/logout or other security features.

The UserDetails interface is a bit incomplete in order to define a user in a real application. It defines getters and no setters. It is not a big deal, but the real pain is that the username (a string) is considered as 'the' key. Most software developers will prefer a long id.

To solve these issues, we define a PracticalUser interface:
public interface PracticalUserDetails
        extends UserDetails, CredentialsContainer {

    long getId();

    void setPassword(String password);

    void setAccountExpired(boolean b);

    void setAccountLocked(boolean b);

    void setCredentialsExpired(boolean b);

    void setEnabled(boolean b);

    void setAuthorities(
        Collection<? extends GrantedAuthority> authorities);

}
Typically, one would use JPA annotations on the implementation bean and save it in a database in a real application. However, for this example, the DAO will register users in an in-memory map as described further.

The UserDetailsService interface does not provide a get user per name or id, which is necessary for an administrator (for example). More, it does not allow to retrieve all existing users' id and name, or to update or insert users, or even to delete them.

Therefore, we create a PracticalUserDetailsService interface to solve these issues:
public interface PracticalUserDetailsService
        extends UserDetailsService {

    Set<PracticalUserDetailsDAO.UserIdentifiers> getUsers();

    void deleteUser(long id);

    void upsertUser(PracticalUserDetails user);

    PracticalUserDetails getUser(long id);

    PracticalUserDetails getUser(String username);

}
The corresponding implementation is called PracticalUserDetailsServiceInMemory for this example.

In-Memory DAO

To keep this example simple, we define a simple PracticalUserDetailsDAO:
public interface PracticalUserDetailsDAO<U extends PracticalUserDetails> {

    void create(U user);

    boolean contains(U user);

    U read(String username);

    U read(long id);

    void update(U user);

    void delete(String username);

    void delete(long id);

    interface UserIdentifiers {
        long getId();
        String getUsername();
    }

    Set<UserIdentifiers> getUsers();

}
We also define a special user id and name identifier interface to retrieve the set of existing user data, without returning all users. Our implementation of PracticalUserDetailsDAO is PracticalUserDetailsDAOInMemory.

In a real implementation, using a JPA Repository is more appropriate.

Configuration

In the security.xml file, we define our practical user detail service (it will be registered in the authentication manager) and the in-memory DAO bean:
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http auto-config="true">
    </http>

    <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref='practicalUserDetailsServiceInMemory' />
    </authentication-manager>

    <beans:bean id="pud"
        class="com.jverstry.DAO.PracticalUserDetailsDAOInMemory">
    </beans:bean>

</beans:beans>

The JSP Pages

We use two pages. The main page displays registered users (together with a delete link) and registration form:


The second page is displayed when the Create User button is clicked to check the name and the password:


The Controller

The controller is used to check the username and password:
@Controller
public class MyController {

    @Autowired
    private PracticalUserDetailsServiceInMemory pudm;

    @RequestMapping(value = "/")
    public ModelAndView index() {

        ModelAndView result = new ModelAndView("index");

        result.addObject("users", this.pudm.getUsers());

        return result;

    }

    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable(value="id") String id) {

        this.pudm.deleteUser(Long.parseLong(id));

        return "redirect:/";

    }

    @RequestMapping(value = "/create")
    @SuppressWarnings("AssignmentToMethodParameter")
    public ModelAndView add(
            @RequestParam(value="name")
            String name,
            @RequestParam(value="password")
            String password) {

        name = StringUtils.replace(name, " ", "");
        password = StringUtils.replace(password, " ", "");

        String errorMsg = "";

        if ( name.length() == 0 ) {
            errorMsg += "Name is empty ";
        }

        if ( password.length() == 0 ) {
            errorMsg += "Password is empty ";
        }

        if ( errorMsg.isEmpty() ) {
            this.pudm.upsertUser(new PracticalUserDetailsImpl(name, password));
        }

        ModelAndView result = new ModelAndView("create");

        result.addObject("errorMsg", errorMsg);
        result.addObject("username", name);

        return result;

    }

}

Running The Example

One can run it using the maven tomcat:run goal. Then, browse:

  http://localhost:9191/spring-mvc-customized-user/

More Spring related posts here.

Execute Spring ACL SQL Script In Memory

This post describes how to execute the Spring ACL script to create ACL tables in an in-memory HSQL database instance. The code is available at GitHub in the Execute-ACL-SQL-Scripts-In-Memory directory.

In-Memory DataSource

We are using a configuration classe implementing the DisposableBean interface to shut down the created HSQL embedded database nicely.
@Configuration
public class InMemoryDataSource implements DisposableBean {

    private EmbeddedDatabase ed;

    @Bean(name="hsqlInMemory")
    public EmbeddedDatabase hsqlInMemory() {

        if ( this.ed == null ) {

            EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();

            this.ed = builder.setType(EmbeddedDatabaseType.HSQL)
                .addScript("aclSchema.sql").build();

        }

        return this.ed;

    }

    @Override
    public void destroy() {

        if ( this.ed != null ) {
            this.ed.shutdown();
        }

    }

}
When creating the database, we also have the aclSchema.sql script executed. It must be located at the root of the resource directory:


The content of the script is taken from the Spring documentation appendix.

Checking Table Creation

We extract the list table of tables in the controller. Technically speaking, we should do this at the service/DAO level, but for the sake of this example, we'll keep it simple:
@Controller
public class MyController {

    @Autowired
    EmbeddedDatabase hsqlInMemory;

    @RequestMapping(value = "/")
    public ModelAndView home() {

        ModelAndView result = new ModelAndView("index");

        ArrayList<String> tables = new ArrayList<String>();

        JdbcTemplate tplate = new JdbcTemplate(hsqlInMemory);

        SqlRowSet retr = tplate.queryForRowSet(
            "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES");

        while (retr.next()) {
            tables.add(retr.getString(1));
        }

        result.addObject("tables", tables);

        return result;

    }

}

Running The Example

One can run it using the maven tomcat:run goal. Then, browse:

  http://localhost:8585/execute-acl-sql-scripts-in-memory/

We find the tables we have created:


More Spring related posts here.

Monday, 1 April 2013

Centering An Image Or Text Within A Div

This post explains how to center an image or text in HTML using CSS. The code example is available on GitHub in the Center-Image-Text-Div directory.

Centering An Image Vertically And Horizontally Within A Div

The method described here requires to know the size of the image. The HTML is the following:
<div id="myDiv">
    <img id="myImg" src="SomeImg.jpg">
</div>
The CSS is the following:
#myDiv {
    height: 100%;
    width: 100%;
}

#myImg {
    position: absolute;
    top: 50%;
    left: 50%;
    /* My image height divided by 2 */
    margin-top: -47px;
    /* My image width divided by 2 */
    margin-left: -188px;
}
The image is always positioned at the center of the window, even when it is resized. This example is inspired from the solution provided by deviousdodo on a StackOverflow question.

Centering Text Within A Div

The HTML is the following:
<div id="width:100%">
    <div id="someText">This text is always centered!</div>
</div>
The CSS is the following:
#someText {
    width: 300px;
    margin: 0px auto;
    text-align: center;
}
One must set a width larger than the text, and set the text alignment to centered.

Thursday, 28 March 2013

Java ServiceLoader Example

Defining an API and developing the corresponding implementation has become an uber mainstream practice when developing large Java applications. Modularization is such an useful design principle, especially to avoid spaghetti code, for testing and debugging, and for re-implementation of old code.

Many developers seek to separate API interfaces and abstract classes from their implementation in separate packages. Yet, this almost always leads to cycles between java packages (api refers to impl, and vice-versa). There has been many frameworks, such as OSGi, supporting modularization, but the documentation has not always been good and complete. Many developers have struggled with class loading issues too.

Fortunately, Java has delivered the ServiceLoader utility since release 6. The example described in this post is available from Github in the Java-ServiceLoader directory. It is inspired from here.

Service & Implementation

We define a simple interface and its implementation:
package com.service.API;

public interface MyService {
    long getTime();
}


package com.service.API.Impl;

import com.service.API.MyService;

public final class MyServiceImpl implements MyService {

    public MyServiceImpl() { };

    @Override
    public long getTime() {
        return System.currentTimeMillis();
    }

}
The API and the implementation are located in different packages. Only the implementation refers to the API. The implementation must have a public parameterless constructor.

Service Loading

Next, we declare the implementation in a file having the fully qualified name of the API under the META-INF/services directory in the .jar:


The file contains fully qualified name of the implementation:

    com.service.API.Impl.MyServiceImpl

Next, we load the service using the ServiceLoader:
public class MyApp {

    public static <T> T loadService(Class<T> api) {

        T result = null;

        ServiceLoader<T> impl = ServiceLoader.load(api);

        for (T loadedImpl : impl) {
            result = loadedImpl;
            if ( result != null ) break;
        }

        if ( result == null ) throw new RuntimeException(
            "Cannot find implementation for: " + api);

        return result;

    }

    public static final MyService myService = loadService(MyService.class);

    public static void main(String[] args) {

        System.out.println("Time is: " + myService.getTime());

    }

}
The service implementation is loaded with the loadService static method. The main method prints the current time in milliseconds. It is that simple!

Sunday, 24 March 2013

Java TestNG Example

This post illustrates some of the feature of TestNG. The code example is available at GitHub in the Java-TestNG directory. We use maven. Therefore, the configuration will located in the pom.xml.

Source Code

We use a very simple class returning integers for testing purposes:
public class Generate {

    private Generate() { }

    public static int aOne() {
        return 1;
    }

    public static int aTwo() {
        return 2;
    }

    ...

}

Test Code

The test code for the above class is the following:
public class GenerateNGTest {

    public GenerateNGTest() { }

    @Test(groups = {"testGroupA"})
    public void testAOne() {
        assertEquals(1,Generate.aOne());
    }

    @Test(groups = {"testGroupA", "testGroupB", "windows.QTests"})
    public void testATwo() {
        assertEquals(2,Generate.aTwo());
    }

    @Test(groups = {"testGroupA", "testGroupC", "windows.PTests"})
    public void testAThree() {
        assertEquals(3,Generate.aThree());
    }

    @Parameters({ "testNgParam" })
    @Test(groups = {"testGroupA"})
    public void testAFour(@Optional("4") String testNgParam) {
        assertEquals(Integer.parseInt(testNgParam),Generate.aFour());
    }

    @Parameters({ "testNgParam2" })
    @Test(groups = {"testGroupA"})
    public void testASix(String testNgParam2) {
        assertEquals(Integer.parseInt(testNgParam2),Generate.aSix());
    }

    public class DataForTests {

        @DataProvider(name = "forTestAFive")
        public Object[][] forTestAFive() {
            return new Object[][] {
                { new Integer(5) },
                { new Integer(6) }
            };
        }

    }

    @Test(dataProvider = "forTestAFive", dataProviderClass = DataForTests.class)
    public void testAFive(int param) {
        assertEquals(param,Generate.aFive());
    }

    @Test(dependsOnGroups = { "windows.*" })
    public void testASeven() {
        assertEquals(7,Generate.aSeven());
    }

}
  • Some test groups are defined for test methods. These can be activated in the configuration described further.
  • The testAFour() method takes in a parameter and defaults to 4 if none is provided.
  • Rather than setting parameters in the configuration, one can define a DataForTests class and use it to pass parameters as in the testAFive() method.
In this example, we do not cover factories and automatic test generation, programmatic executions of tests and test methods interceptors.    

Configuration

In the pom.xml:
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.14</version>
  <configuration>
    <groups>testGroupA</groups>
    <systemPropertyVariables>
      <testNgParam>4</testNgParam>
      <testNgParam2>6</testNgParam2>
    </systemPropertyVariables>
    <parallel>methods</parallel>
    <threadCount>2</threadCount>
  </configuration>
</plugin>
We activate tests belonging to testGroupA and we pass parameter values for testNgParam and testNgParam2. We also let TestNG run each test method in parallel using 2 threads. This can significantly accelerate the testing phase when compiling the project.

Wednesday, 20 March 2013

'package javax.servlet.http does not exist' Solution

This is a common error which occurs when trying to compile a web project. This package is usually provided by the container. However, it is not (always) available at compile time and one should not include it in the final .war too.

If you are using Maven, the solution is simple. Add the following dependency with the provided scope:
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>
Your IDE will be able to compile your project and won't include the library in your .war.

You can also use the following dependency:
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>6.0</version>
    <type>jar</type>
    <scope>provided</scope>
</dependency>