Monday, July 26, 2010

Reading MS Word Document With Java (Apache POI API)

public void readDocument(String fileName){ 
try {
            POIFSFileSystem poifs = new POIFSFileSystem(new FileInputStream(fileName));
            HWPFDocument doc = new HWPFDocument(poifs);
            WordExtractor extractor = new WordExtractor(doc);
            String[] paragraphs = extractor.getParagraphText();
            for (String paragraph : paragraphs) {
                paragraph = paragraph.replaceAll("\\cM?\r?\n", "");
                System.out.println(paragraph);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
}

Saturday, July 24, 2010

Reading System Environment With JAVA

Map sysEnv = System.getenv();
      
for (String key : sysEnv.keySet()) {
     System.out.println(key +" => "+ sysEnv.get(key));
}


System.getenv(); will return java.util.Map of system environment, which will be easy to iterate as other Map in Java.  will be the generic representation of Map

Append Property To System Properties With JAVA

 Properties sysProp = System.getProperties();
        sysProp.setProperty("country", "India");
        System.setProperties(sysProp);
        for (String key : sysProp.stringPropertyNames()) {
            System.out.println(key +" => "+ sysProp.getProperty(key));
        }


appending system property is easy: first get system property and than set new property as pair of key-value. 

Reading System Properties With JAVA

        Properties sysProp = System.getProperties();


        for (String key : sysProp.stringPropertyNames()) {
            System.out.println(key +" => "+ sysProp.getProperty(key));
        }


System.getProperties(); will return the system property as java.utill.Properties object which can easily iterated by the simple for loop. sysProp.stringPropertyNames() will return the Set of all System properties key values.

Reading XML File With Java

public void readXML(String filePath) throws Exception {
        Document doc = getDocument(filePath);
        Element el = doc.getDocumentElement();
        NodeList nodes = el.getChildNodes();
        return xmlReader(nodes, space);
}


public  Document getDocument(String file_path) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream inputStream =  this.getClass().getClassLoader().getResourceAsStream(file_path);
        Document doc = builder.parse(inputStream);    
        return doc;
}


public static void xmlReader(NodeList nodes, String indent) throws Exception {
        int len = nodes.getLength();
        for (int i = 0; i < len; i++) {
            Node child = nodes.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                if (child.hasAttributes()) {
                    NamedNodeMap attrs = child.getAttributes();
                    for (int j = 0; j < attrs.getLength(); j++) {
System.out.println(attrs.item(j).getNodeName());                           System.out.println(attrs.item(j).getNodeValue());
                    }
                }
            }
            if (child.hasChildNodes()) {
                xmlReader(child.getChildNodes(), " " + indent);
            }
        }
}

Writing Excel File With Java (Apache POI API)

public void exportToExcel(String fileName, String sheetName, Vector resultBeans) {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
        int rowIdx = 0;
        short cellIdx = 0;
        rowIdx = 1;
        for (ResultBean bean : resultBeans) {
            cellIdx = 0;
            HSSFRow hssfRow = sheet.createRow(rowIdx++);
            HSSFCell hssfCellID = hssfRow.createCell(cellIdx++);
            hssfCellID.setCellValue(bean.getStudentId());
            HSSFCell hssfCellName = hssfRow.createCell(cellIdx++);
            hssfCellName.setCellValue(bean.getStudentName());
            HSSFCell hssfCellScore = hssfRow.createCell(cellIdx++);
            hssfCellScore.setCellValue(bean.getScore());
        }
        wb.setSheetName(0, sheetName, HSSFWorkbook.ENCODING_COMPRESSED_UNICODE);
        try {
            FileOutputStream outs = new FileOutputStream(new File(fileName));
            wb.write(outs);
            outs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Reading Excel File With Java (Apache POI API)

public void readExcelFile(String filePath, int sheetNo) {
    try {
            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath));
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            HSSFSheet sheet = wb.getSheetAt(sheetNo);
            HSSFRow row;
            HSSFCell cell;
            int totalRow = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < totalRow; i++) {
                row = sheet.getRow(i);         
                int lastCell = row.getLastCellNum();
                for (int j = 0; j < lastCell; j++) {
                     try {
                         cell = row.getCell((short) j);
                         int dataType = cell.getCellType();
                         switch (dataType) {
                            case 0:                        System.out.print(cell.getNumericCellValue() + "\t");
                                break;
                            case 1:
System.out.print(cell.getStringCellValue() + "\t");
                                break;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                                        }
                                        System.out.println();
                              }
    } catch (Exception ex) {
            ex.printStackTrace();
    }
}

Friday, July 23, 2010

Java String Pattern Matching And Getting Group Of Match Token

 Pattern pat = Pattern.compile("JAVA");
 Matcher mat = pat.matcher("concept JAVA concept");
 while (mat.find()) {
        String token = mat.group();
         System.out.println(token);
 }


"JAVA" is any string which can also accept wildcard character. mat.find(); will return whether the matching string found or not, mat.group(); will return matching token.

Java Connection Pooling With Data Sources

public static DataSource setupDataSource(String connectURI,String uName,String pass) {
        ObjectPool connectionPool = new GenericObjectPool(null);
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI,uName, pass);
        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
        PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
        return dataSource;
}


This will create Connection Pooling with DataSources
you can call this method as 


 DataSource dataSource = setupDataSource("jdbc:mysql://localhost:3306/testdb","root","root");
Connection conn =  dataSource.getConnection();
// any db operation;
conn.Close();


and perform any database operation, one thing must keep in your mind i.e. you must have to close connection which will return your connection to current data sources connection pool.

Java Operation Performing As Per Schedule Interval

class Scheduler {
    Timer timer;
    public Scheduler (int seconds, int period) {
        timer = new Timer();
        timer.scheduleAtFixedRate(new RemindTask(), seconds * 1000, period * 1000);
    }
}


class RemindTask extends TimerTask {
         public void run() {
        // performing task operation
        }
}


calling this scheduler as : new Scheduler(10,7);



Writing Java Property Object To File

Properties prop = new Properties();
prop.setProperty("moin","master");
prop.setProperty("Ajija","Moin Master");



FileOutputStream fos = new FileOutputStream(fileName);
prop.store(fos, null);
fos.close();


line prop.store(fos, null); will help you to store java property object to file stream

Reading Property File With Java

Properties p = new Properties();
p.load(new FileInputStream(propFile));


Set set = p.keySet();
Iterator it = set.iterator();
while(it.hasNext()){
      Object keyObj=it.next();
      String key=(String)keyObj;
      if (key.equals(searchKey))
      System.out.println(p.getProperty(key));
}


we can load property file as java property object by writing line, p.load(new FileInputStream(propFile)); after load property file we can easily iterate property one by one as same as java Hashtable.

Thursday, July 22, 2010

Reading Java Object From Database

import java.io.Serializable;
public class Employee implements Serializable {
    private int Id; 
    private String firstName;
}


PreparedStatement pstmt = conn.prepareStatement(SQL_SELECT_QUERY);
pstmt.setLong(1, key);
ResultSet rs = pstmt.executeQuery();
rs.next();


byte[] buf = rs.getBytes("object_value");


if (buf != null){
ObjectInputStream objectIn = new ObjectInputStream(new      ByteArrayInputStream(buf));
Object object = objectIn.readObject();
Employee emp = (Employee) object;
}


here we can not read directly object from Database, we may get this object in byte stream. 


the ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(buf)); statment will reaturn the object input stream from where we will derived java object by Object object = objectIn.readObject(); statment. 


now once you get java object you know this is the object of Employee type, so you can directly cast this object to Employee class. 

Writing Java Object To Database

it is too easy to write java object to database with the use of following code




import java.io.Serializable;
public class Employee implements Serializable {
    private int Id; 
    private String firstName;
}
 

Employee object = new Employee();
PreparedStatement pstmt =conn.prepareStatement(SQL_INSERT_QUERY);
  
pstmt.setString(1, "Employee");
pstmt.setObject(2, object);
pstmt.executeUpdate();

here pstmt.setObject(2, object); statment will write java object to  database as one record record.











implements Serializable is important to serialization of java object to database.

Getting Current Inserted Record's Primary Key

PreparedStatement pstmt = conn.prepareStatement(SQL_QUERY);

pstmt.executeUpdate();

ResultSet rs = pstmt.getGeneratedKeys();
int key = -1;
if (rs.next()) {
    key = rs.getInt(1);
}

here key will return the current inserted record's primary key.