WSO2 CEP - Publish Events Using Java Client

WSO2 CEP - Publish Events Using Java Client

The last article: WSO2 CEP - Hello World!, explained how to set up WSO2 CEP with a simple event processor. This article shows you the way to send events to the CEP using a Java client. Actually it is nothing more than an HTTP client which can send the event to the CEP through HTTP request.

Step 0:
Follow the previous article and setup the CEP engine. This article uses the same event processor and receiver defined in the previous article to test the Java client.

Step 1:
Create a new simple Maven project in Eclipse.

Step 2:
Give the Group Id: "com.javahelps" and Artifact Id: "cepclient" and click on the "Finish" button.
Read More
Prototype Design Pattern

Prototype Design Pattern

Name: Prototype Design Pattern

Type: Creational Design Pattern

Purpose:
  • Improving performance by cloning objects.
  • Minimize complexity in object creation.

Sample Problem and Solution:
Consider a problem where you need a 64x64 grid Board class to represent a chess board. A possible design is provided here.
public class Cell {
    private String color;

    public Cell(String color) {
        this.color = color;

        // Make it time consuming task.
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
    }

    public String getColor() {
        return color;
    }

    @Override
    public String toString() {
        return color.substring(0, 1);
    }
}
In this code, Thread.sleep is used to make the object creation as a time consuming operation.
public class Board {
    public static final int NO_OF_ROWS = 8;
    public static final int NO_OF_COLUMNS = 8;

    private final Cell[][] board;

    public Board() {
        this.board = new Cell[NO_OF_ROWS][NO_OF_COLUMNS];

        for (int row = NO_OF_ROWS - 1; row >= 0; row--) {
            for (int col = NO_OF_COLUMNS - 1; col >= 0; col--) {
                if ((row + col) % 2 == 0) {
                    board[row][col] = new Cell("WHITE");
                } else {
                    board[row][col] = new Cell("BLACK");
                }
            }
        }
    }

    public void print() {
        for (int row = 0; row < NO_OF_ROWS; row++) {
            for (int col = 0; col < NO_OF_COLUMNS; col++) {
                System.out.print(board[row][col] + " ");
            }
            System.out.println();
        }
    }
}
public class Main {

    public static void main(String[] args) {
        // Get the start time
        long startTime = System.currentTimeMillis();

        Board chessBoard = new Board();

        // Get the end time
        long endTime = System.currentTimeMillis();

        System.out.println("Time taken to create a board: " + (endTime - startTime) + " millis");

        // Print the board
        chessBoard.print();
    }

}

Read More

Android 6.0 Runtime Permission Model

The new runtime permission model introduced in Android 6.0 is an important issue to be considered by Android developers. Until Android 6.0, as a developer you might defined the required permissions in the AndroidManifest.xml file and focus on your business logic. However, since Android 6.0 the story becomes more complex, but it provides more security and control over the application to the end user. Let's cover this problem using a simple application.


Read More

Object Graph Mapping with Neo4j-OGM

Neo4j - the open-source graph database, released its own Java Object Graph Mapper recently. Developing Java Business Applications often requires mapping domain object networks to your database. The Neo4j-OGM library is a pure Java library that can store, read and query (annotated) domain objects using Neo4j. It uses Cypher statements execute those operations with Neo4j Server. Earlier Java objects were mapped with Neo4j entities using Spring Data Neo4j 4.0. According to Neo4j's blog, Neo4j-OGM becomes their official library for Object Graph Mapping.
This tutorial helps you to develop a very simple Hello World application using Neo4j-OGM library.

Read More

Android RecyclerView

The RecyclerView widget is a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use the RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events. RecyclerView decouples the positioning, animating items and various event handling into different classes.
This tutorial shows you, how to develop a RecyclerView application.

Step 1:
Create a new Android project "RecyclerView" with package name: "com.javahelps.recyclerview".

Read More

Android Navigation Drawer

The navigation drawer is a panel that displays the app’s main navigation options on the left edge of the screen. It is hidden most of the time, but is revealed when the user swipes a finger from the left edge of the screen or, while at the top level of the app, the user touches the app icon in the action bar. This tutorial guides you on how to create a navigable drawer application.

Step 1:
Create a new Android application using application name: "Navigation Drawer" and package name: "com.javahelps.navigationdrawer".


Step 2:
Select the "Navigation Drawer Activity" as the default activity.


Read More

Singleton Template For Eclipse

Singleton design pattern is one of the mostly used design pattern. This tutorial helps you to add a template in Eclipse to easily create Singleton Java classes.

Step 1:
Go to the Windows → Preferences

Step 2:
Expand the Java → Editor → Templates as shown below.


Read More

Jersey 2.x - Hello, world!

The first tutorial about Jersey: Jersey 1.x - Hello, world! shows the way to develop a simple RESTful Web service application using Jersey 1.19. This tutorial shows you the way to develop the same application using Jersey 2.20. Eclipse for Java EE developers and Apache Tomcat are used to develop the application. If you do not have them, please setup them before continuing this tutorial.

For Ubuntu users:
For any users:
Integrate Tomcat with Eclipse
Read More

Add MySQL JDBC Driver to Eclipse

This tutorial shows you the way to add the latest MySQL JDBC driver to Eclipse. Same steps can be followed to add any other JDBC drivers to Eclipse.

Step 1:
Download and extract the MySQL JDBC connector, from this link: Download Connector/J

Step 2:
Copy the mysql-connector-java-xxx-bin.jar file to any desired folder.

Step 3:
Go to the Window → Preferences in Eclipse.


Read More

JPA - Hello, World! using Hibernate

Java Persistence API (JPA) is a Java application programming interface specification that describes the management of relational data in applications using Java Platform, Standard Edition and Java Platform, Enterprise Edition. Various frameworks like Hibernate, EclipseLink and Apache OpenJPA provide object relational mapping according to JPA standards. This tutorial guides you to develop a simple Java Persistence API (JPA) based database application using Hibernate framework and MySQL database. 
Note: If you prefer Hibernate 5, visit to the new tutorial JPA - Hello, World! using Hibernate 5
You need Eclipse for Java EE developers and MySQL server in your system in-order to try this tutorial.
If you prefer to import the necessary libraries manually as shown in "Step 3 Without Maven", Eclipse for Java developers is enough. Those who prefer Maven projects, need to have M2Eclipse plugin in their Eclipse. This tutorial recommends Eclipse for Java EE, since it has M2Eclipse plugin by default. Also please be informed that the project attached at the end of this tutorial is created using Maven.
Step 1:
Create a database “javahelps” and a table “student” in MySQL.
CREATE DATABASE IF NOT EXISTS javahelps;

CREATE  TABLE javahelps.student ( 
student_id INT NOT NULL ,
student_name VARCHAR(45) NOT NULL ,
student_age INT NOT NULL ,
PRIMARY KEY (student_id) );

Read More

Set Proxy for Maven in Eclipse

If your computer connects with Internet through a proxy server, Maven plugin of Eclipse will not update the project artifacts or Maven plugins. The system proxy settings or proxy settings of Eclipse are not detected by Maven plugin. This tutorial shows you the way to enable proxy for Maven in Eclipse. If you want to configure the proxy for the Apache Maven command line tool, follow the steps 1 and 2 only.

Step 1:
Copy and paste the following content in your favorite editor and save it as settings.xml in the given directory.
<?xml version="1.0" encoding="UTF-8"?>
<settings
 xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
 <pluginGroups/>
 <proxies>
  <!-- Proxy for HTTP -->
  <proxy>
   <id>optional</id>
   <active>true</active>
   <protocol>http</protocol>
   <username>proxyuser</username>
   <password>proxypass</password>
   <host>proxy.host.net</host>
   <port>80</port>
   <nonProxyHosts>local.net</nonProxyHosts>
  </proxy>

  <!-- Proxy for HTTPS -->
  <proxy>
   <id>optional</id>
   <active>true</active>
   <protocol>https</protocol>
   <username>proxyuser</username>
   <password>proxypass</password>
   <host>proxy.host.net</host>
   <port>80</port>
   <nonProxyHosts>local.net</nonProxyHosts>
  </proxy>
 </proxies>

 <servers/>
 <mirrors/>
 <profiles/>
</settings>
Directory for Linux users:
/home/{username}/.m2/
Read More

Install Android Studio in Ubuntu 14.04

Android Studio is the official development tool for Android developers. This tutorial shows you the way to install the latest Android Studio in Ubuntu 14.04. Solutions for some common problems are provided at the end of this tutorial. Android Studio requires Oracle JDK 7.0 or latest in your system. If you do not have JDK, follow this link and install the Java first.


Read More

Hibernate - Hello, World! using Annotation Mapping

This tutorial explains you, how to develop a simple database application using Hibernate Object Relational Mapping (ORM) framework and MySQL database. This article uses Annotation for mapping; the XML mapping is explained in: Hibernate - Hello, World! using XML Mapping

You need Eclipse for Java EE developers and MySQL server in your system in-order to try this tutorial.
If you prefer to import the necessary libraries manually as shown in "Step 3 Without Maven", Eclipse for Java developers is enough. Those who prefer Maven projects, need to have M2Eclipse plugin in their Eclipse. This tutorial recommends Eclipse for Java EE, since it has M2Eclipse plugin by default. Also please be informed that the project attached at the end of this tutorial is created using Maven.
Step 1:
Create a database “javahelps” and a table “student” in MySQL.
CREATE DATABASE IF NOT EXISTS javahelps;

CREATE  TABLE javahelps.student ( 
student_id INT NOT NULL ,
student_name VARCHAR(45) NOT NULL ,
student_age INT NOT NULL ,
PRIMARY KEY (student_id) );

Read More

Hibernate - Hello, World! using XML Mapping

This tutorial explains you, how to develop a simple database application using Hibernate Object Relational Mapping (ORM) framework and MySQL database. This article uses XML mappings; the annotation mapping is explained in: Hibernate - Hello, World! using Annotation Mapping

You need Eclipse for Java EE developers and MySQL server in your system in-order to try this tutorial.
If you prefer to import the necessary libraries manually as shown in "Step 3 Without Maven", Eclipse for Java developers is enough. Those who prefer Maven projects, need to have M2Eclipse plugin in their Eclipse. This tutorial recommends Eclipse for Java EE, since it has M2Eclipse plugin by default. Also please be informed that the project attached at the end of this tutorial is created using Maven.
Step 1:
Create a database “javahelps” and a table “student” in MySQL.
CREATE DATABASE IF NOT EXISTS javahelps;

CREATE  TABLE javahelps.student ( 
student_id INT NOT NULL ,
student_name VARCHAR(45) NOT NULL ,
student_age INT NOT NULL ,
PRIMARY KEY (student_id) );


Step 2:
Create a new Java project “HibernateXML” in Eclipse.

Read More

Jersey 1.x - Hello, world!

Developing RESTful Web services that seamlessly support exposing your data in a variety of representation media types and abstract away the low-level details of the client-server communication is not an easy task without a good toolkit. In order to simplify development of RESTful Web services and their clients in Java, a standard and portable JAX-RS API has been designed. Jersey RESTful Web Services framework is open source, production quality, framework for developing RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 & JSR 339) Reference Implementation.

This tutorial shows how to develop a simple hello world RESTful application using Jersey 1.19. This tutorial uses Eclipse for Java EE developers and Apache Tomcat as the development tools. If you do not have them, please setup them before continuing this tutorial.

For Ubuntu users:
For any users:
Integrate Tomcat with Eclipse

Step 1:
Create a new “Dynamic Web Project” in Eclipse, by NewProjectDynamic Web Project.


Read More
Serialization in Java

Serialization in Java

Serialization is the process of converting Java objects into a stream of bytes. The stream of bytes can be transmitted through a network connection, stored in a database as a BLOB object or saved as a binary file. The stored or transmitted stream of bytes can be reconstructed to Java object later. This article explains Serialization in Java, using a simple step by step example.
Note: The sample codes provided in this tutorial, use try-with-resources blocks to auto close the input and output streams. You need Java 7 or latest version to compile and run these codes. For more information about try-with-resources, visit to this tutorial: Try With Resources
Create a Student class with the attributes name, and age.
public class Student {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}
Create a Main class as shown below, to create an object of Student.
public class Main {

    public static void main(String[] args) {
        Student stu = createStudent();
        System.out.println("Name: " + stu.getName());
        System.out.println("Age: " + stu.getAge());
    }

    /**
     * Create a sample Student object.
     *
     * @return a Student object.
     */
    public static Student createStudent() {
        // Create a Student object
        Student stu = new Student();
        stu.setName("Alice");
        stu.setAge(24);

        return stu;
    }
}

Read More

Android: Memo Application

This article provides a step by step guidance to develop a simple Memo application. You need to have basic knowledge on Android database and ListView to understand and complete this project. If you are not familiar with them, please visit to the following tutorials:

Step 1:
Create a new Android project “Memo”  with a package name “com.javahelps.memo

Step 2:
Right click on the Java package and create a new class 'Memo'. This class will be used as the model to represent the memos later in this project.
package com.javahelps.memo;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Memo implements Serializable {
    private Date date;
    private String text;
    private boolean fullDisplayed;
    private static DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyy 'at' hh:mm aaa");

    public Memo() {
        this.date = new Date();
    }

    public Memo(long time, String text) {
        this.date = new Date(time);
        this.text = text;
    }

    public String getDate() {
        return dateFormat.format(date);
    }

    public long getTime() {
        return date.getTime();
    }

    public void setTime(long time) {
        this.date = new Date(time);
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getText() {
        return this.text;
    }

    public String getShortText() {
        String temp = text.replaceAll("\n", " ");
        if (temp.length() > 25) {
            return temp.substring(0, 25) + "...";
        } else {
            return temp;
        }
    }

    public void setFullDisplayed(boolean fullDisplayed) {
        this.fullDisplayed = fullDisplayed;
    }

    public boolean isFullDisplayed() {
        return this.fullDisplayed;
    }
    @Override
    public String toString() {
        return this.text;
    }
}
The DateFormat is used to format the date when displaying the time of creation of the memo in the application. The fullDisplayed flag is used to define whether the complete memo is displayed to the user or part of the memo only displayed to the user. This property will be used to shrink and expand the memo in the application.

Read More

Global Menu Support for Java Applications in Ubuntu

Java swing applications' menus do not integrate with Ubuntu's global menu. A library called Jayatana is available to enable global menu support for Java swing applications in Ubuntu (From Ubuntu 15.04 Jayatana became a default library but it is disabled since 30-09-2015). There are hundreds of articles available about Jayatana, but this article has an additional hack to remove the irritating message, printed by Jayatana.
If you already have Jayatana in your system, jump to: Remove: Picked up JAVA_TOOL_OPTIONS Message

If you have not noticed any differences between Java swing applications and others, have a look at the following screenshots of Android Studio and Eclipse.

Android Studio without global menu support

Eclipse with global menu
Read More

Thread Deadlock

Thread deadlock is a hot topic in multi-threading, which makes multi-threading a complex area for beginners. Thread deadlock is a situation, where more than one threads with a shared resource are waiting for other thread(s) to release the lock on that shared resource without doing anything usefully.

This article explains the dead lock using a simple Java application, which simulates a bank transaction.

Create an Account class:
public class Account {
    private final String name;
    private double balance;

    public Account(String name) {
        this.name = name;
    }

    public void withdraw(double amount) {
        this.balance -= amount;
    }

    public void deposit(double amount) {
        this.balance += amount;
    }

    public double getBalance() {
        return this.balance;
    }

    @Override
    public String toString() {
        return name;
    }
}

Create a Transaction class which is a sub class of java.lang.Thread:
public class Transaction extends Thread {
    private final String id;
    private final Account from;
    private final Account to;
    private final double amount;

    public Transaction(String id, Account from, Account to, double amount) {
        this.id = id;
        this.from = from;
        this.to = to;
        this.amount = amount;
    }

    @Override
    public void run() {
        // Acquire the lock of Account 'from'
        synchronized (from) {
            from.withdraw(amount);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) { }

            // Acquire the lock of Account 'to'
            synchronized (to) {
                to.deposit(amount);
            }
            // Release the lock of Account 'to'
        }
        // Release the lock of Account 'from'
        System.out.println(amount + "is transfered from " + from + " to " + to);
    }
}
Inside the run method, this class synchronizes the 'from' account first and without releasing the lock, it acquires (at least tries to acquire) the lock of 'to' account. Synchronization is the technique of avoiding data corruption or unexpected results in a shared resource environment. For more details about synchronization, visit to this article: Thread Synchronization in Java.

Create a Main class to execute the application:
public class Main {
    public static void main(String[] args) {
        final Account accA = new Account("Acc 1");
        final Account accB = new Account("Acc 2");
        accA.deposit(1000.00);
        accB.deposit(1000.00);

        Transaction t1 = new Transaction("T01", accA, accB, 100.00);
        Transaction t2 = new Transaction("T02", accB, accA, 500.00);

        t1.start();
        t2.start();
    }
}

Suppose there are two customers want to transfer some amount of money to each other from their account at the same time, there is a possibility of getting thread deadlock during this transaction. If you run this program multiple times, sometimes you will not get any outputs in the terminal. Let's analyze the execution of this code into two cases.

Case 1:
Step 1: Transaction 1 starts first, receives the lock of account A and withdraws the money.
Read More

Inject Views on Android

Have you ever get irritated by the unlimited number of findViewById method calls and complex on-click-listeners? Obviously they increase the complexity of the code and they consume more time as well. Butter Knife is a perfect solution to get out of these irritating and time consuming code segments.

Butter Knife is an injection library used to inject views into Java classes. Using this library is not going to reduce the performance since it uses compile time injection instead of runtime injection. Compared to some other Android libraries and frameworks, it is less featured but personally I like this library a lot for its less configuration and high performance. This article introduces the basic functionalities of Butter Knife and more details can be found at the official website.


Let's create a simple application with a TextBox and a Button to demonstrate the application of Butter Knife.
Read More

Import and Use External Database in Android

This article explains the usage of an Android library which is helpful to import and use external SQLite database into your Android application. It has been a problem for Android developers to release an application with some existing rows of data in the database. For example if you are developing a static application which is used to display some tourist spots in your country, probably you need to release the database with predefined details about the tourist places inside it. However, there are no native ways to import external database easily into your Android application.


The Android SQLiteAssetHelper library allows you to build your SQLite database in your desktop computer, and to import and use it in your Android application. Let's create a simple application to demonstrate the application of this library.

Update: If you want to import database either from assets folder as described here or from an external location like SD card, a new approach is shared in Deploy and Upgrade Android Database From External Directory.

Step 1:
Create a database quotes.db using your favorite SQLite database application (DB Browser for SQLite is a portable cross platform freeware, which can be used to create and edit SQLite databases). Create a table 'quotes' with a single column 'quote'. Insert some random quotes into the table 'quotes'.


Step 2:
The database can be imported into project either directly as it is, or as a compressed file. The compressed file is recommended, if your database is too large in size. You can create either a ZIP compression or a GZ compression.

The file name of the compressed db file must be quotes.db.zip, if you are using ZIP compression or quotes.db.gz, if you are using GZ compression.

Step 3:
Create a new application “External Database Demo” with a package name “com.javahelps.com.javahelps.externaldatabasedemo”.

Step 4:
Open the build.gradle (Module: app) file and add the following dependency.
dependencies {
    compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
}


Once you have saved the build.gradle file click on the 'Sync Now' link to update the project. You can synchronize the build.gradle, by right clicking on the build.gradle file and selecting "Synchronize build.gradle' option as well.

Step 5:
Right click on the app folder and create new assets folder.


Step 6:
Create a new folder 'databases' inside the assets folder.


Step 7:
Copy and paste the  quotes.db.zip file inside the assets/databases folder.



Step 8:
Create a new class 'DatabaseOpenHelper'
package com.javahelps.externaldatabasedemo;

import android.content.Context;

import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class DatabaseOpenHelper extends SQLiteAssetHelper {
    private static final String DATABASE_NAME = "quotes.db";
    private static final int DATABASE_VERSION = 1;

    public DatabaseOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
}
Notice that rather than extending SQLiteOpenHelper, the DatabaseOpenHelper extends  SQLiteAssetHelper class.

Step 9:
Create a new class DatabaseAccess and enter the code as shown below. More details about this class is available at Advanced Android Database tutorial.
package com.javahelps.externaldatabasedemo;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class DatabaseAccess {
    private SQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
    private static DatabaseAccess instance;

    /**
     * Private constructor to aboid object creation from outside classes.
     *
     * @param context
     */
    private DatabaseAccess(Context context) {
        this.openHelper = new DatabaseOpenHelper(context);
    }

    /**
     * Return a singleton instance of DatabaseAccess.
     *
     * @param context the Context
     * @return the instance of DabaseAccess
     */
    public static DatabaseAccess getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseAccess(context);
        }
        return instance;
    }

    /**
     * Open the database connection.
     */
    public void open() {
        this.database = openHelper.getWritableDatabase();
    }

    /**
     * Close the database connection.
     */
    public void close() {
        if (database != null) {
            this.database.close();
        }
    }

    /**
     * Read all quotes from the database.
     *
     * @return a List of quotes
     */
    public List<String> getQuotes() {
        List<String> list = new ArrayList<>();
        Cursor cursor = database.rawQuery("SELECT * FROM quotes", null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            list.add(cursor.getString(0));
            cursor.moveToNext();
        }
        cursor.close();
        return list;
    }
}
In this class only the getQuotes method is implemented to read the data from the database. You have the full freedom to insert, update and delete any rows in the database as usual. For more details, follow this link Advanced Android Database.

All the database related setups are completed and now we need to create a ListView to display the quotes.

Step 10:
Add a ListView in your activity_main.xml.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center" />
</FrameLayout>

Step 11:
Find the object of ListView in the onCreate method of MainActivity and feed the quotes which are read form the database.
package com.javahelps.externaldatabasedemo;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.List;


public class MainActivity extends ActionBarActivity {
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.listView = (ListView) findViewById(R.id.listView);
        DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
        databaseAccess.open();
        List<String> quotes = databaseAccess.getQuotes();
        databaseAccess.close();

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, quotes);
        this.listView.setAdapter(adapter);
    }
}

Step 12:
Save all the changes and run the application.


This library also allows you to upgrade the database using an external SQL script. For more details about this library, visit to its official page.

Find the project at Git Hub.

Update: To store images in this database, read Import Database with Images in Android
Read More

Thread Synchronization in Java

Multi-thread applications are useful to execute more than one operations simultaneously. However, if more than one threads are accessing a shared resource, there is a high risk of data corruption or unexpected result. This article explains the reason for the unexpected results and the possible solution to avoid it.

Even though threads are considered to be executing simultaneously, actually they are executed one after another using time-sharing mechanism of the underlying operating system. (For more details visit to this link). Consider a sample code as shown below.
public class ConcurrencyProblem {
    static int[] array = {0};

    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread() {
            public void run() {
                for(int i = 1; i <= 1000; i++) {
                    increase();
                }
            }
        };

        Thread b = new Thread() {
            public void run() {
                for(int i = 1; i <= 1000; i++) {
                    decrease();
                }
            }
        };

        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println(array[0]);
    }

    public static void increase() {
        array[0]++;
    }

    public static void decrease() {
        array[0]--;
    }
}
In this code thread A is increasing the value of first element of the array by one. At the same time thread B is decreasing the value of first element of the array by one. Both threads are executing these operations 1000 times. So ideally the final result should be 0 since thread A increases the value 1000 times and thread B decreases the value 1000 times. However, when you run this application, sometimes you may get an outputs other than 0. If you run this application again and again, you will get different outputs on each execution.
Read More

Serving Dynamic Content - CGI vs Servlets

Note: This article focuses OCEWCD students, and the term server refers the combination of web server and Servlet container like Apache Tomcat.
In a web application, clients send request to the servers and servers return a response to the client. Once the client receives the response, connection between client and server will get lost. So even if the same client makes another request, server receives it as a new request from a new user, in other words server does not remember the client or the history of transactions with that client. If the request is for a static content like an HTML file or media file, server is much happy with that request and return the file as the response. If the request is for a dynamic content like a web page which contains weather details on that day, or current time (Notice that these details cannot be hard coded in a static HTML file. They have to be generated on runtime) a web server cannot handle that request; it has to be handled by any other helper applications. The helper application can be either a Common Gateway Interface (CGI) or Servlet.
Read More

Java Web Application - Hello World

This tutorial shows you the way to create your first Hello World web application in Java. You need to have Eclipse IDE for Java EE Developers and Apache Tomcat, in order to develop this application. If you have not configured the Apache Tomcat in Eclipse, follow this tutorial and configure it first.

Step 1:
Go to File → New → Project.

Step 2:
Under the Web category, select the Dynamic Web Project option and click on Next.

Step 3:
Give the project name 'Hello World' and click on the Finish button.

Step 4:
Right click on the src folder of 'Hello World' project and select New → Servlet.

Step 5:
Give a package name 'com.javahelps.helloworld' and class name 'HelloWorldServlet' as shown in the screenshot.
Click on the Finish button to create the Servlet.

Step 6:
Modify the Servlet class code as provided below.
package com.javahelps.helloworld;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorldServlet
 */
@WebServlet("/saytime")
public class HelloWorldServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWorldServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.print("<html><body><h1 align='center'>" +
        new Date().toString() + "</h1></body></html>");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}
Here the @WebServlet annotation defines the URL of this Servlet. The doGet method is used to serve the GET requests and doPost method is used to serve the POST requests. According to this code, this Servlet can accept both GET and POST requests but it produces the output only for GET requests. Any POST requests will cause to a blank screen in the browser. PrintWriter is used to write the current time as an HTML content to the response.

Step 7:
Right click on the WebContent folder and create a new HTML file index.html.


Step 8:
Modify the HTML file as shown below.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<a href="saytime">Click Here</a>
</body>
</html>
The hyperlink reference is pointing to the sayhello URL which is defined in the HelloWorldServlet class.

Step 9:
After saving all the changes, right click on the project and select Run As → Run on Server.

Step 10:
Select the Tomcat server and click on the Finish button to run the application.

Now your first application is available at the following link:
http://localhost:8080/Hello_World/



Find the project at Git Hub.
Read More
Bridge Design Pattern

Bridge Design Pattern

Name: Bridge Design Pattern

Type: Structural Design Pattern

Purpose: Decouple abstraction from implementation
                (In other words using composite over inheritance)

Sample Problem and Solution:
Assume that you are required to create some Shapes with two different patterns. Some sample shapes are SolidColorCircle, GradientCircle, SolidColorSquare and GradientSquare. A possible design is provided below.
public interface Shape {
    public void draw();
}
public abstract class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public void draw() {
        System.out.println("Create a circle with radius: " + radius);
    }
}
public class SolidColorCircle extends Circle {
    private String color;

    public SolidColorCircle(double radius, String color) {
        super(radius);
        this.color = color;
    }

    @Override
    public void draw() {
        super.draw();
        System.out.println("Fill with: " + color);
    }
}
public class GradientCircle extends Circle {
    private String colorX;
    private String colorY;

    public SolidColorCircle(double radius, String colorX, String colorY) {
        super(radius);
        this.colorX = colorX;
        this.colorY = colorY;
    }

    @Override
    public void draw() {
        super.draw();
        System.out.println("Fill with: " + colorX + " & " + colorY);
    }
}
Square, SolidColorSquare and GradientSquare are provided in GitHub.
Read More

Advanced Android Database

Even though this tutorial is named as Advanced Android Database, there is nothing advanced in Android database. The last Basic Android Database tutorial explains the quick and dirty way of using SQLite database in your application. This tutorial uses the same problem discussed in the last article, but to explain the recommended way of database access in Android.


The Create, Read, Update and Delete (CRUD) related methods are not explained in this article since those are already explained in the Basic Android tutorial. If you are new to Android Database, please read the Basic Android Database article first and then continue this article in order to learn the best practices.
Read More

Install Apache Tomcat on Ubuntu

Ubuntu repository does not provide the latest version of Apache Tomcat. If you are desired to install the latest version of Apache Tomcat and to add it to the Eclipse, this article is for you.


Step 1:
Download the latest version of Apache Tomcat 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 Tomcat from  the ~/Downloads directory. If your downloaded file is in any other directory, replace the last parameter by the actual file path.
sudo tar -xvzf ~/Downloads/apache-tomcat-8.0.26.tar.gz

Step 4: (Optional)
Rename the folder name to apache-tomcat.
sudo mv apache-tomcat-8.0.26/ apache-tomcat/

Step 5:
Tomcat creates some files at the runtime inside this folder (Log files and some other configuration files). If you want to start Tomcat without root privilege, it is required to change the permission of this directory. Enter the following command to change the permission of apache-tomcat folder.
sudo chmod -R 777 apache-tomcat/

Step 6:
An environment variable has to be added to the system. Enter the following command in the terminal to open the /etc/environment in gedit.
sudo gedit /etc/environment

Step 7:
Add the following line at the end of the file. Save and close the gedit.
CATALINA_HOME="/opt/apache-tomcat"

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 Tomcat server.
$CATALINA_HOME/bin/startup.sh

Step 10:
Visit to the following URL.
http://localhost:8080/

If you get the Apache Tomcat home page, you have successfully installed the Apache Tomcat in your system.

Step 11:
To stop the Tomcat, enter the following command.
$CATALINA_HOME/bin/shutdown.sh

Integrate Tomcat with Eclipse
If you do not have the Eclipse, follow this link and install the Eclipse first.

Step 1:
Open the Eclipse.

Step 2:
Goto Windows → Preferences in the menu bar and select the Runtime Environments under the Server.


Step 3:
Click on the 'Add' button.

Step 4:
Select your Apache Tomcat version under the 'Apache' root and click 'Next'.


Step 5:
Browse and select the Tomcat installation directory.


Step 6:
Click on the 'Finish' button

Step 7:
Click on the 'OK' button to close the Preferences dialog.


Now you are ready to use Apache Tomcat from Eclipse.
Read More

Install the latest Eclipse in Ubuntu

This article shows you the way to install the latest version of Eclipse in Ubuntu. If you do not have Java in your system, follow this link and install the Java first.


Step 1:
Download the desired version of Eclipse 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 Eclipse from ~/Downloads directory. If your downloaded file is in any other directory, replace the last parameter by the actual file path.
sudo tar -xvzf ~/Downloads/eclipse-jee-mars-R-linux-gtk-x86_64.tar.gz

Step 4:
Open another Terminal (Ctrl + Alt + T) and enter the following command to create a shortcut file for eclipse.
gedit eclipse.desktop

Step 5:
In the opened gedit, copy and paste the following text.
[Desktop Entry]
Name=Eclipse
Type=Application
Exec=/opt/eclipse/eclipse
Terminal=false
Icon=/opt/eclipse/icon.xpm
Comment=Integrated Development Environment
NoDisplay=false
Categories=Development;IDE;
Name[en]=Eclipse
Name[en_US]=Eclipse

Step 6:
Save and close the gedit.

Step 7:
Enter the following command in the terminal to install the shortcut.
sudo desktop-file-install eclipse.desktop

Now search for Eclipse in the dashboard and open it.


Fix for unreadable tooltips
In Ubuntu, the default tooltip background is black, which makes it unreadable in Eclipse. To fix this problem, follow these steps.

Step 1:
Enter the following commands one by one, in a Terminal
sudo gedit /usr/share/themes/Ambiance/gtk-2.0/gtkrc
sudo gedit /usr/share/themes/Ambiance/gtk-3.0/settings.ini
sudo gedit /usr/share/themes/Ambiance/gtk-3.0/gtk-main.css

Change the values of tooltip_fg_color and tooltip_bg_color in all the files, to the following values and save the changes.
tooltip_fg_color:#000000
tooltip_bg_color:#f5f5c5

Step 2:
Restart the Eclipse.
Read More
Factory Design Pattern

Factory Design Pattern

Name: Factory Design Pattern

Type: Creational Design Pattern

Purpose:
  • Hide object creation logic
  • Decouple classes from the clients

Sample Problem and Solution:
Consider a problem where you are required to create a library which provides some 2D Shapes. Other developers will use your library to create some shapes with random measurements. A possible design is provided here.
package com.javahelps.shapes;

public interface Shape {
    public void draw();
}
package com.javahelps.shapes;

public class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public void draw() {
        System.out.println("Circle");
    }
}
package com.javahelps.shapes;

public class Square implements Shape {
    private int width;

    public Square(int width) {
        this.width = width;
    }

    @Override
    public void draw() {
        System.out.println("Square");
    }
}
package com.javahelps.shapes;

public class Rectangle implements Shape {
    private int width;
    private int height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public void draw() {
        System.out.println("Rectangle");
    }
}
Read More

Android Spinner

In Android combo box is called as Spinner. This tutorial shows you, how to use Spinner in your application.

Step 1:
Create an Android project with a project name “Spinner Sample” and a package name “com.javahelps.sample.spinner”.

Step 2:
Modify the activity_main.xml as shown below. Notice that there is a UI component Spinner which is the combo box used to display some names of animals.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="Select an animal"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Spinner
        android:id="@+id/cmbAnimals"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/txtInfo" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/cmbAnimals">
        <ImageView
            android:id="@+id/imgAnimal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"/>
    </RelativeLayout>

</RelativeLayout>
Step 3:
The images I have used in this project can be downloaded from this link. Download the images and copy them.

Right click on the drawable folder and select “Paste”.


Read More

Custom Font in Android

This tutorial shows you, how to develop an application in your local language. Since some Android phones have problems with Unicode, you can use custom true-type fonts for your application. The same technique can be used to decorate your application using stylish English fonts as well. This tutorial develops an application to display a welcome message in Tamil. You can use your own font to display whatever you want.

Step 1:
Create an Android application “Custom Font” with a package name “com.javahelps.customfont”.

Step 2:
Add a TextView to the activity_main.xml as shown below.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

Step 3:
Right click on the “res” folder and select NewFolderAssets Folder.


Read More

Immutability Of String

Java defines some objects as immutable objects; developers cannot modify those objects once they are created. String objects and wrapper class objects are the best examples for immutable objects. This article covers the immutable objects and the reason for having immutable objects using String as an example.

Before getting into the actual content, it is required to have a basic knowledge about the equality operator (==). Usually equality operator is used to compare two primitive data types, but it has a different meaning when it is used with references. To compare the content of two objects, equals method is used and the equality operator is used to check whether two references are referring same object.
public class EqualityOperator {
    public static void main(String[] args) {
        Student stu1 = new Student(100);
        Student stu2 = new Student(100);
        Student stu3 = stu1;
        if (stu1 == stu2) { // false
            System.out.println("stu1 == stu2");
        }
        if (stu1.equals(stu2)) { // true
            System.out.println("stu1 equals stu2");
        }
        if (stu1 == stu3) { // true
            System.out.println("stu1 == stu3");
        }
    }
}
For the complete project click on this link.

In the above example stu1 == stu2 returns false, because they refer two different objects. stu1 == stu3 returns true because both references are referring the same object.

Read More

Contact Form

Name

Email *

Message *