Thursday, December 9, 2010

Run java application as a Windows NT Service

SrvAny.exe and its installer "InstSrv.exe" are applications provided by Microsoft. SrvAny allows Windows applications to run as a service. But by using those two exe we make a java class or java jar file as a windows service.
I want to explain by giving a small demo to run a java class as window service.
Step 1: Download srvany.exe and instsrv.exe from this link.


Step 2: Go to DOS prompt and type the command like

c:\ instsrv.exe  srvany.exe
Above command will create a service with the given name in <> brackets.
e.g. c:\srvany\instsrv.exe Testing  c:\srvany\srvany.exe

This will create a service with the name “Testing” ,we can check this by opening the services.msc from from control pannel.

Step 3: Now I am making a folder “Testing”  in c:\ where I am putting my java application which will run as a service.
I am writing a simple program which will write a text file after 5000 ms on the same location.
Source :  TestService.java

import
java.io.*;
public class TestService {

     
      public static void main(String[] args) {
           
                  int i=0;
                  while(true) {
                        System.out.println("------------------------------");
                        System.out.println("Service Start...");
                        System.out.println("------------------------------");
                        try {
                              writeToFile("Services_Test_"+i+".txt");
                              i++;
                              Thread.sleep(5000);
                        } catch (Exception e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                              writeToFile("Error");
                        }
                  }
      }
public static void writeToFile(String filename) {
       
        BufferedWriter bufferedWriter = null;
       
        try {
           
            //Construct the BufferedWriter object
            bufferedWriter = new BufferedWriter(new FileWriter(filename));
           
            //Start writing to the output stream
            bufferedWriter.write("Writing line one to file");
            bufferedWriter.newLine();
            bufferedWriter.write("Writing line two to file");
           
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the BufferedWriter
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Step 4: now we need to configure this java application into windows registry for creating it as a windows nt service.
In step 1 we create a service with the name ”Testing” by using srvany.exe and instsrv.exe
Type regedit in run it will open registry.
Lookup our service in this path in registry window
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Testing





Step 5: Now right click on Testing and add a new key with the name as “Parameters”.


Step 6 : Now click on Parameters then it will show a Defalut  value in right side window .right click on right side window and then select New-> String Value .
Create three String value
1.       Application
2.       AppParameters
3.       AppDirectory
See in the screenshot below.



Step 7 : Click on Application and give the java.exe path of your local machine.


Step 8 : click on AppParameters and give the java class or jar name which we want to run as a service.

Step 9: Click on AppDirectory and give the path of the directory where you put your java application in the system.


Step 10 : Now service is ready to run, we can run and stop this service from services.msc.


Step 10 : Check the output this service will generates the text file in the current location where we put class file. With same manner we can run a jar file as a service.


Enjoy your service :)













Thursday, July 10, 2008

java.util.Calendar package

/*This class shows the different different formta of date.
*dd-mm-yyyy
*dd-MM-yyyy-mm-ss
*The java.util.Calendar class is used to represent the date and time.
The year, month, day, hour, minute, second, and milliseconds can all
be set or obtained from a Calendar object. The default Calendar object
has the current time in it. There are also methods for making data calculations.
*/
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DataFormats
{

public static final String DATE_FORMAT_1 = "yyyy-MM-dd";
public static final String DATE_FORMAT_2 = "yyyy-MM-dd-mm-ss";
public static void main(String[] args)
{
String ddMMYyyy=getDDMMYYYY();
String ddMMYyyymmss=getDDMMYYYYmmss();
System.out.println("Date in dd-MM-yyyy Format = "+getDDMMYYYY());
System.out.println("Date in dd-MM-yyyy-mm-ss Format = "+getDDMMYYYYmmss());
}
//Method for date in dd-MM-yyyy format
public static String getDDMMYYYY()
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_1);
return sdf.format(cal.getTime());
}
//Method for date in dd-MM-yyyy-mm-ss format
public static String getDDMMYYYYmmss()
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_2);
return sdf.format(cal.getTime());
}

}

Wednesday, July 2, 2008

Hitting a URL and get page content into a string

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class UrlHit {

public static void main(String args[])
{
try {

URL cricurl = new URL("http://codeforjava.blogspot.com/2008/06/method-for-copying-only-files-from-one.html");
URLConnection criccon = cricurl.openConnection();
criccon.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(cricurl.openStream()));
String s="";
String strTemp="";


while((strTemp=br.readLine()) != null)
{
strTemp = br.readLine();
s=s.concat(strTemp);
}
s=s.trim();


System.out.println("Got url content - "+s);




} catch (Exception e)
{
e.printStackTrace();
}

}

}

Tuesday, June 24, 2008

Method for copying only files from one location to another location

public static boolean copyAllFiles(File src,File dst) throws IOException{
boolean flag = false;
try
{
if (src.isDirectory())
{
if (!dst.exists())
{
dst.mkdir();
}
File[] srcArr = src.listFiles();
ArrayList flist = new ArrayList();
for(int i=0;i {
if(!srcArr[i].isDirectory())
{
String fileName = srcArr[i].getAbsolutePath();
String[] fileArr = fileName.split("\\\\");
flist.add(fileArr[fileArr.length-1]);
}
}
for (int i=0; i{
copyAllFiles(new File(src, flist.get(i).toString()), new File(dst, flist.get(i).toString()));
}
flag = true;
}
else
{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
flag = true;
}
}
catch(Exception ex)
{ flag = false; }
return flag;
}

java jdbc connectivity with sql server 2000

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connUrl="jdbc:sqlserver://localhost:1433;database=testDB";
Connection con=DriverManager.getConnection(connUrl,dbUser,dbPass);
Statement stmtVMS = con.createStatement();