Monday, October 4, 2010

Sending JSON object to Java and processing

In java script :
function adjustments()
{
    //validation
    var st1="";
    var st2="";
    var gridsData;
    var mygridOne=new Array();
    var mygridTwo=new Array();
    var mygrid1Arry=null;
    var mygrid2Arry=null;

       if(document.getElementById("adjNature").value!='FIFO')
        {
     mygrid1Arry=mygrid1.getSelectedRecords();
     mygrid2Arry=mygrid2.getSelectedRecords();
        }
        else
            {
                   
                mygrid1Arry=Sigma.Grid.getAllRows(mygrid1);
                mygrid2Arry=Sigma.Grid.getAllRows(mygrid2);
                }

       if(mygrid1Arry.length>0 && mygrid2Arry.length>0)
    {

         if(beforeAdjustvalidate())
        {
        for(var i=0;i
        {
            var docType1= mygrid1Arry[i].doctype;
            if(docType1==undefined) { docType1=mygrid1.getColumnValue('doctype', i);}
            var docNum1= mygrid1Arry[i].docno;
              if(docNum1==undefined) { docNum1=mygrid1.getColumnValue('docno', i);}
            var docDate1= mygrid1Arry[i].docdate;
             if(docDate1==undefined) { docDate1=mygrid1.getColumnValue('docdate', i);}
            var docAmount1= mygrid1Arry[i].docamt;
             if(docAmount1==undefined) { docAmount1=mygrid1.getColumnValue('docamt', i);}
               var amtAdjusted1= mygrid1Arry[i].amtadjusted;
             if(amtAdjusted1==undefined) { amtAdjusted1=mygrid1.getColumnValue('amtadjusted', i);}
            var balance1= mygrid1Arry[i].balance;
             if(balance1==undefined) { balance1=mygrid1.getColumnValue('balance', i);}
            var currentAdjustment1= mygrid1Arry[i].curradj;
             if(currentAdjustment1==undefined) { currentAdjustment1=mygrid1.getColumnValue('curradj', i);}
            if(i==(mygrid1Arry.length-1))
            {
                st1+="{docType:'"+docType1+"',docNum:'"+docNum1+"',docDate:'"+docDate1+"',docAmount:'"+docAmount1+"',amtAdjusted:'"+amtAdjusted1+"',balance:'"+balance1+"',currentAdjustment:'"+currentAdjustment1+"'}";

            }else
                st1+="{docType:'"+docType1+"',docNum:'"+docNum1+"',docDate:'"+docDate1+"',docAmount:'"+docAmount1+"',amtAdjusted:'"+amtAdjusted1+"',balance:'"+balance1+"',currentAdjustment:'"+currentAdjustment1+"'},";
        }
        for(var j=0;j
        {
            var docType2= mygrid2Arry[j].doctype;
             if(docType2==undefined) { docType2=mygrid2.getColumnValue('doctype', j);}
            var docNum2= mygrid2Arry[j].docno;
             if(docNum2==undefined) { docNum2=mygrid2.getColumnValue('docno', j);}
            var docDate2= mygrid2Arry[j].docdate;
             if(docDate2==undefined) { docDate2=mygrid2.getColumnValue('docdate', j);}
            var docAmount2= mygrid2Arry[j].docamt;
             if(docAmount2==undefined) { docAmount2=mygrid2.getColumnValue('docamt', j);}
            var amtAdjusted2= mygrid2Arry[j].amtadjusted;
             if(amtAdjusted2==undefined) { amtAdjusted2=mygrid2.getColumnValue('amtadjusted', j);}
            var balance2= mygrid2Arry[j].balance;
             if(balance2==undefined) { balance2=mygrid2.getColumnValue('balance', j);}
            var currentAdjustment2= mygrid2Arry[j].curradj;
             if(currentAdjustment2==undefined) { currentAdjustment2=mygrid2.getColumnValue('curradj', j);}
      
            if(j==(mygrid2Arry.length-1))
            { //alert("docType2-----"+docType2+"---");
                st2+="{docType:'"+docType2+"',docNum:'"+docNum2+"',docDate:'"+docDate2+"',docAmount:'"+docAmount2+"',amtAdjusted:'"+amtAdjusted2+"',balance:'"+balance2+"',currentAdjustment:'"+currentAdjustment2+"'}";
            }
            else
                st2+="{docType:'"+docType2+"',docNum:'"+docNum2+"',docDate:'"+docDate2+"',docAmount:'"+docAmount2+"',amtAdjusted:'"+amtAdjusted2+"',balance:'"+balance2+"',currentAdjustment:'"+currentAdjustment2+"'},";
        }

        st1="["+st1+"],";
        st2="["+st2+"]";
        gridsData='{"grid1-dr":'+ st1;
        gridsData+='"grid2-cr":'+ st2+'}';
 
        var toServer=gridsData;
                       
        /* code started sending JSON Object to server */
        xmlhttp = false;
        if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
            xmlhttp=new XMLHttpRequest();
        } else if (window.ActiveXObject) {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (xmlhttp!=null) {
            url=appsPath+"/finance/adjustCrDrdocs?adjNature="+encodeURIComponent(document.getElementById("adjNature").value);
            xmlhttp.onreadystatechange= function () {
                getAdjDetailsCallback(xmlhttp);
            };
            xmlhttp.open("POST", url, true);
            xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xmlhttp.send(toServer);

        } else {
            alert("Your browser does not support XMLHTTP.");
        }

        }
    /* code ended sending JSON Object to server */


    }

    
    else
    {
        alert("Please select corresponding Cr/Dr documents");
        return false;
    }


}




function getAdjDetailsCallback()
{
    if (xmlhttp.readyState == 4)
    { // Complete
        alert(xmlhttp.responseText);
     var message=xmlhttp.responseXML;
      var recordlength=message.getElementsByTagName("grid").length;
      var docsArray=new Array();
      var amtAdjustedArray=new Array();
              var amtadjusted1=0;
      for(var i=0;i
          {
             var amtadjusted="";
              var record=message.getElementsByTagName("grid");
              var docnum=record[i].getElementsByTagName("docnum")[0].childNodes[0].nodeValue;
              amtadjusted=record[i].getElementsByTagName("amtadjusted")[0].childNodes[0].nodeValue;
              var balance=record[i].getElementsByTagName("balance")[0].childNodes[0].nodeValue;

        
                      var index;
                            var totaldrRecords = Sigma.Grid.getAllRows(mygrid1).size();
                           for(var t=0;t
                               {
                                  var docNumDr= mygrid1.getColumnValue("docno",t);
                                  if(docnum==docNumDr)
                                      {
                                        index=t;
                                         mygrid1.setColumnValue("amtadjusted", index,amtadjusted);
                                         mygrid1.setColumnValue("balance", index,balance);
                                        mygrid1.refresh();
                                       
                                      }
                               }
                                  
                 
               
                           var index1;
                          var totalcrRecords = Sigma.Grid.getAllRows(mygrid2).size();
                           for(var t1=0;t1
                               {
                                  var docNumDr= mygrid2.getColumnValue("docno",t1);
                                  if(docnum==docNumDr)
                                      {
                                        index1=t1;
                                       mygrid2.setColumnValue("amtadjusted", index1,amtadjusted);
                               mygrid2.setColumnValue("balance", index1,balance);
                               mygrid2.refresh();
                                      }
                               }
     }

    }
}


In Java :

public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        System.out.println("-----------------in AdjustmentAction--execute");
        String gridsData = readJSON(request);
        String adjNature = request.getParameter("adjNature") != null ? request.getParameter("adjNature") : "";
        System.out.println("adjNature---------"+adjNature);
        //Use the JSON-Java binding library to create a JSON object in Java
        JSONObject jsonObject = null;
        StringBuffer sb = new StringBuffer();
        response.setContentType("text/xml");
        JSONArray gridOneArray;
        JSONArray gridOneTwo;
        try {
            jsonObject = new JSONObject(gridsData);
            System.out.println("jsonObject-----" + jsonObject);

            System.out.println("grid1------" + jsonObject.get("grid1-dr"));
            System.out.println("grid2------" + jsonObject.get("grid2-cr"));
            System.out.println("grid1-getJSONArray-----" + jsonObject.getJSONArray("grid1-dr"));
            System.out.println("grid2--getJSONArray----" + jsonObject.getJSONArray("grid2-cr"));
            gridOneArray = jsonObject.getJSONArray("grid1-dr");
            gridOneTwo = jsonObject.getJSONArray("grid2-cr");



            sb.append("<message>");
            sb.append("<grids>");
            for (int i = 0; i < gridOneArray.length(); i++) {
                System.out.println("outer for loop 1");
                JSONObject record1 = (JSONObject) gridOneArray.get(i);
                String docType1 = record1.getString("docType");
                Double balance1 = record1.getDouble("balance");
                Double currentAdjustment1;
                try{
                     currentAdjustment1= record1.getDouble("currentAdjustment");
                }catch(Exception e){ currentAdjustment1=0.0d;}
                Double docAmount1 = record1.getDouble("docAmount");
                Double amtAdjusted1 = record1.getDouble("amtAdjusted");
                String docDate1 = record1.getString("docDate");
                String docNum1 = record1.getString("docNum");
                System.out.println("outer for loop 2");

                for (int j = 0; j < gridOneTwo.length(); j++) {
                    JSONObject record2 = (JSONObject) gridOneTwo.get(j);
                    String docType2 = record2.getString("docType");
                    Double balance2 = record2.getDouble("balance");
                  Double currentAdjustment2;
                try{
                     currentAdjustment2= record2.getDouble("currentAdjustment");
                }catch(Exception e){ currentAdjustment2=0.0d;}
                    Double docAmount2 = record2.getDouble("docAmount");
                    Double amtAdjusted2 = record2.getDouble("amtAdjusted");
                    String docDate2 = record2.getString("docDate");
                    String docNum2 = record2.getString("docNum");
                    System.out.println("inner for loop");
                    /*
                     *  Respose XML
                    <message><grids>
                    <grid><docnum>CR0000081</docnum><amtadjusted>9000.0</amtadjusted><balance>3000.0</balance><adjustedDoc>CI0000061</adjustedDoc></grid>
                    <grid><docnum>CI0000061</docnum><amtadjusted>19000.0</amtadjusted><balance>0.0</balance></grid>
                    <grid><docnum>CR0000051</docnum><amtadjusted>10000.0</amtadjusted><balance>10000.0</balance><adjustedDoc>CI0000061</adjustedDoc></grid>
                    </grids></message>
                     *
                     */
                    //business logic for manual adjustment starts here
                    if (adjNature != null && adjNature.equals("manual")) {
                        if (currentAdjustment1 <= currentAdjustment2) {    // Step 1 : deduct currentadj1 in balance2,then if balance1=0 then close the status of doctype1
                            //Step 2 : if balance1!=0,then go to next credit document

                            //Step 1 execution starts here
                            System.out.println("if currentAdjustment1<=balance2--strats");
                            balance2 = balance2 - currentAdjustment2;
                            amtAdjusted2 = amtAdjusted2 + currentAdjustment2;
                            amtAdjusted1 += currentAdjustment1;
                            balance1 = balance1 - currentAdjustment1;
                            sb.append("<grid>");
                            sb.append("<docnum>" + docNum1 + "</docnum>");
                            sb.append("<amtadjusted>" + amtAdjusted1 + "</amtadjusted>");
                            sb.append("<balance>" + balance1 + "</balance>");
                            sb.append("</grid>");
                            sb.append("<grid>");
                            sb.append("<docnum>" + docNum2 + "</docnum>");
                            sb.append("<amtadjusted>" + amtAdjusted2 + "</amtadjusted>");
                            sb.append("<balance>" + balance2 + "</balance>");
                            sb.append("<adjustedDoc>" + docNum1 + "</adjustedDoc>");
                            sb.append("</grid>");
                            System.out.println("if currentAdjustment1<=balance2--ends");
                        } else if (currentAdjustment1 > currentAdjustment2) {
                            //Step 1 : deduct balance2 in currentAdjustment1 then if balance2=0, then close doctype2
                            System.out.println("if currentAdjustment1>balance2--strats");
                            amtAdjusted2 = amtAdjusted2 + currentAdjustment2;
                            amtAdjusted1 += currentAdjustment2;
                            currentAdjustment1 = currentAdjustment1 - currentAdjustment2;
                            System.out.println("currentAdjustment1-2--" + currentAdjustment1);
                            balance1 = balance1 - currentAdjustment2;
                            balance2 = balance2 - currentAdjustment2;
                            sb.append("<grid>");
                            sb.append("<docnum>" + docNum2 + "</docnum>");
                            sb.append("<amtadjusted>" + amtAdjusted2 + "</amtadjusted>");
                            sb.append("<balance>" + balance2 + "</balance>");
                            sb.append("<adjustedDoc>" + docNum1 + "</adjustedDoc>");
                            sb.append("</grid>");
                            System.out.println("if currentAdjustment1>balance2--ends");

                        }
                    // manual end


                    }// END MANUAL IF
                    // FIFO STARTS
                    else if (adjNature != null && adjNature.equals("FIFO")) {
                      if(balance1<=balance2)
                        {    // Step 1 : deduct balance1 in balance2,then if balance1=0 then close the status of doctype1
                        //Step 2 : if balance1!=0,then go to next credit document

                        //Step 1 execution starts here
                        System.out.println("if balance1<=balance2--strats");
                        balance2=balance2-balance1;
                        amtAdjusted2=amtAdjusted2+balance1;
                        amtAdjusted1+=balance1;
                        balance1=balance1-balance1;
                        sb.append("<grid>");
                        sb.append("<docnum>"+docNum1+"</docnum>");
                        sb.append("<amtadjusted>"+amtAdjusted1+"</amtadjusted>");
                        sb.append("<balance>"+balance1+"</balance>");
                        sb.append("</grid>");
                       
                        sb.append("<grid>");
                        sb.append("<docnum>"+docNum2+"</docnum>");
                        sb.append("<amtadjusted>"+amtAdjusted2+"</amtadjusted>");
                        sb.append("<balance>"+balance2+"</balance>");
                        sb.append("<adjustedDoc>"+docNum1+"</adjustedDoc>");
                        sb.append("</grid>");
                        System.out.println("if currentAdjustment1<=balance2--ends");
                        }
                        else if(balance1>balance2)
                        {
                        //Step 1 : deduct balance2 in currentAdjustment1 then if balance2=0, then close doctype2
                        System.out.println("if currentAdjustment1>balance2--strats");
                        amtAdjusted2=amtAdjusted2+balance2;
                        amtAdjusted1+=balance2;
                        currentAdjustment1=currentAdjustment1-balance2;
                        System.out.println("currentAdjustment1-2--"+currentAdjustment1);
                        balance1=balance1-balance2;
                        balance2=balance2-balance2;
                         sb.append("<grid>");
                        sb.append("<docnum>"+docNum1+"</docnum>");
                        sb.append("<amtadjusted>"+amtAdjusted1+"</amtadjusted>");
                        sb.append("<balance>"+balance1+"</balance>");
                        sb.append("</grid>");
                        sb.append("<grid>");
                        sb.append("<docnum>"+docNum2+"</docnum>");
                        sb.append("<amtadjusted>"+amtAdjusted2+"</amtadjusted>");
                        sb.append("<balance>"+balance2+"</balance>");
                        sb.append("<adjustedDoc>"+docNum1+"</adjustedDoc>");
                        sb.append("</grid>");
                        System.out.println("if currentAdjustment1>balance2--ends");

                        }
                        
                    } //FIFO end

                } //inner for loop


            } //outer for loop
            sb.append("</grids>");
            sb.append("</message>");
        } //try
        catch (Exception pe) {
            pe.printStackTrace();
        }


        System.out.println("sb.toString()-----" + sb.toString());
        response.getWriter().write(sb.toString());
        return null;

    }

    private String readJSON(HttpServletRequest request) {
        StringBuffer json = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                json.append(line);
            }
        } catch (Exception e) {
            System.out.println("Error reading JSON String: " + e.toString());
        }
        return json.toString();
    }

Sunday, May 30, 2010

Quartz Scheduler example in Java using Spring


Requirement: Run a task (process) without user intervention at customized regular intervals of time and perform service to your application.
Solution: Quartz Scheduler has this feature of scheduling jobs at specified intervals of time mentioning from seconds to years called cron expression.

  • In spring framework scheduling package we have this Quartz included, so just download the jar spring-context-support.jar into your application.
  • Now we need to identify and configure the Class and the method that needs to be triggered at regular intervals with the cron expression.

Let us move forward with a requirement scenario, say you have an application which brings all the stocks details from another service provider and you want to get those details every afternoon at 2:30 pm.
Say you already have the functionality with the help of a class StocksScheduler.class which extends ContextLoaderPlugIn in spring-webmvc-struts.jar, we have to extend ContextLoaderPlugIn because we want the scheduler to start working on my application start.

Step 1: Define your bean (Class) in which your task is implemented that you want to perform

<bean id="stocksScheduler" class="com.app.stocks.StocksLoader"/>

Step 2: Define the method which has the functionality that you have implemented in the targetMethod property and your class in targetObject property

          <bean  id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
              <property name="targetObject" ref="stocksScheduler" />
              <property name="targetMethod" value="getDailyStocks" />
         </bean>
     
Step 3: Define the cron expression, i.e. the interval that you want your getDailyStocks to run and save in your application, the jobDetail and the cropnExpression

<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
               <property name="jobDetail" ref="jobDetail" />
              <property name="cronExpression" value="${scheduling.stocksCronExpression}" />
            </bean>

Step 4: The scheduling.stocksCronExpression is a property in the property file scheduling.properties file which is defined in your app-context.xml as below
<bean id="propertyConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
              <property name="locations">
                  <list>
                        <value>scheduling.properties</value>
                  </list>
              </property>
          </bean>

Step 5: Scheduling.properties file will contain this property scheduling.stocksCronExpression as follows. The cron expression has to be changed according your required interval.  The following cron expression will make the stocksScheduler run every day at 2:30 pm.

          scheduling.stocksCronExpression = 0 30 14 ? * *

Step 6: We have to include this following plugin into the struts-config.xml file for making our scheduler when the context is loaded.

          <plug-in className="com.app.stocks.StocksLoader" >
                 <set-property property="contextConfigLocation" value="/WEB-INF/app-context.xml"/>
          </plug-in>


 

 

Friday, April 16, 2010

page break when printing

Page breaks between the content. I have so many vouchers to print. I need one voucher in one page with page break. I have developed  like, i have placed the content in a div which has height and width as A4 size.

"<div style='height:900px;border:0px solid #000000'> " .So i got vocuhers as page wise



My code is


  function getdataforprinting(val){
  
   
        xmlhttp = false;
        if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
            xmlhttp=new XMLHttpRequest();
        } else if (window.ActiveXObject) {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        /* ========== AJAX Initializtion ========== */

        if (xmlhttp!=null) {
            url="/getdataforedit"+"?ion="+ion;

            xmlhttp.onreadystatechange= function () { getprint(xmlhttp); };
            xmlhttp.open("POST", url, true);
            xmlhttp.setRequestHeader("Cache-Control","no-cache, private, max-age=0");
            xmlhttp.send(null);

        } else {
            alert("Your browser does not support XMLHTTP.");
        }
    }

    function getprint(httpRequest1)
    {
   
        if(httpRequest1.readyState==4)
        {
    
            if(httpRequest1.status==200)
            {
            
                var rest="";
                var result = httpRequest1.responseXML;
               var suplength=result.getElementsByTagName("supplier").length;
               if(suplength>0)
                   {
                       var msg=result.getElementsByTagName("supplier");
                       for(var t=0;t<suplength;t++)
                           {
                              var suppname=result.getElementsByTagName("suppname")[t].childNodes[0].nodeValue;
                              var billdate=result.getElementsByTagName("billdate")[t].childNodes[0].nodeValue;
                              var paymode=result.getElementsByTagName("paymode")[t].childNodes[0].nodeValue;
                               var ionno=result.getElementsByTagName("ionno")[t].childNodes[0].nodeValue;
                               var bbrcode=result.getElementsByTagName("bbrcode")[t].childNodes[0].nodeValue;
                                var instno=result.getElementsByTagName("instno")[t].childNodes[0].nodeValue;
                                  var instdate=result.getElementsByTagName("instdate")[t].childNodes[0].nodeValue;
                                var billno=result.getElementsByTagName("billno")[t].childNodes[0].nodeValue;
                                 var billamount=result.getElementsByTagName("billamount")[t].childNodes[0].nodeValue;
                                  var amount=result.getElementsByTagName("payamt")[t].childNodes[0].nodeValue;
                                  var suppid=result.getElementsByTagName("suppid")[t].childNodes[0].nodeValue;
  
                      rest+="<div style='height:900px;border:0px solid #000000'>";

   rest+="<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"60%\"><tr>";
  rest+="<td class=\"text_bg\">Inter Office Document Number</td>";
   rest+="<td class=\"text_bg\">"+ionno+"</td>";
   rest+="</tr><tr><td class=\"text_bg\">Supplier payment voucher number</td>";
   rest+="<td class=\"text_bg\">"+suppid+"</td></tr>";
   rest+="<tr><td class=\"text_bg\">Supplier name</td>";
   rest+="<td class=\"text_bg\">"+suppname+"</td></tr><tr><td class=\"text_bg\">Supplier Bill date</td>";
   rest+="<td class=\"text_bg\">"+billdate+"</td></tr><tr><td class=\"text_bg\">Supplier Bill amount</td>";
   rest+="<td class=\"text_bg\">"+billamount+"</td></tr><tr><td class=\"text_bg\">Pay mode</td><td class=\"text_bg\">"+paymode+"</td>";

 
      rest+="</tr><tr><td class=\"text_bg\">Bank Name</td><td class=\"text_bg\">bnk</td></tr><tr>";
   rest+="<td class=\"text_bg\">Branch</td><td class=\"text_bg\">br</td></tr><tr>";
       rest+="<td class=\"text_bg\">Instrument Number</td>";
      rest+="<td class=\"text_bg\">"+instno+"</td></tr><tr><td class=\"text_bg\">Instrument Date</td>";
      rest+="<td class=\"text_bg\">"+instdate+"</td></tr> </table>";
   rest+="</div>";

                           }   //for close



    var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
   disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";

   var docprint= window.open("", "", disp_setting);
   docprint.document.open();
   docprint.document.write('<html>');
   docprint.document.write('<body onLoad="self.print()"><center>');

   docprint.document.write(rest);
   docprint.document.write('</center></body></html>');
   docprint.document.close();
   docprint.focus();
                }
        }


    }}

Tuesday, April 6, 2010