Wednesday, November 18, 2009

Java Communication API - Serial Port Communication

The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports) and limited access to IEEE-1284 (parallel ports), SPP mode.

How To use javax.comm


This package contains following files.
1.    comm.jar
2.    win32com.dll
3.    javax.comm.properties
Place the above files in below location.
comm.jar should be placed in:
    %JAVA_HOME%/lib
    %JAVA_HOME%/jre/lib/ext

win32com.dll should be placed in:
    %JAVA_HOME%/bin
    %JAVA_HOME%/jre/bin
    %windir%System32
javax.comm.properties should be placed in:
    %JAVA_HOME%/lib
    %JAVA_HOME%/jre/lib

Download Link:


How to Read data from Serial Port


import java.io.*;
import java.util.*;
import javax.comm.*;


public class ReadData implements Runnable, SerialPortEventListener {
    static CommPortIdentifier portId;
    static Enumeration            portList;
    InputStream                       inputStream;
    SerialPort                serialPort;
    Thread                     readThread;


public static void main(String[] args) {
    boolean                   portFound = false;
    String                      defaultPort = "/dev/term/a";


          if (args.length > 0) {
              defaultPort = args[0];
          }
  
          portList = CommPortIdentifier.getPortIdentifiers();


          while (portList.hasMoreElements()) {
              portId = (CommPortIdentifier) portList.nextElement();
              if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                   if (portId.getName().equals(defaultPort)) {
                       System.out.println("Found port: "+defaultPort);
                       portFound = true;
                       ReadData reader = new ReadData();
                   }
              }
          }
          if (!portFound) {
              System.out.println("port " + defaultPort + " not found.");
          }
         
    }

   public ReadData() {
          try {
              serialPort = (SerialPort) portId.open("ReadApp", 2000);
          } catch (PortInUseException e) {}


          try {
              inputStream = serialPort.getInputStream();
          } catch (IOException e) {}


          try {
              serialPort.addEventListener(this);
          } catch (TooManyListenersException e) {}


          serialPort.notifyOnDataAvailable(true);


          try {
              serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
                                                   SerialPort.STOPBITS_1,
                                                   SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {}


          readThread = new Thread(this);


          readThread.start();
    }


 public void run() {
          try {
              Thread.sleep(20000);
          } catch (InterruptedException e) {}
    }


 public void serialEvent(SerialPortEvent event) {
          switch (event.getEventType()) {


          case SerialPortEvent.BI:


          case SerialPortEvent.OE:


          case SerialPortEvent.FE:


          case SerialPortEvent.PE:


          case SerialPortEvent.CD:


          case SerialPortEvent.CTS:


          case SerialPortEvent.DSR:


          case SerialPortEvent.RI:


          case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
              break;


          case SerialPortEvent.DATA_AVAILABLE:
              byte[] readBuffer = new byte[20];


              try {
                   while (inputStream.available() > 0) {
                       int numBytes = inputStream.read(readBuffer);
                   }


                   System.out.print(new String(readBuffer));
              } catch (IOException e) {}


              break;
          }
    }


}



How to write data to serial port


import java.io.*;
import java.util.*;
import javax.comm.*;


public class WriteData {
    static Enumeration            portList;
    static CommPortIdentifier portId;
    static String             messageString = "Hello, world!";
    static SerialPort       serialPort;
    static OutputStream       outputStream;
    static boolean          outputBufferEmptyFlag = false;
  

public static void main(String[] args) {
          boolean portFound = false;
          String  defaultPort = "/dev/term/a";


          if (args.length > 0) {
              defaultPort = args[0];
          }


          portList = CommPortIdentifier.getPortIdentifiers();


          while (portList.hasMoreElements()) {
              portId = (CommPortIdentifier) portList.nextElement();


              if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {


                   if (portId.getName().equals(defaultPort)) {
                       System.out.println("Found port " + defaultPort);


                       portFound = true;


                       try {
                             serialPort =
                                 (SerialPort) portId.open("WriteData          
                             ", 2000);
                       } catch (PortInUseException e) {
                             System.out.println("Port in use.");


                             continue;
                       }


                       try {
                             outputStream = serialPort.getOutputStream();
                       } catch (IOException e) {}


                       try {
                             serialPort.setSerialPortParams(9600,
                                                                 SerialPort.DATABITS_8,
                                                                 SerialPort.STOPBITS_1,
                                                                 SerialPort.PARITY_NONE);
                       } catch (UnsupportedCommOperationException e) {}
         


                       try {
                             serialPort.notifyOnOutputEmpty(true);
                       } catch (Exception e) {
                             System.out.println("Error setting event notification");
                             System.out.println(e.toString());
                             System.exit(-1);
                       }
                      
                      
                       System.out.println(
                             "Writing \""+messageString+"\" to "
                             +serialPort.getName());


                       try {
                             outputStream.write(messageString.getBytes());
                       } catch (IOException e) {}


                       try {
                          Thread.sleep(2000);  // Be sure data is xferred before closing
                       } catch (Exception e) {}
                       serialPort.close();
                       System.exit(1);
                   }
              }
          }


          if (!portFound) {
              System.out.println("port " + defaultPort + " not found.");
          }
    }



}





Monday, November 16, 2009

Check Valid XML File Using Java

We can check the XML file is valid or not in different ways. If we are opening the XML file in Internet explorer or XML notepad then if we get some errors means the XML file invalid, so it might be because of unclosed tag or invalid characters.
     Here is the program checks the xml file is valid or not.
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class CheckValidXML {
public static void main(String[] args) {


File xmlFile = new File("XML File Location");
if (xmlFile.exists()) {
if (isValidXMLFile(xmlFile.getAbsolutePath().toString())) {
System.out.println("Valid XML");
}
}
}
private static boolean isValidXMLFile(String filename) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();


try {
File f = new File(filename);
if (f.exists()) {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(f);
return true;
}


} catch (SAXParseException spe) {
System.out.println("Invalid XML");
return false;


} catch (SAXException sxe) {
System.out.println("Invalid XML");
return false;


} catch (ParserConfigurationException pce) {
System.out.println("Invalid XML");
return false;


} catch (IOException ioe) {
System.out.println("Invalid XML");
return false;
}
return true;
}
}


Sunday, November 15, 2009

Java Swing - Icon as JButton

This section illustrates you how to show the icon on the button in Java Swing without border.
Example code.


import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Image;


import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class IconButton extends JDialog {


public IconButton() {


JLabel filename = new JLabel("File Name");
JTextField filenameLoc = new JTextField(10);
Icon image = new ImageIcon(
"url of the image");
JButton iconButton = new JButton(image);
iconButton.setBorderPainted(false);
iconButton.setContentAreaFilled(false);
Container con = getContentPane();
con.setLayout(new FlowLayout());
con.add(filename);
con.add(filenameLoc);
con.add(iconButton);


setLayout(new FlowLayout());
setSize(500, 300);
setVisible(true);
}
public static void main(String[] args) {
IconButton obj = new IconButton();


}
}


Friday, November 13, 2009

Java Report Generation


 iReport 
                   Report generation is process of fetching data from database and displaying those data to Users. It may be with some period of time like weekly, monthly.etc.. Report generation is used to view historical data.
iReport is the free, open source report designer for Jasper Reports, available for all major operating systems under the GNU General Public License. Use iReport to create very complex layouts containing charts, images, sub reports, crosstabs and much more. Access your data through JDBC, Table Models, JavaBeans, XML, Hibernate, CSV, and custom sources. Then publish your reports as PDF, RTF, XML, XLS, CSV, HTML, XHTML, text, DOCX, or Open Office.


Example:- 


   


/* Datewise Report 
 * 
 */
package Package;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.sql.*;
import javax.swing.JDialog;
import javax.swing.ProgressMonitor;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.event.*;


import java.awt.event.*;


import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;


class Datevicereport extends JDialog  {
private boolean isExitOnClose = false;


ProgressMonitor conso;


int counter = 0;


Datevicereport() {
setTitle("Datewise Report");

Report();
this.dispose();
}



public void Report() {
try {
/*
* String jdbcString="jdbc:mysql://"; InetAddress address=null;
* address = InetAddress.getLocalHost(); String Ipaddr =
* address.getHostAddress(); String databaseName =
* jdbcString.concat(Ipaddr).concat("/SinglePhase");
*/
String databaseName = "jdbc:mysql://localhost/singlephase";
String userName = "root";
String password = "";
String reportFile = "DateReport.jrxml";
runReport(databaseName, userName, password, reportFile);
} catch (Exception e) {


}
}


public Connection connectDB(String databaseName, String userName,
String password) {
Connection jdbcConnection = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
jdbcConnection = DriverManager.getConnection(databaseName,
userName, password);
} catch (Exception ex) {
String connectMsg = "Could not connect to the database: "
+ ex.getMessage() + " " + ex.getLocalizedMessage();
System.out.println(connectMsg);
}
return jdbcConnection;
}


public void runReport(String databaseName, String userName,
String password, String reportFile) {
try {
JasperDesign jasperDesign = JRXmlLoader.load(reportFile);
JasperReport jasperReport = JasperCompileManager
.compileReport(jasperDesign);
Connection jdbcConnection = connectDB(databaseName, userName,
password);
JasperPrint jasperPrint = JasperFillManager.fillReport(
jasperReport, null, jdbcConnection);
JasperViewer.viewReport(jasperPrint, isExitOnClose);
OutputStream ouputStream    = new FileOutputStream(new File("C:/catalog.xls"));
ByteArrayOutputStream byteArrayOutputStream    = new ByteArrayOutputStream();
JRXlsExporter exporterXLS = new JRXlsExporter();
exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT,jasperPrint);
exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM,byteArrayOutputStream);
exporterXLS.exportReport();
ouputStream.write(byteArrayOutputStream.toByteArray()); ouputStream.flush();ouputStream.close();
exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE); 
exporterXLS.setParameter(JRXlsExporterParameter.IS_AUTO_DETECT_CELL_TYPE, Boolean.TRUE); 
exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); 
exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);


exporterXLS.exportReport(); 

catch(Exception ex) 
{
String connectMsg = "Could not create the report "
+ ex.getMessage() + " " + ex.getLocalizedMessage();
System.out.println(connectMsg);
}
}


}

Download link:-
    http://jasperforge.org/plugins/project/project_home.php?projectname=ireport


JFreeReport


JFreeReport is a free Java class library for generating reports (GNU LGPL). Includes support for headers, footers, grouping, report functions, print preview, export to PDF and more. Complete source code is included, subject to the GNU LGPL.
Download link:-












Bookmark and Share
Hihera.com
Increase Page Rank Google
TopBlogDir.blogspot.com button
Best Indian websites ranking
Tips for New Bloggers
TopOfBlogs
The Link Exchange - Your ultimate resource for link exchange!

About This Blog

TopOfBlogs

FEEDJIT Live Traffic Feed

  © Blogger template Webnolia by Ourblogtemplates.com 2009

Back to TOP