Link to home
Start Free TrialLog in
Avatar of Ryan Chong
Ryan ChongFlag for Singapore

asked on

Need change this to a class file

Hi,


Recently, I need to able to send sms via a scheduler on a none-Microsoft platform server.

Currently i'm develop the code to send sms using a JSP file, the quesetion is can i executing the JSP file in a scheduler? or how can i amend the code from a JSP file to a Class file?

Here is the sample JSP to send the sms:


<%@include file="./include/setcache.jsp"%>
<%@include file="./include/sendmail2.jsp"%>
<%@include file="./include/sendsms2.jsp"%>

<%@ page language="java" import="Request" %>
<jsp:useBean id="quote" class="Request" scope="page" />
                        
<%@page import="java.io.*" %>
<%@page import="java.util.*" %>
<%@page import="java.text.SimpleDateFormat" %>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory, javax.xml.parsers.DocumentBuilder, org.w3c.dom.*"%>
<%@page import="tht.db.*"%>
<%@page import="java.sql.*"%>
<%@include file="./include/init_destroy.jsp"%>

<%
      boolean ispass = false;
      Statement stm = null;
      ResultSet rs = null;
      
      int emailsent = 0;
      int smssent = 0;
      String brandlist ="";
      String tmpSQL="";
      boolean readisok = false;
      java.util.Vector v;
      String s = "";
      
      java.util.Date today;
      TimeZone tz = TimeZone.getTimeZone("CTT");
      tz.setDefault(tz);

      today = new java.util.Date();
      SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMdd");
    String logname = formatter1.format(today);
       
      String xmlfile = "";
      xmlfile = "vivi_sms_"+logname+".xml";
      
      File dir = new File(application.getRealPath("/xmlcontent/"+xmlfile));
      File dirSent = new File(application.getRealPath("/xmlsuccess/"+xmlfile));
      
      if (dir.exists()) {
      
            //check if the xml is sent already
            
            if (dirSent.exists()==false) {
                  //Do the integration
                  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                  DocumentBuilder db = dbf.newDocumentBuilder();
                  Document doc = db.parse(application.getRealPath("/xmlcontent/"+xmlfile));
                  NodeList compact = doc.getElementsByTagName("compact");
                  NodeList brands = doc.getElementsByTagName("brands");
                  NodeList expiry = doc.getElementsByTagName("expiry_date");
                  NodeList ratings = doc.getElementsByTagName("ratings");
                  
                  int nSize = 0;
                  nSize = compact.getLength();
                  for (int i=0;i<nSize;i++) {
                        brandlist = "";
                        out.println(compact.item(i).getFirstChild().getNodeValue()+"<BR>");
                        out.println(brands.item(i).getFirstChild().getNodeValue()+"<BR>");
                        out.println(expiry.item(i).getFirstChild().getNodeValue()+"<BR>");
                        out.println(ratings.item(i).getFirstChild().getNodeValue()+"<BR><BR>");
                        
                        StringTokenizer str = new StringTokenizer(brands.item(i).getFirstChild().getNodeValue(), ",");
                        while(str.hasMoreTokens()) {
                              brandlist = brandlist + "'" + str.nextToken().trim()+"',";                        
                        }
                        brandlist = brandlist.substring(0,brandlist.length()-1);
                        
                        out.println("result="+brandlist);
      
                        tmpSQL = "Select tblSubscriber.Email, tblSubscriber.Mobile from tblSubscriber, tblmbrViviSubscription "+
                                     "Where tblSubscriber.Email = tblmbrViviSubscription.Email "+
                                     "And tblmbrViviSubscription.Subid in ("+brandlist+") Group By tblSubscriber.Email, tblSubscriber.Mobile";
                        
                        if (conn == null)
                        {
                              throw new Exception("DBConnection no enactment.");
                        }
                        
                        try
                        {
                              String eV = "";
                              String mV = "";
                              eV = (String)session.getAttribute("emailid");
                              mV = (String)request.getParameter("txtmobile");
                              stm = conn.createStatement();
                              rs = stm.executeQuery(tmpSQL);
                              
                              out.println("Start sending sms..<Br>");
                              while (rs.next()) {
                                    /*sendemail2("ryancys@hotmail.com","ryancys@lycos.com","ryan","subj", compact.item(i).getFirstChild().getNodeValue().trim());
                                    emailsent=emailsent+1;*/
                                    sendsms2(rs.getString("mobile"), compact.item(i).getFirstChild().getNodeValue().trim());
                                    smssent=smssent+1;
                              }
                              out.println("End sending sms..<BR>SMS sent: "+smssent);
                        }
                        catch(SQLException e)
                        {
                              //conn.setAutoCommit(true);
                              conn.rollback();
                              e.printStackTrace();
                        }
                        finally
                        {
                              //conn.setAutoCommit(true);
                              conn.commit();
                              
                              if (stm != null)
                              {
                                    stm.close();
                              }
                              
                              if (rs != null)
                              {
                                    rs.close();
                              }
                        }
                        
                        quote.setHost("http://localhost:8080/scbpme/xmlcontent/"+xmlfile);
                        quote.setMethod("get");
            
                        s=quote.action();
            
                        quote.setTemplate("%1");
                        v=quote.parse(s);
            
                        if (v.size()>1)
                          s=v.elementAt(1).toString();
                        else
                          s="";
                        out.println(application.getRealPath("/xmlcontent/"+xmlfile)+"<br>");
                        out.println("v.size()="+v.size()+"<br>");
                        out.println("s="+s+"<br>");
                        if (!s.equals("")) {
                              FileWriter fw = new FileWriter(application.getRealPath("/xmlsuccess/"+xmlfile), true);
                              fw.write(s);
                              fw.flush();
                              fw.close();
                              out.println("XML file saved!");
                        } else {
                              out.println("XML file saved error!");
                        }                        
                  }
            } else {
                  out.println("SMS sent already previosly!");
            }
            
      } else {
            
            //Give 2 more try in 6 hours interval
            // if still not success then inform Administrator      
            out.println("XML file No Found!");
            
      }
      
%>

Thanks
Avatar of Mick Barry
Mick Barry
Flag of Australia image

of course you can convert it to a class :)

In fact you should try and seperate your java code into classes rather than include it in your jsp. This make for a far cleaner solution.
Avatar of ibo
ibo

create a class file out this monster with a constructor that accepts 2 string parameters for textMobile and emailID respectively. its not a good idead to pass an httpservletrequest or httpsession :). loss coupling of codes leads to better code design.
The class would look something like the following.

import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import tht.db.*;
import java.sql.*;

public class SMS
{
      public static void send(Connection conn, File _dir, File _dirSent,
            String eV, String mV)
      {
     boolean ispass = false;
     Statement stm = null;
     ResultSet rs = null;
     
     int emailsent = 0;
     int smssent = 0;
     String brandlist ="";
     String tmpSQL="";
     boolean readisok = false;
     java.util.Vector v;
     String s = "";
     
     java.util.Date today;
     TimeZone tz = TimeZone.getTimeZone("CTT");
     tz.setDefault(tz);

     today = new java.util.Date();
     SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMdd");
   String logname = formatter1.format(today);
       
     String xmlfile = "vivi_sms_"+logname+".xml";
     File dir = new File(_dir, xmlfile);
     File dirSent = new File(_dirSent, xmlfile);
     
     if (dir.exists()) {
     
          //check if the xml is sent already
         
          if (dirSent.exists()==false) {
               //Do the integration
               DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
               DocumentBuilder db = dbf.newDocumentBuilder();
               Document doc = db.parse(dir);
               NodeList compact = doc.getElementsByTagName("compact");
               NodeList brands = doc.getElementsByTagName("brands");
               NodeList expiry = doc.getElementsByTagName("expiry_date");
               NodeList ratings = doc.getElementsByTagName("ratings");
               
               int nSize = 0;
               nSize = compact.getLength();
               for (int i=0;i<nSize;i++) {
                    brandlist = "";
                    System.out.println(compact.item(i).getFirstChild().getNodeValue());
                    System.out.println(brands.item(i).getFirstChild().getNodeValue());
                    System.out.println(expiry.item(i).getFirstChild().getNodeValue());
                    System.out.println(ratings.item(i).getFirstChild().getNodeValue());
                   
                    StringTokenizer str = new StringTokenizer(brands.item(i).getFirstChild().getNodeValue(), ",");
                    while(str.hasMoreTokens()) {
                         brandlist = brandlist + "'" + str.nextToken().trim()+"',";                    
                    }
                    brandlist = brandlist.substring(0,brandlist.length()-1);
                   
                    System.out.println("result="+brandlist);
     
                    tmpSQL = "Select tblSubscriber.Email, tblSubscriber.Mobile from tblSubscriber, tblmbrViviSubscription "+
                               "Where tblSubscriber.Email = tblmbrViviSubscription.Email "+
                               "And tblmbrViviSubscription.Subid in ("+brandlist+") Group By tblSubscriber.Email, tblSubscriber.Mobile";
                   
                    if (conn == null)
                    {
                         throw new Exception("DBConnection no enactment.");
                    }
                   
                    try
                    {
                         //String eV = "";
                         //String mV = "";
                         //eV = (String)session.getAttribute("emailid");
                         //mV = (String)request.getParameter("txtmobile");
                         stm = conn.createStatement();
                         rs = stm.executeQuery(tmpSQL);
                         
                         System.out.println("Start sending sms..");
                         while (rs.next()) {
                              /*sendemail2("ryancys@hotmail.com","ryancys@lycos.com","ryan","subj", compact.item(i).getFirstChild().getNodeValue().trim());
                              emailsent=emailsent+1;*/
                              sendsms2(rs.getString("mobile"), compact.item(i).getFirstChild().getNodeValue().trim());
                              smssent=smssent+1;
                         }
                         System.out.println("End sending sms..");
                         System.out.println("SMS sent: "+smssent);
                    }
                    catch(SQLException e)
                    {
                         //conn.setAutoCommit(true);
                         conn.rollback();
                         e.printStackTrace();
                    }
                    finally
                    {
                         //conn.setAutoCommit(true);
                         conn.commit();
                         
                         if (stm != null)
                         {
                              stm.close();
                         }
                         
                         if (rs != null)
                         {
                              rs.close();
                         }
                    }
                   
                    quote.setHost("http://localhost:8080/scbpme/xmlcontent/"+xmlfile);
                    quote.setMethod("get");
         
                    s=quote.action();
         
                    quote.setTemplate("%1");
                    v=quote.parse(s);
         
                    if (v.size()>1)
                      s=v.elementAt(1).toString();
                    else
                      s="";
                    System.out.println(dir);
                    System.out.println("v.size()="+v.size());
                    System.out.println("s="+s);
                    if (!s.equals("")) {
                         FileWriter fw = new FileWriter(dir.getAbsoultePath(), true);
                         fw.write(s);
                         fw.flush();
                         fw.close();
                         System.out.println("XML file saved!");
                    } else {
                         System.out.println("XML file saved error!");
                    }                    
               }
          } else {
               System.out.println("SMS sent already previosly!");
          }
         
     } else {
         
          //Give 2 more try in 6 hours interval
          // if still not success then inform Administrator    
          System.out.println("XML file No Found!");
         
     }
 }
 }
 
Avatar of Ryan Chong

ASKER

Hi objects,

Compile errors:

C:\tomcat2\webapps\scbpme\WEB-INF\xmlscheduler.java:4: package javax.xml.parsers does not exist
import javax.xml.parsers.*;
^
C:\tomcat2\webapps\scbpme\WEB-INF\xmlscheduler.java:5: package org.w3c.dom does not exist
import org.w3c.dom.*;

...

So, do i need to set the classpath in some where or what is the exact errors? (Using Apache Tomcat 4.0.4 as the web server)
u already have the answer :P
> do i need to set the classpath

yes, or easier still put the relevant jars in your 'ext' directory: <jdk>/jre/lib/ext
All jars located in this directory are automaticaly included in your classpath.

you'll als get an error regarding the variable 'quote'.
It seems is declared in one of your includes, so I didn't know what type it is.
You'll probably also need to pass this as a parameter to the method.
Hi objects,

Here is a java file:

import java.io.*;
import java.util.Vector;
import Request.*;

public class xscheduler
{

     private static Request quote = new Request();
     private static String s="";
    private static Vector v = new Vector();
    private static boolean ispass = false;

     public static void send()
     {

         String tmp = "";
         if (quote == null) {
               quote = new Request();
          }
          quote.setHost("http://210.24.211.64:8080/scbpme/test.jsp");
        quote.setMethod("get");

        s=quote.action();

        quote.setTemplate("%1");
        v=quote.parse(s);

         if (v.size()>0) {
              ispass = true;
               tmp=v.elementAt(1).toString();
          } else {
               ispass = false;
             tmp="can not get quote";
          }
        s = tmp;
     }

     public boolean sendsuccess() {
          return ispass;
     }

}

But it keep return these errors when i compile it, is this related to the classpath problem? For your information, i do use and put a class named Request.class in my WEB-INF/classes folder in Tomcat. But it works in JSP but not working as what showing above, why?
Opps, the errors are typically like:

C:\tomcat2\webapps\scbpme\WEB-INF\xscheduler.java:3: package Request does not exist
import Request.*;
^
C:\tomcat2\webapps\scbpme\WEB-INF\xscheduler.java:8: cannot resolve symbol
symbol  : class Request  
location: class xscheduler
     private static Request quote = new Request();
                       ^
C:\tomcat2\webapps\scbpme\WEB-INF\xscheduler.java:8: cannot resolve symbol
symbol  : class Request  
location: class xscheduler
     private static Request quote = new Request();
                                           ^
C:\tomcat2\webapps\scbpme\WEB-INF\xscheduler.java:18: cannot resolve symbol
symbol  : class Request  
location: class xscheduler
               quote = new Request();
                                    ^
4 errors

Tool completed with exit code 1

Forget about tomcat, you're writing a normal Java class that has nothing to do with tomcat.
What is the quote variable used for?
quote is a Class with can use to get/post a page and return the result from what we get/post.

For more information about the Request, see this:
http://coldjava.hypermart.net/servlets/request.htm

I'm compose the Java class file above to test to get/post from a specify URL.
I see. You're problem is you "import Request.*", which says to import all class in the Request package.
But Request is a class not a package so simply replace the import with:

import Request;

which says to import the Request class.
Hi objects,

I was able to set the classpath and compile the Java file, here is the final Class file:

import java.io.*;
import java.util.Vector;


public class xscheduler
{

     public static Request quote = new Request();
     public static String s="";
    public static Vector v = new Vector();
    public static boolean ispass = false;
     public static String url = "";

     public static void send()
     {
          if (!url.equals("")) {
               try {
                    String tmp = "";
                    if (quote == null) {
                         quote = new Request();
                    }
                    quote.setHost(url);
                    quote.setMethod("get");

                    s=quote.action();

                    quote.setTemplate("%1");
                    v=quote.parse(s);

                    if (v.size()>0) {
                         ispass = true;
                         tmp=v.elementAt(1).toString();
                    } else {
                         ispass = false;
                         tmp="can not get quote";
                    }
                    s = tmp;
               } catch (Exception e) {}

          } else {
               s = "";
          }
     }

     public boolean sendsuccess() {
          return ispass;
     }

     public String getreturn() {
               return s;
     }

     public void setURL(String value) {
               this.url = value;
     }

     public String getURL() {
          return url;
     }
}

And i'm now testing the xscheduler.class by using this JSP file:

<%@ page language="java" import="xscheduler" %>
<%
     
     xscheduler XS = new xscheduler();
     XS.setURL("https://www.experts-exchange.com");
     XS.send();
     
%>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body bgcolor="#FFFFFF" text="#000000">
<%=XS.sendsuccess()%><br>
<%=XS.getURL()%>
<br><br><br>
Here is the content:<br>
<%=XS.getreturn()%>

</body>
</html>

I think the JSP file above will definitely convert to another Class file, so that the cron can execute it.

The question is how do i create a class that it will automatically executing when it startup? > That's mean doing something when the class itself is executing?

thanks
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi objects,

Can i ask again? :P

What is equavalent for this in Java Class?

<%!
    private PoolManager poolMgr;
    private Connection conn;
    private static String APP_CONN_POOL_NAME = "scbpme";
    private static int APP_SUBMISSION_LIMIT = 1250;

    public void jspInit()
    {
        poolMgr = PoolManager.getInstance();
        conn = poolMgr.getConnection(APP_CONN_POOL_NAME);
    }

    public void jspDestroy()
    {
        poolMgr.freeConnection(APP_CONN_POOL_NAME, conn);
    }
%>

I mean jspInit() and jspDestroy(). thank you.
depends how you are going to use it, classes offer you far more flexibility than jsp pages.

Somthing like this maybe:

public class Database
{
   private PoolManager poolMgr;
   private Connection conn;
   private static String APP_CONN_POOL_NAME = "scbpme";
   private static int APP_SUBMISSION_LIMIT = 1250;

   public void Database()
   {
       poolMgr = PoolManager.getInstance();
       conn = poolMgr.getConnection(APP_CONN_POOL_NAME);
   }

   public Connection getConnection()
   {
      return conn;
   }

   public void close()
   {
       poolMgr.freeConnection(APP_CONN_POOL_NAME, conn);
   }
}
Project deployed, you deserve pts, :) cheers.
Good to hear u got deployed.
Thx 4 the pts :-)

http://www.objects.com.au/staff/mick
Brainbench MVP for Java 1
http://www.brainbench.com