Friday, September 21, 2018

Eclipse RAP with Spring Boot

Intro

I like Eclipse :-). I've been using it for many years. I think the IDE is great and it is free! But Eclipse is much more than just the IDE. It is more like an ecosystem of applications, plugins and projects. Anyone can use the Eclipse Framework to create his/her own Eclipse-based application. It is called Eclipse RCP - Rich Client Application. Any RCP is based on the same principles as the Eclipse IDE: the product includes some features, any feature includes some plugins. 


I heard it is possible to include a plugin directly into the product but this is deprecated.
The UI in Eclipse Framework is based on 2 things:
  • The Application model
  • SWT - Standard Widget Toolkit
The Application Model is like a big "Mediator' (remember the pattern?) that handles interactions of many UI components at a high level. It is defined in an XML-like format. It defines windows, parts, commands, handlers, menus etc. 
SWT is a collection of widgets: buttons, labels, dialogs. These widgets are used to create the UI at the lower level than the Application Model. For example the UI within a part (MPart class) is created with SWT.

The Eclipse Framework can also be used to create web applications. It is called Eclipse RAP - Remote Application Platform. The idea is simple and impressive at the same time. The UI is created in Java with SWT widgets. In fact the UI is created with SWT widgets adapted for RAP. Then it is rendered in the browser. There is a special servlet that does the rendering RWTServlet (RWT may stand for Remote Widget Toolkit). Here is the link to the Developer's Guide for RAP.

And finally to the point. We all know that Spring Boot is awesome :-))! It must be the dominant platform for creating web applications. It offers some technologies to create the UI like JSP or Thymeleaf. But JSP is a little old and Thymeleaf could be a little less interactive than RAP. It would be great to make the two work together.

RAP Application with Spring Boot in a WAR file

The first option is to create a WAR with Spring Boot and RAP and deploy it to Tomcat. It is the option described in the Developer's Guide. Here is the link. I copied the important files.
The web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
  version="2.4">

  <context-param>
    <param-name>org.eclipse.rap.applicationConfiguration</param-name>
    <param-value>com.example.HelloWorldConfiguration</param-value>
  </context-param>

  <listener>
    <listener-class>org.eclipse.rap.rwt.engine.RWTServletContextListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>rwtServlet</servlet-name>
    <servlet-class>org.eclipse.rap.rwt.engine.RWTServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>rwtServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app> 

The application configuration:
public class HelloWorldConfiguration implements ApplicationConfiguration {
  public void configure( Application application ) {
    application.addEntryPoint( "/hello", HelloWorld.class, null );
  }
}
And the class:
public class HelloWorld extends AbstractEntryPoint {
  public void createContents( Composite parent ) {
    Label label = new Label( parent, SWT.NONE );
    label.setText( "Hello RAP World" );
  }
}
In order to make it work with the Maven WAR packaging put the web.xml into src/main/webapp/WEB-INF. The entry point in the application configuration must be configured for rwtServlet in web.xml.

For Spring Boot add the following:
@SpringBootApplication
public class SpringApp extends SpringBootServletInitializer {
  public SpringApplicationBuilder configure( SpringApplicationBuilder builder ) {
    return builder.web(WebApplicationType.NONE).sources(<configurations>);
  }
}

In pom.xml set the packaging to war.
<packaging>war</packaging>

There is though one important issue. Eclipse jars are not available in the Maven Central. Maybe it is possible to somehow use the p2 repository but I didn't try that. After all only one jar is necessary. I used the latest available version RAP 3.5. The jar is org.eclipse.rap.rwt_3.5.0.20180613-1038.jar.
I installed it manually to the local Maven repository and used the dependency in the pom.

This was enough to build a WAR and use it in Tomcat 9. No hacks necessary.

RAP Application with Spring Boot in an executable jar

This option looks more convenient. It would be really great to be able to use the RWTServlet inside Spring Boot. Then all the functionality like the executable jar and embedded Tomcat will work out of the box.
First return the main Spring Boot class to normal:

@SpringBootApplication
public class SpringApp {
    public static void main(String[] args) {
        SpringApplication.run(SpringApp.class, args);
    }
}
In fact Spring Boot can add a servlet with a ServletRegistrationBean:

@Bean
public ServletRegistrationBean<RWTServlet> servletRegistrationBean() {
    ServletRegistrationBean<RWTServlet> rwt = new 
ServletRegistrationBean<RWTServlet>(new RWTServlet(),"/hello", "/hello2");
    return rwt;
}

But unfortunately this is not enough. This RWTServlet requires a special context to be bound to the ServletContext. Previously in the WAR example the RWTServletContextListener handled this :-(.

But Spring Boot even in this desperate situation showed was it was worth :-). It can bind custom listeners by declaring them as beans! The default functionality of RWTServletContextListener  required some rework because as it turned out binding this listener from inside Spring Boot had some limitations. This is what I ended up with:

public class RWTSCLSimple extends RWTServletContextListener {

    private ApplicationRunner applicationRunner;

    @Override
    public void contextInitialized( ServletContextEvent event ) {
        ServletContext servletContext = event.getServletContext();
        ApplicationConfiguration configuration = new 
HelloWorldConfiguration();
        applicationRunner = new ApplicationRunner( configuration, 
servletContext );
        applicationRunner.start();
    }

    @Override
    public void contextDestroyed( ServletContextEvent event ) {
        applicationRunner.stop();
        applicationRunner = null;
    }
}

This class simplifies the initial functionality of RWTServletContextListener and removes some method calls which were "not acceptable for a listener not declared in web.xml" :-)). That error message was very funny.

Now this class must be declared as a bean and that's it:
@Bean
public RWTSCLSimple rwtSCListener() {
    return new RWTSCLSimple();
}

All Spring Boot functionality works out of the box, even server.servlet.context-path. If the reader doesn't mind the little workaround this option looks better than the first one.

Tuesday, September 11, 2018

Java's Process with Linux Shells

Intro

Today's post highlights some challenges of using Java's Process with Linux interactive shells and provides solutions to these challenges. 
The goal is more complex than being able to execute a Linux command and print a result. The idea is to be able to execute the shell in an interactive fashion. To be able to pass a command to the shell and print the output. And while java.lang.Process provides the I/O streams to do that there are some challenges involved. 
In my post I'll describe these challenges and show possible solutions. 

Interactive Output

Problem

The problem is that the process may print some data to the output over irregular intervals. The time it takes for a command to execute is not predefined. And it is preferable that the user be able to see the output in real-time.

Solution

Use a thread to read the output from Process.inputStream. The Thread wakes up every n milliseconds, reads what is available from the input stream and send to the appropriate destination. When the user wants to enter a command enter it immediately and return. 

Reading From Streams

This problem may sound silly, I understand. Java has all those great classes like InputStream, InputStreamReader, Reader etc. What is the problem with reading from the InputStream?
I thought along similar lines when began developing this code. But it turned out some issues were not obvious at all. 
Most of us are used to reading from a file. Practically everyone knows how to read from a File. But the important thing is that the file streams do not block at read. The input stream that is returned from Process.getInputStream() can actually block in this code (in bold):

InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
char[] isContents = null;
isr.read(isContents, totalCharsRead, isContents.length - totalCharsRead);

One has to use the isr.ready() method to find out if the next read will block like this:

while (isr.ready() && (totalCharsRead < isContents.length)) {
    currCharsRead = isr.read(isContents, totalCharsRead,      
        isContents.length - totalCharsRead);
    totalCharsRead += currCharsRead;
}

It is also important to understand that InputStream.available() may give you more bytes than is actually available! Yes, that is true but the reason for this unknown. If the char array is declared like this:
char[] isContents = new char[is.available()];
one has to keep track of the actual number of chars read by adding the returned value of InputStreamReader.read to some total value and then using this value.
Here is the complete code:

private String readFromInputStream(InputStream is) {
    try {
        if (is.available() > 0) {

            InputStreamReader isr = new InputStreamReader(is);
            char[] isContents = new char[is.available()];
            int currCharsRead = 0;
            int totalCharsRead = 0;
        
            while (isr.ready() && (totalCharsRead < isContents.length)) {
                currCharsRead = isr.read(isContents, totalCharsRead, isContents.length - totalCharsRead);
                totalCharsRead += currCharsRead;
            }
            return new String(isContents, 0, totalCharsRead);
        }
    } catch (IOException e1) {
        LOG.error("", e1);
    }
    return "";
}

Web UI

If a Web UI is necessary then WebSockets is the likely solution. Spring Boot has a good tutorial on how to use the Stomp client. 

Wednesday, August 29, 2018

2D Transform Pattern

Intro

Today is one more of my pattern ideas. Nothing very modern today, just a problem I ran into once while developing a UI. I hope someone will find this pattern interesting.

Motivation

This pattern formally describes a subclass of problems in programming. It is very common for a program to transform data from one format to another. This pattern describes the transformation from a 1D array to a 2D tree structure. 
1D arrays often may come from the configuration or the database. It is much easier to represent data as a flat array in the configuration file or in the table. The access time is better, the data structure is simpler. Computer programs are very good at working with 1D arrays.
But that is the programming language side. For the user long 1D arrays are very hard to read even if they are sorted. Humans prefer structured data like trees. 

Here is what we have:

0 1 2 ... n
Object Object Object ... Object

And here is what we'd like to show to the user:



The folders could be themselves objects or they could represent a collection of objects.

Applicability

Use this pattern when you need to transform a one-dimensional array of objects into a tree-like structure.

Structure

In order to transform the array into a tree structure this structure must exist before the transformation. The purpose of the code is to fill it in with the appropriate objects. This structure must consist of 2 node types: 
  1. Folders. They are not objects, they contain other folders or objects as children. Within the scope of this pattern we consider only "static" folders. Folders are not created during transformation.
  2. Object-folders. These are objects that can contain other objects as children. They are selected from the initial array. 
We have 2 things in the beginning: the flat array of elements and a tree structure. Here is an example of the tree structure:
The most important part of the pattern is the way to select objects. The "rules to select objects" are represented as template nodes with one or more selector nodes. Like
public class Template {
    private List<Selector> selectors;
    ...

The selector selects some nodes from the array. Any format can be used to specify the rules for the selector. The selectors are processed in the order they are added and the nodes they select from the array are added to the template. If this is an object-folder then only one object may be selected. Here is what the tree structure should look like:

Consequences

This structure with two tiers (Template and Selector) has some important advantages:
  1. Simple rules. Complicated rules can be broken into several simple ones with one selector for every simple rule. This could be even more important if the rules are regular expressions. 
  2. Order control. The order in which the objects are selected can be controlled with proper selectors. Adding selectors in the proper order could achieve the same result as a complicated sorting procedure. In the case special sorting is required that cannot be achieved with selectors the template can use a sorting function.
  3. UI Design. The selector may specify how the selected objects should look to the user. For example the selector may add an icon to the objects or specify the background color. 

Final Thoughts

I do not claim to have invented something completely new. I tried to explain in clear terms how to solve this problem of transformation from a 1D array to a 2D tree structure.

Monday, August 27, 2018

Javascript Inheritance

Intro

Inheritance in Javascript is bad! Everybody who has ever used Javascript knows that. The concept of "method inheritance" and prototypes could be even hard to grasp for someone who is used to more modern languages like Java. It was hard for me as well. But what if you really need to develop a small hierarchy in Javascript? Of course, there are some alternatives like GTW or Typescript with better support for classes and inheritance. But what if your boss just likes Javascript or the customer doesn't want to hear about any modern replacements? And Javascript has a lot of frameworks and libraries. Actually there are approaches to making a small hierarchy possible.

Abstract Factory Approach

Here is what we need to accomplish:

We cannot declare these properties on the functions and then write
BaseObject.prototype = new VeryBaseObject();
ConcreteObject.prototype = new BaseObject();
because modifying any of the maps from BaseObject or VeryBaseObject will change the maps for all descendants.

Solution

We are going to use a factory to create objects. It won't be an abstract factory just a factory. And use the reference to the actual object to set the properties on the object itself. We add some init functions that will create our properties:

Then in the factory we'll call these methods from the ConcreteObject like this:
switch(objectType) {
    case OBJECT_TYPE_CONCRETE1:
        obj = Object.create(new ConcreteObject1()); 
        break;
    ...
}
obj.initvbo();
obj.initbo();
obj.initCustom();

If the function is called from the ConcreteObject instance this will be that instance. And we'll have the necessary properties installed on the instance without affecting the prototype. 
Here is the object structure that we'll get:
With the properties on the ConcreteObject instance we can get a Java-like inheritance on Javascript. 

In fact it could be a bit more complicated than that if different functions need to be called for different object types. Then the method that creates the object must be modified to call the appropriate functions. 

This simple solution may help if it is REALLY necessary to create and use a Java-like object hierarchy in Javascript. 

Spring Data with Thymeleaf

Intro

Today I'll talk about more specific issues. No design patterns or algorithms this time :-). We don't always design software components from scratch. Often we have to try to make existing software components work together. 
Spring Boot is one the best free software in the Java world. It resolved a lot of configuration issues with Spring. It is very flexible and offers great functionality. 
Spring Data is part of the Spring collection of projects. It offers advanced tools for working with databases. Among the most useful is the automatic repository. A class can implement JpaRepository and most methods for working with data will be created automatically. 
Thymeleaf is a HTML template engine. It can use some of Spring Boot's features, like call methods of Spring beans in the template and a lot of other stuff. The official documentation has great tutorials. 
I used spring-boot-starter-parent versions 2.0.1.RELEASE - 2.0.4.RELEASE. Other dependencies were provided by Spring Boot.

Problem Description

The main idea of any application that is working with Spring Boot, Spring Data and Thymeleaf is to edit data in the database. spring-boot-starter-data-jpa includes Hibernate which can be used to manipulate the data in the database. Thymeleaf can be used to show the data to the user. Spring Boot wires it all together. 
A very simple scenario includes one entity with a one-to-many relationship with another entity. The user wants to be able to create a new entity and select the other entity in a HTML select box. 
Here is where the first issue shows up. With the standard Thymeleaf structure the backing bean cannot be assembled.The object that was selected in the select box with the following construct:

<form action="#" th:action="@{/<some Action>}" th:object="${beanObj}" method="post">

    .... <other fields>

    <select th:field="*{room}" class="textinput">
        <option th:each="currRoom : ${allRooms}"      
            th:value="${currRoom}" th:text="${currRoom.name}">no   
            name</option>
    </select>
</form>

is not created by Thymeleaf. I didn't find any mention of this in the official documentation.

Solution

After some debugging I found the root cause. It turned out Thymeleaf passes all the fields as parameters to the POST request. It uses the toString method to transform the object to String and add as a parameter to the POST request. It sends a parameter like this:
room: Room+[id=273,+name=room111]

In the controller method this value must be transformed back to the object form. Spring Boot uses converters to do this. 
The solution is - register the appropriate converters with the conversionService. And use these converters in the toString method of the entities to make sure the same method is used to convert to the String form and back. 

Next Problems

Sounds funny isn't it? The solution has been found but more problems? Actually the described solution works well without Spring Data. With Spring Data the conversion fails again. And Spring Boot wants you to create the entityManagerFactory bean even though this bean was not needed without Spring Data. 

Next Solutions

The problem with the entityManagerFactory bean can be resolved by means of some intensive search on the Internet. Here is the solution I ended up with:

    @Primary
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource ds) {
       LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
       em.setDataSource(ds);
       em.setPackagesToScan("<some packages>");

       JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
       em.setJpaVendorAdapter(vendorAdapter);
       em.setJpaProperties(additionalProperties());
       return em;
    }

    @Bean
    public SessionFactory sessionFactory(@Qualifier("entityManagerFactory") EntityManagerFactory emf) {
        return emf.unwrap(SessionFactory.class);
    }
private Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
        properties.setProperty("hibernate.default_schema", "public");
        properties.setProperty("hibernate.show_sql", "true");
        // Validation will fail because the tables use bigint as the ID but it is mapped to the Integer type by Hibernate
        // Validation expects a 8-bit number as the mapping to bigint.
        properties.setProperty("hibernate.hbm2ddl.auto", "none");
        return properties;
    }

The second problem turned out to be more complicated and required a lot of debugging. Eventually I found out that spring-data somehow changes the conversion service that Spring Boot is using. Instead of the default conversionService with Spring Data mvcConversionService is used. The formatters/converters must be added in your WebMvcConfigurer class (the class that implements WebMvcConfigurer). The method is addFormatters:

    @Override
    public void addFormatters(FormatterRegistry registry) {

        registry.addConverter(new <SomeConverter>);
        ...

Now with all problems resolved Spring Data can work with Thymeleaf. 
Happy coding and diligent debugging! 

Here is a link to Javacodegeeks Spring Data Tutorials

Thursday, August 23, 2018

Draft Tree

Intro

I like blogging about different design patterns, algorithms and approaches to solving different problems. This time I'll describe a problem I ran into some time ago and the approach I found to solve it. I always do not claim to have found a unique and absolutely perfect solution by myself. But I like the idea of keeping and reusing successful and interesting approaches to solving problems. Even if the code cannot be reused the idea itself is often very useful. This is not exactly a design pattern in the classical sense but it is more like a "design approach". But I'll describe it as a design pattern.

Motivation

If one wants to work with a DSL these days he or she usually has to use Antlr. This tool is free (BSD license) but is very useful. The grammars are simple enough. The code can be generated for Java, Javascript and other languages. In fact it is the tool of choice for anyone who wants to take on some DSL-related work.
When the grammar is complete and working well what the user has is the grammar tree. It looks like this:

This example is a logical expression from a simple grammar that parses logical expressions. The tree shows the grammar tree for 1 > 0 OR x < Y AND 10 > Z2. 
Antlr offers great tools to work with these trees: Listeners and Visitors. Listeners fire when a node is encountered and visitors visit nodes one by one. These tools are really great and help a lot. 

But what if the transformation one is trying to accomplish cannot be achieved with Antlr's listeners and visitors? This could be the case if the DSL structure is significantly different from the structure one is trying to achieve (we'll call it 'code structure' from now on. The implication is that the DSL is transformed into source code). 
Some people may try to modify the Antlr tree a little, some may add more complicated listeners/visitors. In this blog post I'll argue that there is a better solution.

Applicability

Use this pattern when you need to perform complicated transformations on the Antlr tree that are hard to accomplish directly with a listener or visitor.

Structure

There is a simple and elegant solution to this problem. We need to introduce an intermediate tree structure. In Java this can be accomplished with the class DefaultMutableTreeNode and other classes from javax.swing.tree. The API may look a bit old-fashioned with Enumeration and no generics but it works. The first tree instance is a copy of the Antlr tree with proper user objects in the nodes. Then we can slowly modify this tree step by step to make it look closer to the code structure. Usually if this structure is used there is no need to do it all in one step. Here is an example of the transformation:

This intermediate tree is like a draft that needs to be improved. After some steps it is ready to be transformed into the final code structure. 

Consequences

  1. Simplicity. The process of transforming the DSL into the code structure can be defined as simple, concise operations on the draft tree. This makes the transformation code less complex. The implementation may even use a modified version of the Assembly Line pattern.
  2. Loose coupling. All the operations on the draft tree are independent of the original DSL and the final code structure. If either the DSL or the code structure has to be modified the draft tree can be adapted to the new form by adding or removing steps. There is not tight coupling between the DSL and the code structure.

Final Thoughts

No sample code can be provided in this case because any code will be more specific than the design approach itself.

Thursday, August 16, 2018

Tree Creation - Mosaic Algorithm

Motivation

When I hear the word 'mosaic' I imagine an old, possibly ancient Roman, house with mosaic floors which depict ancient heroes. In the ancient times slaves spent many years putting the pieces in the correct order. 
The idea of a mosaic algorithm follows a similar pattern. Imagine that you have a lot of binary relations like "node A is the parent of node B", "node C is the child of node D", "nodes B and D are children of the same node". You can get such a set of binary relations from a natural language processing tool. For example the great Standford NLP library can give you a set of relations like 
  • Richard    per:children    Sonya
  • Sonya       per:siblings   Samantha
  • Samantha per:children   Robert
It would be great to build a complete tree from this set of relations. This is what the mosaic algorithm is about.

Applicability

Use this algorithm when you need to create a tree from a set of relations between the nodes. We assume that all the relations are correct even though the algorithm can handle duplicate relations.

Structure

The main idea is to use the set of relations as mosaic pieces. For every relation a fragment of the tree is created or modified. We'll consider 2 cases: a children relation and a sibling relation. Like this:

Subject
Relation
Object
Children
NodeX
children
NodeY
Siblings
NodeA
siblings
NodeB
This converts to the following structures in the code;

For any of these relations any node may already exist among the created fragments. It is also possible that no nodes exist for this relation. The actions necessary are summarized in the table:


Subj doesn’t exist,
Obj doesn’t exist
Subj exists,
Obj doesn’t exist
Subj doesn’t exist,
Obj exists
Subj exists,
Obj exists
Children
Create 2 nodes: one parent, one child
Find the parent in the existing nodes, add a child node
Create the parent node, find the child in the existing nodes and add it as a child to the parent node
Establish the relation if the nodes belong to different fragments (have different roots)
Siblings
Create 2 nodes with a dummy parent
Find the existing sibling, add a dummy parent if necessary, add a new child to the parent
Find the existing sibling, add a dummy parent if necessary, add a new child to the parent
Establish the relation if the nodes belong to different fragments (have different roots)

As every relation is processed either a new fragment is created or an existing fragment is modified. When relation processing is complete we have the full picture.
Only one important part of the algorithm remains - how to find the existing nodes for a relation. To achieve this after every relation is processed the newly created nodes are added to a Map or ArrayList (If the node has a unique key the HashMap is faster than the ArrayList).
An illustration how the tree is evolving as the relations are being processed:

Final Thoughts

I think I should be humble and avoid claiming that a new algorithm has been invented. This algorithm could be a special case of a well-known more general algorithm. But the idea looked interesting and I decided to write a post about it.