Android Studio 3.0 with Kotlin: First Look
Install Oracle JDK 9 on Linux
Install Apache Tomcat on Ubuntu
GitHub Pull Request - A Complete Guide For Beginners
Complex Event Processing - An Introduction
Determine if a String has all Unique Characters

Determine if a String has all Unique Characters

Question: Implement an algorithm to determine if a string has all unique characters.

Example:
The String "Hello" has two "l"s. Therefore, it does not have all unique characters. On the other hand, if you consider the String "World", it is formed using all unique characters.

Break Down:
Let's write a class named TestUniqueness which has a method isUnique which can be called from the main method as given below:
public class TestUniqueness {

    public static void main(String[] args) {
        System.out.println(isUnique("hello"));
        System.out.println(isUnique("world"));
    }

    public static boolean isUnique(String text) {
        return false;
    }
}
Of course, you can write a fancy code to read user input and feed them to an isUnique method. However, to keep the code clean and simple, I am calling the static method isUnique and immediately print the response. The isUnique method returns false all the times. In the following section, we are going to implement the algorithm for the isUnique method.

Read More

Setup Apache Axis2 on Ubuntu

This tutorial helps you to setup Apache Axis2 on Ubuntu and to add it to Eclipse IDE for Java EE Developers.

Step 1:
Download the latest version of Apache Axis2 from this link.

Step 2:
Open the Terminal (Ctrl + Alt + T) and enter the following command to change the directory.
cd /opt/

Step 3:
Enter the command given below to extract the Axis2 from  the ~/Downloads directory. If your downloaded file is in any other directory and replace the last parameter by the actual file path.
sudo unzip ~/Downloads/axis2-1.7.8-bin.zip -d .

Step 4:
Rename the folder name to axis2.
sudo mv axis2-1.7.8/ axis2/

Step 5:
To deploy web services, you may need to add some files inside this folder. Therefore it is required to change the permission of this directory. Enter the following command to change the permission of axis2 folder.
sudo chmod -R 777 axis2/

Step 6:
Environment variables AXIS2_HOME and PATH have to be added to the system. Enter the following command in the terminal to open the /etc/environment.
sudo gedit /etc/environment

Step 7:
Add the following line at the end of the file.
AXIS2_HOME="/opt/axis2"

Add the /opt/axis2/bin to the PATH.

The /etc/environment before the modification.

The /etc/environment after the modification.

Step 8:
Reload the environment variables to the current terminal using this command.
source /etc/environment

Step 9:
Enter the following command to start the Axis2 server.
axis2server.sh

If you are using Java 9 or latest, you may get an error similar to:
"-Djava.endorsed.dirs=/opt/axis2/lib/endorsed:/usr/lib/jvm/jdk-10.0.2/jre/lib/endorsed:/usr/lib/jvm/jdk-10.0.2/lib/endorsed is not supported. Endorsed standards and standalone APIs
in modular form will be supported via the concept of upgradeable modules.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit
".
To fix this problem, open $AXIS2_HOME/bin/axis2Server.sh script and scroll down to the bottom. At the end of the script, you have a command like this:
java $JAVA_OPTS -classpath "$AXIS2_CLASSPATH" \
    -Djava.endorsed.dirs="$AXIS2_HOME/lib/endorsed":"$JAVA_HOME/jre/lib/endorsed":"$JAVA_HOME/lib/endorsed" \
    org.apache.axis2.transport.SimpleAxis2Server \
    -repo "$AXIS2_HOME"/repository -conf "$AXIS2_HOME"/conf/axis2.xml $*
Replace it with the following command. As you can notice, we simply remove the JVM arguments from the command.
java $JAVA_OPTS -classpath "$AXIS2_CLASSPATH" \
    org.apache.axis2.transport.SimpleAxis2Server \
    -repo "$AXIS2_HOME"/repository -conf "$AXIS2_HOME"/conf/axis2.xml $*
Save all the changes and start the server again.

Step 10:
Visit to the following URL.
http://localhost:8080/axis2/services/
If you get the Deployed services page, you have successfully setup the Apache Axis2 in your system.

Step 11:
To stop the Axis2, press Ctrl + C in the terminal which is currently running the axis2server.

Integrate Axis2 with Eclipse
If you do not have Eclipse IDE for Java EE Developers, follow this link and install the Eclipse.

Step 1:
Open the Eclipse.

Step 2:
Goto Windows → Preferences in the menu bar and select the Axis2 Preferences under the Web Services.


Step 3:
Click on the 'Browse' button and select the Axis2 home directory.


Step 4:
Click ‘Apply’ and ‘OK’

Now you are ready to use Apache Axis2 from Eclipse.
Read More
Install MySQL with phpMyAdmin on Ubuntu

Install MySQL with phpMyAdmin on Ubuntu

There are hundreds of articles on how to install phpMyAdmin on Ubuntu. However, none of them showed me an error-free way of installing phpMyAdmin in my system. This article is for those who want to install phpMyAdmin and MySQL without any errors.



phpMyAdmin depends on Apache Server, PHP, and MySQL. Therefore, I recommend to install them before installing phpMyAdmin.

Read More

Deploy and Upgrade Android Database From External Directory

After seeing the huge response for the Import and Use External Database in Android article, I have realized the importance of deploying Android database from external sources. The library used in the above article allows you to import database only from the assets directory. However, recently one of my readers, asked for a way to import and upgrade the database from SD card. As a solution for his use case, I have developed a new library named "externalsqliteimporter" which allows you to import database either from assets directory or from SD card. This article explains the application of this Android library using a sample application.


The ExternalSQLiteImporter library allows you to build your SQLite database on your desktop computer, and to import and use it in your Android application. This library has two separate ways to maintain your database.

This library is still under development. Deploying and upgrading  the database from an external directory is not secure as it is publicly available for third party applications as well. Use that feature with caution. 

Read More

RESTful CRUD With Java and MySQL in Minutes

I keep receiving so many requests for an article on how to access MySQL database from Android application. Even though Android applications can have direct access to MySQL database server, that is not preferred due to security issues and high complexity. The easy and best solution is developing a REST web service to receive the requests from whatever the client (including Android applications) and execute them on the database connected with the web service.

There are so many articles already available on the Internet about how to create a web service to perform Create, Read, Update & Delete (CRUD) operations on a database and how to connect from an Android client. However, I wondered why most of them are using PHP to develop the web service! I believe developers find PHP a less painful language to develop web services than Java. In this article, I am going to show how to develop a RESTful CRUD Web service with Java in minutes. As a matured language Java has enough frameworks to make your task easy. I guarantee that you will never look back for a different language once you know the tools.

Prerequisite:

Read More

Android Studio 3.0 with Kotlin: First Look

The most awaiting release, Android Studio 3.0 has been released a few days back with exciting features including Kotlin and Java 8 support.  Even though developers were able to use Kotlin and Java 8 earlier, this time they do not need any extra configurations to enable them. This article explains how to create a hello world Android application using Kotlin.


Wait... This is Java Helps but I am writing about another language! Am I running out of content? Of course Kotlin is a new language but still, it is running on top of Java Virtual Machine. Kotlin can be compared with Groovy in terms of how it compiles the code. Both of them produce the same binary code that every Java developer is familiar with. Therefore Kotlin is another baby joining the family of JVM languages but with different syntax and more features.

Read More
Install Apache Maven on Linux

Install Apache Maven on Linux

Ubuntu and most other Linux distributions have Apache Maven in their official repository but I prefer manual installation to avoid dependencies like Open JDK. This article explains how you can install the latest Apache Maven in Linux.


Requirements:
Apache Maven depends on Java Development Kit so you must have either Oracle JDK or OpenJDK installed on your system. In case if you do not have JDK in your system, follow these articles first and install Oracle JDK on your computer.

Read More

Install Oracle JDK 9 on Linux

Oracle Java Development Kit 9 has been released recently. This article explains how to manually install the latest Oracle Java Development Kit 9 (Oracle JDK 9) on Linux.


Note: This article uses JDK 9 to demonstrate the installation. In the provided commands, replace the version specific paths and file names according to your downloaded version.

Step 1:
Download the latest JDK(jdk-9$java_update_no_linux-x64_bin.tar.gz) from this official link.
If you want to download to a remote server or if you simply prefer wget, use the command given in this StackOverflow answer: Downloading JDK
Read More
Detect Absence of Events - WSO2 Siddhi Pattern

Detect Absence of Events - WSO2 Siddhi Pattern

WSO2 Siddhi an opensource complex event processing engine which is used to power the WSO2 Analytics Server received a new feature from GSoC project: Non-Occurrence of Events for Siddhi Patterns. Until Siddhi 3.x, patterns can detect only the events that have arrived but building patterns based on events that have not arrived is an essential requirement and even there were questions on StackOverflow regarding this problem:
This article introduces the new pattern to detect absence of events along with its limitations and sample use cases. In order to get a clear idea, let's begin with a sample use case.
This feature is available from Siddhi v4.0.0-M50. Those who prefer stable version have to wait until Siddhi v4.0.0.
Read More
Why should I have supertype reference & subclass object?

Why should I have supertype reference & subclass object?

Just now I've got an email from one of my student with the following question: "Why should we create Animal obj = new Dog(); instead of Dog obj = new Dog();" Of course the example given here is made by myself but the question in detail is why all use super interface or superclass reference instead of using the same class reference. You got the question right? This article answers the question.

The answer is: "It is a best practice being followed by our ancestors. Stop asking questions and code that way :-)" 

Ok, more seriously, consider the following example:

There is a SuperFancyClass created by developer A for some super fancy purposes. Note that all the references are HashMap.
import java.util.HashMap;

public class SuperFancyClass {
    
    private HashMap<String, Object> mapOne;
    private HashMap<Integer, Object> mapTwo;

    public SuperFancyClass() {
        this.mapOne = new HashMap<>();
        this.mapTwo = new HashMap<>();
    }

    public HashMap<String, Object> doStuff1() {
        // Do something
        return this.mapOne;
    }

    public HashMap<String, Object> doStuff2() {
        // Do something
        return this.mapOne;
    }

    public HashMap<Integer, Object> doStuff3() {
        // Do something
        return this.mapTwo;
    }

    // Some other highly complex code here
}
That class is being used by developer B as given below.
import java.util.HashMap;

public class SensitiveAgent {

    public static void main(String[] args) {
        
        SuperFancyClass superFancy = new SuperFancyClass();
        HashMap<String, Object> map1 = superFancy.doStuff1();
        HashMap<String, Object> map2 = superFancy.doStuff2();
        HashMap<Integer, Object> map3 = superFancy.doStuff3();
    }

    // Some other highly complex code here
}
Assuming both classes are highly complex but both developers A and B are happy with what they have, there is nothing else to worry.

As time progress, now developer A wants to make his Maps to maintain the insertion order. The Java API says, HashMap does not respect the insertion order so if you need insertion order, you need to switch to LinkedHashMap.

So now developer A wants to find and replace all of his/her HashMaps by LinkedHashMap. But this will not be such a short happy ending story in a highly complex codebase where there can be several other local HashMaps which cannot be replaced by LinkedHashMap. So in reality, developer A has to go and change everywhere it requires LinkedHashMap as provided below.
import java.util.LinkedHashMap;

public class SuperFancyClass {
    
    private LinkedHashMap<String, Object> mapOne;
    private LinkedHashMap<Integer, Object> mapTwo;

    public SuperFancyClass() {
        this.mapOne = new LinkedHashMap<>();
        this.mapTwo = new LinkedHashMap<>();
    }

    public LinkedHashMap<String, Object> doStuff1() {
        // Do something
        return this.mapOne;
    }

    public LinkedHashMap<String, Object> doStuff2() {
        // Do something
        return this.mapOne;
    }

    public LinkedHashMap<Integer, Object> doStuff3() {
        // Do something
        return this.mapTwo;
    }

    // Some other highly complex code here
}
But now the code of developer B collapses because of the changes in SuperFancyClass. Then developer B has to go and change the references from HashMap to LinkedHashMap as shown below.
import java.util.LinkedHashMap;

public class SensitiveAgent {

    public static void main(String[] args) {
        
        SuperFancyClass superFancy = new SuperFancyClass();
        LinkedHashMap<String, Object> map1 = superFancy.doStuff1();
        LinkedHashMap<String, Object> map2 = superFancy.doStuff2();
        LinkedHashMap<Integer, Object> map3 = superFancy.doStuff3();
    }

    // Some other highly complex code here
}

Rule of debugging:

Now, this is the time to introduce an important rule of debugging:
Fixing a bug is equivalent to making several other bugs.
In other words, if you modify an existing code, the number of changes you have made will be proportional to the number of newly expected bugs because we are all human and we do mistakes. Without our intention, we might delete a local variable that hides an instance variable. Or else we might modify that single line which causes to bring the entire world to end. So always keep your changes as less as possible.

Coming back to the previous scenario, developer A modifies the SuperFancyClass in 7 places and developer B has to modify the SensitiveAgent in 3 places. Even in a code-base which contains two dummy classes, there are 10 places altogether to modify. Just imagine a project with hundreds/thousands of classes and millions of lines. Yep, they do exist and it will be catastrophic.

Time to travel back...
Suppose if the developer A designed his/her class as given below using super interface references (However the objects must be created using a subclass. See the constructor):
import java.util.Map;
import java.util.HashMap;

public class SuperFancyClass {
    
    private Map<String, Object> mapOne;
    private Map<Integer, Object> mapTwo;

    public SuperFancyClass() {
        this.mapOne = new HashMap<>();
        this.mapTwo = new HashMap<>();
    }

    public Map<String, Object> doStuff1() {
        // Do something
        return this.mapOne;
    }

    public Map<String, Object> doStuff2() {
        // Do something
        return this.mapOne;
    }

    public Map<Integer, Object> doStuff3() {
        // Do something
        return this.mapTwo;
    }

    // Some other highly complex code here
}
The developer B would develop his/her code like this because the return types of those methods are Map; the super interface:
import java.util.Map;

public class SensitiveAgent {

    public static void main(String[] args) {
        
        SuperFancyClass superFancy = new SuperFancyClass();
        Map<String, Object> map1 = superFancy.doStuff1();
        Map<String, Object> map2 = superFancy.doStuff2();
        Map<Integer, Object> map3 = superFancy.doStuff3();
    }

    // Some other highly complex code here
}
Now if the same situation comes where the developer A wants to preserve insertion order in his/her maps, only lines he/she has to change are just those two lines inside the constructor as shown below:
import java.util.Map;
import java.util.LinkedHashMap;

public class SuperFancyClass {
    
    private Map<String, Object> mapOne;
    private Map<Integer, Object> mapTwo;

    public SuperFancyClass() {
        this.mapOne = new LinkedHashMap<>();
        this.mapTwo = new LinkedHashMap<>();
    }

    public Map<String, Object> doStuff1() {
        // Do something
        return this.mapOne;
    }

    public Map<String, Object> doStuff2() {
        // Do something
        return this.mapOne;
    }

    public Map<Integer, Object> doStuff3() {
        // Do something
        return this.mapTwo;
    }

    // Some other highly complex code here
}
Developer B does not need to change anything because there is nothing changed in the API level (return types are not changed by developer A). So now the same behavior is achieved with less number of modifications (This time only 2). This is what we call extensible, modifiable, (all those blah-blah-blah-able) code.

Then why not Object instead of Map?
Now you may have a question: Should we always use the super most interface/class as the reference? Not always. It depends on the requirements. Climbing towards super types means, we are limiting the features because 99% of the time, subclasses have more features than supertypes. For example, compare java.lang.Number with its subclasses or compare java.util.Collection with its subinterfaces/classes. So use the supertype reference which has all the functionalities you are expected to have.

Is the rule applied to local variables?
Then what is the advantage of using super reference in local variables which have no impact on others? I guess this is because we developers are used to that and there is nothing wrong with following the same practice in local variables. For example, consider this case:
import java.util.List;
import java.util.ArrayList;

public class HelloWorld {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        System.out.println(list);
    }
}
In this code, there is no advantage of using super interface reference but I do write this way because I am used to it. If there are no disadvantages, why do you bother with it? Keep calm and code your references in supertype :-)
Read More

Microservices Framework for Java (MSF4J) - HelloWorld!

In a recent article: Microservices in a minute, I have introduced a lightweight microservice framework: WSO2 MSF4J. That tutorial shows you how to create a microservice in minutes using the Maven archetype. However, the libraries available in the public Maven repositories are bit older and there are new releases after MSF4J 2.0.1 which are available in WSO2's Maven repository. This article shows you how to create a microservice using the latest stable release of MS4J Framework.

Requirements:
  • Java Development Kit 1.8
  • Apache Maven 3.x
  • Postman or CURL
  • Eclipse IDE for Java EE Developers / Any IDEs with Maven support
Read More

Install Oracle JDK 8 on Linux

Oracle Java is the proprietary, reference implementation for Java. This is no longer currently available in a supported Ubuntu repository. This article shows you the way to manually install the latest Oracle Java Development Kit (Oracle JDK) in Ubuntu.


Note: This article uses JDK8_Update_$java_update_no to demonstrate the installation. In the provided commands, replace the version specific paths and file names to your downloaded version.

Oracle JDK 9 has some differences in its directory structure. Therefore, another article on how to install Oracle JDK 9 is available here: Install Oracle JDK 9 on Linux

Step 1:
Download the latest JDK(jdk-Xuxx-linux-xXX.tar.gz) from this official link.
If you want to download to a remote server or if you simply prefer wget, use the command given in this Stackoverflow answer: Downloading JDK
Read More

Parse PCAP files in Java

This article is for those who have spent hours like me to find a good library that can parse raw PCAP files in Java. There are plenty of open source libraries already available for Java but most of them are acting as a wrapper to the libpcap library which makes them hard to use for simple use cases. The library I came across: pkts is a pure Java library which can be easily imported into your project as a Maven dependency. This article introduces the pkts library using a HelloWorld application to parse a PCAP output.

Requirements:
  • Java IDE with Maven support (Eclipse IDE for Java EE is used here)
  • The PCAP file you want to parse
Read More

Contact Form

Name

Email *

Message *