Monday, 26 December 2016

How to write Native methods?

The Java Native method is a great way to gain and merge the power of C or C++ programming into Java.

Writing native methods involves importing C code into Java application. We'll follow few steps to create native methods -
1. Writing and Compiling Java Code
2. Creating C header (.h file)
3. Writing C code
4. Creating shared code library (.dll file) for Windows and (.so file) for Unix
5. Run Application.

In our example, we are using gcc compiler for C and considering path for gcc and java are set in the environment. Here we will create two methods - printMessage() which will print message in the console and printSum() which will print the sum of two numbers.

Project Structure -



Step 1 : Writing and Compiling Java Code

(NativeClass.java )

package com.anjan.api;

public class NativeClass {

static{
System.loadLibrary("nativedemo"); //Load native library at runtime nativedemo.dll (windows) and nativedemo.so (unix)
}

public native void printMessage();
public native int printSum(int a, int b);
}

(MainClass.java)

package com.anjan.main;

import com.anjan.api.NativeClass;

public class MainClass {

public static void main(String args[]){
NativeClass cls = new NativeClass();
cls.printMessage();
System.out.println(cls.printSum(5, 3));
}

}


After writing the Java Code, compile the code. After compiling the code, .class files will be generated in bin folder of the project.

Step 2 : Creating C header file (.h file)

To generate header file, follow the below steps -
(a) Go to the command prompt.
(b) Go to the bin directory of the project
      e.g - cd C:\NativeDemo\bin
(c) We'll use javah command to generate header file. Execute the below command to generate header file (.h file) for NativeClass
      e.g - javah com.anjan.api.NativeClass

A file com_anjan_api_NativeClass.h will be generated in bin folder. Create cfiles directory in the project and copy the header file into it.

(com_anjan_api_NativeClass.h)

Step 3 : Writing C Code

Create NativeClass.c inside cfiles folder and we'll write the logic for printMessage() and printSum() method in C file.

(NativeClass.c)

Step 4 : Creating Shared code library (.dll file)

To generate the shared code library (.dll file), we will go to cfiles directory in command prompt and we execute the below command.

gcc -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o <dll file name> <cfilename>

e.g -
gcc -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o nativedemo.dll NativeClass.c

After executing the above command .dll file will be generated inside cfiles directory.
The dll file name should be same as the library name provided to load library in Java class.

Step 5 : Run Application

To execute the application, we will have to set the VM arguments for the application.

To set the VM arguments, follow the below steps -
(a) Right click on the Project and go to Run As -> Run Configurations
(b) In main tab, browse the project and enter the Main class of the project. Click Apply

(c) Go to Arguments tab, and enter the VM arguments and Click Apply and Run
-Djava.library.path=<directory containing dll file>

e.g -
-Djava.library.path=cfiles




Output -

I am Native Method
8

Thursday, 22 December 2016

How to modify the value of final fields in Java?

In JDK 1.1.x, we were not able to modify/access private fields using Reflection in Java. If someone tried to access fields which is inaccessible, the method throws an IllegalAccessException.

In JDK 1.2.x, we could make private fields accessible with setAccessible(true) method. We can even modify the final fields with Reflection.

If we set a final field of primitive type at declaration time, the value will be inlined, if the type is primitive or a String.

Lets see an example to modify final field of primitive integer type, Integer type and String type using Reflection -


import java.lang.reflect.Field;

public class ReflectionDemo {

private final String strVal1;
private final String strVal2 = "Anjan";
private final String strVal3;
private final String strVal4 = "XYZ";
private final Integer wrapperInt = 45;
private final int primInt1;
private final int primInt2 = 11;

public ReflectionDemo() {
primInt1 = 10;
strVal1 = "dummy";
strVal3 = "test";
}

public String toString() {
return "strVal1 : " + strVal1 + "; strVal2 : " + strVal2 + "; strVal3 : " + strVal3 + "; strVal4 : " + strVal4
+ "; wrapperInt : " + wrapperInt + "; primInt1 : " + primInt1
+ "; primInt2 : " + primInt2;
}

public void getMethodParameterValue(Object obj) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Class<?> cls = obj.getClass();

// Changing the value of String type which is initialized at Constructor - strVal1
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
field.set(strVal1, "new Dummy".toCharArray());

// Changing the value of String type which is declared - strVal2
field = String.class.getDeclaredField("value");
field.setAccessible(true);
field.set(strVal2, "new Anjan".toCharArray());

// Changing the value of String type which is initialized at Constructor - strVal3
field= cls.getDeclaredField("strVal3");
field.setAccessible(true);
field.set(obj, "new Test");

// Changing the value of String type which is declared - strVal4
field = cls.getDeclaredField("strVal4");
field.setAccessible(true);
field.set(obj, "new XYZ");

// Changing the value of Integer type which is declared - wrapperInt
field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
field.set(wrapperInt, 30);

// Changing the value of primitive int type which is initialized at Constructor - primtInt1
field = cls.getDeclaredField("primInt1");
field.setAccessible(true);
field.set(obj, new Integer(48));

// Changing the value of primitive int type which is declared - primInt2
field cls.getDeclaredField("primInt2");
field.setAccessible(true);
field.set(objnew Integer(100));

}

public static void main(String args[]) throws NoSuchFieldException, IllegalAccessException {
ReflectionDemo demo = new ReflectionDemo();
System.out.println(demo);
demo.getMethodParameterValue(demo);
System.out.println(demo);

}
}

Output -

strVal1 : dummy; strVal2 : Anjan; strVal3 : test; strVal4 : XYZ; wrapperInt : 45; primInt1 : 10; primInt2 : 11

strVal1 : new Dummy; strVal2 : new Anjan; strVal3 : new Test; strVal4 : XYZ; wrapperInt : 30; primInt1 : 48; primInt2 : 11


As we discussed earlier that if we set a final field of primitive type and String at declaration time, the value will be inlined. The above highlighted field values are not changed, as strVal4 is String type and primInt2 is primitive type and we have set the values of these fields at declaration time. Hence the field value doesn't get changed.

To modify the value of final primitive type or String type we need to set the value in Constructors. 

Wednesday, 14 December 2016

How to Convert IPv4 address to Long in Java?

While working with an application, there is a requirement of getting the long value of user IP address and I needed to convert the long value to IP address. To fulfill this requirement, I wrote one class IPConversion with two methods - ipToLong and longToIP.

ipToLong method takes the user IPv4 address as input in the form of String value and returns the long value of the IP.

And longToIP method takes the long value of IPv4 address as input and return the IP address.

I have written one Exception class IPInvalidFormatException, which will be called if the format of IP address is not valid.

Now let us see the example -

class IPInvalidFormatException extends Exception{

IPInvalidFormatException(){
System.out.println("Invalid IP Format Exception");
}

@Override
public String toString() {
return "Invalid IP Format";
}

}

public class IPConversion {

 // Method to convert IPv4 to Long
 public long ipToLong(String addr) throws IPInvalidFormatException {
String[] addrArray = addr.split("\\.");

long num = 0;
for (int i = 0; i < addrArray.length; i++) {
if(addrArray.length != 4){
throw new IPInvalidFormatException();
}
int power = 3 - i;

num += ((Integer.parseInt(addrArray[i]) % 256 * Math
.pow(256, power)));
}
return num;
}

 // Method to convert Long to IPv4
 public String longToIP(long l) {
return ((l >> 24) & 0xFF) + "." + ((l >> 16) & 0xFF) + "."
+ ((l >> 8) & 0xFF) + "." + (l & 0xFF);
}

public static void main(String args[]) throws IPInvalidFormatException{

IPConversion ip = new IPConversion();
System.out.println(ip.ipToLong("10.138.161.136"));
System.out.println(ip.longToIP(176857480));
System.out.println(ip.ipToLong("10.138.161.136.0"));
}
}

Output -

176857480
10.138.161.136
Invalid IP Format Exception
Exception in thread "main" Invalid IP Format
at com.anjan.test.IPConversion.ipToLong(IPConversion.java:24)
at com.anjan.test.IPConversion.main(IPConversion.java:44)

Saturday, 10 December 2016

How to move mouse pointer in Java?

In real time situation, sometimes we need our system should be active or it should not go to sleep mode while executing some programs. And we do not have admin rights for our system to change the sleep time for our system.

As a workaround we can move our mouse pointer after a certain time so that the system should not get into sleep mode or always in Active mode till the mouse pointer programs is executing.

Let us look into the program for moving the mouse pointer using Java -


import java.awt.Robot;
import java.util.Random;

public class MouseMover {

    public static final int TIME_IN_SECONDS = 5000;
    public static final int MAX_Y = 400;
    public static final int MAX_X = 400;

    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        Random random = new Random();
        while (true) {
      robot.mouseMove(random.nextInt(MAX_X), random.nextInt(MAX_Y));
            Thread.sleep(TIME_IN_SECONDS);
        }
    }
}

In the above program we are moving the mouse pointer after every 5 seconds.We set the maximum X and Y axis of the screen in which the mouse pointer will be moving to make the System active.

How to Connect to Database in Java?

In Java, we can connect Database using JDBC (Java Database Connectivity). To connect any database using JDBC we need the hostname, username, password etc. In few cases we need SID as well. 

The first important thing which is needed to connect any database is its JDBC Driver. There are four types of driver - Type I, II, III and IV. 

In our example, we are going to use thin driver and Oracle database in our example.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {
private static Connection connection = null;
// First way to Create JDBC Connection
public static Connection getConnection_1(String url, String userName, String password){
try {
connection = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(urluserNamepassword);
} catch (SQLException e) {

} catch (ClassNotFoundException e) {

}
 return connection;
}
// Second way to Create JDBC Connection 
public static Connection getConnection_2(String url, String userName, String password){
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection(url, userName, password);
} catch (SQLException e) {

}
return connection;
}

public static void main(String args[]) throws SQLException{
String sHost = "XXX.XX.XXX.XXX";
String sPort = "1521";
String sSid = "ANJAN";
String url = "jdbc:oracle:thin:@" + sHost + ":" + sPort + ":" + sSid;
String userName = "System";
String password = "1234";
Connection con1 = DBConnection.getConnection_1(url, userName, password);
if(con1 != null){
System.out.println("Connected");
con1.close();
}
Connection con2 = DBConnection.getConnection_2(url, userName, password);
if(con2 != null){
System.out.println("Connected");
con2.close();
}
 
}
}


Output -

Connected
Connected