Friday, 30 June 2017

PowerMock, EasyMock : Mock an object

In this post, I am going to explain how to create mock object and how to mock the methods of the mocked object.

By using PowerMock class 'createMock' method we can create a mock object. Once the mock object is created, we can set expectations to the methods.

Following snippet, create mock object for File class, and set expectations to the methods 'getName', 'getAbsolutePath’.

File file = PowerMock.createMock(File.class);
                
EasyMock.expect(file.getName()).andReturn("TestFile");
EasyMock.expect(file.getAbsolutePath()).andReturn("/Users/HariKrishna/TestFile");
                
PowerMock.replayAll();

Following is the complete working application.

Test.java
package com.sample.tests;

import java.io.File;

import org.easymock.EasyMock;
import org.powermock.api.easymock.PowerMock;

public class Test {

 public static void main(String args[]){
  File file = PowerMock.createMock(File.class);
  
  EasyMock.expect(file.getName()).andReturn("TestFile");
  EasyMock.expect(file.getAbsolutePath()).andReturn("/Users/HariKrishna/TestFile");
  
  PowerMock.replayAll();
  
  System.out.println(file.getName());
  System.out.println(file.getAbsolutePath());
 }
}



Previous                                                 Next                                                 Home

Thursday, 29 June 2017

Derby: JDBC program using the client driver and Network Server

In my previous post, I explained jdbc application using embedded derby server. In this post, I am going to show you how to connect to derby server using jdbc and perform CRUD operations.

Below step-by-step procedure explains how to start derby server and how to connect it by using jdbc.

Step 1: Create a directory ‘derby_example_jdbc’.

Step 2: Go to the directory ‘derby_example_jdbc’ and start the derby server.

On Windows
java -jar %DERBY_HOME%\lib\derbyrun.jar server start

On Linux platforms
java -jar $DERBY_HOME/lib/derbyrun.jar server start

You can able to see below messages, once the server started successfully.
C:\Users\Krishna\Documents\Study\Apache Derby\examples\derby_example_jdbc>java -jar "%DERBY_HOME%"\lib\derbyrun.jar server start
Thu Jun 29 14:13:38 IST 2017 : Security manager installed using the Basic server security policy.
Thu Jun 29 14:13:38 IST 2017 : Apache Derby Network Server - 10.13.1.1 - (1765088) started and ready to accept connections on port 1527

From above messages, it is clear that the server started listening on port 1527.

Step 3: Open Eclipse, create new maven project.


Right click on Eclipse ‘Project Explorer’ -> New -> Other.

Select ‘Maven Project’ and press next.


Select the check box ‘Create a simple project (skip archetype selection)’.

Press Next.

Give the group id and project id as 'jdbc_helloworld'.


Click on the button Finish.

It creates project structure like below.

Step 4: Add derby jdbc dependency to pom.xml.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>jdbc_helloworld</groupId>
  <artifactId>jdbc_helloworld</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.derby/derbyclient -->
    <dependency>
      <groupId>org.apache.derby</groupId>
      <artifactId>derbyclient</artifactId>
      <version>10.13.1.1</version>
    </dependency>


  </dependencies>
</project>


Step 5: Create a package com.sample.

Define class ‘Test’ under the package ‘com.sample’.

Test.java
package com.sample;

/* Step 1: Import sql package */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test {

  private static String driver = "org.apache.derby.jdbc.ClientDriver";
  private static String dbName = "organization";
  private static String connectionURL = "jdbc:derby://localhost:1527/" + dbName + ";create=true";

  public static void main(String args[]) throws SQLException, ClassNotFoundException {
    /* Step 2: Load Driver */
    System.out.println("Loading/Registering driver");
    Class.forName(driver);

    /* Step 3: Open connection to database */
    System.out.println("Connecting to database");
    Connection conn = DriverManager.getConnection(connectionURL);

    /* Create table employee */
    String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
    Statement stmt = conn.createStatement();
    stmt.execute(query);

    /* Insert data to employee table */
    query = "INSERT INTO employee values(1, 'Krishna')";
    stmt.execute(query);
    query = "INSERT INTO employee values(2, 'Arjun')";
    stmt.execute(query);

    query = "SELECT * FROM employee";
    ResultSet rs = stmt.executeQuery(query);

    while (rs.next()) {
      int id = rs.getInt("id");
      String name = rs.getString("name");
      System.out.println(id + " " + name);
    }
    rs.close();
    conn.close();
  }
}


Output
Loading/Registering driver
Connecting to database
1 Krishna
2 Arjun

Load Derby Driver
Below statements are used to load derby embedded driver.
private static String driver = " org.apache.derby.jdbc.ClientDriver";
Class.forName(driver);

Connect to the server
Below statements are used to connect to the server.
private static String dbName = "organization";
private static String connectionURL = "jdbc:derby://localhost:1527/" + dbName + ";create=true";
Connection conn = DriverManager.getConnection(connectionURL);

Create table employee
String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
Statement stmt = conn.createStatement();
stmt.execute(query);

Insert data into employee table
String query = "INSERT INTO employee values(1, 'Krishna')";
stmt.execute(query);
query = "INSERT INTO employee values(2, 'Arjun')";
stmt.execute(query);

Display the records in employee table
query = "SELECT * FROM employee";
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
         int id = rs.getInt("id");
         String name = rs.getString("name");
         System.out.println(id + " " + name);
}

Close result set and connection
rs.close();
conn.close();





Previous                                                 Next                                                 Home

Derby: Run a JDBC program using the embedded driver

In my previous posts, I explained how to create database and tables using both embedded mode and client-server mode.

Let’s try to connect to the embedded Derby driver using jdbc. JDBC stands for Java Database Connectivity, and is a platform independent interface between databases and Java. Just like packages awt, swing, and lang, jdbc is also a package, that allows Java programs to access database management systems like MySql, oracle, db2 etc.,

If you are new to jdbc, I refer you go through my below tutorial.

Below step by step procedure explains simple jdbc program that creates employee table, insert 3 records into it and display the employee table.

Step 1: Open Eclipse, create new maven project.

Right click on Eclipse ‘Project Explorer’ -> New -> Other.

Select ‘Maven Project’ and press next.

Select the check box ‘Create a simple project (skip archetype selection)’.

Press Next.

Give the group id and project id as 'jdbc_helloworld'.

Click on the button Finish.

It creates project structure like below.

Step 2: Add derby jdbc dependency to pom.xml.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>jdbc_helloworld</groupId>
  <artifactId>jdbc_helloworld</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.derby/derby -->
    <dependency>
      <groupId>org.apache.derby</groupId>
      <artifactId>derby</artifactId>
      <version>10.13.1.1</version>
    </dependency>

  </dependencies>
</project>

Note
If you got any error like 'java.lang.ClassNotFoundException: org.apache.derby.jdbc.EmbeddedDriver' it may be because the scope of the dependency is set to test.

                 <!-- https://mvnrepository.com/artifact/org.apache.derby/derby -->
                 <dependency>
                          <groupId>org.apache.derby</groupId>
                          <artifactId>derby</artifactId>
                          <version>10.13.1.1</version>
                          <scope>test</scope>
                 </dependency>
                
You need to remove the <scope> element from the dependency and update the dependency like below.

                 <!-- https://mvnrepository.com/artifact/org.apache.derby/derby -->
                 <dependency>
                          <groupId>org.apache.derby</groupId>
                          <artifactId>derby</artifactId>
                          <version>10.13.1.1</version>
                 </dependency>

Step 3: Create a package com.sample.

Define class ‘Test’ under the package ‘com.sample’.


Test.java

package com.sample;

/* Step 1: Import sql package */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class Test {

  private static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
  private static String dbName = "organization";
  private static String connectionURL = "jdbc:derby:" + dbName + ";create=true";

  public static void main(String args[]) throws SQLException, ClassNotFoundException {
    /* Step 2: Load Driver */
    System.out.println("Loading/Registering driver");
    Class.forName(driver);

    /* Step 3: Open connection to database */
    System.out.println("Connecting to database");
    Connection conn = DriverManager.getConnection(connectionURL);

    /* Create table employee */
    String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
    Statement stmt = conn.createStatement();
    stmt.execute(query);

    /* Insert data to employee table */
    query = "INSERT INTO employee values(1, 'Krishna')";
    stmt.execute(query);
    query = "INSERT INTO employee values(2, 'Arjun')";
    stmt.execute(query);

    query = "SELECT * FROM employee";
    ResultSet rs = stmt.executeQuery(query);

    while (rs.next()) {
      int id = rs.getInt("id");
      String name = rs.getString("name");
      System.out.println(id + " " + name);
    }
    rs.close();
    conn.close();
  }
}

Output

Loading/Registering driver
Connecting to database
1 Krishna
2 Arjun


Load Derby Driver
Below statements are used to load derby embedded driver.
private static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName(driver);

Connect to the embedded server
Below statements are used to connect to the embedded server.
private static String dbName = "organization";
private static String connectionURL = "jdbc:derby:" + dbName + ";create=true";
Connection conn = DriverManager.getConnection(connectionURL);

Create table employee
String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
Statement stmt = conn.createStatement();
stmt.execute(query);

Insert data into employee table
String query = "INSERT INTO employee values(1, 'Krishna')";
stmt.execute(query);
query = "INSERT INTO employee values(2, 'Arjun')";
stmt.execute(query);

Display the records in employee table
query = "SELECT * FROM employee";
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
         int id = rs.getInt("id");
         String name = rs.getString("name");
         System.out.println(id + " " + name);
}

Close result set and connection
rs.close();
conn.close();


Previous                                                 Next                                                 Home

Derby: Run SQL commands using the client

In my previous post, I explained simple application using derby in embedded mode. In this post, I am going to explain how to use Derby in Client-server model.

Below step-by-step procedure explain the setup.

Step 1: Start Derby Server.
We need to run 'derbyrun.jar' file to start the server.

On Windows
java -jar %DERBY_HOME%\lib\derbyrun.jar server start

On Linux systems
java -jar $DERBY_HOME/lib/derbyrun.jar server start

C:\>java -jar "%DERBY_HOME%"\lib\derbyrun.jar server start
Wed Jun 28 16:37:16 IST 2017 : Security manager installed using the Basic server security policy.
Wed Jun 28 16:37:16 IST 2017 Thread[main,5,main] java.io.FileNotFoundException: C:\derby.log (Access is denied)
Wed Jun 28 16:37:17 IST 2017 : Apache Derby Network Server - 10.13.1.1 - (1765088) started and ready to accept connections on port 1527
Wed Jun 28 16:37:17 IST 2017 : Apache Derby Network Server - 10.13.1.1 - (1765088) started and ready to accept connections on port 1527

As you see the console, you can observe server started listening on port 1527.

Step 2: Create a directory ‘derby_example2’.

Step 3: Open other command prompt and navigate to the directory ‘derby_example2’.

Run the command ij.

ij command is presented in 'DERBY_HOME/bin' directory. Make sure you added 'DERBY_HOME/bin' to your system path.

ij tool is the client application that is used to connect to Derby server.
Type below command to create database.

CONNECT 'jdbc:derby://localhost:1527/organization;create=true';

C:\Users\Krishna\Documents\Study\Apache Derby\examples\derby_example2>ij
ij version 10.13
ij> CONNECT 'jdbc:derby://localhost:1527/organization;create=true';
ij>

Below table summarizes different token of above command.

Token
Description
CONNECT
CONNECT command is used Used to establish a connection to a database.
jdbc:derby
The JDBC protocol specification for the Derby driver.
localhost:1527
Local host and port where the server is running. If the server running on other machine, then give the IP address of the machine and the port where the server is running
organization
The name of the database. Since no filepath is specified, the database is created in the default working directory 'derby_samples'
;create=true
Create attribute is used to create a database. Derby does not have an SQL ‘create database’ command.
;
The semicolon is the ij command terminator.

Step 4: Create a table employee.

Syntax
CREATE TABLE table_name(
  column1 data_type,
  column2 data_type,
         ...
         ...
  columnn data_type,
  PRIMARY KEY(columns)
);

Use below command to create table employee.

CREATE TABLE employee (id INT, name VARCHAR(20));

ij> CREATE TABLE employee (id INT, name VARCHAR(20));
0 rows inserted/updated/deleted

Step 4: Insert data into the table ‘employee’.

Use below commands to insert records to the table ‘employee’.

INSERT INTO employee VALUES (1, 'Hari Krishna');
INSERT INTO employee VALUES (2, 'Gopi Battu');
INSERT INTO employee VALUES (3, 'Chamu Majety');

ij> INSERT INTO employee VALUES (1, 'Hari Krishna');
1 row inserted/updated/deleted
ij> INSERT INTO employee VALUES (2, 'Gopi Battu');
1 row inserted/updated/deleted
ij> INSERT INTO employee VALUES (3, 'Chamu Majety');
1 row inserted/updated/deleted


Step 5: Display the records from the table ‘employee’.

ij> SELECT * FROM employee;
ID         |NAME
--------------------------------
1          |Hari Krishna
2          |Gopi Battu
3          |Chamu Majety

3 rows selected

Step 6: Exit the client by typing the command exit;

Step 7: Stop the derby server by using below command.

On Windows machines
java -jar %DERBY_HOME%\lib\derbyrun.jar server shutdown

On Linux machines
java -jar $DERBY_HOME/lib/derbyrun.jar server shutdown

C:\Users\Krishna\Documents\Study\Apache Derby\examples\derby_example2>java -jar "%DERBY_HOME%"\lib\derbyrun.jar server shutdown
Wed Jun 28 16:47:56 IST 2017 : Apache Derby Network Server - 10.13.1.1 - (1765088) shutdown



Previous                                                 Next                                                 Home

Derby: Hello World Application

In this post, I am going to show, how to create a database, table and insert records into the table.

Step 1: Create a directory 'derby_samples'.

Step 2: Open command prompt/terminal, navigate to the directory 'derby_samples'  and type the command ‘ij’.

C:\Users\Krishna\Documents\Study\Apache Derby\examples\derby_samples>ij
ij version 10.13
ij>

ij command is located in 'DERBY_HOME/bin' directory. Make sure  'DERBY_HOME/bin' is added to your system path.

ij tool is the client application that connects to Derby server.

Step 2: Create and connect to the database ‘organization’.

Below statement is used to create and connect to the database ‘organization’.

CONNECT 'jdbc:derby:organization;create=true';

Below table summarizes the tokens of above command.
Token
Description
CONNECT
CONNECT command is used Used to establish a connection to a database.
jdbc:derby
The JDBC protocol specification for the Derby driver.
organization
The name of the database. Since no filepath is specified, the database is created in the default working directory 'derby_samples'
;create=true
Create attribute is used to create a database. Derby does not have an SQL ‘create database’ command.
;
The semicolon is the ij command terminator.

In ij prompt type below command.


CONNECT 'jdbc:derby:organization;create=true';
Once the command is executed successfully, you can able to see ‘derby.log’ and organization directory in ‘derby_samples’ directory.

Step 3: Create a table employee.

Syntax
CREATE TABLE table_name(
  column1 data_type,
  column2 data_type,
         ...
         ...
  columnn data_type,
  PRIMARY KEY(columns)
);

Use below command to create table employee.

CREATE TABLE employee (id INT, name VARCHAR(20));

ij> CREATE TABLE employee (id INT, name VARCHAR(20));
0 rows inserted/updated/deleted


Step 4: Insert data into the table ‘employee’.

Use below commands to insert records to the table ‘employee’.

INSERT INTO employee VALUES (1, 'Hari Krishna');
INSERT INTO employee VALUES (2, 'Gopi Battu');
INSERT INTO employee VALUES (3, 'Chamu Majety');

ij> INSERT INTO employee VALUES (1, 'Hari Krishna');
1 row inserted/updated/deleted
ij> INSERT INTO employee VALUES (2, 'Gopi Battu');
1 row inserted/updated/deleted
ij> INSERT INTO employee VALUES (3, 'Chamu Majety');
1 row inserted/updated/deleted

Step 5: Display the records from the table ‘employee’.

ij> SELECT * FROM employee;
ID         |NAME
--------------------------------
1          |Hari Krishna
2          |Gopi Battu
3          |Chamu Majety


Step 6: Exit from Derby by typing exit; command.



Previous                                                 Next                                                 Home

Setting up Apache Derby

Software Requirements
Install Java 1.6 or higher.

Below step-by-step procedure explains how to set up Derby in your machine.

Step 1: Download Derby.
Go to below location and get the latest version of the Derby.

At the time of writing this post, ‘10.13.1.1’ is the latest version.

Step 2: Set ‘DERBY_HOME’ variable.
Extract the downloaded zip file from step1.

set DERBY_HOME environment variable to the root directory of the Derby installation (Extracted Location).

For example
I extracted Derby to the localtion, 'C:\Users\Krishna\Documents\Study\Apache Derby\Software\db-derby-10.13.1.1-bin'. So the environment variable DERBY_HOME should set to the value 'C:\Users\Krishna\Documents\Study\Apache Derby\Software\db-derby-10.13.1.1-bin'.

How to set DERBY_HOME in Windows?
Right click on my computer -> Properties.

Click on ‘Advanced Settings’.

Go to ‘Advanced’ tab and click on ‘Environment Variables’.


Click on New button under ‘System Variables’ section.
Give the name as ‘DERBY_HOME’ and value as, the path where you extracted the derby. For ex: I given as
‘C:\Users\Krishna\Documents\Study\Apache Derby\Software\db-derby-10.13.1.1-bin’


That’s it, you are done.

Verify whether DERBY_HOME set properly or not.
Open new command prompt and type echo %DERBY_HOME’. If you got the value that you set previously, then you are done.

Add %DERBY_HOME%/bin to system path.

Setting DERBY_HOME in Linux Environment
Korn and bash shells:
export DERBY_HOME=derby-install-dir

Bourne shell:
DERBY_HOME=derby-install-dir
export DERBY_HOME

C shell:
setenv DERBY_HOME derby-install-dir

Add bin directory of Derby to system path.


Previous                                                 Next                                                 Home