Thursday, September 4, 2014

Read XML data and Insert to MsSQL database



















//MsSqlConnectionData.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class MsSqlConnectionData {


public static Connection getconnection()
{
Properties properties = new Properties();
Connection con = null;
try {
String URL = "jdbc:sqlserver://20.1.1.4;databaseName=SampleTestDB";
String username = "sa";
String password = "Esales123";

Properties info = new Properties();
info.put("user", username);
info.put("password", password);
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(URL, info);
con.setAutoCommit(false);

} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("MsSQL Connection Error " + e.toString());
e.printStackTrace();
}

return con;
}
}
--------------------------------------------------------------------------------------------------------------------------

//ReadXML.java

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXML
{
public static void main (String[] args)throws Exception
{
Connection connectionobj = null;
Statement insertStmt = null;
try
{
connectionobj = MsSqlConnectionData.getconnection();
        insertStmt = connectionobj.createStatement();
       
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("D://userData.xml"));

doc.getDocumentElement().normalize();

NodeList listOfstate = doc.getElementsByTagName("state");

for (int loop = 0; loop < listOfstate.getLength(); loop++)
{
Node prop1 = listOfstate.item(loop);
NodeList listchd = prop1.getChildNodes();

NamedNodeMap attr1 = prop1.getAttributes();
if (attr1 != null)
{
Node countryNode = attr1.getNamedItem("name");
String state = (String)countryNode.getNodeValue();

for (int innerLoop = 0; innerLoop < listchd.getLength(); innerLoop++)
{
if (listchd.item(innerLoop).getNodeType() == Node.ELEMENT_NODE)
{
String countyName = "";
Node chdnode = listchd.item(innerLoop);
Attr attrName = ((Element) chdnode).getAttributeNode("NAME");

if (attrName.getValue() != null) {
countyName = attrName.getValue();
String sqlStatement = "INSERT INTO T601_US_Cities (state,city) VALUES ('"+ state + "','"+ countyName + "')";
insertStmt.addBatch(sqlStatement);
}
}
}//end of inner for Loop
}
}//end of for Loop

int[]  rowsInsert = insertStmt.executeBatch();
connectionobj.commit();
insertStmt.clearBatch();
System.out.println("No. of Rows Inserted :"+rowsInsert.length);
}
catch (Exception e)
{
System.out.println("Exception :" + e.getMessage());
}
finally{      
        try {
connectionobj.close();
insertStmt.close();
} catch (SQLException e) {
System.out.println("ERROR IN Finally : "+e.getMessage());
}
       }
}//end of main Program
}

Friday, August 8, 2014

Get value of selected row from table JSP

http://www.daniweb.com/web-development/jsp/threads/454437/get-value-of-selected-row-from-table-jsp

Thursday, July 31, 2014

Avoid NullPointerException


public class AvoidNullPointerException {

public static void main(String[] args) {

String  name = null;

//wrong way - may cause NullPointerException
if(name.equals("siva")){
System.err.println("This may result in NullPointerException if unknownObject is null");
}

//right way - avoid NullPointerException even if unknownObject is null
if("siva".equals(name)){
   System.err.println("better coding avoided NullPointerException");
}
else{
System.err.println("avoided Null Pointer Exception");
}
}
}

Wednesday, July 30, 2014

Convert Any Date Format


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import junit.framework.TestCase;

public class TestDateUtil
{
public static void main(String[] args)
{      
       try{
        //String invoice = "2018/05/27";
        //String invoice = "78987465454";
          String invoice = "04-27-2012";
                //String invoice = "04/27/1998";
        //String invoice = "27/2014/01";
       
       Date convrtDate = DateUtil.convertToDate(invoice);
     
       DateFormat dateFormatNeeded = new SimpleDateFormat("yyyy");
       String yearNeeded = dateFormatNeeded.format(convrtDate);  
     
       System.out.println("Year = "+yearNeeded);
     
       }
       catch (Exception e)
       {
        // e.printStackTrace();
        System.out.println("Not a valid format");
}
   }
public static class DateUtil
{
   public static Date convertToDate(String input)
   {    
   List<SimpleDateFormat> dateFormats = new ArrayList<SimpleDateFormat>();
       
   dateFormats.add(new SimpleDateFormat("MM/dd/yyyy"));
   dateFormats.add(new SimpleDateFormat("MM-dd-yyyy"));

   dateFormats.add(new SimpleDateFormat("yyyy/MM/dd"));
   dateFormats.add(new SimpleDateFormat("yyyy-MM-dd"));
 
   dateFormats.add(new SimpleDateFormat("dd/yyyy/MM"));
 
 
       Date date = null;
       if(input == null)
           return null;
     
   
       for (SimpleDateFormat format : dateFormats)
       {
           try
           {
               format.setLenient(false);
               date = format.parse(input);
           }
           catch (ParseException e)
           {}
           if (date != null)
           {
               break;
           }
       }

       return date;
   }
}
}

Remove Zeros in String


public class RemoveZero {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String invNO = "00000025454";

String regex = "^0*";
 
String foo = invNO.replaceAll(regex, "");

System.out.println(foo);


}

}

Get IP Address

import java.net.InetAddress;
import java.net.UnknownHostException;

public class MyIpByHost
{

    public static void main(String a[])
    {
        try
        {
            InetAddress host = InetAddress.getByName("www.flipkart.com");
            System.out.println(host.getHostAddress());
        }
        catch (UnknownHostException ex)
        {
            ex.printStackTrace();
        }
       
    }
}

Adding number of days to a Date

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTotal {


public static void main(String[] args) throws Exception
{
DateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// Date todayDate = new Date();
Date todayDate = sdf.parse("20140711");
     

Calendar calendar = Calendar.getInstance();
calendar.setTime(todayDate);
calendar.add(Calendar.DATE, 30);

Date calDate = (Date)sdf.parse(sdf.format(calendar.getTime()));

String promsDate = sdf.format(calDate);

System.out.println("Promise Date : " + promsDate);
   
}

}