Handling properties file using Java

Handling properties file using Java

Introduction:

Properties are configuration values managed as key/value pairs. In each pair, the key and value are both String values. The key identifies, and is used to retrieve, the value, much as a variable name is used to retrieve the variable’s value. For example, a Client Server application should communicate with each other,so the Server information has to be stored in Client in  order to establish the communication with the Server. The server information like IP Address can be stored and retrieved from the Properties file.

Basics on Handling Properties file:

The following procedures has to be followed in order to write Properties to Properties file.

The following procedures has to be followed in order to Read Properties from Properties file.

  • Create instance of Properties file.
  • Load the FileInput Stream Object
  • Read the Value using the Key value. ( using getProperties method )
  • Close the Input Stream Object

Click here to see more details on Properties class.

Example:

The following example shows how to Write Properties into Properties file.

/* PropTest.java by elangovan */
import java.util.*;
import java.io.*;
class PropTest
{
	public static void main(String args[]) throws IOException
	{
		if( args.length < 2)
		{
			System.out.println("Usage: PropTest <UserName> <FavColor>");
			System.exit(0);
		}
		Properties prop=new Properties();
		FileOutputStream out=new FileOutputStream(new File("UserSetting.ini"));
		prop.setProperty("UserName",args[0]);
		prop.setProperty("FavColor",args[1]);
		prop.store(out,"");
		out.close();
	}
}

Running the program

javac PropTest.java
java PropTest MyName Blue

The following example shows how to Read from Properties file.

/* PropTest.java by elangovan */
import java.util.*;
import java.io.*;
class PropReadTest
{
	public static void main(String args[]) throws IOException
	{
		String UserName="",FavColor="";
		Properties prop=new Properties();
		FileInputStream fin=new FileInputStream(new File("UserSetting.ini"));
		prop.load(fin);
		UserName = prop.getProperty("UserName");
		FavColor = prop.getProperty("FavColor");
		fin.close();
		System.out.println("User name is:"+UserName);
		System.out.println("Favourte Color is:"+FavColor);
	}
}

Running the program

javac PropReadTest.java
java PropReadTest

Getting IP Address of Machine in VC++

Getting IP Address of machine in VC++

Introduction:

Here we can see how to get the multiple ip address available in machine and display it in Multi line text box in MFC.

How To start:

here am used MFC dialog based application you can change it accordingly.

note: make sure to select Socket support in Application Wizard

How to make Multi line text Box in MFC:

To make a Editbox as multi line text box follow this procedure .

  • Select the edit box and select the properties
  • Select Multiline checked
  • Select want return checked

Selection will look like as follows

  • Create member variable as Value type using Class Wizard. to insert a new line in edit box we should use “\r\n“.
  • for example if the member variable is m_Text we can use as follows
m_Text="\r\n Hi \r\n This \r\n Multiline \r\n Sample";

Code To Get the IP Address:

The following code gets and displays the IP Address of the machine in the edit box.

void CDispalyIPAddressDlg::OnGetIP()
{
 UpdateData(TRUE);
 char HostName[128];
 //Get host name and Check is there was any error
 if (gethostname(HostName, sizeof(HostName)) == SOCKET_ERROR)
 {
 AfxMessageBox("Error in Getting Host Info");
 CDialog::OnCancel();
 }
 //Get the ip address of the machine using gethostbyname function
 struct hostent *IpList = gethostbyname(HostName);
 m_List+="Host Name is:";
 m_List+=HostName;
 m_List+="\r\n";
 if (IpList == 0)
 {
 AfxMessageBox("Yow! Bad host lookup.");
 CDialog::OnCancel();
 }
 m_List+="\r\n\r\nIP Address Available are:\r\n";
 m_List+="----------------------------------------------------------\r\n";
 //Enumerate list of Ip Address available in the machine
 for (int i = 0; IpList->h_addr_list[i] != 0; ++i)
 {
 struct in_addr addr;
 memcpy(&addr, IpList->h_addr_list[i], sizeof(struct in_addr));
 CString str=inet_ntoa(addr);
 m_List=m_List+ str;
 m_List+="\r\n" ;
 }
 m_List+="-----------------------------------------------------------\r\n";
 UpdateData(FALSE);
}

Final Output

Final looks like in the following screen shot.

Read more of this post

Connecting Java and MySQL using JConnector

Connecting Java and MySQL using JConnector

Here we can see how to connect a Java Front end with MySQL DB using JConnector. There are lot of ways to connect Java and MySQL. JConnector is is one of the best solution to do that. You can choose the your option based on your requirement.

Software Requirements:

  • MySQL ( Click here to download )
  • JConnector( click here to download )
  • JDK ( click here to download )

Step By Step Process:

  • Copy the JConnector JAR file to the following path,

C:\Program Files\Java\jre6\lib\ext

  • Set the Class path:
  1. Right click the My Computer select Properties
  2. Select advanced tab
  3. Select Environment Variables: Create/Modify the CLASSPATH variable.
  4. Add the following in CLASSPATH “C:\Program Files\Java\jre6\lib\ext\mysql-connector-java-5.1.7-bin.jar” (Note: if you are modifying the CLASSPATH variable prefix “;” before the path)
  • Create a table and insert data.
use test;
create table User(UserName varchar(30),Age integer);
insert into User values(“Name1″,24);
insert into User values(“Name2″,25);
insert into User values(“Name3″,26);
  • Creating a Front End Java code to communicate with the DB. For demonstration I used Simple Console application.

import java.sql.*;
class JavaTest
{
 public static void main(String args[])
 {
 Connection conn = null;
 Statement stmt = null;
 ResultSet rs = null;
 try
 {
 String userName = "root";
 String password = "admin";
 String url = "jdbc:mysql://localhost/test";
 Class.forName("com.mysql.jdbc.Driver").newInstance();
 conn = DriverManager.getConnection(url, userName, password);
 System.out.println("After GetConnection");
 stmt = conn.createStatement();
 String quary = "select * from User";
 rs = stmt.executeQuery(quary);
 while (rs.next())
 {
 System.out.println("User Name is:"+rs.getString(1));
 System.out.println("User Age is:"+rs.getString(2));
 }
 }
 catch (Exception e)
 {
 e.printStackTrace();
 }
 finally
 {
 if (conn != null)
 {
 try
 {
 conn.close();
 }
 catch (Exception e)
 {
 System.out.println("Error Closing Connection");
 }
 }
 }
 }
}

Creating A Exe in Java

How to create A Exe in Java for Windows

Here we can see how to create a Exe using Java. This is offten usefull if you want to run your java application like a native executable. Here am going to demonstrate this with the help of a simple Java Swing Application.

What is exe?

In windows Environment we often came across of term called exe. It stands for executable file, which will be executed when ever the user double clicks the icon. In java we can make a executable jar that will be executed when ever user double clicks it. But it will have .jar extension that often make people its not native application.

For example a company created a SWING based application with Windows look and feel to make it like native application. But still it will not fulfill the need as it has the .jar extension.

How to create a Simple Swing Application?

Here am going to create a simple JFrame based Swing application. To create your swing application you just need to extend the JFrame class.

import javax.swing.JFrame;
class MyApplication extends JFrame
{
}

Here we can see how to create a simple Swing application:

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.FlowLayout;
class MyApplication extends JFrame implements ActionListener
{
 MyApplication()
 {
 JButton SayHello=new JButton("Say Hello ");
 SayHello.addActionListener(this);
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 setLayout(new FlowLayout());
 add(SayHello);
 setVisible(true);
 setSize(350,80);
 }
 public void actionPerformed(ActionEvent e)
 {
 JOptionPane.showMessageDialog(this, "Hello All this is Sample Swing Application", "This is Titile", JOptionPane.OK_OPTION);
 }
 public static void main(String args[])
 {
 new MyApplication().setTitle("This is Sample Application");
 }
}

Creating executable jar file:

The following shows How to create executable Jar file

  • Creating manifest file:

First step in Creating executable jar is creating manifest file. Manifest file contains information’s on how the Application is going to be launched like class name and version name ect. The following shows the sample manifest file for our Swing Application.

Manifest-Version: 1.2
Main-Class: MyApplication
Created-By: 1.4 (Sun Microsystems Inc.)
  • And now time to put all together

Compile the java application

javac MyApplication.java
  • Create the Executable Jar file using the following command
jar cvfm MyApplication.jar manifestfile MyApplication.class

To learn more on JAR file specification click here

There was some Open Source Tools were available to make an executable jar to exe the following are some of them

Time to create a exe with the help of  Launch4J:

As we already created the Executable JAR our work here is very little. It is straight forward to create EXE in Launch4J.

  • Set basic Options: The Following are mandatory fields in the Basic Tab. ( see the screen shot for basic options )
    • Output File Name : Give a Valid file name with EXE extenstion.
    • Jar name : Give the JAR file as input.

  • Set JRE versions: ( See Screen Shot for more info )
    • Set Min JRE version     : Give a Valid JRE version
    • Set MAX JRE version  : Give a Valid JRE Version

Just Save the project. And Click build Wrapper option. Now Exe will be produced in the mentioned path.

Thanks

Shutdown System using Java Native Interface (JNI)

Shutdown System using Java Native Interface (JNI)

What is JNI?

The JavaTM Native Interface (JNI) is a powerful feature of the Java platform. Applications that use the JNI can incorporate native code written in programming languages such as C and C++, as well as code written in the Java programming language. The JNI allows programmers to take advantage of the power of the Java platform, without having to abandon their investments in legacy code. Because the JNI is a part of the Java platform, programmers can address interoperability issues once, and expect their solution to work with all implementations of the Java platform.

Who need’s JNI?

JNI is useful for the programmer who wants to perform a low level programming activity’s with System. For example performing Native IPC or Kernel/Shell related operations.

What i Should learn to be JNI programmer?

Knowledge in Core java and Hand on any low level( C or C++ ) programming language is enough.

Find best resources on C and C++ click here

What are the tools/ software required?

For compiling the Java program and generating JNI headers we need

For Compiling and generating Dll

Here i am going to demonstrate it with the help of two most popular C/ C++ compilers Microsoft Visual studio and MinWG( minimal GNU compiler for Windows)

How to create JNI program

  1. Create Java program which should export the Native methods
  2. Create .h file using javah tool ( ie. javah class-name )
  3. Create .c/cpp file to implement the methods.
  4. Compile and like as DLL ( Dynamic Link Library )
  5. Run and test the program.

Creating Java Program:

// JavaShutdown.java
class JavaShutdown
{
    private native void Shutdown();
    static
    {
          System.loadLibrary("ShutdownImpl");
    }
    public static void main(String args[])
    {
          new JavaShutdown().Shutdown();
    }
}

Compiling Java program:

Generating class file,

javac JavaShutdown.java

Generating Header file

javah JavaShutdown

To know more about javah click here

Generating DLL:

Here am going to create DLL in two ways one is using Microsoft Visual Studio and Using MinGW. First we can see the steps to create a DLL using MVS

Creating DLL using Microsoft Visual Studio ( VC++ Compiler )

Here am going to use Microsoft Visual C++ 6.0 which i acquainted very well,

The following show step by step process of creating DLL in VC++:
  • Create a new Project in VC++ File > New > Projects -> Select Win32 Dynamic Link Library > Enter the Project Name (ie. ShutdownImpl )

  • Select Empty Dll Project then Finish Button Give OK in Project Information Dialog
  • Add New Source File into the Project by clicking File> New > Source File > C / Cpp header files ( ie. ShutdownImpl.c ) Make sure to give

  • Implement the JNI functions in ShutdownImpl.c Copy and paste the following code into the ShutdownImpl.c file
#include<stdio.h>
#include<windows.h>
#include "JavaShutdown.h"
JNIEXPORT void JNICALL Java_JavaShutdown_Shutdown(JNIEnv *env, jobject obj)
{
 printf("Shuting Down....");
 ExitWindows(EWX_POWEROFF,NULL);
}

ExitWindows function is a native method used for Shutdown the system in windows Environment. To know more about ExitWindows Click here

You can also use EWX_FORCE along with EWX_POWEROFF to force power off (ie. ExitWindows( EWX_FORCE || EWX_POWEROFF, NULL);

Also see ExitWindowsEx

  • Set the Path of the JNI headers and Compiled JNI Header file by Tools > Options > Directory tab and make sure Include files selected

  1. Add the path of Java Include Library
  2. Add the path of Java WIN32 Header file
  3. Add the path contains your Java header file ( directory contains the JavaShutdown.h ” )
  • Compile and Build the DLL
  • Copy the Dll to the directory which contains the Java Source files and Run the java Application.

java JavaShutdown

Creating a DLL using MinGW( best option for me )

  • Create a new Text file in notepad or any editors. Copy and paste the following source code. Save As ShutdownImpl.c
#include<stdio.h>
#include<windows.h>
#include "JavaShutdown.h"
JNIEXPORT void JNICALL Java_JavaShutdown_Shutdown(JNIEnv *env, jobject obj)
{
 printf("Shuting Down....");
 ExitWindows(EWX_POWEROFF,NULL);
}
  • Compile the C program using the following command. ( note: class path for MinGW compiler is set properly)
    • Give it in single line
gcc -Wall -D_JNI_IMPLEMENTAION_ -Wl,--kill-at -I "C:\Program Files\Java\jdk1.6.0_13\include" -I "C:\Program Files\Java\jdk1.6.0_13\include\win32" -shared -o ShutdownImpl.dll ShutdownImpl.c
  • Now Run the java Application.

java JavaShutdown

Please post your comments

Thank you

elangovan