Monday, December 6, 2010

Part 1 of 6: RS232 Communication Using JAVA

===============================================================
Click HERE -PART 2 of 6
===============================================================
If you are not sure about –

Ø What is the difference between DCE and DTE?
Ø What is the significance of RTS, DTS, CS, ACK, NACK, STX, ETX etc in Serial Communication?
Ø Whether to implement event based or time based communication?
Ø Whether to transmit data in Hex, ASCII or Hex dumps?
Ø Which combination of Baud rate, data bits, parity bit, hardware flow, and stop bit one should use?
And
> If you don’t know that native JAVA doesn’t have unsigned bytes and serial communication is less error prone if you transmit data in unsigned bytes.
And
Ø
If you are looking for a very simple solution to implement the complex flow of serial communication?
Ø If you are looking for a JAVA based solution of serial communication?
If answers to most of questions are YES, then you are at right page. Here we will go through a small tutorial to make you master of serial communication in JAVA.
Note:
Ø This tutorial assumes that you have eclipse install on your system.
Ø You have basic knowledge of JAVA.

Thursday, June 24, 2010

XML to HashMap in JAVA

Hi Guys,

This program will convert any XML document to a HashMap in Java.
Download - Please download it from here-
http://code.google.com/a/eclipselabs.org/p/java-utility/downloads/list

1) Program 1: XMLToMap.java
This is the main java program. It has public static void main method.
2) Program 2: ValueHandler.java
This is the program which will actually do the conversion.
3) Prgram 3: StringToSteam.java
This is just a small util which will convert String to InputStream.

How to use?
1) Please unzip the zip file.
2) Copy all the 3 files in same folder
3) Run XMLToMap.java

The program will run on Java 1.5 and higher.

Thursday, June 10, 2010

com port communication using java

NOTE: For step by step tutorial please click on this link -
COM PORT COMMUNICATION USING JAVA (RS232JAVA-1.0.0 API)

import gnu.io.*;
import java.io.*;

public class ComPortTest
{

/*
 * This program will connect to COM PORT Device and send TEST MESSAGE to it.
 * After sleeping for 500ms , It will read the response from SAME DEVICE.
 * copyright (c) 2011 http://www.jovialjava.blogspot.com
 * For detailed Tutorial please check it out - 
 * http://jovialjava.blogspot.com/2010/12/rs232-communication-using-java.html
 */
public boolean testComPort(String comPort, String testMessage){
    CommPortIdentifier portIdentifier = null;
    try{
        portIdentifier = CommPortIdentifier.getPortIdentifier(comPort);
        if (portIdentifier.isCurrentlyOwned())
        {
            System.out.println("Port in already in use, owner ["+ portIdentifier.getCurrentOwner()+"]");
            return false;
        }else{
            SerialPort serialPort = (SerialPort) portIdentifier.open("ListPortClass", 300);
            System.out.println("COM PORT NAME -["+portIdentifier.getName()+"] BAUD RATE ["+serialPort.getBaudRate()+"]" );
            serialPort.setSerialPortParams(300, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            OutputStream mOutputToPort = serialPort.getOutputStream();
            InputStream mInputFromPort = serialPort.getInputStream();
            mOutputToPort.write(testMessage.getBytes());
            System.out.println("Byte Sent");
            mOutputToPort.flush();
            System.out.println("Waiting for response");
            Thread.sleep(500);
            byte mBytesIn [] = new byte[20];
            mInputFromPort.read(mBytesIn);
            String value = new String(mBytesIn);
            System.out.println("Response from Serial Device: "+value);
            mOutputToPort.close();
            mInputFromPort.close();
            serialPort.close();
            System.out.println("!!! ======================== COM PORT TEST - PASS =============================!!!");
            return true;
        }
    }catch(NoSuchPortException nspe){
            System.out.println("No such port ["+comPort+"] found on system "+ nspe.getMessage());
    }catch(PortInUseException piue){
            System.out.println("port ["+comPort+"] is already in use, owner["+ portIdentifier.getCurrentOwner()+"] "+piue.getMessage());
    }catch(UnsupportedCommOperationException ucoe){
            System.out.println("Setting Communciation Operations - 300, DataBits -"+ SerialPort.DATABITS_8+", StopBits "+ SerialPort.STOPBITS_1+", Parity "+ SerialPort.PARITY_NONE);
            System.out.println("Communication Operations are not supported on port ["+comPort+"] "+ ucoe.getMessage());            
    }catch(IOException ioe){
            System.out.println("IOExceptin while trying to communicate with COM PORT device "+ ioe.getMessage());
    }catch(InterruptedException ie){
            System.out.println("Interruption while waiting for response from COM Device "+ ie.getMessage());
    }
    return false;
}

    public static void main(String... args){
            new ComPortTest().testComPort("COM1", "JOVIAL JAVA");    
    }
} 

Monday, May 31, 2010

Hex to ASCII and ASCII to Hex in JAVA


"HEX to ASCII Conversion in JAVA":

public static String hexToASCII(String hex){       
          if(hex.length()%2 != 0){
             System.err.println("requires EVEN number of chars");

             return null;
          }
          StringBuilder sb = new StringBuilder();               
          //Convert Hex 0232343536AB into two characters stream.
          for( int i=0; i (LessThan) hex.length()-1; i+=2 ){

               /*
                * Grab the hex in pairs
                */

              String output = hex.substring(i, (i + 2));

              /*
               * Convert Hex to Decimal
               */

              int decimal = Integer.parseInt(output, 16);                 
              sb.append((char)decimal);             
          }           
          return sb.toString();
    }


"ASCII to Hex Conversion In JAVA" :

public static String asciiToHex(String ascii){
        StringBuilder hex = new StringBuilder();
       
        for (int i=0; i < ascii.length(); i++) {
            hex.append(Integer.toHexString(ascii.charAt(i)));
        }      
        return hex.toString();
    } 

Read properties file in Java

the main essence of program is following method, How ever u can download a working copy form here-
http://code.google.com/a/eclipselabs.org/p/java-utility/downloads/list

public static boolean readProperties(String fileName, Properties pro) throws IOException{
try{
File f = new File(fileName);
// Check the important properties of properties file.
if(f.exists() && f.canRead() && f.isFile()){
FileInputStream in = new FileInputStream(f);
// Just load the properties file here
pro.load(in);
return true;
}
else{
logger.info(f.getAbsolutePath());
if(!f.exists())
logger.error("File not found!");
if(!f.canRead())
logger.error("Can not read the file !");
if(!f.isFile())
logger.error("Not a file !");
return false;
}
}
catch(IOException e){
logger.error("Exception while reading the properties file :"+ e.getMessage());
throw e;
}
}

Sunday, May 30, 2010

java regex to validate email

/**
*@author Sunny Jain
*@Email i_look_like_sunny@hotmail.com
*@version 1.0
*@since 02-March-2010
*@about - this Class will use regular express to validate the email address.
*\\p{Alpha} means - any alphabet ( case insensitive)
*\\p{Alnum} means - any alphabet + any digit ( case insensitive)
*It checks any email address that ends with .com, .org, and co.(any country)
*/

public class Main {

public static void main(String... args){
String alpha = "i_look_like_sunny@hotmail.co.in";
String ALPHAREGEX = "[\\p{Alpha}]+[\\p{Alnum}_.]*[@][\\p{Alnum}]+[.]" +
"(([cC][oO][mM])|([oO][rR][gG])|([cC][oO][.][\\p{Alpha}]*))";

System.out.println(ALPHAREGEX);
System.out.println(alpha.matches(ALPHAREGEX));
}
}