Friday, April 10, 2020

Creating multipurpose executable Jar file

As the title says, this recipe is focused on creating a multipurpose jar file, where a single jar file can be used for multiple requirements. I am going to cover the whole process by diving into the following steps:
1) Create a Java application
2) Bundling into an executable Jar file
3) Running a Jar file

I take a problem scenario to explain the above steps and how they are carried out.

We want to have a java application, which should have addition, subtraction, multiplication and division functionalities,  that we can call those functionalities providing the command line parameters. For example

add 2 4 4 (result=2+4+4)
subtract 54 12  (result=54+12)
multiply 12 54 55 (result=12*54*55)
divide 34 17 (result=34/17)

So, let's start:
1) Create a Java application
I am creating a Java application with Gradle as a build tool because it is easy to use. I am creating 4 classes with the main method which is responsible for corresponding operation and parameters. One option could be to create a single method and get an operation as a parameter, which makes it really complex to handle parameters. If we create a main method for each operation, it makes our tasks of handling parameters easy.

So, I begin with creating four java classes with main method, which manipulates the arguments to get the corresponding result. Because the example task is very simple, our actual task could be way bigger with many dependent libraries. So, we define a bunch of libraries in "build.gradle" file and we create a "fatJar" with all dependencies included in the jar file. An alternative will be we copy dependent libraries in the classpath.

I begin with the fatJar method, which create a jar file with all dependent libraries automatically from gradle. For this, we have to write a method to create fatJar. Have a look at the sample build.gradle file.

File: build.gradle


The method jar create the jar file without dependencies. But the fatJar create a jar file with all dependencies, and we can use out of the box.

So, after definition of Gradle build information.

Now, we create class files with specific operation in main methods. The class files look something like this:

The application structure looks like this:

So far, we have created a java application with the required operations.

2) Bundling into an executable Jar file

Bundling into an executable Jar file is quite easy because we have already written a method in build.gradle file above. So, we just call

gradle clean && gradle fatJar

The created Jar file will be in folder build/libs as shown above(Operations.jar)

Note: If we simply run "gradle build", then it will create a thin jar file(i.e. without dependencies)

3) Running a Jar file

The Last Step is to execute the Jar file Operations.jar. The bundled jar file includes all the classes, and we can run all operations providing corresponding arguments.
For example:
java -cp Operations.jar com.kpaudel.operations.Add 12 34.33 45.3


Similarly, we can check all other operations providing the parameters. 

java -cp Operations.jar com.kpaudel.operations.Subtract 123.56 23

java -cp Operations.jar com.kpaudel.operations.Multiply 12.2 34.5

java -cp Operations.jar com.kpaudel.operations.Division 12 2 2

So, we can independently manage each operation with their own arguments, which makes very easy to handle input arguments. Apart from this advantage, bundling into a single jar file makes it easy to deploy, which means only a single jar file with many operations can be called separately.

I am using this method to create download and upload operations for my cloud storage, getting advantage of using the same jar file for different purposes of download and upload operations(with independent input parameters.) 

I hope you have enjoyed this recipe.  Thanks for reading :)

Tuesday, December 31, 2019

Bye bye 2019

My 2018 technical resolutions were:
1) GIT = Thorough Learning

  • Created git repository server
  • Learned git client commands
  • Learned more in professional work in the new company      
2) Gradle = Thorough Learning

  • Learned some groovy language concepts
I got familiar with another popular build tool maven from professional work.

3) NodeJS = Implement RestAPI (with NoSQL DB)
     Positive: familiar with the server with nodejs
4) NoSQL(MongoDB) (partly from professional project)
    Positive: Familiar with MongoDB

5) ReactJS
    Negative: Could not manage time to learn ReactJS

6) Docker
  Positive: Learning with ongoing professional work.

7) RestAPI (Server & Client) (from the professional project)
  Neutral: Learned something but not advanced.

8) WebSocket Server & Client (Spring & NodeJS) (from professional project)
  Neutral: Not so positive progress.

9) Python(with Tensorflow)
  Positive: Learned virtual environment, Tkinter GUI tool, deployment with docker.

10) Hobby Projects in Arduino & Raspberry PI: Implement the above technologies in these projects
 Neutral: Learned something but not enough.

11) Jenkins
Positive: Implemented Jenkins to automate the build and deploy process. (partly from professional work)

12)Spring Boot: (from the professional project)
Positive: Learned spring boot concepts from professional work. 

Wednesday, October 30, 2019

LED Strips Programming (Arduino)

Today, I am going to share my experience on the LED Strips programming using Arduino. It will be fantastic to decorate on Christmas nights, which you can program each LEDs as required like we could create a cool animation.

This article does not go into detail. This will just give you the idea on how we can program LED strips and you can program the lights according to your need.

Let's begin, we need the following items before we begin the programming.

1) Arduino
2) Power Source (10 V)
3) Wires
4) LED Strip

We connect the power source to one end of the led strip. Normally positive wire of strip is red, and negative is white. The white is grounded with the ground of strip. Strip has also cables to be connected to the Arduino. The red and white are 5v and GND respectively. GND should be connected to the negative of the power supply. Note that the green color cable is used for the color signal which we normally connect to PIN 7 of Arduino.

Now we come to our actual task: programming. Before we start we have to install the needed libraries.

We need Adafruit_Neopixel and optional Tinkerkit libraries. Adafruit library is used to actual programming while Tinkerkit libraries make it easy to read sensor values because we are using sensor to control the led lights.

#include "Adafruit_NeoPixel.h"
#include "TinkerKit.h"
#include "math.h"

#define PIN 7

#define NUMPIXELS 20

Here the PIN is the output PIN of Arduino, and a number of pixels(NUMPIXELS)  mean the number LEDs in the LED.

We further define the required variables as follows:

// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

TKLightSensor lightSensor(I0);
TKButton onOffButton(I1);
TKPotentiometer potentiometer(I2);

bool increasing = true;

// we want to randomly select from these colours

const int COLOURS[][3] = {
    {25512864}, //Red
    {6425564},  //Green
    {6464255},  //Blue
    {25525532}, //Yellow
    {25564255}, //Pink
    {64255255}, //Cyan
    {255255255} //White

const int NCOLOURS = sizeof(COLOURS) / sizeof(*COLOURS);

// this structure holds the state of the given pixel

struct PixelState
    // is the pixel currently on
    boolean on;
    // time at which the pixel was turned on or off
    unsigned long timeMarkMs;
    // amount of time for which the pixel should remain off
    unsigned long offTimeMs;
    // selected colout if the pixel is on
    int selectedColour;
    // most recent max brightness. We keep this to stop us
    // sending colour changes to the pixels if it is unnecessary
    // this is important, because neopixels use a timing-based protocol
    int mostRecentBrightness;
    boolean increasing;

// we have 4 pixels

struct PixelState pixel[NUMPIXELS];

// I want the pixels to sparkle, so I will use a triangle wave,
// which is to say that they will come on at full brightness and them fade

const unsigned long FADE_TIME_MS = 1000; // three seconds

// the pixels should come on at a random time, To simulate this,
// the pixel will be off for a random amount of time.

const int MIN_OFF_TIME_MS = 500;
int MAX_OFF_TIME_MS = 2500;
//int delayValue=500;

After this, we initialize everything in the setup block.

void setup()
    for (int i = 0; i < NUMPIXELS; i++)
        pixel[i].on = false;
        pixel[i].timeMarkMs = millis();
        pixel[i].offTimeMs = random(MIN_OFF_TIME_MS, MAX_OFF_TIME_MS);
        pixel[i].increasing = true;
        pixel[i].selectedColour = random(NCOLOURS);

    strip.begin(); // Allocate NeoPixel buffer
    strip.clear(); // Make sure strip is clear;

Now the interesting part is to actually define animation which runs continuously in a loop.

void loop()
    for (int i = 0; i < NUMPIXELS; i++)
        float light =;
        int button =;
        int dimmerValue =;

        MAX_OFF_TIME_MS = map(dimmerValue, 0102410000600);

        if (light > 50)

        if (pixel[i].on)
            // pixel is on

            if (millis() - pixel[i].timeMarkMs >= FADE_TIME_MS)
                // time to turn the pixel off
                strip.setPixelColor(i, 000);
                pixel[i].timeMarkMs = millis();
                pixel[i].offTimeMs = random(MIN_OFF_TIME_MS, MAX_OFF_TIME_MS);
                Serial.print("off time");
                pixel[i].mostRecentBrightness = 0;
                pixel[i].on = false;
                // calculate the new brightness as flaoting point
                // this is the bit that you change if you want the fade pattern to change
                float brightness = 1 - (millis() - pixel[i].timeMarkMs) / ((float)FADE_TIME_MS);
                brightness = brightness * brightness; //gamma correction

                // ok. do we actually need to change the pixel colour?
                int mostRecentBrightness = 255 * brightness;
                if (mostRecentBrightness != pixel[i].mostRecentBrightness)
                    // yes we do
                    pixel[i].mostRecentBrightness = mostRecentBrightness;
                                        (int)(COLOURS[pixel[i].selectedColour][0] * brightness),
                                        (int)(COLOURS[pixel[i].selectedColour][1] * brightness),
                                        (int)(COLOURS[pixel[i].selectedColour][2] * brightness));
            // pixel is off. do we need to turn it on?

            if (millis() - pixel[i].timeMarkMs > pixel[i].offTimeMs)
                pixel[i].on = true;
                pixel[i].mostRecentBrightness = 0; // this will force an update next loop
                pixel[i].selectedColour = random(NCOLOURS);
                pixel[i].timeMarkMs = millis();


This example code is a just a kind of animation I have created. But we can use the power of
Arduino to define cool animations in your own way.
Just try yourself :)

Monday, April 22, 2019

Arduino Basics

Arduino is a simple, programmable micro-controller.  In this article, I am gonna write some tips which make programming with Arduino more simple.

1) Installation 

The first step will be the installation of Arduino from here:

You, normally select the latest version for download, not nightly build versions.

I downloaded 1.8.9 version.

Extract the downloaded compressed file into /opt/arduino (for example). Just run the file inside the extracted Arduino folder.

2) Settings for Visual Studio Code

After installation is complete, we have to carry out some settings in visual studio code. First, install the Arduino extension and after installation is complete, restart IDE. Then we create a workspace folder.

~/workspace/arduino /src/Project1

Now, we open the arduino folder from VSCode IDE. Now, using


A: Arduino:BoardConfig
B: Arduino:Initialize
C: Arduino:Select Serial Port

The final step is to define the build folder in arduino.json created in the root directory.

 "output": "build",

This is, I guess, automatically created. But to be safe, add this line.

3) Create a Program

The most interesting part is here.

Create a new program example.ino  with the following contents

void setup() {
// initialize digital pin LED_BUILTIN as an output.

// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second

Then we first verify the correctness of the program. And then upload the program.

Verification:  CTRL+SHIFT+P => Arduino:Verify  (Shortcut: CTRL+ALT+R)
Upload: CTRL+SHIFT+P => Arduino:Upload (Shortcut: CTRL+ALT+U)

Problems faced

While uploading I faced the following problem

An error occurred while uploading the sketch
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied

I did not know how secure is this, but I made the terminal readable and writable for all. And restarted IDE, then it worked! I ran the following command from the terminal.

sudo chmod a+rw /dev/ttyACM0 

Now, we can use the power of visual studio code to develop Arduino programs. 

Note: Because we can not place multiple files and run. To achieve this we create a folder structuer inside src folder of root.  For example:


Monday, March 11, 2019

Simple Windows Installer

For windows system, is there any possibilities of creating a packaged installer like DEB in Ubuntu system? I have carried out some research and studies to find out the solution for this. Although there are possibilities to create a packages exetutable installers using different tools. After thorough comparison and reviews I got to conclusion that NSIS (Nullsoft Scriptable Install System) provides the best solution for that. It is really simple, everything is scripts, also very scalabale and powerful.

So, lets get started!

I create a basic installer using some files and scripts as resources. Please note that there are many possibilities we could add more functionalities. This article describes a very basic example on how we can create a simple installable packaged executable which can be deployed for installation.

We just write scripts into a file with extension *.nsi and installer is created from the scripts defined in the file. There are possibilities to create shortcuts, copy resources, define UI and many more. 

The first step to begin with is to install NSIS software which can be found at

After installation, we have to install NSIS plugin for visual studio code. Then, we have advantage of autocompletion and easy compilation. 

Writing a NSI file is divied into different blocks with their specific tasks and all blocks are run sequentially(there are some exceptions like Uninstall block runs at the time of uninstalling the application.) 

1) Definition Block

This block defines different variables which we wanted to define here. We can define a variable using

!define MUI_PRODUCT "Frietec Google Service"
!define AUTHOR ""

2) Basic Block

The basic block is very important because we define the Name, output file and install directory where the application is supposed to be installed. For example

OutFile "FE-Google.exe"
InstallDir "C:\Frietec\${MUI_PRODUCT}"

3) Macro Block

We can create installed without macro block, but using macro block makes further improvements such as greater looking GUI and so on. A sample macro block is 

!include MUI2.nsh
!define MUI_ICON "Resources\installer.ico"
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_LANGUAGE "German"

4) Section Block

The section block backbone where we define the processese of installation in different sections. We define scripts to copy resources or create uninstaller and define scripts and so on. 

For example:

Section "install" Installation
  # Copy scripts 
  SetOutPath $INSTDIR
  #File Scripts\Calendar.bat
  #File Scripts\Drive.bat
  #File Scripts\Email.bat
  File /r Scripts scripts
  SetOutPath $INSTDIR\resources
  File Resources\email.ico
  File Resources\drive.ico
  File Resources\calendar.ico
  File Resources\installer.ico  
  WriteUninstaller $INSTDIR\uninstall.exe

Section "Shortcuts"
  CreateDirectory "$Desktop\${MUI_PRODUCT}"
  CreateShortCut "$Desktop\${MUI_PRODUCT}\Uninstall.lnk" "$INSTDIR\Uninstall.exe"
  CreateShortCut "$Desktop\${MUI_PRODUCT}\Shortcut to Email.lnk" $INSTDIR\scripts\"Email.bat" Icon $INSTDIR\resources\"email.ico"
  CreateShortCut "$Desktop\${MUI_PRODUCT}\Shortcut to Drive.lnk" $INSTDIR\scripts\"Drive.bat" Icon $INSTDIR\resources\"drive.ico"
  CreateShortCut "$Desktop\${MUI_PRODUCT}\Shortcut to Kalendar.lnk" $INSTDIR\scripts\"Calendar.bat" Icon $INSTDIR\resources\"calendar.ico"  

  CreateDirectory "$SMPROGRAMS\${MUI_PRODUCT}"
  CreateShortCut "$SMPROGRAMS\${MUI_PRODUCT}\Uninstall.lnk" "$INSTDIR\Uninstall.exe"
  CreateShortCut "$SMPROGRAMS\${MUI_PRODUCT}\Email.lnk" "$INSTDIR\scripts\Email.bat" Icon $INSTDIR\resources\"email.ico"
  CreateShortCut "$SMPROGRAMS\${MUI_PRODUCT}\Drive.lnk" "$INSTDIR\scripts\Drive.bat" Icon $INSTDIR\resources\"drive.ico"
  CreateShortCut "$SMPROGRAMS\${MUI_PRODUCT}\Kalendar.lnk" "$INSTDIR\scripts\Calendar.bat" Icon $INSTDIR\resources\"calendar.ico"

Section "Uninstall"
  Delete $INSTDIR\uninstall.exe
  RMDir /r "$INSTDIR\*.*"
  #Delete $INSTDIR\*.*
  Delete "$Desktop\${MUI_PRODUCT}\*.*"
  RMDir "$Desktop\${MUI_PRODUCT}"
  #Delete "$Desktop\FE-Google\Shortcut to Kalendar.lnk"

5) Function Block

The block block is where we define functions. A typical usage is to display messagebox when installation success or uninstallation is done.

For example:

#Function that calls a messagebox when installation finished correctly
Function .onInstSuccess
  MessageBox MB_OK "You have successfully installed ${MUI_PRODUCT}. Use the desktop icon to start the program."
Function un.onUninstSuccess 
  MessageBox MB_OK "Sie haben erfolgereich deinstalliert=> ${MUI_PRODUCT}."

The compilation creates an executable installer file in the same directory. We can execute this file to get installed. Similarly we can install it by clicking the unistall link in the installation directory or can be defined as a short for simplicity.

The full project is available at the following github location:

Friday, February 22, 2019

Spring Boot with GWT using gradle build

Today I am going to write an interesting concept, which will be quite useful to quickly start and deploy a  big project without worrying about any javascript complexities.

It is well accepted that Spring Boot is very popular backend framework and I have to say, it is not quite supportive for front-end development. For that we have to use frontend development system using Javascript, because Javascript is the only option. And the communication to the server using Javascript makes less maintainable code. Also, using GWT, we write both server and client side program using a single programming language Java, which makes it a very scalabale and maintaible project. That's my experience because I use a framework called echo( which is quite stable and very very maintainable.

Lets begin implementing Spring boot with GWT. It seems a bit complicated, have a patience because end result is very interesting.

I am using eclipse IDE for development. So, I assume you have already installed it including JDK(1.8 is preferrable). Please be sure the installed gradle version is greater or equal to 4.0 for SpringBoot to work.

Step 1: Project Creation

Now create a new gradle project from eclipse IDE or using gradle command.

gradle init --type java-library

and just import created project into eclipse. This is the basic project project. We have modify this project.

Step 2: Configuration

We carry out build configuration in build.gradle file. It is recommended to remove all the contents and use the following content:
classpath 'org.wisepersist:gwt-gradle-plugin:1.0.6'

//Required for springboot
id 'java'
id 'org.springframework.boot' version '2.1.3.RELEASE'
apply plugin: 'gwt'
apply plugin: 'io.spring.dependency-management'

sourceCompatibility =1.8
def GWT_VERSION='2.8.2' //latest version


//not needed (if you use default values). The following values
// are default values, so not necessary.
sourceSets{ "src/main/java"
main.resources.srcDir "src/main/resources" "src/test/java"
test.resources.srcDir "src/test/resources"

//Just add this 4 libraries for gwt
    //Spring libraries
      exclude module: 'spring-boot-starter-tomcat'    
 //gwt configuration
     modules 'com.kpaudel.frontend.SpringBootGwt'

task copyGWTCode(type:Copy){
  //from compileGwt.outputs
  from file("${buildDir}/gwt/out")
  into file("${buildDir}/resources/main/static")

 copyGWTCode.dependsOn compileGwt

  dependsOn copyGWTCode
  mkdir "${buildDir}/target"


Step 3: Create a GWT module

It is important step. Here we provide the path of the module definition file. This file defines all GWT related information.  There can be multiple modules,  which should be first define in build.gradle file(in gwt block) above. In packaging system, suppose we create a package called

Then module information file is located in the package(the file extension of module file name is always *.gwt.xml). We create a module definition file name with the following contents:


So, we create two packages, one for client and one for shared.

com.kpaudel.frontend.client This package for client only files
com.kpaudel.frontend.shared This package for shared files(both client and server)

Like we defined entry point class in module definition file above, we create a Java File as entry point:
Here is a very simple example:

package com.kpaudel.frontend.client;


public class SpringBootGwt implements EntryPoint {

public void onModuleLoad() {
RootPanel.get().add(new Label("Hello World"));

Step 4: Compilation

What we did so far can convert our java files into javascript file using the following gradle script in the project root path.

./gradlew compileGwt

The compiled javascript files are located in build/gwt/out/frontend folder. The folder name frontend comes from the module name defined in the module definition file.

Step 5: Server Stuffs

Now, we can do server stuffs now. Because we are backed up by very powerful spring framework, so we can do whatever we want using this technology.

Step 6: Packaging

Packing stuffs into a bundle jar is a bit complicated in the sense that we have to include some scripts in build.gradle file. Please have a look at the last lines of build.gradle file.

Sunday, February 10, 2019