Wednesday, July 4, 2012

how to save a object in database using java



import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
static final String saveReportSQLStat =
    "Insert into DOCUMENT_GEN " +
        "(ID_BUS, ID_BUS_FLNG, CD_DOC_TYPE, " +
            "TS_CREATED, DT_CYCLE, TX_DOCUMENT) " +
    "values(?, ?, 'FI', " +
            "?, ?, ?)";
public void saveReport(String businessID, String filingNumber,
        SavedReportResult savableReport, Connection con)
    throws CRDException, SQLException
{
    PreparedStatement prepStat = null;
    boolean newManager = false;
    if(savableReport == null)
        return;
   
    try{
        if(con == null){
            newManager = true;
            con = DBManager.getConnection();
        }
        prepStat = con.prepareStatement(saveReportSQLStat);
        prepStat.setString(1, businessID);
        prepStat.setString(2, filingNumber);
        prepStat.setTimestamp(3, DateFormatter.getInstance().getTimeStamp(savableReport.getFilingDate(), savableReport.getFilingTime()));
        prepStat.setString(4, savableReport.getFilingDate());
        if (savableReport != null) {
            StringWriter writer = new StringWriter();
       
            try {
                Marshaller.marshal(savableReport, writer);
            } catch (MarshalException e) {
                throw new CRDException(e.getMessage());
            } catch (ValidationException e) {
                throw new CRDException(e.getMessage());
            }
            ByteArrayInputStream is =
                new ByteArrayInputStream(writer.toString().getBytes());
            prepStat.setBinaryStream(5, is, is.available());
        } else {
            prepStat.setNull(5, Types.BLOB);
        }
        prepStat.execute();
        prepStat.close();
    }finally{
        if(prepStat != null)   
            prepStat.close();
        if(con != null && newManager)
            con.close();
        prepStat = null;
        con = null;       
    }
}

get the object from database using java

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;

static final String getOnlineBusinessFilingReportSQL = "Select TX_DOCUMENT from DOCUMENT_GEN where ID_BUS_FLNG = ? with UR ";
public SavedReportResult getOnlineBusinessFilingReport(String filingNumber)throws CRDException, SQLException {
    PreparedStatement prepStat = null;
    ResultSet rs = null;
    Connection con = null ;
    SavedReportResult savedReport = null;
    boolean newManager = false;
    try {
        String busIdWithoutSpace = StringUtils.deleteWhitespace(filingNumber);
        filingNumber = StringUtils.leftPad(busIdWithoutSpace, 10, '0');
    } catch (NumberFormatException e) {
    }
    try {       
        con = DBManager.getConnection();
        prepStat = con.prepareStatement(getOnlineBusinessFilingReportSQL);
        prepStat.setString(1, filingNumber != null ? filingNumber.trim() : "");
        rs = prepStat.executeQuery();
        if(rs.next()){
            InputStream is =
                rs.getBinaryStream(1);
            if(is != null){
                BufferedReader reader =
                    new BufferedReader(new InputStreamReader(is));
                try {
                    try {
                        savedReport =
                            (SavedReportResult) Unmarshaller.unmarshal(SavedReportResult.class, reader);
                   
                    } catch (ValidationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } catch (MarshalException e) {
                    throw new CRDException(e.getMessage());
                }
            }
        }
        rs.close();
        prepStat.close();
} finally {
        if(rs != null)
            rs.close();
        if(prepStat != null)   
            prepStat.close();
        if(con != null && newManager)
                con.close();
        rs = null;   
        prepStat = null;
        con = null;       
    }
    return savedReport;
}

convert Object into a file using java


//Java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;

import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

/**
 * This class demonstrates the conversion of an arbitrary object file to a
 * PDF using JAXP (XSLT) and FOP (XSL:FO).
 */
public class GenericPDFGenerator {
   
    /*
     * This method accepts a list SavedReportResult objects, an xsl file to transform
     * and destination output stream
     */
    public void convert2PDF(InputSource inputSource, XMLReader xmlReader, InputStream xsltInputStream, OutputStream out)
                throws IOException, FOPException, TransformerException {

        //Construct driver
        Driver driver = new Driver();

        //Setup logger
        Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
        driver.setLogger(logger);
        MessageHandler.setScreenLogger(logger);

        //Setup Renderer (output format)
        driver.setRenderer(Driver.RENDER_PDF);


        try {
            driver.setOutputStream(out);

            //Setup XSLT
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(xsltInputStream));

            //Setup input for XSLT transformation
            Source src = new SAXSource(xmlReader, inputSource);

            //Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(driver.getContentHandler());

            //Start XSLT transformation and FOP processing
            transformer.transform(src, res);
        } finally {
            out.close();
        }
    }
}

Thursday, June 14, 2012

ajax call from java script....

var custID = document.getElementById("customerID").value;
        var custName = document.getElementById("customerName").value;
        var left = (screen.width/2) - (650/2);
        var top = (screen.height/2) - (450/2);
        if((document.getElementById("customerID").value == "") && (document.getElementById("customerName").value == "")){
            alert("Please enter Customer ID or Customer Name to search.");
            document.getElementById("customerID").focus();
            return false;
        } else {       
            //window.open("FileDocumentServlet?eid=<%=FileDocumentEventNames.BUSINESS_FORMATION_SEARCH_CUST%>&customerID="+custID+"&customerName="+custName, "customerWindow",
            //"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width=850,height=430,top="+top+",left="+left);
            document.getElementById("button").click();
            var url = "FileDocumentServlet?eid=<%=FileDocumentEventNames.BUSINESS_FORMATION_SEARCH_CUST%>&customerID="+custID+"&customerName="+custName;
            if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
                  xmlhttp=new XMLHttpRequest();
            } else {// code for IE6, IE5     
                  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function(){
              if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ 
                 var customerResult = xmlhttp.responseText;
                    document.getElementById("popupContact").innerHTML = customerResult;                 
                    return true;
                 } else {
                     document.getElementById("popupContact").innerHTML = document.getElementById("loadingMessageId").innerHTML;
                 }
             }  
             xmlhttp.open("POST",url,true);
          xmlhttp.send();
                 
        }

return value from ahref tag in javascript

<a href="#" onclick="return editRecord(<%=i%>)"><img src="images/icon2_edit.gif"></a>&nbsp;&nbsp;&nbsp;

java script array values sending to java

var columns =document.getElementById("columnSize").value;
        var columnsName = new Array();
        var columnsValue = new Array();
         for(var i=0 ;i<columns;i++){
            if(document.getElementById("insertRow"+i).value == ""){
                alert('Please fill the all fields');
                return false;
            }
        }
        var rows = document.getElementById("rowSize").value;
        for(var i=0 ;i<columns;i++){
            var character =  document.getElementById("insertRow0").value;
            if(document.getElementById("columnValue0"+i).value == character.toUpperCase()){
                alert('Entered value already avilable');
                return false;
            }
            if(document.getElementById("columnValue0"+i).value == character.toLowerCase()){
                alert('Entered value already avilable');
                return false;
            }
        }

        for(var i=0;i<columns;i++){
        var colname =document.getElementById("columnName"+i).value;
        columnsName[i]=colname;
        }
        for(var i=0 ;i<columns;i++){
        var rowValue =document.getElementById("insertRow"+i).value;
        columnsValue[i]=rowValue;
        }
        var tableName1 = document.getElementById("referenceTables").value;
        document.form1.eid.value= "9827" ;
        document.form1.tableName.value= tableName1 ;
        document.form1.action ="Admin?columnsName="+columnsName.join("&columnsName=")+"&columnsValue="+columnsValue.join("&columnsValue=");
          document.form1.submit();
          return true;

Wednesday, May 23, 2012

String util services for String handling in java


public static boolean equalsIgnoreCase(String str1, String str2) {
        return ((str1 == null) ? (str2 == null) : str1.equalsIgnoreCase(str2));
    }
 public static boolean equals(String str1, String str2) {
        return ((str1 == null) ? (str2 == null) : str1.equals(str2));
    }

    public static String trim(String str) {
        return ((str == null) ? null : str.trim());
    }

   public static boolean isNotEmpty(String str) {
        return ((str != null) && (str.length() > 0));
    }

  public static boolean isEmpty(String str) {
        return ((str == null) || (str.length() == 0));
    }


    public static boolean isBlank(String str) {
        int strLen;

        if ((str == null) || ((strLen = str.length()) == 0)) {
            return true;
        }

        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }

        return true;
    }

 public static boolean isNotBlank(String str) {
        int strLen;

        if ((str == null) || ((strLen = str.length()) == 0)) {
            return false;
        }

        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return true;
            }
        }

        return false;
    }
public static boolean equalNullOrTrimEmpty(String str1, String str2){
        return (str1 == null
                    ? (str2 == null
                            ? true
                            : (str2.trim().equals("")
                                ? true
                                : false))
                    : (str2 == null
                            ? (str1.trim().equals("")
                                ? true
                                : false)
                            : (str1.trim().equals(str2.trim()))
                        )
                );                        
    }

public static boolean equalNullOrTrimEmptyIgnoreCase(String str1, String str2){
        return (str1 == null ? (str2 == null ? true : (str2.trim().equals("") ? true : false)): (str2 == null? (str1.trim().equals("")? true: false): (str1.trim().equalsIgnoreCase(str2.trim()))));                        
    }


public static String getFormattedAmount(double param) {
        if(param == 0.0)
            return "$0.00";
        return NumberFormat.getCurrencyInstance().format(param);   
    }
   
    public static String getFormattedAmount(String param) {
        if(isEmpty(param))
            return "";
        if (param.startsWith("$")){
            return param;
        }
        try{
            double f1=Double.parseDouble(param);
            return NumberFormat.getCurrencyInstance().format(f1);   
        }catch(NumberFormatException e){
            return param;
        }
    }
   
    public static String getPercentage(double val){
        return NumberFormat.getPercentInstance().format(val);
    }
   
    public static String getPercentage(int actualVal, int totalVal){
        return getPercentage((1.0*actualVal)/(1.0*totalVal));
    }   



 public static String getAlpha(String str) {
        if ((str == null) || isEmpty(str)) {
            return null;
        }

        StringBuffer buf = new StringBuffer(str.length());
        int sz = str.length();

        for (int i = 0; i < sz; i++) {
            if (Character.isLetter(str.charAt(i)) == true) {
                buf.append(str.charAt(i));
            }
        }

        return buf.toString();
    }


public static String getAlphaNumeric(String str) {
        if ((str == null) || isEmpty(str)) {
            return null;
        }

        StringBuffer buf = new StringBuffer(str.length());
        int sz = str.length();

        for (int i = 0; i < sz; i++) {
            if (Character.isLetterOrDigit(str.charAt(i)) == true) {
                buf.append(str.charAt(i));
            }
        }

        return buf.toString();
    }

 public static String getAlphaNumericStar(String str) {
        if ((str == null) || isEmpty(str)) {
            return null;
        }

        StringBuffer buf = new StringBuffer(str.length());
        int sz = str.length();

        for (int i = 0; i < sz; i++) {
            if ((Character.isLetterOrDigit(str.charAt(i)) == true) ||
                    (str.charAt(i) == '*')) {
                buf.append(str.charAt(i));
            }
        }

        return buf.toString();
    }