Pages

Showing posts with label java8. Show all posts
Showing posts with label java8. Show all posts

Thursday, November 10, 2016

Template Engines at One : Spring-Boot and Engines setup review after Deprecated Velocity.


  Let’s dive for while into the Template engines problematics of MVC based frameworks. 

  In next minutes the text will brings you to the mystery of different templating possibilities supported by Spring Boot framework.   

  Spring Boot became to be very popular because of its configuration possibilities  and full support of spring based application. Spring Boot follows the simple moto “just run”, wait a sec, no, it’s not NIKE. In the age of “Micro-Services” and cutting monoliths this motto, in     Spring way, has quite nice impact on desired application prototyping.  

  I don’t think there is any necessity to go much deeper into the Model View Controller (MVC) design pattern issue because there is a mass of other articles which can be easily found. 
  The main intent of the following text is to review the setups of the different Java Template Engines for Spring based application. How can even such question come into the focus ?   
  Well, the reason is that Velocity Engine is deprecated for a while and a lot developers around the globe need to find well fitting alternative.
  Let’s begin and define the set for our test. We put into the comparison following engines:

  1. Apache Velocity
  2. Apache FreeMarker 
  3. Thymeleaf
  4. Pebble
  I’ve not included JSP Engine because JSPs are mature technology and has been around since the early days, which means that thousands and more articles has been already written around. The fact that JSPs are really hard to beat in case of raw speed stays but this is not in the focus now.

  By having prepared MvcConfiguration class which extends WebMvcConfigurerAdapter:
@Configuration
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
...
  The mentioned MvcConfiguration class must define @Bean ViewResolver that can negotiate about the proper request ViewResolver.
@Bean(name = "viewResolver")
public ViewResolver contentNegotiatingViewResolver( ContentNegotiationManager manager) {
        List resolvers = ...
  Each of mentioned template engines has under the folder webapp its own directory dedicated only to it. Such directory (velocity, freemarker, thymeleaf and pebble) contains only engine related files.
  And here is the Deprecated engine that has been widely used over last several years: 

Apache Velocity 
   Apache Velocity Template Engine is used for the comparison and also to make testing other three alternatives (FreeMarker, Thymeleaf and Pebble) little bit simpler. Apache Velocity is one of Jakarta project. Each of Velocity templates is processed but not compiled to Java which supports better code separation.
Following code snippets configures Spring Boot ViewResolver and enables the Velocity usage:
...
@Bean(name = "velocityViewResolver")
public ViewResolver getVelocityViewResolver() {
   VelocityViewResolver resolver = new VelocityViewResolver();
   resolver.setSuffix(".vm");
   resolver.setCache(true);
   return resolver;
}
...
  Having configured ViewResolver we need to add it to the contentNegotiatingViewResolver @Bean which  gives us the access to the ContentNegotiationManager. The ContentNegotiationManager provides look up methods to the file extensions based on MediaType. In the example case will be 
used based for specific engine file suffix search
...
@Bean(name = "viewResolver")
public ViewResolver contentNegotiatingViewResolver( ContentNegotiationManager manager) {
   List resolvers =
      Arrays.asList(getVelocityViewResolver(),
      ...
  Inside the directory webapp we create directory velocity and simple velocity template. We call the file test.vm and it will contain following content:
<html lang="en">
<head>
    <title>Test Velocity</title>
</head>
<body>
<h2>This is $test</h2>
</body>

</html>
  We are almost done. There is only one more important thing. For setting up specific Spring Boot application properties has been used configuration file called application.properties located inside the project resources folder. 
In velocity case it will contain loader path setup (ps: you can customise it)
spring.velocity.resourceLoaderPath=/velocity/
  Congratulation!  Deprecated Template Engine Velocity us UP and Running, but this is not all what we want to achieve so we continue with the next alternative:

Apache FreeMarker
  The 1st considered candidate as the replacement to Velocity is the FreeMarker. FreeMarker is currently coming from the Apache projects incubator supporeted by Apache Software Foundation (ASF). ASF puts its effort to support FreeMarker development, which is very good sign, for long life. The one more reason may be that FreeMarker is widely used across the Apache family projects, good example is newly accepted NetBeans one!
Let’s add FM support to sample project by configuring ViewResolver in the following way:
@Bean(name = "freeMarkerViewResolver")
public ViewResolver getFreeMakerViewResolver() {
   FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
   resolver.setSuffix(".ftl");
   resolver.setCache(true);
   return resolver;
}
  We need to add also properly FreeMarker ViewResolver to the ContentNegotiationManager inside the MvcConfiguration @Bean:
@Bean(name = "viewResolver")
public ViewResolver contentNegotiatingViewResolver( ContentNegotiationManager manager) {
   List resolvers =
      Arrays.asList(getVelocityViewResolver(),
                    getFreeMakerViewResolver(),
                    ...
  Now is the sample application ready for the simple FreeMarker templates. Inside the webapp folder we create new folder called freemarker and we add following two files:
index.ftl
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test applicaiton</title>
</head>
<body>
<h2>This is test application Main sample site</h2>
</body>

</html>
and magic.ftl file which will contains simple FM tags
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Magic Spell: ${word}!</title>
</head>
<body>
<h2>MagicHappens by word: ${word}!</h2>
</body>

</html>
but hold on it’s not enough in case of FreeMarker we can not forget to properly add configuration inside the application.properties file:
spring.freemarker.templateLoaderPath=/freemarker/
  Now it’s done we have FreeMarker up and running inside our sample project!
Well done and we can move to the next one which is:

Pebble Template Engine
  It’s quite new player on the market. It promises quite useful inheritance features and easy to read syntax but comment this is out of the scope of this article. This article is focused on ViewResolver Configuration and having it up and running as the motto of Spring Boot. As the first step we need to again configure ViewResolver properly. In case of Pebble, all is slightly more complicated because the result of the configuration is extremely closely connected with the Servlet config it self. Let’s see, we go back again in the @Bean  MvcConfiguration and we add: 
@Bean(name="pebbleViewResolver")
public ViewResolver getPebbleViewResolver(){
   PebbleViewResolver resolver = new PebbleViewResolver();
   resolver.setPrefix("/pebble/");
   resolver.setSuffix(".html");
   resolver.setPebbleEngine(pebbleEngine());
   return resolver;
}
  Previous has been mentioned that Template may support configuration by application.properties file, this is currently not the case of Pebble. We need to configure all manually and we need to define more Pebble related @Bean
@Bean
public PebbleEngine pebbleEngine() {
  return new PebbleEngine.Builder()
                .loader(this.templatePebbleLoader())
                .extension(pebbleSpringExtension())
                .build();
}

@Bean
public Loader templatePebbleLoader(){
   return new ServletLoader(servletContext);
}

@Bean
public SpringExtension pebbleSpringExtension() {
  return new SpringExtension();
}
  As you can see the templatePebbleLoader @Bean requires direct access to the ServletContext which needs to be injected into the configuration @Bean
@Autowired
private ServletContext servletContext;
...
  It also means that by doing this Pebble takes over the any created servlet and will play default choice when any other exists. This may not be bad but when you want to use Pebble and for example Thymeleaf together, you need to do slightly more Spring hacking.

Now we have prepared Pebble configuration so let’s create new pebble folder under the webapp and add a new template file pebble.html
<html>
<head>
    <title>{{ pebble }}</title>
</head>
<body>
{{ pebble }}
</body>

</html>
Now we are ready, Pebble is up and running and we can go directly to the last option: 

Thymeleaf Template Engine
  Thymeleaf present itself as the ideal choice for HTML5 JVM web development, it may be true but it’s over the scope of this article and you can try this claim by using the example project over my GitHub account. Thymeleaf has better Spring support  than Pebble. This allows us to use for its configuration application.properties file and add Thymeleaf setup options there:
spring.thymeleaf.prefix=/thymeleaf/
spring.thymeleaf.suffix=.html
but the rest is very similar to Pebble,
@Bean(name = "thymeleafViewResolver")
public ViewResolver getThymeleafViewResolver() {
  ThymeleafViewResolver resolver = new ThymeleafViewResolver();
  resolver.setTemplateEngine(getThymeleafTemplateEngine());
  resolver.setCache(true);
  return resolver;
}
  Thymeleaf takes similarly control over the any new Servlet creation as you can see in MvcConfiguration @Bean
@Bean(name ="thymeleafTemplateEngine")
public SpringTemplateEngine getThymeleafTemplateEngine() {
  SpringTemplateEngine templateEngine = new SpringTemplateEngine();
  templateEngine.setTemplateResolver(getThymeleafTemplateResolver());
  return templateEngine;
}

@Bean(name ="thymeleafTemplateResolver")
public ServletContextTemplateResolver getThymeleafTemplateResolver() {
  ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
  templateResolver.setPrefix("/thymeleaf/");
  templateResolver.setSuffix(".htm");
  return templateResolver;
}
  Now it’s time to add ViewResolver into the content negotiation configuration: 
@Bean(name = "viewResolver")
public ViewResolver contentNegotiatingViewResolver( ContentNegotiationManager manager) {
   List resolvers =
      Arrays.asList(getVelocityViewResolver(),
                    getFreeMakerViewResolver(),
//                  getPebbleViewResolver()
                    getThymeleafViewResolver()
                );
      ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
      resolver.setViewResolvers(resolvers);
      resolver.setContentNegotiationManager(manager);
      return resolver;
}
...
  As the last step we create again under what webapp folder new folder called thymeleaf and we add thyme.htm file there: 
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Thymeleaf</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'HERE IS, ' + ${thyme} + '!'" />
</body>

</htm>
  And big applause you have successfully configured all four Spring Boot Supported Template Engines. 
At the end of the configuration section, it is important to point out that each of engines has assigned its own @Controller which is responsible for proper output generation: 

1.Velocity Controller 
@Controller
public class VelocityHelloController {

    @RequestMapping(value = "/velocity")
    public String test(Model model){
        System.out.println("Test");
        model.addAttribute("test", "Here is Velocity");
        return "test";
    }

}
2. FrameMarker
@Controller
public class FMHelloController {


    @RequestMapping("/")
    public String index(){
        System.out.println("INDEX");
        return "index";
    }

    @RequestMapping("/magic")
    public String magic(Model model, @RequestParam(value = "word", required=false, defaultValue="MagicHappens") String word) {
        System.out.println("MAGIC");
        model.addAttribute("word", word);
        return "magic";
    }

}
3. Pebble
@Controller
public class PebbleHelloController {

    @RequestMapping(value = "/pebble")
    public String something(Model model){
        System.out.println("Pebble");
        model.addAttribute("pebble", "The Pebble");
        return "pebble";
    }
}
4.Thymeleaf
@Controller
public class TLHelloController {


    @RequestMapping(value = "/thyme")
    public String something(Model model){
        System.out.println("Thymeleaf");
        model.addAttribute("thyme", "The Thymeleaf");
        return "thyme";
    }

}

Configuration experience Summary
  Now is the right time to write few last words about the general feeling from all mentioned possibilities. I don’t want to highlight any of those tested choices as the best replacement to the Deprecated Velocity Template Engine but from the configuration experiences and Spring framework support, I’d choose FrameMarker. By Choosing FreeMarker I won’t be limited in using Velocity and any other option in parallel, but as has been mentioned before doing right choice is out of the scope of this article. 
I've created sample gradle project which imports all Temple engines starter. This setup can be find inside the configuration file build.gradle


dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
    compile("org.springframework.boot:spring-boot-starter-freemarker:$springBootVersion")
    compile("org.springframework.boot:spring-boot-starter-velocity:$springBootVersion")
    compile("org.springframework.boot:spring-boot-starter-thymeleaf:$springBootVersion")
    compile("com.mitchellbosecke:pebble-spring-boot-starter:$pebbleVersion")
    testCompile "junit:junit:${junitVersion}"
}

Enjoy the sample project in testing yours choice !!!


used versions:
Java JDK: 1.8.111
Spring-Boot:  1.4.1.RELEASE

Pebble: 2.2.3

Monday, October 24, 2016

Robo4j introduction to the reactive "real-time" micro-services based IoT system development

  
Robo4j testing system : camera unit, ultra-sonic, gyro, color and touch sensors. Whole system contains also one  Raspberry Pi, Lego Brick and CuBox i4Pro (4-core CPU) with 500GB hard-drive as re-usable data-storage. Whole system is powered by 2x2500mAh and one 25000mAh unit.
  What is going to be discussed in this article is the high level perspective of the upcoming robo4j.io framework and the Internet Of Things (IoT) system design, so let’s move forward.
  Over the last few years has been one of the most emerging topic micro-services (and still is) followed by reactive manifesto, which explains how to design non-blocking highly responsive, resilient, elastic and message driven parts of the application. From my perspective, all those articles have been focused on the web applications of middle and big sizes. Most of the articles have been describing the best practices about how to split the monolithic systems or how to employ the news trends in micro-services and non-blocking design patterns. 
  Only few of them have been touching other emerging technologies around Internet of Things (IoT) in the way I’ve been searching for. 
  Over the years, reading many of them, I got a strong feeling that the way how we intend to develop IoT systems is, that we take already developed robust technologies and we make them smaller.  These days we have on the market good examples of the successes, we do use Spring-boot, Netty, Vert.x or others.  Those frameworks allow us basically to connect the developed system with different types of databases, analysed and react on events or data, obtained from the data storages. 
The question is still there,  is this really enough ? 
Is such kind of abstraction good enough that it could allows us to develop robust IoT systems ? 
  The IoT systems that can react on incoming events, sorts them properly and in special cases forwards them to the proper system parts, which could process and execute such events ? 
  I don’t think so or I’ve not found anything like this on the market.

  We can go further in questioning ourselves about the IoT possibilities, which can quite soon turn into the Artificial Intelligence discussion. In my opinion, the AI question is not relevant for the article, because even most of the currently available IoT systems can’t still exhibit its intelligence in the manner of intelligent (independent) decisions. This question is reserved for another IoT focused article. 
  Let’s go back to the main topic: advanced Internet of Things system development and design. Before we start here a small review of the definition taken from Wikipedia: 
   “The Internet of Things (IoT) is the internetworking of physical devices, vehicles, buildings and other items—embedded with electronics, software, sensors, actuators, and network connectivity that enable these objects to collect and exchange data”. In other words IoT are objects that are connected to the internet or other networks and those objects are allowed to receive and process data. 

   The definition looks pretty cool and good so far, until you try to use some of those connected “smart” objects together. Now is the IoT system the collection of the independent IoT units and suddenly nothing works as expected due to connection instability, communicaiton protocols message ordering etc. 
  Although such a system has been assembled from cutting edge parts, altogether they simply don’t work, due to previously touched issues or other ones we are not even aware of. The whole development may turn into the really FUZZY mode.  
Such a style of development I normally call try, push, deploy development (TPDD) but this style may not fully satisfy the expectations or needs, it simply doesn’t work in a long term perspective. PS: there is still a chance that I may be wrong.
The described situation can become really frustrating and stressful, especially when there are not so many possibilities on the market. You may use ROS (Robot Operating System) but … let’s go back.

  The lack of proper tools on the market was main motivation to develop robo4j.io framework which satisfies the following needs: 
  1. The robo4j.io is capable to synchronise incoming asynchronous events/messages under the dynamically changing conditions at “real-time” . 
  2. The robo4j.io framework should be able to allow and enforce rapid micro-sevices based system development.
  3. The robo4j.io should be a light framework that is capable to run on any hardware supported by JVM. It means on any Java Powered device and it provides full performance
  4. The robo4j.io should be independent, not hardware specific, it must be flexible to extend
  5. The robo4j.io should have a control over all running units inside the robo4j.io eco-system 
  6. The robo4.io should enforce communication with external systems
  7. The robo4j.io should be easy to use
   All those seven mentioned points are really challenging. Any of them is trivial as it may seem.  I’ve taken this challenge and I’ve developed such a tool that satisfies all of them. I’ve developed already the mentioned robo4j.io framework.
  The robo4j.io framework allows to connect and control any device that is accessible over the specific type of network (Ethernet, WiFi, Bluetooth etc.) or wire. And moreover,  robo4j.io enforce the usage of any of technology running on JVM with its natural language (Scala, Groovy etc.).
   
  Now it’s time to take a look at the basic framework architecture from a high level perspective which is the main intent of this article. The image below shows the high perspective reaction between the different parts inside the robo4j eco-system. It’s important to see the differences between the inputs to the system.
Robo4j framework high-perspective architecture
  Such input could be provided by Sensors, Motors (Engines) or RoboSockets types. The incoming messages is then processed by the system itself and serialised in the manner that the result can be executed on the connected hardware.
Inside the message process stage the system may use different types of datastorages that are available to a specific RoboUnit. This means, that each RoboUnit may have or not it’s specific data resource or each RoboUnit may share them with another one in reactive, non-blocking manner. 
  The Robo4j Message Bus is not dependent on the order, how any specific message is processed. The bus consumes the messages in order of their arrival. The bus may dynamically change the conditions in real time. The pre-results are then moved into the MessageReactors parts. Those parts have again connections to the datastorages, where their results can be stored. The final result can be executed on the real hardware or can involve the whole system state inside the predefined cloud. 
  Finally we are at the end of the motivaiton article about robo4j.io framework. The whole text should motivate you to use it, because the Internet of Things is the future of IT. 
The future of IoT includes the communicaiton security, different kinds of messages processing and reaction on them. The Robo4j framework is supposed to be part of this future.
Stay tuned.
Robo4j IoT system (robot) is discovering a park



   

Sunday, August 21, 2016

Java 8: How to create executable fatJAR withouch IDE :: command-line : explained

  The executable fatJAR (fat Java ARchive) is pretty handy thing. Besides the fact that it can be quite big, it contains all necessary libraries to execute the developed program. 
The JAR file is based on ZIP format.
  In the previous posts:
a.  "Java 8 : How to create executable JAR without IDE, command-line :: explained"
b.  "Java 8 : How to create executable JAR without IDE with packages, command-line :: explained
we have explained how we handle pure JAVA project without any external libraries with or without complicated package structure. 
  The goal of current post is to create fatJAR file. The JAR which contains all necessary external libraries. Let's start slowly by creating new pure java project over the command line. We call it 
"Executable-Two" (GitHub)
  The executable-two project has following folder structure:
./ExecutableTwo.jar
./libs
./libs/ExecutableOne.jar
./out
./README.md
./src
./src/main
./src/main/java
./src/main/java/com
./src/main/java/com/exec
./src/main/java/com/exec/two
./src/main/java/com/exec/two/Main.java
./src/main/resources
./src/main/resources/META-INF
./src/main/resources/META-INF/MANIFEST.MF
  The folder LIBS contains previously created JAR file "ExecutableOne.jar". 
The "ExecutableOne.jar" contains the MagicService class which we will use inside the project "ExecutableTwo". We will instantiate the class MagicService and execute the public method getMessage(). All this will happen inside the Main class of the project "ExecutableTwo". Let's create following Main class in the project 
package com.exec.two :
1 package com.exec.two;                                                                                                                                                                  
2                                                                                                                                                                                        
3 import com.exec.one.service.MagicService;                                                                                                                                              
4                                                                                                                                                                                        
5 public class Main {                                                                                                                                                                    
6                                                                                                                                                                                        
7     public static void main(String[] args){                                                                                                                                            
8                                                                                                                                                                                        
9         System.out.println("Executable-Two Main");                                                                                                                                     
10         MagicService service = new MagicService();                                                                                                                                     
11         System.out.println("MagicService from Executable-ONE");                                                                                                                        
12         System.out.println("MESSAGE: " + service.getMessage());                                                                                                                        
13                                                                                                                                                                                        
14     }                                                                                                                                                                                  
15                                                                                                                                                                                        
16 }
   Now we have everything ready for fatJAR file creation. We have imported MagicService from the jar library we have previously created and we have executed it's getMessage() method. 
For the next steps we will use javac and jar tools provided by Java JDK. Let's open the command line and compile the project. In the command we need to inform the compiler that we should extend its classpath about the used library.
$javac -cp ./src/main/java 
./src/main/java/com/exec/two/*.java -d ./out/ 
-classpath ./libs/ExecutableOne.jar
  The "Executable-Two" project has been successfully compiled into the OUT directory.
Now it's time to properly prepare OUT directory for fatJAR creation. Inside the directory are available only compiled class we have created for project "Executable-Two". We will use again for JAR file creation jar tool, but the problem is that jar tool reads only the file physically located on the filesystem. The jar tool won't read compressed jar file. 
It means even when we copy the ExecutableOne.jar into the OUT directory jar tool will not unpack the ExecutableOne.jar file and the library will be add to the result but ignored.

   The problem is that $java -jar tool does not read inner packaged *.jar archive files!  

  It implies that we need to unpack previously created Java Archive (JAR) "Executable-One.jar" into the "Executable-Two" project OUT directory.
Open the command line and type: 
$cp libs/ExecutableOne.jar ./out/
$cd ./out
$tar xf ExecutableOne.jar
$rm ExecutableOne.jar 
  Used JAR tool command options: x - extract, f - file
  Now  "Executable-Two" project output directory OUT is ready to be used as the source folder for the new JAR file.
NOTE: inside every executable jar file is only one MANIFES.FM file available.
  For packing our "Executable-Two" project into the JAR archive file we do use newly created manifest file located in the folder ./src/main/resources/META-INF/ :
1 Manifest-Version: 1.0                                                                                                                                                                  
2 Class-Path: .                                                                                                                                                                          
3 Main-Class: com.exec.two.Main   
and now we can pack all together by typing:
$jar cvfm ExecutableTwo.jar ./src/main/resources/META-INF/MANIFEST.FM -C./out/ .
  When we executed the created fatJAR file we received following output:
$java -jar ./ExecutableTwo.jar
output:
Executable-Two Main
MagicService from Executable-ONE
MESSAGE: Magic Message
  Now we have achieved the GOAL and we have created "Executable-two.jar" executable fat Java Archive.
Congratulation!

Friday, August 19, 2016

Java 8 : How to create executable JAR without IDE with packages, command-line :: explained

  Following post is the extension to of the Executable-One project. In the previous post was explained how to create simple executable jar file. 
  The goal of this post is to show how to deal with more complicated package structure. 
We create MagicService which provides us getMessage() method with the String output. 
Let's open the command line and create new folder SERVICE with file MagicService.java: 
command
$mkdir src/main/java/com/exec/one/service
$vi src/main/java/com/exec/one/service/MagicService.java
  The newly created MagicService may look in following example: 
1 package com.exec.one.service;                                                                                                                                                          
2                                                                                                                                                                                        
3 public class MagicService {                                                                                                                                                            
4                                                                                                                                                                                        
5     private final String message;                                                                                                                                                      
6     public MagicService(){                                                                                                                                                             
7         this.message = "Magic Message";                                                                                                                                                
8     }                                                                                                                                                                                  
9                                                                                                                                                                                        
10     public String getMessage(){                                                                                                                                                        
11         return message;                                                                                                                                                                
12     }                                                                                                                                                                                  
13                                                                                                                                                                                        
14 }
  The MagicService is obviously located on the different place in the package structure then the Main class. Now we go back to the Main class and import the newly created MagicService
  After the import and service instantiation the Main class will receive the access to the getMessage() method. 
The Main class will change: 
1 package com.exec.one;                                                                                                                                                                  
2                                                                                                                                                                                        
3 import com.exec.one.service.MagicService;                                                                                                                                              
4                                                                                                                                                                                        
5 public class Main {                                                                                                                                                                    
6     public static void main(String[] args){                                                                                                                                            
7         System.out.println("Main Class Start");                                                                                                                                        
8         MagicService service = new MagicService();                                                                                                                                     
9         System.out.println("MESSAGE : " + service.getMessage());                                                                                                                       
10     }                                                                                                                                                                                  
11 } 
  Now we have reached the point where the code is ready to compile. 
Let's go back to the command line and go into root folder of the Executable-One project. 
  The first step will be to compile/re-compile Executable-One project into the OUT folder. For those purposes we need add the location of newly created class MagicService.java. 
javac -cp ./src/main/java ./src/main/java/com/exec/one/*.java ./src/main/java/com/exec/one/**/*.java -d ./out/
  The second step is to create executable JAR file from compiled classes. We don't need to make any changes to the command because we have not changes JAR file logic. It means MANIFEST.FM file stays without any changes: 
1 Manifest-Version: 1.0                                                                                                                                                                  
2 Class-Path: .                                                                                                                                                                          
3 Main-Class: com.exec.one.Main 

And we  are free to use command from previous blog post:
jar cvfm ExecutableOne.jar ./src/main/resources/META-INF/MANIFEST.MF -C ./out/ .
end
We are done with the JAR file. Now we can execute it in the command line with following output:
$java -jar ExecutableOne.jar 
output: 
Main Class Start
MESSAGE : Magic Message

  We have done enough changes for the upcoming blogpost focused on creating fatJAR file with libraries and again without ANY IDE or building tools such as Gradle, Maven or Ant, all is pure command line and Java JDK

NOTE: details to javac, jar tools were explained in the PREVIOUS POST.

Thursday, August 18, 2016

Java 8 : How to create executable JAR without IDE, command-line :: explained

  In the world of build tools (Ant, Maven or Gradle) it may seems to not being even useful to think about the command line. The most of famous IDEs (IntelliJ, Eclipse or NetBeans ... others) offers building tools implementation immediately.  
  But in some of very few moments you have only the command line and no internet (someone has turned it off)
What will you do then ? 
  In this post we compile simple project with multiple classes and library dependencies . The classes are located on different places in the project package structure. We will also create appropriate manifest file. 
 The goal of this post to have executable JAR file. Let's call it ExecutableOne.jar. 
The only requirements is to have properly configured java JDK. In this blog post is used java 1.8 build 91. 
  All is ready and we can open the command line and continue...
Let's start with creation of simple project: executable-one
The example project structure is following Maven Standad Directory Layout structure: 
./libs
./out
./README.md
./src
./src/main
./src/main/java
./src/main/java/com
./src/main/java/com/exec
./src/main/java/com/exec/one
./src/main/resources

   As our intent is to create executable JAR file we create main class in the 
package:  com.exec.one 
Package can be find in the folder SRC/MAIN/JAVA of our sample project structure.
1  package com.exec.one;
2
3  public class Main {
4     public static void main(String[] args){                                                                                                                                            
5         System.out.println("Main Class Start");                                                                                                                                        
6     }                                                                                                                                                                                  
7 } 

Inside the folder SRC/MAIN/RESOURCES we create META-INF folder and then inside we place MANIFEST.FM file. 
Let's open the newly created MANIFEST.FM file and put basic description. 

1 Manifest-Version: 1.0   
2 Class-Path: .                                                                                                                                                                          
3 Main-Class: com.exec.one.Main

NOTE: There will be the only one MANIFEST.FM file per JAR file. 
MANIFEST file contains details how JAR file will be used. We don't go into deep details only let's be focused on the option we have defined: 
1. Manifest-Version  : manifest file version 
2. Class-Path: The application or extension class loader uses the value of this attribute to construct its internal search path. Originally class loader downloads and opens each element in its search path. For this purposes simple linear search algorithm has been used.
3. Main-Class: there is the name of the class which will the launcher load at the startup time 
... for more information use google

  Now we create the first version of executable JAR file without any *.jar library. The LIBS folder in our project structure is still empty. 
  First we need to compile the project by using javac and the output we store inside the 
OUT folder. Let's go back to our command line and inside the root of the poject type:
$javac -cp ./src/main/java ./src/main/java/com/exec/one/*.java -d ./out/
project is compiled into the OUT directory. You can check it by using ls command.
  Second step we create executable JAR file from the resources located inside the OUT directory. We go back to the command line and type following command:
$jar cvfm ExecutableOne.jar ./src/main/resources/META-INF/MANIFEST.MF -C ./out/ .
  Brief explanation of the JAR tool options we have used: 
c - indicates we want to create new jar file
v - generates for us verbose output to standard output
f - specifies the jarfile to be created 
m - indicates manifest file we use. Manifest file includes name: value pairs 
option -C indicates temporary changes directory. Classes are added from this directory to the jar file. The dot indicates all classes (files).

FINAL RESULT -> opent the command line and type: 
$java -jar ./ExecutableOne.jar
standard output: 
Main Class Start

The blog post will continue
   The next post will show how to create fatJAR file with libraries without using any IDE, only pure command line.

My GiTHub Project: execute-one


Monday, June 13, 2016

Robo4j log stardate 2242.007: alfa-0.2 is out


  This short blog post doesn't intent to be documentation to the new Robo4j.io alfa-0.2 release. This blog post is more like log what kind of new features are inside. 
  In the alfa-0.2 release I've included initial version of robot communication over the HTTP layer. The module is called "robo4j-brick-client". This module can be compiled as a standalone application by using gradle command. I've put there possibility to build up fatJar file. 
This *.jar file is then uploaded to the LegoEV3 brick and run as the program. 
  The "robo4j-brick-client" does included tiny server. The tiny server employs the socket communication. The server task is to handle incoming massive streams of requests. Communication is simple JSON like! (not final version
  The web server responsibility is to analyse, consume and transform incoming tasks/event into the internal signals. Those signals are queued and latter processed by the underlaying hardware. In early-bird releases it will be mostly LegoEV3 Robot. 
  Current release slowly introduces AGENT based structure which will responsible for monitoring, analysis and latter system rearrangement at the runtime. Underlaying agent technology will be also responsible for Robot decisions. 
  Robo4j.io future is bright  ... a lot of amazing things are coming and they will be there soon. 

PS: I'm not planing publish full Robo4j.io the highly responsive version.