Link to home
Start Free TrialLog in
Avatar of sadaf_syed
sadaf_syed

asked on

i have this code which works great in test but in live i get an error in the catalina log. i am posting my code and the error please help

i have this code for sending emails to users. the client end is a jsp and it calls a controller. they both work fine in the test environment but in the live environment i can not send attachments the email sending fails. i am attaching both the jsp, the controller class and the catalina error. please help.

catalina error:
java.io.FileNotFoundException: C:\a.txt (No such file or directory)
      at java.io.FileInputStream.open(Native Method)
      at java.io.FileInputStream.<init>(FileInputStream.java:106)
      at java.io.FileInputStream.<init>(FileInputStream.java:66)
      at com.comtrol.actions.EmailAction.emailInsertSave(EmailAction.java:557)
      at com.comtrol.actions.EmailAction.perform(EmailAction.java:103)
      at com.synfoserv.actions.ActionServlet.service(ActionServlet.java:186)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
      at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
      at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:535)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
      at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929)
      at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
      at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
      at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577)
      at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
      at java.lang.Thread.run(Thread.java:534)


jsp code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>

<%@ include file="/header.jsp" %>
<%@ page import = "com.synfoserv.beans.*" %>
<%@ page import = "java.util.*" %>
<jsp:useBean id="listing" class="java.util.ArrayList" scope="request"></jsp:useBean>

<title><database:label controlname="header_emailedit"/></title>
<script type="text/javascript" src="https://localhost:8443/crm/js/jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
      tinyMCE.init({
            mode : "textareas",
            theme : "advanced",
            plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager",
            theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
// Drop lists for link/image/media/template dialogs
template_external_list_url : "js/template_list.js",
external_link_list_url : "js/link_list.js",
external_image_list_url : "js/image_list.js",
media_external_list_url : "js/media_list.js",
spellchecker_rpc_url : "http://localhost:8084/crm/js/jscripts/tiny_mce/plugins/spellchecker/rpc.php",
spellchecker_languages : "+English=en" ,
      });
      </script>
</head>

<body class=stdbody>

<script>
parent.menu.setSubmit();
</script>
<%
//if cmd is to insert a record -> change the command to insert
String sCmd = (String) request.getAttribute ("cmd");

if (sCmd==null) sCmd=request.getParameter ("cmd");

if (sCmd.endsWith ("contextedit") ){
            sCmd = sCmd.substring (0,sCmd.length()-11)+"save";
} else if (sCmd.endsWith ("edit")){
      sCmd = sCmd.substring (0,sCmd.length()-4)+"save";
} else if (sCmd.endsWith ("insert")) {
      sCmd = sCmd + "save";
}
UserBean uBean = (UserBean) session.getAttribute("userbean");
request.setAttribute("browser",uBean.getBrowser());
%>      
<script LANGUAGE="JavaScript1.2">

function removeAttachment(){
  document.dataentry.filelist.remove(document.dataentry.filelist.selectedIndex);
}

function addFile(sFile){
  var option = document.createElement("OPTION");
  option.text = sFile;
  option.value = sFile;
  if(document.dataentry.browser.value == "IE"){
    document.dataentry.filelist.add(option);
  }else{
    document.dataentry.filelist.add(option,null);
  }
  document.dataentry.fileselector.value="";
  document.dataentry.fileselector.text="";
}

function addFiles(fl){
  var newOpt1 = new Option(document.dataentry.file2upload.value, document.dataentry.file2upload.value);
  fl.options[fl.length] = newOpt1;
  document.dataentry.file2upload.value = "";
  updateList(fl);
}

function removeFiles(fl){
  var selItem = fl.selectedIndex;
  fl.options[selItem] = null;
  updateList(fl)
}

function updateList(fl){
  var i;
  document.dataentry.filelist.value = "";
  for (i = 0; i < fl.length; i++){
    document.dataentry.filelist.value = document.dataentry.filelist.value + fl.options[i].value + ";";
  }
}

<!--
function validate(cmd)
{
  var i = 0;
  if ((document.dataentry.emailto.value=="")||
      (document.dataentry.emailfrom.value=="") ||
      (document.dataentry.emailsubject.value=="")) {
          alert ("You must fill in all of the required fields!")
    return false;
  } else {
    setCmd(cmd);
  }
}
//-->
</script>

<form name=dataentry action="Controller?cmd=email_insertsave" ENCTYPE="multipart/form-data" onSubmit="return validate('<%=sCmd%>');" method="post" onClick="highlight(event)" onKeyPress="highlight(event)">

  <input type="hidden" name="action" value="<%=request.getAttribute("action")%>">
  <input type="hidden" name="cmd" value="">
  <input type="hidden" name="browser" value="<%=request.getAttribute("browser")%>">

  <TABLE width="100%" cellpadding="0" cellspacing="1">
    <TR>
      <TD class=headerow colSpan=4>
        <TABLE width="100%" cellpadding="0" cellspacing="0">
          <TR>
            <TD class=headerow colspan="2">
              <database:label controlname="header_emailedit"/>
            </TD>
            <TD align="right">
              <database:nav controlname="button_send" modulename="CALL"
                            isbutton="y" security="CHANGE" buttontype="submit"/>
              <database:nav controlname="button_cancel" modulename="CALL"
                            isbutton="y" security="CHANGE" buttontype="reset"/>
            </TD>
          </TR>
        </TABLE>
      </TD>
    </TR>

    <%
      Iterator iter = listing.iterator();
      boolean isHighlighed = false;
      iter.hasNext();
      CallListBean  clbObj = (CallListBean) iter.next();
    %>      

    <input type="hidden" name="companyid" value="<%=clbObj.getCompanyId()%>">
    <input type="hidden" name="divisionid" value="<%=clbObj.getDivisionId()%>">
    <input type="hidden" name="personid" value="<%=clbObj.getPersonId()%>">
    <input type="hidden" name="callid" value="<%=clbObj.getCallId()%>">
    <input type="hidden" name="assignto" value="<%=clbObj.getAssignTo()%>">
    <input type="hidden" name="activitytype" value="<%=clbObj.getActivityType()%>">
    <input type="hidden" name="regarding" value="<%=clbObj.getRegarding()%>">
    <input type="hidden" name="status" value="<%=clbObj.getStatus()%>">
    <input type="hidden" name="duedate" value="<%=clbObj.getDueDate()%>">
    <input type="hidden" name="duetime" value="<%=clbObj.getDueTime()%>">
    <input type="hidden" name="emailto" value="<%=request.getAttribute("emailto")%>">
    <input type="hidden" name="emailfrom" value="<%=request.getAttribute("emailfrom")%>">
    <input type="hidden" name="from" value="<%=request.getAttribute("from")%>">
    <input type="hidden" name="to" value="<%=request.getAttribute("to")%>">
    <input type="hidden" name="bcc" value="<%=request.getAttribute("to")%>">

    <TR>
      <TD class=labelcolumn><database:label controlname="email_to"/></TD>
      <TD class=textcolumn ><%=request.getAttribute("to")%></TD>
      <TD class=labelcolumn><database:label controlname="email_from"/></TD>
      <TD class=textcolumn><%=request.getAttribute("from")%></TD>
    </TR>
    <TR>
      <TD class=labelcolumn></TD>
      <TD class=textcolumn ><%=request.getAttribute("emailto")%></TD>
      <TD class=labelcolumn></TD>
      <TD class=textcolumn><%=request.getAttribute("emailfrom")%></TD>
    </TR>
    <TR>
      <TD class=labelcolumn colspan='1'>CC:</TD>
      <TD class=textcolumn colspan='3'>
        <INPUT name='cclist' value='' style="WIDTH: 400px;" class="textbox"></INPUT>
        <LABEL>&nbsp;(Use semi-colon as address delimiter)</LABEL>
      </TD>
    </TR>
    <TR>
      <TD class=labelcolumn colspan='1'>BCC:</TD>
      <TD class=textcolumn colspan='3'>
        <INPUT name='bcclist' value='<%=request.getAttribute("bcc")%>'
               style="WIDTH: 400px;" class="textbox"></INPUT>
        <LABEL>&nbsp;(Use semi-colon as address delimiter)</LABEL>
      </TD>
    </TR>
    <TR>
      <TD class=labelcolumn colspan=1><database:label controlname="email_subject"/></TD>
      <TD class=textcolumn colspan=3>
        <INPUT name="emailsubject" class="required" style="WIDTH: 100%;"
               value="<%=clbObj.getSummary()%>"></INPUT>  
        <div class=error><%=request.getAttribute("emailsubject_error")%></div>
      </TD>
    </TR>
    <TR></TR>
    <TR>
      <TD class=labelcolumn colspan="2"><database:label controlname="email_body"/></TD>
      <TD colspan="2" class=textcolumn></TD>
    </TR>
    <TR>
      <TD class=textcolumn colSpan=4>
        <TEXTAREA  name="emailbody" class=required
                   style="WIDTH: 100%; HEIGHT: 200px"><%=clbObj.getNote()%></TEXTAREA>
          <div class=error><%=request.getAttribute("emailbody_error")%></div>
      </TD>
    </TR>
    <TR>
      <TD class=labelcolumn colspan='4'>File Attachment: (attachment is placed in the documents area)</TD>
    </TR>  
    <TR>
      <TD class=labelcolumn colspan='1'>Attach:</TD>
      <TD class=textcolumn colspan='3' align='left'>
        <INPUT type='FILE' name='file2upload' size='50' maxlength='255'></INPUT>
        <INPUT type='button' value='Add' name='fileadd' onclick='addFiles(this.form.uploadlist);'></INPUT>
      </TD>
    </TR>
    <TR>
      <TD colspan='1' align='left'>File List:</TD>
      <TD colspan='3' align='left'>
        <SELECT name='uploadlist' style='WIDTH: 400px' size='10'></SELECT>
        <INPUT type='hidden' name='filelist'></INPUT>
        <INPUT type='button' value='Remove' name='fileremove' onclick='removeFiles(this.form.uploadlist);'></INPUT>
      </TD>
    </TR>
    <TR>
      <TD class=labelcolumn style='HEIGHT: 10px;'></TD>
      <TD class=labelcolumn style='HEIGHT: 10px;'></TD>
      <TD class=labelcolumn style='HEIGHT: 10px;'></TD>
      <TD class=labelcolumn style='HEIGHT: 10px;'></TD>
    </TR>
    <TR>
      <TD class=labelcolumn><database:label controlname="create_date"/></TD>
      <TD class=textcolumn ><%=clbObj.getCreateDate()%></TD>
      <TD class=labelcolumn><database:label controlname="create_user"/></TD>
      <TD  class=textcolumn ><%=clbObj.getCreateUser()%></TD>
    </TR>
    <TR>
      <TD class=labelcolumn><database:label controlname="modify_date"/></TD>
      <TD class=textcolumn ><%=clbObj.getModifyDate()%></TD>
      <TD class=labelcolumn><database:label controlname="modify_user"/></TD>
      <TD class=textcolumn ><%=clbObj.getModifyUser()%></TD>
    </TR>
    <TR>
      <TD class=headerow colSpan=4>
        <TABLE width="100%" cellpadding="0" cellspacing="0">
          <TR>
            <TD class=headerow colspan="2">
              <database:label controlname="header_emailedit"/>
            </TD>
            <TD align="right">
              <database:nav controlname="button_send" modulename="CALL"
                            isbutton="y" security="CHANGE" buttontype="submit"/>
              <database:nav controlname="button_cancel" modulename="CALL"
                            isbutton="y" security="CHANGE" buttontype="reset"/>
            </TD>
          </TR>
        </TABLE>
      </TD>
    </TR>
  </TABLE>
</form>

<script>document.dataentry.emailsubject.focus();</script>
</body>
</html>

j am copying the controller class into the code snippet.

the code works fine. just i need to resolve the error or understand the reason for the error in live.
package com.comtrol.actions;
 
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.DataHandler;
import java.io.File;
import java.io.FileInputStream;
 
import com.synfoserv.actions.*;
import com.synfoserv.global.connections.*;
import com.synfoserv.global.*;
import com.synfoserv.global.security.*;
import com.synfoserv.beans.*;
import com.synfoserv.global.util.*;
import java.util.*;
 
import com.comtrol.global.util.DataTypeConversion;
import com.comtrol.global.util.SConfigReader;
import com.comtrol.global.util.MultipartRequest;
import com.comtrol.global.CONSTANTS;
import com.comtrol.beans.*;
import com.comtrol.actions.CDMSAction;
 
import java.io.*;
  
/**
 * <p>Title: SynergyCRM</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: Comtrol Corporation</p>
 * @author Kevin Wilson
 * @version 1.0
 */
 
public class EmailAction extends ActionBase implements Action {
  private boolean MBLNDEBUGMODE = false; //for debugging message ease
  private HttpSession session= null;
  private String msUsername = null;
  private String msCallId;
  private boolean mbLimit=false;
  private String msNextJsp = "/norecord.jsp";
  private String msContentType = null;
  private File mFile = null;
  
  public EmailAction(){super();}
  
  public ActionRouter perform(HttpServlet servlet, 
                              HttpServletRequest req, 
                              HttpServletResponse res) 
                              throws java.io.IOException, ServletException{
    String sNextJsp = "/norecord.jsp";
    session=req.getSession();
    UserBean ubObject = (UserBean) session.getAttribute("userbean"); //retrieving security user bean
    msUsername = ubObject.getUserId();
    Hashtable htSecurity =  ubObject.getSecurity();
    String sCmd = (String) req.getParameter("cmd");
    
    //bypass this for emailing forgotten passwords.
    if(!sCmd.equals("email_reqpassword") & !sCmd.equals("email_getpassword")){
      //make sure user has valid perms for both
      mbLimit = ((SecurityBean) htSecurity.get("PERSON")).getLimit();
      if(!mbLimit)
        mbLimit = ((SecurityBean) htSecurity.get("CALL")).getLimit();
    }
    
    try{
      getConnection(servlet);
 
      if (sCmd.equals("email_edit")){
        populateErrorFields(req);
        boolean bOverride = true; // action is always based on context
        req.setAttribute("listing",emailEdit(req,bOverride));
        req.setAttribute("action","update"); 
        sNextJsp = msNextJsp;
      }else if (sCmd.equals("email_save")){
        if (isValid(req)){
          emailUpdate(req);
          req.setAttribute("listing",emailEdit(req,false));
        }
        sNextJsp = msNextJsp;
      }else if (sCmd.equals("email_insert")){
        //need to add context check to ensure process is not violated
        ContextBean cBean =  (ContextBean) session.getAttribute("context");
        String sPersonId = cBean.getPersonId();
        boolean bParentsExist = true;
       
        sNextJsp ="/norecord.jsp";  
        
        if(sPersonId == null || sPersonId.equalsIgnoreCase("0")){
          bParentsExist = false;
        }
 
        if(bParentsExist){
          populateErrorFields(req);
          req.setAttribute("listing",emailInsert(req));
          sNextJsp ="/EmailTo.jsp";
        }
      }else if (sCmd.equals("email_insertsave")){
        if (isValid(req)){
          emailInsertSave(servlet,req,res);
          req.setAttribute("listing",emailEdit(req,true));
          req.setAttribute("cmd","email_edit"); //resetting the servlet command to edit mode
          sNextJsp = msNextJsp;
        } else {
          req.setAttribute("cmd","email_insert");
          sNextJsp = "/EmailTo.jsp";
        }
      }else if (sCmd.equals("email_reqpassword")){
        sNextJsp = "/ForgotPassword.jsp";
      }else if (sCmd.equals("email_getpassword")){
        emailPassword(req);
        sNextJsp = "/ForgotPasswordMsg.jsp";
      }else if(sCmd.equals("email_rma")){
        populateErrorFields(req);
        req.setAttribute("listing",emailRMAInfo(req,servlet));
        sNextJsp ="/EmailRMA.jsp";
      }
      else if(sCmd.equals("email_case")){
        populateErrorFields(req);
        req.setAttribute("listing", emailCaseInfo(req, servlet));
        sNextJsp="/EmailTo.jsp";
      }
      else if(sCmd.equals("email_tracking")){
        populateErrorFields(req);
        req.setAttribute("listing", emailTrackingInfo(req, servlet));
        sNextJsp="/EmailTo.jsp";
      }
    }
    catch (Exception _e) {
      _e.printStackTrace();
      sNextJsp="/norecord.jsp";
    }
    finally {
      try{close();}
      catch (Exception _e) {
        _e.printStackTrace();
        sNextJsp="/norecord.jsp";
      }
    }
 
    return new ActionRouter(sNextJsp);
  }
  
  //This must pull the rma, its items and set the info to assign an action.
  private ArrayList emailRMAInfo(HttpServletRequest req,HttpServlet servlet){
    Utils utilObj = new Utils();
    ArrayList alCallList = new ArrayList();
    ArrayList alRMAList = new ArrayList();
    ArrayList alRMAItemList = new ArrayList();
    CallListBean clbObj = new CallListBean();
    CONSTANTS constants = new CONSTANTS();
    int nPorts = 0;
    
    HttpSession  session = req.getSession();
    ContextBean cBean = (ContextBean) session.getAttribute("context");
    UserBean uBean = (UserBean)session.getAttribute("userbean");
    
    String sRMAId = cBean.getRmaId();
    String sPEmail = getEmailFromPersonId(cBean.getPersonId());
    String sUEmail = uBean.getEMailAddress();
    String sPersonFrom = (uBean.getFirstName() + " " + uBean.getLastName());
    
    //setup call activity info
    clbObj.setAssignTo(msUsername);
    clbObj.setRegarding("RMA");
    clbObj.setActivityType("EMAIL");
    clbObj.setStatus("COMPLETED");
    clbObj.setDueDate(utilObj.formatDate(utilObj.currentTimestamp()));
    clbObj.setDueTime(utilObj.formatTime(utilObj.currentTimestamp()));
    clbObj.setComName(cBean.getComName());
    clbObj.setCompanyId(cBean.getCompanyId());
    clbObj.setDivName(cBean.getDivName());
    clbObj.setDivisionId(cBean.getDivisionId());
    clbObj.setFName(cBean.getFName());
    clbObj.setLName(cBean.getLName());
    clbObj.setPersonId(cBean.getPersonId());
    clbObj.setSummary("RMA [#" + sRMAId + "]: Comtrol Return Material Authorization");
    
    req.setAttribute("emailfrom", sUEmail);
    req.setAttribute("emailto", sPEmail);
    req.setAttribute("from", sPersonFrom);
    req.setAttribute("to", (cBean.getFName() + " " + cBean.getLName()));
    req.setAttribute("bcc", sUEmail);
    req.setAttribute("browser",uBean.getBrowser());
 
    String sRmaDate = req.getParameter("rmadate");
    String sRmaType = req.getParameter("type");
    String sAssignTo = req.getParameter("assnto");
    String sAuthBy = req.getParameter("authby");
    String sPrgId = req.getParameter("prgmid");
    String sProgramId = req.getParameter("programid");
    String sRegCode = req.getParameter("programregcode");
    String sRmaStatus = req.getParameter("rmastatus");
    
    StringBuffer sb = new StringBuffer();
    
    sb.append("-CUSTOMER SERVICE CONTACT-\n");
    sb.append(sPersonFrom + "<br>");
    sb.append(sUEmail + "<br>");
    sb.append("Toll Free: 1-800-926-6876<br>");
    sb.append("Local Area: 763-494-4100<br>");
    sb.append("<br>");
    sb.append("-RMA INFORMATION-<br>");
    sb.append("RMA #: " + sRMAId + "<br>");
    sb.append("RMA DATE: " + sRmaDate + "<br>");
    sb.append("RMA STATUS: " + sRmaStatus + "<br>");
    sb.append("ASSIGNED TO: " + sAssignTo + "<br>");
    sb.append("AUTHORIZED BY: " + sAuthBy + "<br>");
    
    sb.append("<br>");
    sb.append("-SHIPPING INSTRUCTIONS-<br>");
    sb.append(constants.msRMAShipInstr);
    sb.append("<br>");
    sb.append("RMA #: " + sRMAId + "<br>");
    sb.append("<br>");
    
    CDMSAction a = new CDMSAction();
    
    if(sProgramId != null && sProgramId.length() > 0){
      ArrayList al = a.getRegisteredProductsList(servlet,sRegCode,sProgramId);
      
      sb.append("\n-PROMOTION INFORMATION-<br>");
      sb.append("PROMOTION: " + sPrgId + "<br>");
      sb.append("REGISTRATION CODE: " + sRegCode + "<br><br>");
      sb.append(constants.msSH2DM1HDR + "<br>");
      
      if(al.size() > 0){
        Iterator i = al.iterator();
        sb.append("\nProducts registered:<br>");
        nPorts = 0;
        while(i.hasNext()){
          CDMSCustomerProductBean cpb = (CDMSCustomerProductBean)i.next();
          sb.append("SKU: " + cpb.getModelNo() + "&nbsp&nbsp&nbsp");
          if(cpb.getNumPorts().equalsIgnoreCase("48")){
            String sPorts = cpb.getNumPorts().trim();
            sPorts = sPorts.substring(0, 1) + "/" + sPorts.substring(1, 2);
            sb.append("PORTS: " + sPorts + "&nbsp&nbsp&nbsp");
            sb.append("S/N: " + cpb.getSerialNo() + "<br>" );
            sb.append("       *4 or 8 port product, using 8 ports to calculate total ports.*<br>");
            nPorts = nPorts + 8;
          }else{
            sb.append("PORTS: " + cpb.getNumPorts() + "&nbsp&nbsp&nbsp");
            sb.append("S/N: " + cpb.getSerialNo() + "<br>" );
            nPorts = nPorts + Integer.parseInt(cpb.getNumPorts());
          }  
        }
        
        sb.append("Total Ports: " + Integer.toString(nPorts) + "<br>");
      }
    }//end promo product listing
    
    if(sRMAId != null && sRMAId.length() > 0){
      alRMAItemList = getRMAItems(sRMAId,servlet);
 
      if(alRMAItemList.size() > 0){
        Iterator it = alRMAItemList.listIterator();
        sb.append("\nProducts returned:<br>");
        nPorts = 0;
        while(it.hasNext()){
          RMAItemListBean bean = (RMAItemListBean)it.next();
          String sPorts = a.getPortCount(servlet,bean.getPartNo());
          
          sb.append("SKU: " + bean.getPartNo() + "&nbsp&nbsp&nbsp");
          
          if(sPorts.equalsIgnoreCase("48")){
            sPorts = sPorts.substring(0, 1) + "/" + sPorts.substring(1, 2);
            sb.append("PORTS: " + sPorts + "&nbsp&nbsp&nbsp");
            sb.append("S/N: " + bean.getSerial() + "<br>" );
            sb.append("       *4 or 8 port product, using 8 ports to calculate total ports.*\n");
            nPorts = nPorts + 8;
          }else{
            sb.append("PORTS: " + sPorts + "&nbsp&nbsp&nbsp");
            sb.append("S/N: " + bean.getSerial() + "<br>" );
            nPorts = nPorts + Integer.parseInt(sPorts);
          }
        }
        
        sb.append("Total Ports: " + Integer.toString(nPorts) + "<br>");
      }
    }
 
    clbObj.setNote(sb.toString());
  
    alCallList.add(clbObj);
    
    return alCallList;
  }
  
  private ArrayList getRMAItems(String sRMAId, HttpServlet servlet){
    ArrayList al = new ArrayList();
    RMAItemAction ria = new RMAItemAction();
    try{al = ria.getRmaItems(servlet,sRMAId);}
    catch(Exception e){e.printStackTrace();}
    return al;
  }
  
  private ArrayList emailCaseInfo(HttpServletRequest req, HttpServlet servlet){
    
    HttpSession  session = req.getSession();
    CallListBean clbObj = new CallListBean();
    ContextBean cBean = (ContextBean) session.getAttribute("context");
    UserBean uBean = (UserBean)session.getAttribute("userbean");
    ArrayList alCallList = new ArrayList();
    
    String sCaseId = cBean.getCaseId();
    String sPEmail = getEmailFromPersonId(cBean.getPersonId());
    String sUEmail = uBean.getEMailAddress();
    String sPersonFrom = (uBean.getFirstName() + " " + uBean.getLastName());
    
    clbObj.setActivityType("EMAIL");
    clbObj.setAssignTo(msUsername);
    clbObj.setStatus("COMPLETED");
    clbObj.setComName(cBean.getComName());
    clbObj.setCompanyId(cBean.getCompanyId());
    clbObj.setDivName(cBean.getDivName());
    clbObj.setDivisionId(cBean.getDivisionId());
    clbObj.setFName(cBean.getFName());
    clbObj.setLName(cBean.getLName());
    clbObj.setPersonId(cBean.getPersonId());
    clbObj.setDueDate(utilObj.formatDate(utilObj.currentTimestamp()));
    clbObj.setDueTime(utilObj.formatTime(utilObj.currentTimestamp()));
    clbObj.setSummary("Case [#" + sCaseId + "]: Comtrol Case Information");
    
    req.setAttribute("emailfrom", sUEmail);
    req.setAttribute("emailto", sPEmail);
    req.setAttribute("from", sPersonFrom);
    req.setAttribute("to", (cBean.getFName() + " " + cBean.getLName()));
    req.setAttribute("bcc", sUEmail);
    req.setAttribute("browser",uBean.getBrowser());
    
    StringBuffer sb = new StringBuffer();
    
    sb.append("Case Info");
    sb.append("<br>" + req.getParameter("summary"));
    sb.append("<br>" + req.getParameter("note"));
    clbObj.setNote(sb.toString());
  
    alCallList.add(clbObj);
    
    return alCallList;
    
  }
  
  //Not implemented
  private ArrayList emailTrackingInfo(HttpServletRequest req, HttpServlet servlet){
    
    HttpSession  session = req.getSession();
    CallListBean clbObj = new CallListBean();
    ContextBean cBean = (ContextBean) session.getAttribute("context");
    UserBean uBean = (UserBean)session.getAttribute("userbean");
    ArrayList alCallList = new ArrayList();
    
    String sRMAId = cBean.getRmaId();
    String sTrackingNo = req.getParameter("trackingno");
    String sPEmail = getEmailFromPersonId(cBean.getPersonId());
    String sUEmail = uBean.getEMailAddress();
    String sPersonFrom = (uBean.getFirstName() + " " + uBean.getLastName());
    
    clbObj.setActivityType("EMAIL");
    clbObj.setAssignTo(msUsername);
    clbObj.setStatus("COMPLETED");
    clbObj.setComName(cBean.getComName());
    clbObj.setCompanyId(cBean.getCompanyId());
    clbObj.setDivName(cBean.getDivName());
    clbObj.setDivisionId(cBean.getDivisionId());
    clbObj.setFName(cBean.getFName());
    clbObj.setLName(cBean.getLName());
    clbObj.setPersonId(cBean.getPersonId());
    clbObj.setDueDate(utilObj.formatDate(utilObj.currentTimestamp()));
    clbObj.setDueTime(utilObj.formatTime(utilObj.currentTimestamp()));
    clbObj.setSummary("Comtrol RMA [#" + sRMAId + "]: Tracking Information");
    
    req.setAttribute("emailfrom", sUEmail);
    req.setAttribute("emailto", sPEmail);
    req.setAttribute("from", sPersonFrom);
    req.setAttribute("to", (cBean.getFName() + " " + cBean.getLName()));
    req.setAttribute("bcc", sUEmail);
    req.setAttribute("browser",uBean.getBrowser());
    
    StringBuffer sb = new StringBuffer();
    
    sb.append("Tracking information for RMA #" + sRMAId);
    sb.append("<br>" + sTrackingNo.toUpperCase());
    StringTokenizer st = new StringTokenizer(sTrackingNo);
    while(st.hasMoreTokens()){
      String sTemp = st.nextToken();
      if (sTemp.length() == 18 && sTemp.substring(0, 2).equalsIgnoreCase("1Z")){ //UPS
        sb.append("<br>Click on the link below to view your shipment's progress:");
        sb.append("<br><br>http://wwwapps.ups.com/WebTracking/processInputRequest?TypeOfInquiryNumber=T&InquiryNumber1="
                    + sTemp);
      }
    }
    
    clbObj.setNote(sb.toString());
  
    alCallList.add(clbObj);
    
    return alCallList;
    
  }
  
  private String getEmailFromPersonId(String sPersonId){
    String sEmailAddy = "";
    
    try{
      String sSQL = "SELECT EMAIL FROM PERSON WHERE PERSON_ID = "+ sPersonId;
      stmt = m_conDb.createStatement();
      stmt.execute(sSQL);
      rs = stmt.getResultSet();
      
      if(rs.next()){
        sEmailAddy = rs.getString("EMAIL");
      }
    }catch(Exception e){
      e.printStackTrace();
    }
    
    return sEmailAddy;
  }
  
  public String getEmailFromPersonId(String sPersonId, Connection conn){
    String sEmailAddy = "";
    
    try{
      String sSQL = "SELECT EMAIL FROM PERSON WHERE PERSON_ID = "+ sPersonId;
      stmt = conn.createStatement();
      stmt.execute(sSQL);
      rs = stmt.getResultSet();
      if(rs.next()){sEmailAddy = rs.getString("EMAIL");}
      rs.close();
      stmt.close();
    }catch(Exception e){e.printStackTrace();}
    
    return sEmailAddy;
  }
  
  private void emailPassword(HttpServletRequest req){
                               
    boolean blnEmailSent = false;
    String sEmailFrom = "indeo@comtrol.com";
    String sEmailTo = req.getParameter("emailaddress");
    String sUserId = null;
    String sPassword = null;
    String sSubject = null;
    String sBody = null;
    
    //find email address in user list
    String sSQL = "SELECT USER_ID,PASSWORD FROM S_USER WHERE LOWER(EMAIL) = '" +
                  sEmailTo.toLowerCase() + "' AND IS_ACTIVE = 'Y' AND ACTIVE = 'Y'";
    try{
      stmt = m_conDb.createStatement();
      stmt.execute(sSQL);
      rs = stmt.getResultSet();
      
      if(rs.next()){
        sUserId = rs.getString("USER_ID");
        sPassword = rs.getString("PASSWORD");
      }
      
      if(sUserId != null & sPassword != null){
        sSubject = "Your Indeo Account Information";
        sBody = "User Name: " + sUserId + "<br>" + "Password: " + sPassword;
        blnEmailSent = processMailItem(sEmailFrom,sEmailTo,sSubject,sBody,req);
        if(!blnEmailSent){
          req.setAttribute("emailpassmsg", 
            "There was a problem emailing your account information. Please contact the application administrator if the problem persists."
          );
        }else{
          req.setAttribute("emailpassmsg", "");
        }
      }else{
        req.setAttribute("emailpassmsg", "Invalid email address or address not found.");
      }
    }catch(Exception e){
      req.setAttribute("emailpassmsg", "Invalid email address or address not found.");
      e.printStackTrace();
    }
  }
  
  //inserts new record
  private void emailInsertSave(HttpServlet servlet,HttpServletRequest req,HttpServletResponse res){
    /*
    ContextBean cBean = (ContextBean) session.getAttribute("context");
    String sCompanyId = cBean.getCompanyId();
    String sDivisionId = cBean.getDivisionId();
    String sPersonId = cBean.getPersonId();
    String sQuoteId = cBean.getQuoteId();
    String sOpportunityId = cBean.getOpportunityId();
    String sOrderId = cBean.getOrderId();
    */
    boolean blnEmailSent = false;
    
    //now send the email
    try{
      String sFilePrefix = "file:///";
      char chUnixSeperator = 47;
      char chWinSeperator = 92;
      String sTempDir = servlet.getServletContext().getRealPath("/") + "temp";
      sTempDir = sTempDir.replace(chWinSeperator, chUnixSeperator);
      
      MultipartRequest mpr = new MultipartRequest(req, sFilePrefix + sTempDir);
            
      if(mpr != null){
        String sURL = sFilePrefix + sTempDir;
        String sEmailTo = mpr.getParameter("emailto");
        String sEmailFrom = mpr.getParameter("emailfrom");
        String sPersonFrom = mpr.getParameter("from");
        String sPersonTo = mpr.getParameter("to");
        String sCCList = mpr.getParameter("cclist");
        String sBCCList = mpr.getParameter("bcclist");
        String sCallId = mpr.getParameter("callid");
        String sAssignto = mpr.getParameter("assignto");
        String sActivityType = mpr.getParameter("activitytype");
        String sRegarding = mpr.getParameter("regarding");
        String sDueDate = mpr.getParameter("duedate");
        String sDueTime = mpr.getParameter("duetime");
        String sStatus = mpr.getParameter("status");
        String sSummary = mpr.getParameter("emailsubject");
        String sNote = mpr.getParameter("emailbody");
        String sCompanyId = mpr.getParameter("companyid");
        String sDivisionId = mpr.getParameter("divisionid");
        String sPersonId = mpr.getParameter("personid");
        
        String sFilesUpload = mpr.getParameter("filelist");
        //System.out.println(sFilesUpload);
        if (sFilesUpload == null) sFilesUpload = "";
 
    
        String sFile = null;
        String strFileSysName = null;
        
        //Gets any files still left in the files2upload input box
        /*Enumeration enumFiles = mpr.getFileNames();
        if(enumFiles.hasMoreElements()) {
          sFile = (String)enumFiles.nextElement();
          msContentType = mpr.getContentType(sFile);
          strFileSysName = mpr.getFilesystemName(sFile);
          sFile = strFileSysName;
          mFile = new File(sTempDir + "/" + sFile);
          System.out.println(sFile);
          //System.out.println(msContentType);
        }
        */
        //Gets all files stored in filelist hidden input
        StringTokenizer st = new StringTokenizer(sFilesUpload, ";");
        String[] sFileList = new String[st.countTokens()];
        File[] fFileList = new File[st.countTokens()];
        //sFile = sFilesUpload + sFile;
        
        int fCount = 0;
        while(st.hasMoreTokens()){
          String sTempName = st.nextToken();
          byte[] bbuf = new byte[(int)new File(sTempName).length()];
          FileInputStream fis = new FileInputStream(sTempName);
          fis.read(bbuf);
          fis.close();
          
          FileOutputStream fos = new FileOutputStream(sTempDir + System.getProperty("file.separator") + 
                                         sTempName.substring(sTempName.lastIndexOf(System.getProperty("file.separator"))+1));
          fos.write(bbuf);
          fos.flush();
          fos.close();
          
          sFileList[fCount] = sTempName.substring(sTempName.lastIndexOf("\\") + 1);
          fFileList[fCount] = new File(sTempDir + "/" + sFileList[fCount]);
          fCount++;
        }
        
        //if true then email was sent successfully
        blnEmailSent = processMailItem(sEmailFrom,sEmailTo,sPersonFrom,
                                       sPersonTo,sSummary,sNote,mpr,req,
                                       sCCList,sBCCList,sFileList,fFileList,sURL);
        
        if(blnEmailSent){                                     
          try{
            boolean blnRtn = false;
 
            blnRtn = insertCallRecord(sCallId,sAssignto,sActivityType,
                                      sRegarding,sDueDate,sDueTime,
                                      sStatus,sSummary,sNote,req,sCCList,
                                      sBCCList,sFileList,sCompanyId,sDivisionId,sPersonId);
 
            if(blnRtn){
              msNextJsp ="/EmailSentMsg.jsp";
            }
            else{
              req.setAttribute("errmsg","Email call record for call_id = " + msCallId + 
                                        "was unable to create activity record but email " + 
                                        "was sent successfully.");
              msNextJsp ="/ErrorMsgPage.jsp"; 
            }
          }
          catch(Exception _e){
            req.setAttribute("errmsg","Email call record for call_id = " + msCallId + 
                                      "was unable to create activity record but email " + 
                                      "was sent successfully. Advise application administrator " + 
                                      "to checks logs for StackTrace Output.");
            msNextJsp ="/ErrorMsgPage.jsp"; 
            _e.printStackTrace();
          }
        }else{
          msNextJsp ="/EmailFailedMsg.jsp";
        }
      }else{
        msNextJsp ="/EmailFailedMsg.jsp"; 
      }
    }
    catch(Exception _e){
      msNextJsp ="/EmailFailedMsg.jsp"; 
      _e.printStackTrace();
    }
  }//end emailInsertSave()
  
  private boolean uploadDocuments(String sCallId,HttpServletRequest req,
                                  HttpServletResponse res,HttpServlet servlet,
                                  String sFile){
    ContextBean cBean = (ContextBean) session.getAttribute("context");
    String sCompanyId = cBean.getCompanyId();
    String sDivisionId = cBean.getDivisionId();
    String sPersonId = cBean.getPersonId();
    String sQuoteId = cBean.getQuoteId();
    String sOpportunityId = cBean.getOpportunityId();
    String sOrderId = cBean.getOrderId();
    String sSummary = "Email Attachment For Activity #" + sCallId;
    
    if(sDivisionId==null || sDivisionId.length()==0){sDivisionId = "0";} 
    if(sPersonId==null || sPersonId.length()==0){sPersonId = "0";} 
    if(sOpportunityId==null || sOpportunityId.length()==0){sOpportunityId = "0";} 
    if(sQuoteId==null || sQuoteId.length()==0){sQuoteId = "0";} 
    if(sOrderId==null || sOrderId.length()==0){sOrderId = "0";} 
    
    try{
      Utils utilObj = new Utils();
      
      StringBuffer sSQL = new StringBuffer();
      sSQL.append("INSERT INTO DOCUMENT ");
      sSQL.append("(DOCUMENT_ID,COMPANY_ID,DIVISION_ID,");
      sSQL.append("PERSON_ID,OPPORTUNITY_ID,QUOTE_ID,ORDER_ID,");
      sSQL.append("CREATE_USER,CREATE_DATE,");
      sSQL.append("FILENAME,CONTENT,MIME_TYPE,MODIFY_USER,MODIFY_DATE,");
      sSQL.append("SYNC_DATE,SYNC_USER,ACTIVE,SUMMARY");
      sSQL.append(") VALUES(");
      sSQL.append("?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
      
      java.sql.Timestamp tsp = utilObj.currentTimestamp();
      byte bBlob[] = null;
      
      int intFileCount = 1;
      for(int i=0; i < intFileCount; i++){
        bBlob = new byte[(int)mFile.length()];
        FileInputStream fis = new FileInputStream(mFile);
        fis.read(bBlob);
        fis.close();
        if(bBlob != null){
          //must have new one for each file
          pstmt = m_conDb.prepareStatement(sSQL.toString());
 
          int iPrimaryKey = KeyGenerator.getInstance().generateKey(req);
          pstmt.setInt(1,iPrimaryKey);
 
          pstmt.setInt(2,Integer.parseInt(sCompanyId));
          pstmt.setInt(3,Integer.parseInt(sDivisionId));
          pstmt.setInt(4,Integer.parseInt(sPersonId));
          pstmt.setInt(5,Integer.parseInt(sOpportunityId));
          pstmt.setInt(6,Integer.parseInt(sQuoteId));
          pstmt.setInt(7,Integer.parseInt(sOrderId));
          pstmt.setString(8,msUsername);
          pstmt.setTimestamp(9,tsp);
          pstmt.setString(10,sFile);
          pstmt.setObject(11,bBlob);
          pstmt.setString(12,msContentType);
          pstmt.setString(13,msUsername);
          pstmt.setTimestamp(14,tsp);
          pstmt.setTimestamp(15,tsp);
          pstmt.setString(16,msUsername);
          pstmt.setString(17,"Y");
          pstmt.setString(18,sSummary);
          pstmt.execute();
          pstmt = null;
        }
        
        bBlob = null;
        fis = null;
      }//end file for loop
      
      return true;
    }
    catch(Exception _e){
      _e.printStackTrace();
      return false;
    }
  }//end uploadDocuments()
  
  private boolean insertCallRecord(String sCallId,String sAssignto,String sActivityType,
                                   String sRegarding,String sDueDate,String sDueTime,
                                   String sStatus,String sSummary,String sNote,
                                   HttpServletRequest req, String sCCList,
                                   String sBCCList,String[] sFile,String sCompanyId,
                                   String sDivisionId,String sPersonId){
 
    /*                                   
    ContextBean cBean = (ContextBean) session.getAttribute("context");
    String sCompanyId = cBean.getCompanyId();
    String sDivisionId = cBean.getDivisionId();
    String sPersonId = cBean.getPersonId();
    String sQuoteId = cBean.getQuoteId();
    String sOpportunityId = cBean.getOpportunityId();
    String sOrderId = cBean.getOrderId();
    */
    
    DataTypeConversion dtc = new DataTypeConversion();
    
    if(sFile != null)
      sNote = "ATTACHMENT: " + sFile + "\n" + sNote;
    
    if(sBCCList != null)
      sNote = "\n" + "BCC: " + sBCCList + "\n" + sNote;
    
    if(sCCList != null)
      sNote = "\n" + "CC: " + sCCList + "\n" + sNote;
    
    try{
      Utils utilObj = new Utils();
      java.sql.Timestamp tsp = utilObj.currentTimestamp();
 
      StringBuffer sSQL = new StringBuffer();
      sSQL.append("INSERT INTO CALL ");
      sSQL.append("(CALL_ID,COMPANY_ID,DIVISION_ID,PERSON_ID,OPPORTUNITY_ID,");
      sSQL.append("QUOTE_ID, ORDER_ID, CREATE_USER, CREATE_DATE,ASSIGN_TO,");
      sSQL.append("STATUS,SUMMARY,NOTE,REGARDING,ACTIVITY_TYPE,DUE_DATE,");
      sSQL.append("DUE_TIME,MODIFY_USER,MODIFY_DATE,SYNC_DATE,SYNC_USER,ACTIVE,DUETIME) ");
      sSQL.append("VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
 
      pstmt = m_conDb.prepareStatement(sSQL.toString());
      int iPrimaryKey = KeyGenerator.getInstance().generateKey(req);
      pstmt.setInt(1,iPrimaryKey);
      pstmt.setInt(2,Integer.parseInt(sCompanyId));
 
      if (sDivisionId==null || sDivisionId.length()==0){
        pstmt.setInt(3, 0);
      } else {
        pstmt.setInt(3,Integer.parseInt(sDivisionId));
      }
 
      if (sPersonId==null || sPersonId.length()==0){
        pstmt.setInt(4, 0);
      } else {
        pstmt.setInt(4,Integer.parseInt(sPersonId));
      }
 
      pstmt.setInt(5, 0);
/*
      if (sOpportunityId==null || sOpportunityId.length()==0){
        pstmt.setInt(5, 0);
      } else {
        pstmt.setInt(5,Integer.parseInt(sOpportunityId));
      }
*/
      pstmt.setInt(6, 0);
/*      
      if (sQuoteId==null || sQuoteId.length()==0){
        pstmt.setInt(6, 0);
      } else {
        pstmt.setInt(6,Integer.parseInt(sQuoteId));
      }
*/
      pstmt.setInt(7, 0);
/*      
      if (sOrderId==null || sOrderId.length()==0){
        pstmt.setInt(7, 0);
      } else {
        pstmt.setInt(7,Integer.parseInt(sOrderId));
      }
*/
      pstmt.setString(8,msUsername);
      pstmt.setTimestamp(9,tsp);
      pstmt.setString(10,sAssignto);
      pstmt.setString(11,sStatus);
      pstmt.setString(12,sSummary);
      pstmt.setString(13,sNote);
      pstmt.setString(14,sRegarding);
      pstmt.setString(15,sActivityType);
      if (sDueDate==null || sDueDate.length()==0){
        pstmt.setDate(16,null);
      } else {
        pstmt.setDate(16,new java.sql.Date(tsp.getTime()));
      }
      pstmt.setString(17,sDueTime);
      pstmt.setString(18,msUsername);
      pstmt.setTimestamp(19,tsp);
      pstmt.setTimestamp(20,tsp);
      pstmt.setString(21,msUsername);
      pstmt.setString(22,"Y");
      pstmt.setTime(23,dtc.getISOTime(sDueTime));
      pstmt.execute();
 
      msCallId = String.valueOf(iPrimaryKey);
      sCallId = msCallId;
      
      return true;
    }
    catch(Exception _e){
      _e.printStackTrace();
      return false;
    }
  }
  
  public boolean processMailItem(String sEmailFrom,String sEmailTo,String sSubject,String sMsg,Connection c,String sCCList) throws Exception{
 
    try{
      Properties mailProps = new Properties();
      String mailHostIP = SConfigReader.getStringConfigValue("email_server",c);
      mailProps.put("mail.host", mailHostIP);
      mailProps.put("mail.transport.protocol", "smtp");
    
      Session mailSession = Session.getInstance(mailProps);
      MimeMessage m = new MimeMessage(mailSession);
      
      InternetAddress addy = null; //generic var used for iteration
      InternetAddress addrTo = new InternetAddress(sEmailTo);
      InternetAddress addrFrom = new InternetAddress(sEmailFrom);
      Address[] addrs = new Address[1];
      Address[] addrsCC = null;
      
      addrs[0] = addrTo;
      m.setRecipient(Message.RecipientType.TO, addrs[0]);
      
      addrs[0] = addrFrom;
      m.setFrom(addrs[0]);
      m.setReplyTo(addrs);
 
      if(sCCList != null && sCCList.length() > 0 && sCCList.indexOf(";") > 0){
        StringTokenizer sCCTokens = new StringTokenizer(sCCList,";");
        addrsCC = new Address[sCCTokens.countTokens()];
        int i = 0;
        while(sCCTokens.hasMoreTokens()){
          addrsCC[i] = new InternetAddress(sCCTokens.nextToken());
          i += 1;
        }
        m.setRecipients(Message.RecipientType.CC, addrsCC);
      }else if(sCCList != null && sCCList.length() > 0){
        addrsCC = new Address[1];
        addrsCC[0] = new InternetAddress(sCCList);
        m.setRecipients(Message.RecipientType.CC, addrsCC);
      }      
      
      m.setSubject(sSubject);
      m.setSentDate(new java.util.Date());
      m.setContent(sMsg, "text/html");
      
      Transport.send(m);
      
      return true;
    }
    catch(Exception _e){
      System.out.println("public->processMailItem() error");
      _e.printStackTrace();
      return false;
    }
  }
  
  public boolean processMailItem(String sEmailFrom,String sEmailTo,
                                  String sSubject,String sMsg, HttpServletRequest req) 
                                  throws Exception{
 
    try{
      Properties mailProps = new Properties();
      String mailHostIP = SConfigReader.getStringConfigValue("email_server",req);
      mailProps.put("mail.host", mailHostIP);
      mailProps.put("mail.transport.protocol", "smtp");
    
      Session mailSession = Session.getInstance(mailProps);
      
      InternetAddress addy = null; //generic var used for iteration
      InternetAddress addrTo = new InternetAddress(sEmailTo);
      InternetAddress addrFrom = new InternetAddress(sEmailFrom);
    
      MimeMessage m = new MimeMessage(mailSession);
      Address[] addrs = new Address[1];
    
      addrs[0] = addrTo;
      m.setRecipient(Message.RecipientType.TO, addrs[0]);
      
      addrs[0] = addrFrom;
      m.setFrom(addrs[0]);
      m.setReplyTo(addrs);
      
      m.setSubject(sSubject);
      m.setSentDate(new java.util.Date());
      m.setContent(sMsg, "text/html");
      
      Transport.send(m);
      
      return true;
    }
    catch(Exception _e){
      System.out.println("public->processMailItem() error");
      _e.printStackTrace();
      return false;
    }
  }
  
  private boolean processMailItem(String sEmailFrom,String sEmailTo, 
                                  String sPersonFrom, String sPersonTo,
                                  String sSubject,String sMsg,
                                  MultipartRequest mpr, HttpServletRequest req,
                                  String sCCList, String sBCCList,
                                  String[] sFile, File[] fFile, String sURL) throws Exception{
 
    try{
      Properties mailProps = new Properties();
      String mailHostIP = SConfigReader.getStringConfigValue("email_server",req);
      mailProps.put("mail.host", mailHostIP);
      mailProps.put("mail.transport.protocol", "smtp");
    
      Session mailSession = Session.getInstance(mailProps);
      
      InternetAddress addy = null; //generic var used for iteration
      InternetAddress addrTo = new InternetAddress(sEmailTo, sPersonTo);
      InternetAddress addrFrom = new InternetAddress(sEmailFrom, sPersonFrom);
    
      Address[] addrsCC = null;
      if(sCCList != null && sCCList.length() > 0 && sCCList.indexOf(";") > 0){
        StringTokenizer sCCTokens = new StringTokenizer(sCCList,";");
        addrsCC = new Address[sCCTokens.countTokens()];
        int i = 0;
        while(sCCTokens.hasMoreTokens()){
          addrsCC[i] = new InternetAddress(sCCTokens.nextToken());
          i += 1;
        }
      }else if(sCCList != null && sCCList.length() > 0){
        addrsCC = new Address[1];
        addrsCC[0] = new InternetAddress(sCCList);
      }
      
      
      Address[] addrsBCC = null;
      if(sBCCList != null  && sBCCList.length() > 0 && sBCCList.indexOf(";") > 0){  
        StringTokenizer sBCCTokens = new StringTokenizer(sBCCList,";");
        addrsBCC = new Address[sBCCTokens.countTokens()];
        int i = 0;
        while(sBCCTokens.hasMoreTokens()){
          addrsBCC[i] = new InternetAddress(sBCCTokens.nextToken());
          i += 1;
        }
      }else if(sBCCList != null && sBCCList.length() > 0){
        addrsBCC = new Address[1];
        addrsBCC[0] = new InternetAddress(sBCCList);
      }
      
      MimeMessage m = new MimeMessage(mailSession);
      Address[] addrs = new Address[1];
    
      addrs[0] = addrTo;
      m.setRecipient(Message.RecipientType.TO, addrs[0]);
      
      addrs[0] = addrFrom;
      m.setFrom(addrs[0]);
      m.setReplyTo(addrs);
      
      if(addrsCC != null)
        m.setRecipients(Message.RecipientType.CC, addrsCC);
      
      if(addrsBCC != null)
        m.setRecipients(Message.RecipientType.BCC,addrsBCC);
 
      m.setSubject(sSubject);
      m.setSentDate(new java.util.Date());
 
      if(sURL != null && sFile.length > 0 && fFile.length > 0){
        javax.mail.internet.MimeBodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart();
        messageBodyPart.setText(sMsg);
        javax.mail.Multipart multipart = new javax.mail.internet.MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
 
        //System.out.println(sURL + "/" + sFile);
        
        // Part two is attachment
        for(int f = 0; f < sFile.length; f++){
          javax.mail.internet.MimeBodyPart attachmentBodyPart = new javax.mail.internet.MimeBodyPart();
          //java.net.URL url = new java.net.URL(sURL + "/" + sFile);
          javax.activation.FileDataSource source = new javax.activation.FileDataSource(fFile[f]);
          //javax.activation.URLDataSource source = new javax.activation.URLDataSource(url);
          attachmentBodyPart.setDataHandler(new DataHandler(source));
          attachmentBodyPart.setFileName(sFile[f]);
          multipart.addBodyPart(attachmentBodyPart);
          m.setContent(multipart);
        }
      }else{
        //System.out.println("sFile or sURL was null for email_to:" + sEmailTo);
        m.setContent(sMsg, "text/html");
      }
      
      Transport.send(m);
      
      return true;
    }
    catch(Exception _e){
      System.out.println("processMailItem() error");
      _e.printStackTrace();
      return false;
    }
  }
  
  // updates the existing record with new data
  private void emailUpdate(HttpServletRequest req){
    
    Utils utilObj = new Utils();
    java.sql.Timestamp tsp = utilObj.currentTimestamp();
    
    try{
      String sCallId = (String) req.getParameter("callid");
      String sAssignto = (String) req.getParameter("assignto");
      String sActivityType = (String) req.getParameter("activitytype");
      String sRegarding = (String) req.getParameter("regarding");
      String sDueDate = (String) req.getParameter("duedate");
      String sDueTime = (String) req.getParameter("duetime");
      String sStatus = (String) req.getParameter("status");
      
      String sSummary = (String) req.getParameter("summary");
      String sNote = (String) req.getParameter("note");
      
      //Call Prepare statement for SAP DB
      StringBuffer sSQL = new StringBuffer();
      sSQL.append("UPDATE CALL ");
      sSQL.append("SET ASSIGN_TO=?, STATUS=?, REGARDING=?, ACTIVITY_TYPE=?, DUE_DATE=?, ");
      sSQL.append("DUE_TIME=?, SUMMARY=?, NOTE=?, MODIFY_DATE=?, MODIFY_USER=?, SYNC_DATE=?, SYNC_USER=? WHERE CALL_ID=?");
      pstmt = m_conDb.prepareStatement(sSQL.toString());
      pstmt.setString(1,sAssignto);
      pstmt.setString(2,sStatus);
      pstmt.setString(3,sRegarding);
      pstmt.setString(4,sActivityType);
      if (sDueDate==null || sDueDate.length()==0){
        pstmt.setDate(5,null);
      } else {
        pstmt.setDate(5,new java.sql.Date(dtf.parse(sDueDate).getTime()));
      }
      pstmt.setString(6,sDueTime);
      pstmt.setString(7,sSummary);
      pstmt.setString(8,sNote);
      pstmt.setTimestamp(9,tsp);
      pstmt.setString(10,msUsername);
      pstmt.setTimestamp(11,tsp);
      pstmt.setString(12,msUsername);
      pstmt.setInt(13,Integer.parseInt(sCallId));
      
      
      pstmt.executeUpdate();
    }
    catch (Exception _e) {
      _e.printStackTrace();
    }
  }
  
    
   //displays edit form in the insert mode
  private ArrayList emailInsert(HttpServletRequest req){
    ArrayList alEmailList = new ArrayList();
    CallListBean clbObj = new CallListBean();
    Utils utilObj = new Utils();
    
    HttpSession  session = req.getSession();
    ContextBean cBean = (ContextBean) session.getAttribute("context");
    UserBean uBean = (UserBean)session.getAttribute("userbean");
    
    clbObj.setAssignTo(msUsername);
    clbObj.setRegarding("OTHER");
    clbObj.setActivityType("EMAIL");
    clbObj.setStatus("COMPLETED");
    clbObj.setDueDate(utilObj.formatDate(utilObj.currentTimestamp()));
    clbObj.setDueTime(utilObj.formatTime(utilObj.currentTimestamp()));
    clbObj.setComName(cBean.getComName());
    clbObj.setCompanyId(cBean.getCompanyId());
    clbObj.setDivName(cBean.getDivName());
    clbObj.setDivisionId(cBean.getDivisionId());
    clbObj.setFName(cBean.getFName());
    clbObj.setLName(cBean.getLName());
    clbObj.setPersonId(cBean.getPersonId());
    
    String sPEmail = (String) req.getParameter("email");
    String sUEmail = uBean.getEMailAddress();
    String sPersonFrom = (uBean.getFirstName() + " " + uBean.getLastName());
    req.setAttribute("emailfrom", sUEmail);
    req.setAttribute("emailto", sPEmail);
    req.setAttribute("from", sPersonFrom);
    req.setAttribute("to", (cBean.getFName() + " " + cBean.getLName()));
    req.setAttribute("bcc", sUEmail);
    req.setAttribute("browser",uBean.getBrowser());
    
    alEmailList.add(clbObj);
    return alEmailList;
  }
  
  private ArrayList emailEdit(HttpServletRequest req, boolean bOverride){
    
    ArrayList alEmailList = new ArrayList();
    
    HttpSession  session = req.getSession();
    ContextBean cBean = (ContextBean) session.getAttribute("context");
    
    String sOrderId="0";
    String sQuoteId="0";
    String sOpportunityId="0";
    String sCompanyId="0";
    String sPersonId="0";
    String sDivisionId="0";
    String sCallId="0";
    String sAssignto = "";
    String sActivityType ="";
    String sRegarding ="";
    String sStatus = "";
    String sCallNum ="";
    String sSummary = "";
    String sStartDate= "";
    String sFName = "";
    String sLName = "";
    String sComName = "";
    String sDivName = "";
    String sEndDate="";
    
    try{
      //getting data from the request object'
      
      if(bOverride){sCallId=msCallId;} 
      else{sCallId = (String) req.getParameter("callid");}
      
      cstmt = m_conDb.prepareCall("{call sp_call_edit(?,?,?,?,?,?,?)}");
      
      cstmt.setString(1,sCallId);
      cstmt.setString(2,"0");
      cstmt.setString(3,"0");
      cstmt.setString(4,"0");
      cstmt.setString(5,"0");
      cstmt.setString(6,"0");
      cstmt.setString(7,"0");
      
      cstmt.execute();
      rs= cstmt.getResultSet();
      
      if (rs.next()){
        CallListBean clbObj = getListBean(rs,true);
        alEmailList.add(clbObj);
      }
    }
    catch (Exception _e) {
      _e.printStackTrace();
    }
 
    return alEmailList;
  }
  
  private CallListBean getListBean(ResultSet _rs, boolean bSetSession ) throws Exception{
    CallListBean clbObj = new CallListBean();
 
    clbObj.setCallId((String) _rs.getString("CALL_ID"));
    
    String sCompanyId = (String) _rs.getString("COMPANY_ID");
    clbObj.setCompanyId(sCompanyId);
    
    String sDivisionId = (String) _rs.getString("DIVISION_ID");
    clbObj.setDivisionId(sDivisionId);
    
    String sPersonId = (String) _rs.getString("PERSON_ID");
    clbObj.setPersonId(sPersonId);
    
    String sOpportunityId = (String) _rs.getString("OPPORTUNITY_ID");
    clbObj.setOpportunityId(sOpportunityId);
    
    String sQuoteId=(String) _rs.getString("QUOTE_ID");
    clbObj.setQuoteId(sQuoteId);
    
    String sOrderId=(String) _rs.getString("ORDER_ID");
    clbObj.setOrderId(sOrderId);
    
    
    clbObj.setAssignTo(utilObj.nullToEmpty((String) _rs.getString("ASSIGN_TO")));
    clbObj.setStatus(utilObj.nullToEmpty((String) _rs.getString("STATUS")));
    clbObj.setRegarding(utilObj.nullToEmpty((String) _rs.getString("REGARDING")));
    clbObj.setActivityType(utilObj.nullToEmpty((String) _rs.getString("ACTIVITY_TYPE")));
    
    Timestamp ts= _rs.getTimestamp("DUE_DATE");
    if (ts==null){
      clbObj.setDueDate("");
    } else {
      java.sql.Date dt = new java.sql.Date(ts.getTime());
      clbObj.setDueDate(dtf.format(dt));
    }
    clbObj.setDueTime(utilObj.nullToEmpty((String) _rs.getString("DUE_TIME")));
    clbObj.setSummary(utilObj.nullToEmpty((String) _rs.getString("SUMMARY")));
    clbObj.setNote(utilObj.nullToEmpty((String) _rs.getString("NOTE")));
    clbObj.setCreateDate(utilObj.formatDateTime(_rs.getTimestamp("CREATE_DATE")));
    clbObj.setCreateUser(utilObj.nullToEmpty((String) _rs.getString("CREATE_USER")));
    clbObj.setModifyDate(utilObj.formatDateTime(_rs.getTimestamp("MODIFY_DATE")));
    clbObj.setModifyUser(utilObj.nullToEmpty((String) _rs.getString("MODIFY_USER")));
    if (bSetSession){
      String sComname = utilObj.nullToEmpty((String) _rs.getString("COM_NAME"));
      clbObj.setComName(sComname);
      
      String sDivname = utilObj.nullToEmpty((String) _rs.getString("DIV_NAME"));
      clbObj.setDivName(sDivname);
      
      
      String sFname = utilObj.nullToEmpty((String) _rs.getString("FNAME"));
      clbObj.setFName(sFname);
      
      String sLname = utilObj.nullToEmpty((String) _rs.getString("LNAME"));
      clbObj.setLName(sLname);
      
      
      
      //setting up context
      
      ContextBean cBean = new ContextBean();
      cBean.setPersonId(sPersonId);
      cBean.setFName(sFname);
      cBean.setLName(sLname);
      
      cBean.setCompanyId(sCompanyId);
      cBean.setComName(sComname);
      
      cBean.setDivisionId(sDivisionId);
      cBean.setDivName(sDivname);
      
      cBean.setOpportunityId(sOpportunityId);
      cBean.setQuoteId(sQuoteId);
      cBean.setOrderId(sOrderId);
      
      session.setAttribute("context",cBean);
    }
    return clbObj;
  }
  
  private boolean isValid(HttpServletRequest req){
    boolean isValid=true;
    
    if (!validate(req,"email_to","emailto"))isValid=false;
    if (!validate(req,"email_from","emailfrom"))isValid=false;
    if (!validate(req,"email_subject","emailsubject"))isValid=false;
    //if (!validate(req,"email_body","emailbody"))isValid=false;
 
    if (!isValid){
      CallListBean clbObj = new CallListBean();
      clbObj.setCallId(req.getParameter("callid"));
      clbObj.setAssignTo(req.getParameter("assignto"));
      clbObj.setActivityType(req.getParameter("activitytype"));
      clbObj.setRegarding(req.getParameter("regarding"));
      clbObj.setDueDate(null);
      clbObj.setDueTime(null);
      clbObj.setStatus(req.getParameter("status"));
      clbObj.setSummary(req.getParameter("emailsubject"));
      clbObj.setNote(req.getParameter("emailbody"));
      
      ArrayList alEmailList = new ArrayList();
      alEmailList.add(clbObj);
      req.setAttribute("listing",alEmailList);
    }
 
    return isValid;
  }
  
  private void populateErrorFields(HttpServletRequest req){
    req.setAttribute("error","&nbsp;");   //error message
    req.setAttribute("emailto_error","");
    req.setAttribute("emailfrom_error","");
    req.setAttribute("emailsubject_error","");
    req.setAttribute("emailbody_error","");
  }
  
}

Open in new window

Avatar of Dejan Pažin
Dejan Pažin
Flag of Austria image


Do you have the  "C:\a.txt" file in your test environment? It looks like the system is trying to read it, but the file is not there.
Avatar of sadaf_syed
sadaf_syed

ASKER

in the test environment i can access the file, and attach. Its in the live environment that I can not attach the file. This code works in my test environment but not in the live.
ASKER CERTIFIED SOLUTION
Avatar of Dejan Pažin
Dejan Pažin
Flag of Austria 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
but the file is there i can open the file from that location.

i think the error is in this function:


 boolean blnEmailSent = false;
    
    //now send the email
    try{
      String sFilePrefix = "file:///";
      char chUnixSeperator = 47;
      char chWinSeperator = 92;
      String sTempDir = servlet.getServletContext().getRealPath("/") + "temp";
      sTempDir = sTempDir.replace(chWinSeperator, chUnixSeperator);
      
      MultipartRequest mpr = new MultipartRequest(req, sFilePrefix + sTempDir);
            
      if(mpr != null){
        String sURL = sFilePrefix + sTempDir;
        String sEmailTo = mpr.getParameter("emailto");
        String sEmailFrom = mpr.getParameter("emailfrom");
        String sPersonFrom = mpr.getParameter("from");
        String sPersonTo = mpr.getParameter("to");
        String sCCList = mpr.getParameter("cclist");
        String sBCCList = mpr.getParameter("bcclist");
        String sCallId = mpr.getParameter("callid");
        String sAssignto = mpr.getParameter("assignto");
        String sActivityType = mpr.getParameter("activitytype");
        String sRegarding = mpr.getParameter("regarding");
        String sDueDate = mpr.getParameter("duedate");
        String sDueTime = mpr.getParameter("duetime");
        String sStatus = mpr.getParameter("status");
        String sSummary = mpr.getParameter("emailsubject");
        String sNote = mpr.getParameter("emailbody");
        String sCompanyId = mpr.getParameter("companyid");
        String sDivisionId = mpr.getParameter("divisionid");
        String sPersonId = mpr.getParameter("personid");
        
        String sFilesUpload = mpr.getParameter("filelist");
        System.out.println(sFilesUpload);
        if (sFilesUpload == null) sFilesUpload = "";
 
    
        String sFile = null;
        String strFileSysName = null;
        
        //Gets any files still left in the files2upload input box
       Enumeration enumFiles = mpr.getFileNames();
        if(enumFiles.hasMoreElements()) {
          sFile = (String)enumFiles.nextElement();
          msContentType = mpr.getContentType(sFile);
          strFileSysName = mpr.getFilesystemName(sFile);
          sFile = strFileSysName;
          mFile = new File(sTempDir + "/" + sFile);
          System.out.println(sFile);
          System.out.println(msContentType);
        }
        
        //Gets all files stored in filelist hidden input
        StringTokenizer st = new StringTokenizer(sFilesUpload, ";");
        String[] sFileList = new String[st.countTokens()];
        File[] fFileList = new File[st.countTokens()];
        //sFile = sFilesUpload + sFile;
        
        int fCount = 0;
        while(st.hasMoreTokens()){
          String sTempName = st.nextToken();
          byte[] bbuf = new byte[(int)new File(sTempName).length()];
          FileInputStream fis = new FileInputStream(sTempName);
          fis.read(bbuf);
          fis.close();
          
          FileOutputStream fos = new FileOutputStream(sTempDir + System.getProperty("file.separator") + 
                                         sTempName.substring(sTempName.lastIndexOf(System.getProperty("file.separator"))+1));
          fos.write(bbuf);
          fos.flush();
          fos.close();
          
          sFileList[fCount] = sTempName.substring(sTempName.lastIndexOf("\\") + 1);
          fFileList[fCount] = new File(sTempDir + "/" + sFileList[fCount]);
          fCount++;
        }
        
        //if true then email was sent successfully
        blnEmailSent = processMailItem(sEmailFrom,sEmailTo,sPersonFrom,
                                       sPersonTo,sSummary,sNote,mpr,req,
                                       sCCList,sBCCList,sFileList,fFileList,sURL);
        
        if(blnEmailSent){                                     
          try{
            boolean blnRtn = false;
 
            blnRtn = insertCallRecord(sCallId,sAssignto,sActivityType,
                                      sRegarding,sDueDate,sDueTime,
                                      sStatus,sSummary,sNote,req,sCCList,
                                      sBCCList,sFileList,sCompanyId,sDivisionId,sPersonId);
 
            if(blnRtn){
              msNextJsp ="/EmailSentMsg.jsp";
            }
            else{
              req.setAttribute("errmsg","Email call record for call_id = " + msCallId + 
                                        "was unable to create activity record but email " + 
                                        "was sent successfully.");
              msNextJsp ="/ErrorMsgPage.jsp"; 
            }
          }
          catch(Exception _e){
            req.setAttribute("errmsg","Email call record for call_id = " + msCallId + 
                                      "was unable to create activity record but email " + 
                                      "was sent successfully. Advise application administrator " + 
                                      "to checks logs for StackTrace Output.");
            msNextJsp ="/ErrorMsgPage.jsp"; 
            _e.printStackTrace();
          }
        }else{
          msNextJsp ="/EmailFailedMsg.jsp";
        }
      }else{
        msNextJsp ="/EmailFailedMsg.jsp"; 
      }
    }
    catch(Exception _e){
      msNextJsp ="/EmailFailedMsg.jsp"; 
      _e.printStackTrace();
    }
  }//end emailInsertSave()
  
  private boolean uploadDocuments(String sCallId,HttpServletRequest req,
                                  HttpServletResponse res,HttpServlet servlet,
                                  String sFile){
    ContextBean cBean = (ContextBean) session.getAttribute("context");
    String sCompanyId = cBean.getCompanyId();
    String sDivisionId = cBean.getDivisionId();
    String sPersonId = cBean.getPersonId();
    String sQuoteId = cBean.getQuoteId();
    String sOpportunityId = cBean.getOpportunityId();
    String sOrderId = cBean.getOrderId();
    String sSummary = "Email Attachment For Activity #" + sCallId;
    
    if(sDivisionId==null || sDivisionId.length()==0){sDivisionId = "0";} 
    if(sPersonId==null || sPersonId.length()==0){sPersonId = "0";} 
    if(sOpportunityId==null || sOpportunityId.length()==0){sOpportunityId = "0";} 
    if(sQuoteId==null || sQuoteId.length()==0){sQuoteId = "0";} 
    if(sOrderId==null || sOrderId.length()==0){sOrderId = "0";} 
    
    try{
      Utils utilObj = new Utils();
      
      StringBuffer sSQL = new StringBuffer();
      sSQL.append("INSERT INTO DOCUMENT ");
      sSQL.append("(DOCUMENT_ID,COMPANY_ID,DIVISION_ID,");
      sSQL.append("PERSON_ID,OPPORTUNITY_ID,QUOTE_ID,ORDER_ID,");
      sSQL.append("CREATE_USER,CREATE_DATE,");
      sSQL.append("FILENAME,CONTENT,MIME_TYPE,MODIFY_USER,MODIFY_DATE,");
      sSQL.append("SYNC_DATE,SYNC_USER,ACTIVE,SUMMARY");
      sSQL.append(") VALUES(");
      sSQL.append("?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
      
      java.sql.Timestamp tsp = utilObj.currentTimestamp();
      byte bBlob[] = null;
      
      int intFileCount = 1;
      for(int i=0; i < intFileCount; i++){
        bBlob = new byte[(int)mFile.length()];
        FileInputStream fis = new FileInputStream(mFile);
        fis.read(bBlob);
        fis.close();
        if(bBlob != null){
          //must have new one for each file
          pstmt = m_conDb.prepareStatement(sSQL.toString());
 
          int iPrimaryKey = KeyGenerator.getInstance().generateKey(req);
          pstmt.setInt(1,iPrimaryKey);
 
          pstmt.setInt(2,Integer.parseInt(sCompanyId));
          pstmt.setInt(3,Integer.parseInt(sDivisionId));
          pstmt.setInt(4,Integer.parseInt(sPersonId));
          pstmt.setInt(5,Integer.parseInt(sOpportunityId));
          pstmt.setInt(6,Integer.parseInt(sQuoteId));
          pstmt.setInt(7,Integer.parseInt(sOrderId));
          pstmt.setString(8,msUsername);
          pstmt.setTimestamp(9,tsp);
          pstmt.setString(10,sFile);
          pstmt.setObject(11,bBlob);
          pstmt.setString(12,msContentType);
          pstmt.setString(13,msUsername);
          pstmt.setTimestamp(14,tsp);
          pstmt.setTimestamp(15,tsp);
          pstmt.setString(16,msUsername);
          pstmt.setString(17,"Y");
          pstmt.setString(18,sSummary);
          pstmt.execute();
          pstmt = null;
        }
        
        bBlob = null;
        fis = null;
      }//end file for loop
      
      return true;
    }
    catch(Exception _e){
      _e.printStackTrace();
      return false;
    }
  }//end uploadDocuments()

Open in new window

okay i have narrowed it down to this. I have the file upto line 63 of the above code snippet.
but the file value becomes null or is not carried over via the FileInputStream fis function, this is where the value becomes null and i get the file not found error.

Once again the point i would like to clarify is the path is correct, and this code works in my development environment but not in my production environment.

So please help me quickly!
could some one help me retype this bit of code i lose the file here in the loop :

 FileInputStream fis = new FileInputStream(sTempName);
          fis.read(bbuf);
          fis.close();
         
          FileOutputStream fos = new FileOutputStream(sTempDir + System.getProperty("file.separator") +
                                         sTempName.substring(sTempName.lastIndexOf(System.getProperty("file.separator"))+1));
          fos.write(bbuf);
          fos.flush();
          fos.close();
         
          sFileList[fCount] = sTempName.substring(sTempName.lastIndexOf("\\") + 1);
          fFileList[fCount] = new File(sTempDir + "/" + sFileList[fCount]);
          fCount++;
after line 63 in the above copied code snippet.

SOLUTION
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
This also explains why it was working when you were running it locally...  Because the client machine and the server were the same machine (so the file was magically on both machines) ;-)

Tim
You had verified that this c:\a.txt exists ON THE SERVER and not on the machine you invoke the html page from, right?
Oops. Had to press refresh - Tim got this before me :)
so how do i recode this. I am relatively new to java. So i am not sure how to do the file upload to send it in with the email.
also the whole program is in java, so why it is not a SAP environement. This is a web based application with using, java, java script, html, jsp and a controller servlet. just need help with the file upload and attachment so the attachment goes through with the email being sent out.
You seem to get a request object of type:

  com.comtrol.global.util.MultipartRequest;

You should be able to extract the file out of that, but I have never heard of that class, and I guess someone in your office wrote it, as it has the same package names as your class you present here...
And I thought:

   com.synfoserv.

classes were SAP classes..  I may be wrong

But I haven't seen these before, so I don't know what web framework you are using...
i am using the netbeans ide and this web application is connected to a maxdb data base.

how will i extract the file from   com.comtrol.global.util.MultipartRequest;. I am relatively new to java so please help.
I have no idea.  I assume you know what frameworks you are using?  

They should appear in the "Libraries" section of your project in the Project browser the the left hand side of NetBeans

Where did you get this code from?  Who wrote the com.comtrol.global.util.MultipartRequest class?

Was it someone where you work?  I only ask because your class seems to be in a similar package "com.comtrol.actions", or is this just something you chose based on the other classes you were importing?

Try holding down "CTRL" and clicking on the MultipartRequest word on line 504 of that file you first posted...

Tim
yes those are package files.. im not sure how this is related.. i really just need help re writing the file input and output statements so that the file can be read into the server and then output as an attachment with the email... i really just need help here:
 FileInputStream fis = new FileInputStream(sTempName);
          fis.read(bbuf);
          fis.close();
         
          FileOutputStream fos = new FileOutputStream(sTempDir + System.getProperty("file.separator") +
                                         sTempName.substring(sTempName.lastIndexOf(System.getProperty("file.separator"))+1));
          fos.write(bbuf);
          fos.flush();
          fos.close();
         
          sFileList[fCount] = sTempName.substring(sTempName.lastIndexOf("\\") + 1);
          fFileList[fCount] = new File(sTempDir + "/" + sFileList[fCount]);
          fCount++;

so if you could help me re write that bit of code that would be great. the code works great if i have no email attachments so i dont need to change anything anywhere else.. just here..
Again, I don't know what framework you are using, so if you can't tell me, I can't help...
i am using the netbeans IDE.. this is simply a web app using a controller servlet mainly in java script and jsps... the application itself is put on a linux server kads. so its url is https://kads...

its using the basic mvc framework and the project itself is on netbeans...  
Which basic MVC framework?

Where did you get it from?  Did you write it yourself?
yes it is written in house.
thanks for all your help since i am relatively new to java it took me a while to understand everything. the error seems to be in the requested multipart file stated in the include staement as it uploads and saves the files.
I am attaching the code for it below. i am also trying to debug it but would appreciate all the help i can get. thank you.
// Copyright (C) 1998 by Jason Hunter <jhunter@acm.org>.  All rights reserved.
// Use of this class is limited.  Please see the LICENSE for more information.
 
package com.comtrol.global.util;
 
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
 
/** 
 * A utility class to handle <tt>multipart/form-data</tt> requests,
 * the kind of requests that support file uploads.  This class can 
 * receive arbitrarily large files (up to an artificial limit you can set),
 * and fairly efficiently too.  
 * It cannot handle nested data (multipart content within multipart content)
 * or internationalized content (such as non Latin-1 filenames).
 * <p>
 * It's used like this:
 * <blockquote><pre>
 * MultipartRequest multi = new MultipartRequest(req, ".");
 * &nbsp;
 * out.println("Params:");
 * Enumeration params = multi.getParameterNames();
 * while (params.hasMoreElements()) {
 *   String name = (String)params.nextElement();
 *   String value = multi.getParameter(name);
 *   out.println(name + " = " + value);
 * }
 * out.println();
 * &nbsp;
 * out.println("Files:");
 * Enumeration files = multi.getFileNames();
 * while (files.hasMoreElements()) {
 *   String name = (String)files.nextElement();
 *   String filename = multi.getFilesystemName(name);
 *   String type = multi.getContentType(name);
 *   File f = multi.getFile(name);
 *   out.println("name: " + name);
 *   out.println("filename: " + filename);
 *   out.println("type: " + type);
 *   if (f != null) {
 *     out.println("f.toString(): " + f.toString());
 *     out.println("f.getName(): " + f.getName());
 *     out.println("f.exists(): " + f.exists());
 *     out.println("f.length(): " + f.length());
 *     out.println();
 *   }
 * }
 * </pre></blockquote>
 *
 * A client can upload files using an HTML form with the following structure.
 * Note that not all browsers support file uploads.
 * <blockquote><pre>
 * &lt;FORM ACTION="/servlet/Handler" METHOD=POST
 *          ENCTYPE="multipart/form-data"&gt;
 * What is your name? &lt;INPUT TYPE=TEXT NAME=submitter&gt; &lt;BR&gt;
 * Which file to upload? &lt;INPUT TYPE=FILE NAME=file&gt; &lt;BR&gt;
 * &lt;INPUT TYPE=SUBMIT&GT;
 * &lt;/FORM&gt;
 * </pre></blockquote>
 * <p>
 * The full file upload specification is contained in experimental RFC 1867,
 * available at <a href="http://www.ietf.org/rfc/rfc1867.txt">
 * http://www.ietf.org/rfc/rfc1867.txt</a>.
 *
 * @author <b>Jason Hunter</b>, Copyright &#169; 1998-1999
 * @version 1.6, 00/03/19, better WebSphere 2.x/3.x content type workaround
 * @version 1.5, 00/02/04, added auto MacBinary decoding for IE on Mac
 * @version 1.4, 00/01/05, added getParameterValues(),
 *                         WebSphere 2.x getContentType() workaround,
 *                         stopped writing empty "unknown" file
 * @version 1.3, 99/12/28, IE4 on Win98 lastIndexOf("boundary=") workaround
 * @version 1.2, 99/12/20, IE4 on Mac readNextPart() workaround
 * @version 1.1, 99/01/15, JSDK readLine() bug workaround
 * @version 1.0, 98/09/18
 */
public class MultipartRequest {
 
  private static final int DEFAULT_MAX_POST_SIZE = 30720 * 1024;  // 30 Meg
  private static final String NO_FILE = "unknown";
 
  private HttpServletRequest req;
  private File dir;
  private int maxSize;
 
  private Hashtable parameters = new Hashtable();  // name - Vector of values
  private Hashtable files = new Hashtable();       // name - UploadedFile
 
  /**
   * Constructs a new MultipartRequest to handle the specified request, 
   * saving any uploaded files to the given directory, and limiting the 
   * upload size to 1 Megabyte.  If the content is too large, an
   * IOException is thrown.  This constructor actually parses the 
   * <tt>multipart/form-data</tt> and throws an IOException if there's any 
   * problem reading or parsing the request.
   *
   * @param request the servlet request
   * @param saveDirectory the directory in which to save any uploaded files
   * @exception IOException if the uploaded content is larger than 1 Megabyte
   * or there's a problem reading or parsing the request
   */
  public MultipartRequest(HttpServletRequest request,
                          String saveDirectory) throws IOException {
    this(request, saveDirectory, DEFAULT_MAX_POST_SIZE);
  }
 
  /**
   * Constructs a new MultipartRequest to handle the specified request, 
   * saving any uploaded files to the given directory, and limiting the 
   * upload size to the specified length.  If the content is too large, an 
   * IOException is thrown.  This constructor actually parses the 
   * <tt>multipart/form-data</tt> and throws an IOException if there's any 
   * problem reading or parsing the request.
   *
   * @param request the servlet request
   * @param saveDirectory the directory in which to save any uploaded files
   * @param maxPostSize the maximum size of the POST content
   * @exception IOException if the uploaded content is larger than 
   * <tt>maxPostSize</tt> or there's a problem reading or parsing the request
   */
  public MultipartRequest(HttpServletRequest request,
                          String saveDirectory,
                          int maxPostSize) throws IOException {
    // Sanity check values
    if (request == null)
      throw new IllegalArgumentException("request cannot be null");
    if (saveDirectory == null)
      throw new IllegalArgumentException("saveDirectory cannot be null");
    if (maxPostSize <= 0) {
      throw new IllegalArgumentException("maxPostSize must be positive");
    }
 
    java.net.URI fURI = null;
    try{fURI = new java.net.URI(saveDirectory);}
    catch(URISyntaxException uriE){
      throw new IllegalArgumentException("saveDirectory could not be converted to URI");
    }
    // Save the request, dir, and max size
    req = request;
    //dir = new File(saveDirectory);
    dir = new File(fURI);
    maxSize = maxPostSize;
 
    // Check saveDirectory is truly a directory
    if (!dir.isDirectory())
      throw new IllegalArgumentException("Not a directory: " + saveDirectory);
 
    // Check saveDirectory is writable
    if (!dir.canWrite())
      throw new IllegalArgumentException("Not writable: " + saveDirectory);
 
    // Now parse the request saving data to "parameters" and "files";
    // write the file contents to the saveDirectory
    readRequest();
  }
 
  /**
   * Constructor with an old signature, kept for backward compatibility.
   * Without this constructor, a servlet compiled against a previous version 
   * of this class (pre 1.4) would have to be recompiled to link with this 
   * version.  This constructor supports the linking via the old signature.
   * Callers must simply be careful to pass in an HttpServletRequest.
   * 
   */
  public MultipartRequest(ServletRequest request,
                          String saveDirectory) throws IOException {
    this((HttpServletRequest)request, saveDirectory);
  }
 
  /**
   * Constructor with an old signature, kept for backward compatibility.
   * Without this constructor, a servlet compiled against a previous version 
   * of this class (pre 1.4) would have to be recompiled to link with this 
   * version.  This constructor supports the linking via the old signature.
   * Callers must simply be careful to pass in an HttpServletRequest.
   * 
   */
  public MultipartRequest(ServletRequest request,
                          String saveDirectory,
                          int maxPostSize) throws IOException {
    this((HttpServletRequest)request, saveDirectory, maxPostSize);
  }
 
  /**
   * Returns the names of all the parameters as an Enumeration of 
   * Strings.  It returns an empty Enumeration if there are no parameters.
   *
   * @return the names of all the parameters as an Enumeration of Strings
   */
  public Enumeration getParameterNames() {
    return parameters.keys();
  }
 
  /**
   * Returns the names of all the uploaded files as an Enumeration of 
   * Strings.  It returns an empty Enumeration if there are no uploaded 
   * files.  Each file name is the name specified by the form, not by 
   * the user.
   *
   * @return the names of all the uploaded files as an Enumeration of Strings
   */
  public Enumeration getFileNames() {
    return files.keys();
  }
 
  /**
   * Returns the value of the named parameter as a String, or null if 
   * the parameter was not sent or was sent without a value.  The value 
   * is guaranteed to be in its normal, decoded form.  If the parameter 
   * has multiple values, only the last one is returned (for backward 
   * compatibility).  For parameters with multiple values, it's possible
   * the last "value" may be null.
   *
   * @param name the parameter name
   * @return the parameter value
   */
  public String getParameter(String name) {
    try {
      Vector values = (Vector)parameters.get(name);
      if (values == null || values.size() == 0) {
        return null;
      }
      String value = (String)values.elementAt(values.size() - 1);
      return value;
    }
    catch (Exception e) {
      return null;
    }
  }
 
  /**
   * Returns the values of the named parameter as a String array, or null if 
   * the parameter was not sent.  The array has one entry for each parameter 
   * field sent.  If any field was sent without a value that entry is stored 
   * in the array as a null.  The values are guaranteed to be in their 
   * normal, decoded form.  A single value is returned as a one-element array.
   *
   * @param name the parameter name
   * @return the parameter values
   */
  public String[] getParameterValues(String name) {
    try {
      Vector values = (Vector)parameters.get(name);
      if (values == null || values.size() == 0) {
        return null;
      }
      String[] valuesArray = new String[values.size()];
      values.copyInto(valuesArray);
      return valuesArray;
    }
    catch (Exception e) {
      return null;
    }
  }
 
  /**
   * Returns the filesystem name of the specified file, or null if the 
   * file was not included in the upload.  A filesystem name is the name 
   * specified by the user.  It is also the name under which the file is 
   * actually saved.
   *
   * @param name the file name
   * @return the filesystem name of the file
   */
  public String getFilesystemName(String name) {
    try {
      UploadedFile file = (UploadedFile)files.get(name);
      return file.getFilesystemName();  // may be null
    }
    catch (Exception e) {
      return null;
    }
  }
 
  /**
   * Returns the content type of the specified file (as supplied by the 
   * client browser), or null if the file was not included in the upload.
   *
   * @param name the file name
   * @return the content type of the file
   */
  public String getContentType(String name) {
    try {
      UploadedFile file = (UploadedFile)files.get(name);
      return file.getContentType();  // may be null
    }
    catch (Exception e) {
      return null;
    }
  }
 
  /**
   * Returns a File object for the specified file saved on the server's 
   * filesystem, or null if the file was not included in the upload.
   *
   * @param name the file name
   * @return a File object for the named file
   */
  public File getFile(String name) {
    try {
      UploadedFile file = (UploadedFile)files.get(name);
      return file.getFile();  // may be null
    }
    catch (Exception e) {
      return null;
    }
  }
 
  /**
   * The workhorse method that actually parses the request.  A subclass 
   * can override this method for a better optimized or differently
   * behaved implementation.
   *
   * @exception IOException if the uploaded content is larger than 
   * <tt>maxSize</tt> or there's a problem parsing the request
   */
  protected void readRequest() throws IOException {
    // Check the content length to prevent denial of service attacks
    int length = req.getContentLength();
    if (length > maxSize) {
      throw new IOException("Posted content length of " + length + 
                            " exceeds limit of " + maxSize);
    }
 
    // Check the content type to make sure it's "multipart/form-data"
    // Access header two ways to work around WebSphere oddities
    String type = null;
    String type1 = req.getHeader("Content-Type");
    String type2 = req.getContentType();
    // If one value is null, choose the other value
    if (type1 == null && type2 != null) {
      type = type2;
    }
    else if (type2 == null && type1 != null) {
      type = type1;
    }
    // If neither value is null, choose the longer value
    else if (type1 != null && type2 != null) {
      type = (type1.length() > type2.length() ? type1 : type2);
    }
 
    if (type == null || 
        !type.toLowerCase().startsWith("multipart/form-data")) {
      throw new IOException("Posted content type isn't multipart/form-data");
    }
 
    // Get the boundary string; it's included in the content type.
    // Should look something like "------------------------12012133613061"
    String boundary = extractBoundary(type);
    if (boundary == null) {
      throw new IOException("Separation boundary was not specified");
    }
 
    // Construct the special input stream we'll read from
    MultipartInputStreamHandler in =
      new MultipartInputStreamHandler(req.getInputStream(), length);
 
    // Read the first line, should be the first boundary
    String line = in.readLine();
    if (line == null) {
      throw new IOException("Corrupt form data: premature ending");
    }
 
    // Verify that the line is the boundary
    if (!line.startsWith(boundary)) {
      throw new IOException("Corrupt form data: no leading boundary");
    }
 
    // Now that we're just beyond the first boundary, loop over each part
    boolean done = false;
    while (!done) {
      done = readNextPart(in, boundary);
    }
  }
 
  /**
   * A utility method that reads an individual part.  Dispatches to 
   * readParameter() and readAndSaveFile() to do the actual work.  A 
   * subclass can override this method for a better optimized or 
   * differently behaved implementation.
   * 
   * @param in the stream from which to read the part
   * @param boundary the boundary separating parts
   * @return a flag indicating whether this is the last part
   * @exception IOException if there's a problem reading or parsing the
   * request
   *
   * @see readParameter
   * @see readAndSaveFile
   */
  protected boolean readNextPart(MultipartInputStreamHandler in,
                                 String boundary) throws IOException {
    // Read the first line, should look like this:
    // content-disposition: form-data; name="field1"; filename="file1.txt"
    String line = in.readLine();
    if (line == null) {
      // No parts left, we're done
      return true;
    }
    else if (line.length() == 0) {
      // IE4 on Mac sends an empty line at the end; treat that as the end.
      // Thanks to Daniel Lemire and Henri Tourigny for this fix.
      return true;
    }
 
    // Parse the content-disposition line
    String[] dispInfo = extractDispositionInfo(line);
    String disposition = dispInfo[0];
    String name = dispInfo[1];
    String filename = dispInfo[2];
 
    // Now onto the next line.  This will either be empty 
    // or contain a Content-Type and then an empty line.
    line = in.readLine();
    if (line == null) {
      // No parts left, we're done
      return true;
    }
 
    // Get the content type, or null if none specified
    String contentType = extractContentType(line);
    if (contentType != null) {
      // Eat the empty line
      line = in.readLine();
      if (line == null || line.length() > 0) {  // line should be empty
        throw new 
          IOException("Malformed line after content type: " + line);
      }
    }
    else {
      // Assume a default content type
      contentType = "application/octet-stream";
    }
 
    // Now, finally, we read the content (end after reading the boundary)
    if (filename == null) {
      // This is a parameter, add it to the vector of values
      String value = readParameter(in, boundary);
      if (value.equals("")) {
        value = null;  // treat empty strings like nulls
      }
      Vector existingValues = (Vector)parameters.get(name);
      if (existingValues == null) {
        existingValues = new Vector();
        parameters.put(name, existingValues);
      }
      existingValues.addElement(value);
    }
    else {
      // This is a file
      readAndSaveFile(in, boundary, filename, contentType);
      if (filename.equals(NO_FILE)) {
        files.put(name, new UploadedFile(null, null, null));
      }
      else {
        files.put(name,
          new UploadedFile(dir.toString(), filename, contentType));
      }
    }
    return false;  // there's more to read
  }
 
  /**
   * A utility method that reads a single part of the multipart request 
   * that represents a parameter.  A subclass can override this method 
   * for a better optimized or differently behaved implementation.
   *
   * @param in the stream from which to read the parameter information
   * @param boundary the boundary signifying the end of this part
   * @return the parameter value
   * @exception IOException if there's a problem reading or parsing the 
   * request
   */
  protected String readParameter(MultipartInputStreamHandler in,
                                 String boundary) throws IOException {
    StringBuffer sbuf = new StringBuffer();
    String line;
 
    while ((line = in.readLine()) != null) {
      if (line.startsWith(boundary)) break;
      sbuf.append(line + "\r\n");  // add the \r\n in case there are many lines
    }
 
    if (sbuf.length() == 0) {
      return null;  // nothing read
    }
 
    sbuf.setLength(sbuf.length() - 2);  // cut off the last line's \r\n
    return sbuf.toString();  // no URL decoding needed
  }
 
  /**
   * A utility method that reads a single part of the multipart request 
   * that represents a file, and saves the file to the given directory.
   * A subclass can override this method for a better optimized or 
   * differently behaved implementation.
   *
   * @param in the stream from which to read the file
   * @param boundary the boundary signifying the end of this part
   * @param dir the directory in which to save the uploaded file
   * @param filename the name under which to save the uploaded file
   * @exception IOException if there's a problem reading or parsing the 
   * request
   */
  protected void readAndSaveFile(MultipartInputStreamHandler in,
                                 String boundary,
                                 String filename,
                                 String contentType) throws IOException {
    OutputStream out = null;
    // A filename of NO_FILE means no file was sent, so just read to the
    // next boundary and ignore the empty contents
    if (filename.equals(NO_FILE)) {
      out = new ByteArrayOutputStream();  // write to nowhere
    }
    // A MacBinary file goes through a decoder
    else if (contentType.equals("application/x-macbinary")){
      File f = new File(dir + File.separator + filename);
      out = new MacBinaryDecoderOutputStream(
            new BufferedOutputStream(
            new FileOutputStream(f), 8 * 1024));
    }
    // A real file's contents are written to disk
    else {
      File f = new File(dir + File.separator + filename);
      out = new BufferedOutputStream(new FileOutputStream(f), 8 * 1024);
    }
 
    byte[] bbuf = new byte[100 * 1024];  // 100K
    int result;
    String line;
 
    // ServletInputStream.readLine() has the annoying habit of 
    // adding a \r\n to the end of the last line.  
    // Since we want a byte-for-byte transfer, we have to cut those chars.
    boolean rnflag = false;
    while ((result = in.readLine(bbuf, 0, bbuf.length)) != -1) {
      // Check for boundary
      if (result > 2 && bbuf[0] == '-' && bbuf[1] == '-') { // quick pre-check
        line = new String(bbuf, 0, result, "ISO-8859-1");
        if (line.startsWith(boundary)) break;
      }
      // Are we supposed to write \r\n for the last iteration?
      if (rnflag) {
        out.write('\r'); out.write('\n');
        rnflag = false;
      }
      // Write the buffer, postpone any ending \r\n
      if (result >= 2 && 
          bbuf[result - 2] == '\r' && 
          bbuf[result - 1] == '\n') {
        out.write(bbuf, 0, result - 2);  // skip the last 2 chars
        rnflag = true;  // make a note to write them on the next iteration
      }
      else {
        out.write(bbuf, 0, result);
      }
    }
    out.flush();
    out.close();
  }
 
  // Extracts and returns the boundary token from a line.
  //
  private String extractBoundary(String line) {
    // Use lastIndexOf() because IE 4.01 on Win98 has been known to send the
    // "boundary=" string multiple times.  Thanks to David Wall for this fix.
    int index = line.lastIndexOf("boundary=");
    if (index == -1) {
      return null;
    }
    String boundary = line.substring(index + 9);  // 9 for "boundary="
 
    // The real boundary is always preceeded by an extra "--"
    boundary = "--" + boundary;
 
    return boundary;
  }
 
  // Extracts and returns disposition info from a line, as a String array
  // with elements: disposition, name, filename.  Throws an IOException 
  // if the line is malformatted.
  //
  private String[] extractDispositionInfo(String line) throws IOException {
    // Return the line's data as an array: disposition, name, filename
    String[] retval = new String[3];
 
    // Convert the line to a lowercase string without the ending \r\n
    // Keep the original line for error messages and for variable names.
    String origline = line;
    line = origline.toLowerCase();
 
    // Get the content disposition, should be "form-data"
    int start = line.indexOf("content-disposition: ");
    int end = line.indexOf(";");
    if (start == -1 || end == -1) {
      throw new IOException("Content disposition corrupt: " + origline);
    }
    String disposition = line.substring(start + 21, end);
    if (!disposition.equals("form-data")) {
      throw new IOException("Invalid content disposition: " + disposition);
    }
 
    // Get the field name
    start = line.indexOf("name=\"", end);  // start at last semicolon
    end = line.indexOf("\"", start + 7);   // skip name=\"
    if (start == -1 || end == -1) {
      throw new IOException("Content disposition corrupt: " + origline);
    }
    String name = origline.substring(start + 6, end);
 
    // Get the filename, if given
    String filename = null;
    start = line.indexOf("filename=\"", end + 2);  // start after name
    end = line.indexOf("\"", start + 10);          // skip filename=\"
    if (start != -1 && end != -1) {                // note the !=
      filename = origline.substring(start + 10, end);
      // The filename may contain a full path.  Cut to just the filename.
      int slash =
        Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
      if (slash > -1) {
        filename = filename.substring(slash + 1);  // past last slash
      }
      if (filename.equals("")) filename = NO_FILE; // sanity check
    }
 
    // Return a String array: disposition, name, filename
    retval[0] = disposition;
    retval[1] = name;
    retval[2] = filename;
    return retval;
  }
 
  // Extracts and returns the content type from a line, or null if the
  // line was empty.  Throws an IOException if the line is malformatted.
  //
  private String extractContentType(String line) throws IOException {
    String contentType = null;
 
    // Convert the line to a lowercase string
    String origline = line;
    line = origline.toLowerCase();
 
    // Get the content type, if any
    if (line.startsWith("content-type")) {
      int start = line.indexOf(" ");
      if (start == -1) {
        throw new IOException("Content type corrupt: " + origline);
      }
      contentType = line.substring(start + 1);
    }
    else if (line.length() != 0) {  // no content type, so should be empty
      throw new IOException("Malformed line after disposition: " + origline);
    }
 
    return contentType;
  }
}
 
 
// A class to hold information about an uploaded file.
//
class UploadedFile {
 
  private String dir;
  private String filename;
  private String type;
 
  UploadedFile(String dir, String filename, String type) {
    this.dir = dir;
    this.filename = filename;
    this.type = type;
  }
 
  public String getContentType() {
    return type;
  }
 
  public String getFilesystemName() {
    return filename;
  }
 
  public File getFile() {
    if (dir == null || filename == null) {
      return null;
    }
    else {
      return new File(dir + File.separator + filename);
    }
  }
}
 
 
// A class to aid in reading multipart/form-data from a ServletInputStream.
// It keeps track of how many bytes have been read and detects when the
// Content-Length limit has been reached.  This is necessary since some 
// servlet engines are slow to notice the end of stream.
//
// Mac users: The Mac doesn't like class names which exceed 32 characters
// (including the ".class") so while this class is usable from a JAR 
// anywhere, it won't compile on a Mac.
//
class MultipartInputStreamHandler {
 
  ServletInputStream in;
  int totalExpected;
  int totalRead = 0;
  byte[] buf = new byte[8 * 1024];
 
  public MultipartInputStreamHandler(ServletInputStream in,
                                     int totalExpected) {
    this.in = in;
    this.totalExpected = totalExpected;
  }
 
  // Reads the next line of input.  Returns null to indicate the end
  // of stream.
  //
  public String readLine() throws IOException {
    StringBuffer sbuf = new StringBuffer();
    int result;
    String line;
 
    do {
      result = this.readLine(buf, 0, buf.length);  // this.readLine() does +=
      if (result != -1) {
        sbuf.append(new String(buf, 0, result, "ISO-8859-1"));
      }
    } while (result == buf.length);  // loop only if the buffer was filled
 
    if (sbuf.length() == 0) {
      return null;  // nothing read, must be at the end of stream
    }
 
    sbuf.setLength(sbuf.length() - 2);  // cut off the trailing \r\n
    return sbuf.toString();
  }
 
  // A pass-through to ServletInputStream.readLine() that keeps track
  // of how many bytes have been read and stops reading when the 
  // Content-Length limit has been reached.
  //
  public int readLine(byte b[], int off, int len) throws IOException {
    if (totalRead >= totalExpected) {
      return -1;
    }
    else {
      if (len > (totalExpected - totalRead)) {
        len = totalExpected - totalRead;  // keep from reading off end
      }
      int result = in.readLine(b, off, len);
      if (result > 0) {
        totalRead += result;
      }
      return result;
    }
  }
}
 
 
// Class to filters MacBinary files to normal files on the fly
// Optimized for speed more than readability
class MacBinaryDecoderOutputStream extends FilterOutputStream {
 
  int bytesFiltered = 0;
  int dataForkLength = 0;
 
  public MacBinaryDecoderOutputStream(OutputStream out) {
    super(out);
  }
 
  public void write(int b) throws IOException {
    // Bytes 83 through 86 are a long representing the data fork length
    // Check <= 86 first to short circuit early in the common case
    if (bytesFiltered <= 86 && bytesFiltered >= 83) {
      int leftShift = (86 - bytesFiltered) * 8;
      dataForkLength = dataForkLength | (b & 0xff) << leftShift;
    }
    // Bytes 128 up to (128 + dataForkLength - 1) are the data fork
    else if (bytesFiltered < (128 + dataForkLength) && bytesFiltered >= 128) {
      out.write(b);
    }
    bytesFiltered++;
  }
 
  public void write(byte b[]) throws IOException {
    write(b, 0, b.length);
  }
 
  public void write(byte b[], int off, int len) throws IOException {
    // If the write is for content past the end of the data fork, ignore
    if (bytesFiltered >= (128 + dataForkLength)) {
      bytesFiltered += len;
    }
    // If the write is entirely within the data fork, write it directly
    else if (bytesFiltered >= 128 && 
             (bytesFiltered + len) <= (128 + dataForkLength)) {
      out.write(b, off, len);
      bytesFiltered += len;
    }
    // Otherwise, do the write a byte at a time to get the logic above
    else {
      for (int i = 0 ; i < len ; i++) {
        write(b[off + i]);
      }
    }
  }
}

Open in new window

So, as the comment in the top of that file shows, you need to enumerate through the parts in the MultiPartRequest object, and extract the file out of the relevant part...

Instead of what you are currently doing

After looking at the code, you are passing a folder to the constructor of MultipartRequest.

It looks like the file will be in here, and you can get a handle to it using mpr.getFile()
ok  im not sure what you mean. sorry, could you explain a bit more.
You create a MultipartRequest object here:

        MultipartRequest mpr = new MultipartRequest(req, sFilePrefix + sTempDir);

The second parameter (according to the code you posted) is a temp folder where the files are stored

Have a look, and see...

Then, to get a File object from the mpr, just follow the instructions at the top of the MultipartRequest source code you just posted...

You need the getFile() method
oh thanks alot. one more question though, where do i create this in the multipart file or in the emailaction file i had posted earlier? thanks again for all your help i really do appreciate it.
When you post the form (in the HTML, you have it specified as being a multipart post), the <INPUT TYPE="FILE"> input will get parsed by the MultipartRequest object, and should be available in your server code by calling the mpr.getFile method

This will return you a File object which points to the file in the folder specified by the MultipartRequest object

Assuming the MultipartRequest class you have does its job right ;-)

Good luck with it ;-)

And glad I could help :-)

If you have the javadoc for that class, as I said there will be an example in the top of the doc...  You can see it in the java source file, but it will be easier to read in the javadoc, as it's written in HTML

Tim
>> have resolved this by myself need to close this question

What a joke

They didn't solve this themselves at all, they found the problem through a large amount of hand holding and explanation of the basics of web programming, understanding your tools and frameworks, and the difference between a server machine and the localhost client
Split between me and dejanpazin

He spotted the original issue, and I did the follow-up work