DateFormat problem

Hi,
I have the input date in my csv file as a string and I was able to convert into into the required format which is: "YYYY-MM-DDTHH:MI:SS"
The problem when when my input date is in the format 01/22/2009 it works fine but when I have the date as 1/22/2009 or a 1/3/2009, it fails to transform (i.e., when MM and DD just M and D for single digit months and days).
Can anyone please help me on how can I convert the input string to MM/DD/YYYY before I convert it to the required format.
Thanks and appreciate your help
-Prapoorna

Hi,
     You can use nested substring Xpath functions and concat all these strings to form your standard format. I was facing similar problem to convert date from YYYY/MM/DD 00:00:00 to YYYY-MM-DDThh:mm:ss format.
     I have use the below mentioned code to convert the date format where $date is the input date variable.
<db:P_X_DATE_FROM>
<xsl:value-of select='concat(substring($date,1.0,4.0),"-",substring($date,6.0,2.0),"-",substring($date,9.0,2.0),"T",substring($date,12.0,8.0))'/>
</db:P_X_DATE_FROM>
     I think you have to do the reverse thing here. You have to take two characters for both DD and MM incase of ‘01/22/2009’. In case of ‘1/22/2009’ or ‘11/3/2008’ you should take only one character.
     I think this information can help you.
Thanks & Regards,
Jyotirmoy.

Similar Messages

  • DateFormat problem xsd

    Hi all,
    I have an ESB project in which there is a file adapter. This file adapter reads files from a folder applying this files an xsd.
    In each file, there is a date which can be 22-FEB-2007 or 2-FEB-2007. The problem is the day, which can be a 1 digit number or a 2 digit number.
    In the xsd file, I have defined the date element like this:
    <xsd:element name="FechaFin" type="xsd:dateTime" nxsd:skipMode="before"
    nxsd:skip="20" nxsd:dateFormat="dd-MMM-yyyy hh:mm"
    nxsd:localeLanguage="es" nxsd:style="terminated"
    nxsd:terminatedBy="${eol}">
    </xsd:element>
    So, it works all right when the date in the source file is 22-FEB-2007, but gives an unparseable error when the date in the source file is 2-FEB-2007.
    I tried doing this:
    <xsd:element name="FechaFin" type="xsd:dateTime" nxsd:skipMode="before"
    nxsd:skip="20" nxsd:dateFormat=’"d-MMM-yyyy hh:mm” | “dd-MMM-yyyy hh:mm"’
    nxsd:localeLanguage="es" nxsd:style="terminated"
    nxsd:terminatedBy="${eol}">
    </xsd:element>
    which again gave an unparseable error.
    And also tried this:
    <xsd:element name="FechaIni"
    nxsd:skip="19" nxsd:skipMode="before"
    nxsd:localeLanguage="es" nxsd:style="fixedLength"
    nxsd:length="17">
    <xsd:simpleType>
    <xsd:restriction base="xsd:dateTime">
    <xsd:pattern
    value="([0-3])?[0-9][-][A-Z][A-Z][A-Z][-][0-2][0-2][0-9][0-9]"/>
    </xsd:restriction>
    </xsd:simpleType>
    </xsd:element>
    This works, I mean, the file adapter reads the file and gets the date but the element is a string, so, when i try to save that date in the database, it saves a wrong date. (string saved as date gives a wrong result)
    I also tried reading the date as a string, and after that, converting that string in a dateTime type in the xsl mapping file. But again didn't work. The date gets read as a string ok, and then in the mapping file the result is a blank element.
    Does anybody know how can I solve this problem? I really need help, don't know what else to do...
    Thanks a lot in advance.
    Zaloa

    Hi again,
    I tried to solve the dates problem using a simpleType definition with a union element inside. This way, it would be possible to parse one format or another, right? So this is what I wrote:
    <xsd:element name="FechaIni" type="tipoFecha" nxsd:skip="19"
    nxsd:skipMode="before"
    nxsd:localeLanguage="es" nxsd:style="fixedLength"
    nxsd:length="17">
    </xsd:element>
    <xsd:simpleType name="tipoFecha">
    <xsd:union>
    <xsd:simpleType nxsd:dateFormat="dd-MMM-yyyy hh:mm">
    <xsd:restriction base="xsd:dateTime">
    </xsd:restriction>
    </xsd:simpleType>
    <xsd:simpleType nxsd:dateFormat="d-MMM-yyyy hh:mm">
    <xsd:restriction base="xsd:dateTime">
    </xsd:restriction>
    </xsd:simpleType>
    </xsd:union>
    </xsd:simpleType>
    With this, if the file has 22-FEB-2007 or 2-FEB-2007, is read ok. The problem is that nxsd:dateFormat is not working in the simpleType element.I mean, the date is read as a string.
    Does anybody now how to solve this? Or where can I find nxsd:dateFormat documentation?
    Please, I need help with this. Thanks anyway,
    Zaloa
    Message was edited by:
    Zaloa

  • DateFormat problem in xsd

    Hi all,
    I have an ESB project in which there is a file adapter. This file adapter reads files from a folder applying this files an xsd.
    In each file, there is a date which can be 22-FEB-2007 or 2-FEB-2007. The problem is the day, which can be a 1 digit number or a 2 digit number.
    In the xsd file, I have defined the date element like this:
    <xsd:element name="FechaFin" type="xsd:dateTime" nxsd:skipMode="before"
    nxsd:skip="20" nxsd:dateFormat="dd-MMM-yyyy hh:mm"
    nxsd:localeLanguage="es" nxsd:style="terminated"
    nxsd:terminatedBy="${eol}">
    </xsd:element>
    So, it works all right when the date in the source file is 22-FEB-2007, but gives an unparseable error when the date in the source file is 2-FEB-2007.
    I tried doing this:
    <xsd:element name="FechaFin" type="xsd:dateTime" nxsd:skipMode="before"
    nxsd:skip="20" nxsd:dateFormat=’"d-MMM-yyyy hh:mm” | “dd-MMM-yyyy hh:mm"’
    nxsd:localeLanguage="es" nxsd:style="terminated"
    nxsd:terminatedBy="${eol}">
    </xsd:element>
    which again gave an unparseable error.
    And also tried this:
    <xsd:element name="FechaIni"
    nxsd:skip="19" nxsd:skipMode="before"
    nxsd:localeLanguage="es" nxsd:style="fixedLength"
    nxsd:length="17">
    <xsd:simpleType>
    <xsd:restriction base="xsd:dateTime">
    <xsd:pattern
    value="([0-3])?[0-9][-][A-Z][A-Z][A-Z][-][0-2][0-2][0-9][0-9]"/>
    </xsd:restriction>
    </xsd:simpleType>
    </xsd:element>
    This works, I mean, the file adapter reads the file and gets the date but the element is a string, so, when i try to save that date in the database, it saves a wrong date. (string saved as date gives a wrong result)
    I also tried reading the date as a string, and after that, converting that string in a dateTime type in the xsl mapping file. But again didn't work. The date gets read as a string ok, and then in the mapping file the result is a blank element.
    Does anybody know how can I solve this problem? I really need help, don't know what else to do...
    Thanks a lot in advance.
    Zaloa

    Hi again,
    I tried to solve the dates problem using a simpleType definition with a union element inside. This way, it would be possible to parse one format or another, right? So this is what I wrote:
    <xsd:element name="FechaIni" type="tipoFecha" nxsd:skip="19"
    nxsd:skipMode="before"
    nxsd:localeLanguage="es" nxsd:style="fixedLength"
    nxsd:length="17">
    </xsd:element>
    <xsd:simpleType name="tipoFecha">
    <xsd:union>
    <xsd:simpleType nxsd:dateFormat="dd-MMM-yyyy hh:mm">
    <xsd:restriction base="xsd:dateTime">
    </xsd:restriction>
    </xsd:simpleType>
    <xsd:simpleType nxsd:dateFormat="d-MMM-yyyy hh:mm">
    <xsd:restriction base="xsd:dateTime">
    </xsd:restriction>
    </xsd:simpleType>
    </xsd:union>
    </xsd:simpleType>
    With this, if the file has 22-FEB-2007 or 2-FEB-2007, is read ok. The problem is that nxsd:dateFormat is not working in the simpleType element. I mean, the date is read as a string.
    Does anybody now how to solve this? Or where can I find nxsd:dateFormat documentation?
    Please, I need help with this. Thanks anyway,
    Zaloa
    Message was edited by:
    zaloa

  • DateFormat  Problem by "recycling" legacy systems

    Folks,
    Congratulations to the Jheadstart development team!
    Now I am traing to "recycle" a legacy system and have problems with the German DateFormat 01.03.2005 and the expected dd-MMM-yyyy DateFormat...
    What should I do?
    Regards
    Boris

    Boris,
    When you generate an application with JHeadstart, you can specify the desired date format in the Application Structure File, at Service level.
    See also the JHeadstart Developer's Guide, Chapter 5, and look for date format. It tells you how to specify different formats for different languages.
    kind regards,
    Sandra Muller
    JHeadstart Team
    Oracle Consulting

  • Dateformat Problems

    I'm getting a wierd problem with dateformat, coldfusion
    version 6,1. I just installed the updater as well, but not sure if
    I now need to run it, or how to run it. There were mentions of this
    problem in the updater fixes, so it might well be down to that.
    If I need to run the updater can someone tell me how?
    Here's the issue anyway
    Can anyone tell me why this dateformat string works
    #DATEFORMAT("Mon, 23 Oct 2006 07:04 CDT", "m/d/")#
    I get 10/23
    While this one
    #DATEFORMAT("Wed, 18 Oct 2006 07:40 CDT", "m/d/")#
    gives me this java error
    Parameter validation error for function DATEFORMAT.
    The value of the parameter 1, which is currently "Wed, 18 Oct
    2006 07:40 CDT", must be a class java.util.Date value.
    I'm ouputting some dates from an rss feed and some dates
    work, and some don't, while they are all in the same format?
    Any help will be greatly appreciated.

    > The value of the parameter 1, which is currently "Wed,
    18 Oct 2006 07:40 CDT",
    Right. "Wed, 18 Oct 2006 07:40 CDT" is a string...
    > must be a class java.util.Date value.
    ... not a java.util.Date. So that explains the error.
    Although the error
    pretty much did that too ;-)
    As per
    http://livedocs.macromedia.com/coldfusion/7/htmldocs/00000441.htm,
    dateFormat() does not take a string as its first argument, it
    takes a date.
    I suggest you attempt to parse your string with
    parseDateTime():
    http://livedocs.macromedia.com/coldfusion/7/htmldocs/00000594.htm
    Then you can use the result in dateFormat().
    Adam

  • ThinGraph timezone / dateFormat problem

    Hey,
    We're using BI Beans to display history statistics concerning security attacks/issues per day. Normally, the X-axis looks like this (dots act like spaces):
    18....21....24....27....30....02....05....08....11....14
    Oct 10............................Nov............................
    A customer of ours complained last week about his graph labels on the X-axis to be displayed incorrectly. They sent a screenshot displaying the labels like this (*vertically* aligned underneath the X-axis, dots act like spaces):
    2010-....2010-....2010-....2010-....2010-....2010-....
    We were thinking this had to do with the daylight saving time switch of last week, so we started to investigate why especially this customer had problems and the others didn't. Then we saw that the Java timezone was set to Australia/Sydney instead of our software's default Etc/GMT. That seemed to be causing the problem described here. It appears that the Tasmanian timezone is the only Australian Timezone that shows the X-axis labels correctly.
    We currently changed the customer's timezone to the one above, but what could be causing the dateFormat to be displayed incorrectly? It seems the Date objects are just printed out as 2010-10-18 hh:ss (only the '2010-' part is visible on the graph), instead of actually formatting them.
    I already did a search on Google and this forum, but I can't seem to find any thread concerning the problem we have.
    The version of the library we're using (and this in a Java 1.5 environment):
    ComponentBuildVersion=3.2.2.0.24.2
    ComponentBuildMode=nondebug
    Copyright=Copyright ¬ 2001, 2005, Oracle. All rights reserved.
    ComponentNumber=10.1.2.67.0
    ReleaseDescription=BI Beans 10.1.2 Production Release
    We're not actually defining a custom dateFormat in our XML configuration. We only use the predefined Oracle constants, which have always worked up until now, for the default timezone:
    <Graph version="3.2.0.22" name="Graph" ... timeAxisTimeFormat="NONE" timeAxisDayFormat="AUTOMATIC" timeAxisMonthFormat="MONTH_SHORT" timeAxisYearFormat="YEAR_SHORT" graphType="LINE_VERT_ABS">
    Anyone else had this problem?
    Thanks and kind regards,
    Jeroen

    If you're in the states that value is probably correct. What you are looking at is the date and time "01 Jan 70 00:00:00 GMT" translated into your own time zone.
    That's what 0 epoch time means.
    If you want "now" do
    Timestamp = new Timestamp(System.currentTimeMillis());

  • A dateformat problem!

    A date may be represented in the form : yyddd.
    For example, a date 01035 would represent 4 February, 2001, while 99365 would represent 31 December 1999.
    how can i write a Java prog which takes an integer parameter in the above form and returns the date as a String in the ddmmyy form?
    can any one pls give me a solution for that?

    A date may be represented in the form : yyddd.
    For example, a date 01035 would represent 4 February,
    2001, while 99365 would represent 31 December 1999.
    how can i write a Java prog which takes an integer
    parameter in the above form and returns the date as a
    String in the ddmmyy form?
    can any one pls give me a solution for that?Check out the SimpleDateFormat Class
    http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html
    An input format of yyDDD and an output format of ddMMyy seems reasonable
    Good Luck
    Lee

  • Problem in parsing date having Chinese character when dateformat is 'MMM'

    I m calling jsp page using following code:
    var ratewin = window.showModalDialog("Details.jsp?startDate="+startDate,window, dlgSettings );
    In my javascript when checked by adding alerts I m getting correct values before passing to jsp,
    alert("startDate:"+startDate);
    In jsp page my code is like below:
    String startDate = request.getParameter("startDate");     
    but here I m getting garbage values in month when the dateformat is 'MMM', because of which date parsing is failing.
    This happens only Chinese character.
    following 2 encoding are already in my jsp page,can anyone help to find solution?
         <%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
         <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"/>
    I have even tried to read it as UTF-8 but still that's failing.

    This is my actual code
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    public class TestingDate {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              String dateFormat="EEEE, MMM d h:mm a";
              Date test=new Date(2007,0,19, 19, 31);
              System.out.println(" original date is "+test);
              String stringResult=DateToString(test,dateFormat);
              System.out.println("Date to string is "+stringResult);
              Date dateResult=stringToDate(stringResult,dateFormat);
              System.out.println(" String to date is "+dateResult);
              String stringResult2=DateToString(dateResult,dateFormat);
              System.out.println(" Date to string  is "+stringResult2);
    public static String DateToString(Date test, String dateFormat) {
             String result = null;
             try {
                  DateFormat myDateFormat = new SimpleDateFormat(dateFormat);
                     result = myDateFormat.format(test);
                     //System.out.println(" reslut date is "+result);
              } catch (Exception e) {
                   System.out.println(" Exception is "+e);
              return result;
    public static Date stringToDate(String strDate,String dateFormat1){
         Date result1=null;
         try {
              DateFormat myDateFormat = new SimpleDateFormat(dateFormat1);
              result1=myDateFormat.parse(strDate);
         catch(Exception e){
              System.out.println(" exception is "+e);
         return result1;
    }I am facing problem in getting the actual date. Please suggest the solution.

  • DateFormat parse problem

    Hello all,
    I'm trying to parse a simple date, using java version 1.4.12, but for some reason an exception is thrown. Here is the code:
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
    Date date = format.parse("Nov 4, 2003 8:14 PM");
    Can anyone help?
    Thanks

    I always use SimpleDateFormat. One thing might be that the parsing pattern returned for your default locale doesn't match your input String.

  • DateFormat parsing problem

    Hi,
    A little limitation I have discovered in DateFormat.
    I'm using SimpleDateFormat, and I supply the format "HH:mm"
    I expect the DateFormat parsing to fail when calling parse() for Strings such as "12:13:13", since in the format there is no seconds-resolution.
    Instead, the parsing runs without exception and returns the time 12:13:00 (The seconds are truncated).
    Is thyere a way to make the DateFormat to fail and throw an exception in such a scenario?
    Thanks,
    Miki

    I doubt it. Also, if you enter an invalid date such as Dec 34 2004, it may (or may not) return an invalid date such as something like Aug 23 1834 rather than throw an exception. I think its best to pass the string to a validate format class that you custom write to check the format (such as xx:xx:xx), and also a validate date class (after passing the validate format) that you custom write to see if its a valid date (such as Dec 34, or if Feb 29, 2003 really is a leap year).
    Actually, I dont even use the classes such as DateFormat class directly in my code. Instead, I have a custom class with a host of static functions (containing DateFormat) to do all kinds of date/timestamp/string convertions to deal with dates. My code uses that class instead.

  • Dateformat expire problem

    here is the code i have but if i take this out of the page it
    works fine... for some reason it does not like the +90... where am
    i going wrong?
    please help

    I assume you are trying to add 90 days to that date? If you
    are, try this:
    dateFormat("10/07/2008"+90,"mm/dd/yyyy") Basically, add the
    double quotes around the date.
    I would suggest though that you use the dateAdd() function to
    do this. Something like:
    dateAdd("d",90,"10/07/2008")
    Hope this helps!

  • Problems with DateFormat

    All,
    I am using a DateFormat to format TimeStamps to useful strings. I am getting some rather unexpected results in the form of extra leading zeros.
    For example,
    1) 03/07/2002 14:0043:51PM
    2) 03/07/2002 0014:43:51PM
    3) 0003/07/2002 14:0043:51PM
    4) 03/0007/2002 14:43:51PM
    Any ideas?
    -jonathan

    I have seen reports about the DateFormat class giving erroneous results when it's used to create TimeStamps for log files, this could be a bug -- you might want to check the bug database to see if it's been fixed and at what revision number when it was fixed. In the meantime, you might want to format the date yourself with something like this (it might even be faster)
    import java.util.*;
    class DateFormat {
       static Calendar c=Calendar.getInstance(TimeZone.getDefault(),Locale.getDefault());
       public static String Now () {
          c.setTime(new Date(System.currentTimeMillis()));
          int hour=c.get(Calendar.HOUR_OF_DAY);
          String AMPM=" AM";
          if (hour>11) AMPM=" PM";
          return i2s(c.get(Calendar.MONTH),2) + "/"+
                 i2s(c.get(Calendar.DATE),2) + "/"+
                 i2s(c.get(Calendar.YEAR),4) + " "+
                 i2s(hour,2) + ":"+
                 i2s(c.get(Calendar.MINUTE),2) + ":"+
                 i2s(c.get(Calendar.SECOND),2)+AMPM;
       private static String i2s(int in, int len) {
          String tmp=""+in;
          if (tmp.length()>len) return tmp.substring(tmp.length()-len);
          while (tmp.length()<len) tmp="0"+tmp;
          return tmp;
       public static void main(String[] args) {
          System.out.println(Now());
    }V.V.

  • Problem with DateFormat.parse

    hi,
    I'm working using Java 1.5.
    i'm using SimpleDateFormat to parse date strings. My program has the following piece of code:
    Class DateConverter {
    SimpleDateFormat m_sdate = null ;
    public DateConverter() {
    this.m_sdate = new SimpleDateFormat("yyyyMMdd") ;
    public Date to_date(String dstr) {
    return this.m_sdate.parse(dstr) ;
    The date parsing works fine as long as I give dates upto "00010101" but throws java.text.ParseException for the value "00001231". I was just eager to know whether 00010101 is the least date that can be parsed???
    Thanks,
    Venkatesh

    I don't get a ParseException with your code; if there is an earliest date that can be parsed it's not 1/1/1.fmt = new SimpleDateFormat("yyyy/MM/dd");
    new SimpleDateFormat("dd.MM.y G").format(fmt.parse("0/12/31"));
    output: <31.12.01 BC>

  • Problem with ENCTYPE='multipart/form-data'

    In my program I want to upload a file along with other details.
    I've dowloaded org.apache.commons.fileupload.* jar files and everything works fine only if I give
    <INPUT TYPE='file' NAME='file1'>
    i.e the file is uploaded
    But if I add any other field it becomes blank
    Title : <INPUT id=text1 maxlength="30" name=GHN1 >
    the value of GHN1 becomes blank. what cud be the problem.
    Here is my program
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,java.text.SimpleDateFormat.*,java.text.ParseException.*,java.text.*,java.text.DateFormat.*,java.util.*,java.util.Date.*,com.gh.db.*,org.apache.commons.fileupload.*,org.apache.commons.fileupload.servlet.ServletFileUpload,org.apache.commons.fileupload.disk.DiskFileItemFactory,org.apache.commons.io.FilenameUtils,java.io.*,java.io.File,java.lang.Exception" errorPage="Error.jsp" %>
    <%
    String TACm1="";
    String TASid,Nme="",Cm2="",GHN1="",GHN2="",GHN3="",Sid="";
    TACm1=((request.getParameter("TAIdCombo"))!=null?(request.getParameter("TAIdCombo")):"");
    DBconnection TApool = DBconnection.getInstance();
    Connection con2 = TApool.getConnection();
    con2.setAutoCommit(false);
    Statement TAst1 = con2.createStatement();
    ResultSet TArs1 = null,rs2=null,rs1=null;
    Cm2=((request.getParameter("TMIdCombo2"))!=null?(request.getParameter("TMIdCombo2")):"");
    java.util.Date d1;
    java.sql.Date d2;
    SimpleDateFormat format=new SimpleDateFormat("dd/MM/yyyy");
    %>
    <html>
    <head>
    <TITLE>Guest Houses of DOS</TITLE>
    </head>
    <%@ include file="StdValidations.js" %>
    <%@ page buffer="1094kb"%>
    <script Language="JavaScript">
    </script>
    <body onload="window.history.forward(1);">
    <FORM ENCTYPE='multipart/form-data' name="GHInfoDetails1"
         method='POST' action="GHInfoDetails1.jsp">'<br><br><br>
    <center>
    <%      
         String LoginName= "";
         String Name= "";
         String SectionName= "";
         try
              LoginName = session.getAttribute("LoginName").toString();
              Name = session.getAttribute("Name").toString();
              SectionName = session.getAttribute("SectionName").toString();     
         catch(NullPointerException npe)
              %>
              <jsp:forward page="LoginHere.jsp" >
              <jsp:param name="SessionMode" value="Session Expired try again to log on" />
              </jsp:forward>
              <%
    %>
    <%
              GHN1 = request.getParameter("GHN1");
              if (GHN1 == null) GHN1 = "";
              GHN2 = request.getParameter("GHN2");
              if (GHN2 == null) GHN2 = "";
              GHN3 = request.getParameter("GHN3");
              if (GHN3 == null) GHN3 = "";
    %>
         <table width="100%" bgcolor="#F7EDF7">
              <tr >
              <td align="center">
                   <img src="Images/Title2.gif">
              </td>
              </tr>
              </table>
              <table width="100%" bgcolor="#F7EDF7">
              <tr>
              <td >
                   <b><font face="Times New Roman, Times, serif" color="#402180" size="+1">Logged in as:  <%= Name %></font></b>
              </td>
              <td >
                   <b><font face="Comic Sans MS" color="#402180" size="+1">Other Details of Guest House</font></b>
              </td>
              <td align="right">
                   <b><font face="Times New Roman, Times, serif" color="#402180" size="+1">Logout</font></b>
              </td>
              </tr>
         </table>
              <table width="100%" bgcolor="#B6C7E5" border="1">
              <tr>
              <td valign="top">
              </br>
              <p><img src="Images/bullet.gif"><b><font face="Times New Roman, Times, serif" color="#402180" size="+0">Defining Guest House Information</font></b></p>
              <p><img src="Images/bullet.gif"><b><font face="Times New Roman, Times, serif" color="#402180" size="+0">Cancelling Guest House Information</font></b></p>
              </td>
              <td align="left"></br>
                   <table width="100%" bgcolor="#B6C7E5">
                   <tr>
                                  <td width="60%" align="right"></br>
                                  <P >Category :  <select onChange="TAMAssignCombo2();" name="TMIdCombo2" style="WIDTH: 120px" >
                                                                <option value="-">Select</option>
                                                                <% try
                                                                     PreparedStatement ps6=con2.prepareStatement("Select CategoryName from TableCategory order by CategoryName");
                                                                     rs2 = ps6.executeQuery();     
                                                                     while(rs2.next())
                                                                          Sid=rs2.getString(1);
                                                                               %>
                                                                                    <option value = "<% out.write(Sid); %>"><% out.write(Sid); %></option>
                                                                               <%
                                                                catch(Exception e)
                                                                     e.printStackTrace();
                                                                %>
                                                                     <Script>alert("Exception Occured : <%= e %>");</Script>
                                                                <%
                                                                %>
                                                 </select>
                                  </P>
                   </td>
                   </tr>
                   <tr align="center">
                   <td>
                        Title :     <INPUT id=text1 maxlength="30" name=GHN1 onKeyPress="if (((event.keyCode > 32) && (event.keyCode < 48)) || ((event.keyCode > 57) && (event.keyCode < 65)) || ((event.keyCode > 90) && (event.keyCode < 97))) event.returnValue=false;">
                   </td>
                   </tr>
                   <tr align="center">
                   <td>
                        Reference No :     <INPUT id=text1 maxlength="100" name=GHN2 onKeyPress="if (((event.keyCode > 32) && (event.keyCode < 48)) || ((event.keyCode > 57) && (event.keyCode < 65)) || ((event.keyCode > 90) && (event.keyCode < 97))) event.returnValue=false;">
                   </td>
                   </tr>
                   <tr align="center">
                   <td>
                        Date :     <INPUT id=text1 maxlength="30" name=GHN3 >
                   </td>
                   </tr>
                   <tr align="center">
                   <td >
                   </br>
                                           File Name:        <INPUT TYPE='file' NAME='file1'></p>
                   </td></tr>
                   <tr>
                   <td align="center">
                                                         <INPUT TYPE='submit' VALUE='Submit' ></br>
                   <b><font face="Times New Roman, Times, serif" color="#402180" size="3">(Information like distance,direction from central places such as Railway station, Airport, Bus Terminal....etc can be added in a file of windows format(such as word, pdf...) and can be uploaded through this screen. This will be displayed for the ISRO Guests.</font></b>)
                   </td>
                   </tr>
                   </table>
              </td>
              </tr>
              </table>
              <table width="100%" bgcolor="#B6C7E5">
              <tr>
              <td align="center">
                   </br>
                   <img src="Images/Home.jpg">
              </td>
              </tr>
              </table>     
    <% if (ServletFileUpload.isMultipartContent(request))
         GHN1 = request.getParameter("GHN1");
         if (GHN1 == null) GHN1 = "";
         GHN2 = request.getParameter("GHN2");
         if (GHN2 == null) GHN2 = "";
         GHN3 = request.getParameter("GHN3");
         if (GHN3 == null) GHN3 = "";
         DiskFileUpload fileUpload = new DiskFileUpload();
         List list = null;
         try
              list = fileUpload.parseRequest(request);
         catch(FileUploadException ex)
              throw new ServletException("Wrapped",ex);
         Iterator iter = list.iterator();
         while (iter.hasNext())
         FileItem item = (FileItem) iter.next();
         if (!item.isFormField())
              File itemFile = new File(item.getName());
              Nme=itemFile.getName();
              %>
              <%
              File destDir = new File(getServletContext().getRealPath("/")
                                       +"stored");
         if(!destDir.exists())
              destDir.mkdirs();
         File destFile = new File(getServletContext().getRealPath("/")
                                       +"stored"+File.separator+itemFile.getName());
         try
              item.write(destFile);
         catch(Exception ex)
              //throw new ServletException("Wrapped",ex);
         TACm1=SectionName;
         %><script>alert("<%=GHN1%>");</script><%
         try
              PreparedStatement ps26=     con2.prepareStatement("select CategoryNo from TableCategory where CategoryName=?");
              ps26.setString(1,Cm2);
              rs1=ps26.executeQuery();
              while (rs1.next())
                   PreparedStatement ps16=con2.prepareStatement("inset into TableMetaData (CategoryNo,Title,RefernceNo,Date,FileName) values(?,?,?,?,?)");
                   ps16.setString(1,rs1.getString(1));
                   ps16.setString(2,GHN1);
                   ps16.setString(3,GHN2);
                   d1=format.parse(GHN3);
                   d2=new java.sql.Date(d1.getTime());     
                   ps16.setDate(4,d2);
                   ps16.setString(5,Nme);
                   int NoOfRows=ps16.executeUpdate();
                   con2.commit();
         catch(Exception e)
              e.printStackTrace();
         %>
                             <script> alert("Error : <%= e %>"); </script>
         <%
    %>
    <%
              if (TAst1 != null) TAst1.close();
                                  if (con2 != null)
                                       con2.rollback();
                                       con2.setAutoCommit(true);
                                       TApool.returnConnection(con2);
              %>
    <input name="HomePage" type="hidden">
    </form>
    </body>
    </html>

    This article is worth reading: http://balusc.blogspot.com/2007/11/multipartfilter.html

  • Problem with jsp and controller

    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%>
    <%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
    <%@ page import='com.uk.nhs.training.data.ActivityMatrix'%>
    <SCRIPT language="JavaScript" type="text/javascript">
    function bookActivity()
    if (document.bookActivityController.activitySelect.selectedIndex == 0)
    alert("Please Select Activity");
    else if (document.bookActivityController.trainerId.selectedIndex == 0)
    alert ( "Please Select Trainer");
    else if(document.bookActivityController.fromDate.value=="")
    alert("Please supply the Start Date of Activity")
    else
    validateForExistingCourses();
    function validateForExistingCourses()
    flag="wait";
    var trainerId=document.getElementById("trainerId").value;
    var fromDate=document.getElementById("fromDate").value;
    var toDate=document.getElementById("toDate").value;
    var activityId=document.getElementById("activitySelect").value;
    url="ajaxList.htm?actionType=checkBookedCoursesActivities&trainerId="+trainerId+"&fromDate="+fromDate+"&toDate="+toDate+"&activitySelect="+activityId;
    what = "checkForPreBookedCoursesActivities(req.responseXML)";
    doCallback(null);
    function checkForPreBookedCoursesActivities(theXmlResponse)
    // alert("in here in checking prebookedCourses");
    if(theXmlResponse != null)
         var isActivityExisting = theXmlResponse.getElementsByTagName('existingActivity')[0].text;
         var isCourseExisting = theXmlResponse.getElementsByTagName('existingbookedcourse')[0].text;     
              if(isActivityExisting=="Y")
              alert("Activity You are trying to book for Trainer already exists");
              return false;
              else if(isCourseExisting=="Y")
              if(confirm('Conflict Message. The dates choosen conflict with a current booking. Do you want to override'))
    window.open("/training1.1/secure/prebookedEvents.htm","clientwindow",'StatusBar', 'toolbar=yes,resizable=yes,scrollbars=yes,width=500,height=400,left=0,top=0');
    return false;
    else
    document.bookActivityController.action="/training1.1/secure/bookActivityTrainer.htm?actionType=submitForm";
    document.bookActivityController.submit();
    function goHomePage()
         window.location="/training1.1/secure/welcome.htm";
    function showHideAmPm(divId)
    if(document.bookActivityController.halfday.checked==true)
    showDiv(divId);
    else
    hideDiv(divId);
    function showDiv(divId)
    var item = document.getElementById(divId);
    alert("show item"+item);
    if (item)
    item.className='unhidden';
    function hideDiv(divId)
    var item = document.getElementById(divId);
    alert("unhide item"+item);
    if (item)
    item.className='hidden';
    function getActivitiesPm()
    if(document.bookActivityController.am.checked==true)
    document.bookActivityController.pm.checked=false;
    flag="wait";
         url="ajaxList.htm?actionType=activities&keyword=PM";
         what = "setActivities(req.responseXML)";
         doCallback(null);
         document.bookActivityController.activityTimeSelect.value="halfday";
         document.bookActivityController.activityTimeSubType.value="pm";
         // alert("subType"+document.bookActivityController.activityTimeSubType.value);
    function getActivitiesAm()
    if(document.bookActivityController.pm.checked==true)
    document.bookActivityController.am.checked=false;
    flag="wait";
         url="ajaxList.htm?actionType=activities&keyword=AM";
         what = "setActivities(req.responseXML)";
         doCallback(null);
         document.bookActivityController.activityTimeSelect.value="halfday";
         document.bookActivityController.activityTimeSubType.value="pm";
    function getSingleDayActivities()
    if(document.bookActivityController.singleday.checked==true)
    document.bookActivityController.moredays.checked=false;
    document.bookActivityController.halfday.checked=false;
    hideDiv('partofhalfday');
    document.bookActivityController.activityTimeSelect.value="fullday";
    flag="wait";
         url="ajaxList.htm?actionType=activities&keyword=FullDay";
         what = "setActivities(req.responseXML)";
         doCallback(null);
    else
    hideDiv('activitySelect');
    function getMoreDaysActivities()
    alert();
    if(document.bookActivityController.moredays.checked==true)
    document.bookActivityController.singleday.checked=false;
    document.bookActivityController.halfday.checked=false;
    hideDiv('partofhalfday');
    document.bookActivityController.activityTimeSelect.value="moredays";
    flag="wait";
         url="ajaxList.htm?actionType=activities&keyword=FullDay";
         what = "setActivities(req.responseXML)";
         doCallback(null);
    else
    hideDiv('activitySelect');
    showDiv('dateTo');
    function setActivities(theXmlResponse)
              //start filling the Venues Select boxes now
              if(theXmlResponse != null)
                   var coursesBox=document.getElementById("activitySelect");
                   coursesBox.options.length=0;
                   var activityElementsLength=theXmlResponse.getElementsByTagName('activity').length;     
                   var activityElementsArray=theXmlResponse.getElementsByTagName('activity');
                   //alert("length"+activityElementsLength+activityElementsArray);                              
              for(x = 0; x < activityElementsLength; x++)
                        //coursesBox.options[coursesBox.options.length] = new Option(coursesElementsArray[x].firstChild.text, coursesElementsArray[x].lastChild.text);
                        var optn = document.createElement("OPTION");
                   optn.text = activityElementsArray[x].firstChild.text;
    optn.value = activityElementsArray[x].lastChild.text;
    coursesBox.options.add(optn);
         if (activityElementsLength>0)
                   showDiv('activityTD');
              flag="release";
    </script>
    <div id="content"><!-- Top story -->
    <div id="topstory" class="box">
    <div id="topstory-img"></div>
    <!-- /topstory-img -->
    <div id="topstory-desc">
    <div id="topstory-title"><strong>BOOK Activity</strong></div>
    <!-- /topstory-title -->
    <div id="topstory-desc-in"></div>
    <!-- /topstory-desc-in --></div>
    <!-- /topstory-desc --></div>
    <!-- /topstory -->
    <div id="bodycontent">
    <% int errorCount=0; %>          
              <spring:bind path="bookactivityevent.*">
              <c:forEach items="${status.errorMessages}" var="error">
                        <B><font color="red">Error: <c:out value="${error}"/></font><B/>
                        <% errorCount++; %>
              </c:forEach>
              </spring:bind>
    <form method="post" name="bookActivityController" action="<c:url value="/secure/bookActivityTrainer.htm"/>">
    <table align="right" width="50%" border=0>
    <input type="hidden" name="activityTimeSelect"/>
    <input type="hidden" name="activityTimeSubType"/>
    <tr>
    <td align="left">
    <INPUT TYPE="checkbox" NAME="halfday" onclick="showHideAmPm('partofhalfday')">Half Day    
    <div align="left "id="partofhalfday" class="hidden">
    <INPUT TYPE="RADIO" NAME="am" onClick="getActivitiesAm()" value="am">AM <INPUT TYPE="RADIO" NAME="pm" onClick="getActivitiesPm()">PM <BR>
    </div>
    </td>
    </tr>
    <tr><td><INPUT TYPE="checkbox" NAME="singleday" onClick="getSingleDayActivities()"> Single Day</td>
    </tr>
    <tr>
    <td><INPUT TYPE="checkbox" NAME="moredays" onClick="getMoreDaysActivities()"> More Days</td>
    </tr>
         <tr>
              <td align="left" id="activityTD">Activity :
              <c:set var="activityMap" value=${requestScope.activityMap}/>
         <c:choose>
                        <c:when test="${activityMap = null}"
         <spring:bind path="bookactivityevent.userSuppliedActivity.activity.activityId">
              <select name="activitySelect" id="activitySelect" size="1"
                   STYLE="width: 150px">
                   <option value="Choose Activity" default>Choose Activity</option>
              </select>
              </spring:bind>
              </c:when>
              <c:otherwise>      
              <spring:bind path="bookactivityevent.userSuppliedActivity.activity.activityId">
              <select name="activitySelect" id="activitySelect"
                   size="1" STYLE="width: 150px">
                   <option value="" default>Choose Activity</option>
                   <c:forEach var="activity" items="${activityMap}" varStatus="a">
                        <c:choose>
                             <c:when
                                  test="${(bookactivityevent !=null) && (bookactivityevent.userSuppliedActivity.activity.activityId == activity.activityId)}">
                                  <option value="<c:out value="${activity.activityId}"/>" selected><c:out
                                       value="${activity.activityId}" /></option>
                             </c:when>
                             <c:otherwise>
                             <option value="<c:out value="${activity.activityId}"/>"><c:out
                                       value="${activity.activity}"/>
                             </c:otherwise>
                        </c:choose>
                   </c:forEach>
              </select>
         </spring:bind>
         </c:otherwise>
         </c:choose>
         </td>
    </tr>
         <tr>
              <td align="left">Trainer:
              <spring:bind path="bookactivityevent.userSuppliedActivity.trainer.trainerId">
              <select name="trainerId" id="trainerId"
                   size="1" STYLE="width: 150px">
                   <option value="" default>Choose Trainer</option>
                   <c:forEach var="trainer" items="${trainers}" varStatus="a">
                        <c:choose>
                             <c:when
                                  test="${(bookactivityevent !=null) && (bookactivityevent.userSuppliedActivity.trainer.trainerId == trainer.trainerId)}">
                                  <option value="<c:out value="${trainer.trainerId}"/>" selected>
                                  <c:out value="${trainer.firstName}"/>&nbsp<c:out
                                       value="${trainer.surName}" /></option>
                             </c:when>
                             <c:otherwise>
                                  <option value="<c:out value="${trainer.trainerId}"/>"><c:out
                                       value="${trainer.firstName}"/>&nbsp<c:out
                                       value="${trainer.surName}" /></option>
                             </c:otherwise>
                        </c:choose>
                   </c:forEach>
              </select>
         </spring:bind>     
              </td>
         </tr>
         <tr>
              <td align="left" id="dateFrom">From Date
              <spring:bind path="bookactivityevent.userSuppliedActivity.dateFrom">
              <input type="text" name="dateFrom" value=""/>
              </spring:bind>
              <img
                   src="../design/cal.gif" width="16" height="16" border="0"
                   alt="Click Here to Pick up the date"></td>
         </tr>
         <tr>
              <td align="left" id="dateTo" class="hidden">To Date
              <spring:bind path="bookactivityevent.userSuppliedActivity.dateTo">
              <input type="text" name="dateTo" value=""/>
              </spring:bind>
              <img
                   src="../design/cal.gif" width="16" height="16" border="0"
                   alt="Click Here to Pick up the date"></td>
         </tr>
         <tr>
              <td align="left" colspan="2"><input type="submit" name="_target1" value="BookActivity"/></td>
                   <c:if test="${(bookactivityevent != null) && (not empty bookactivityevent.conflictBookings)}">
    <td align="left" colspan="2"><input type="submit" name="_target2" value="OverRideBookings"/></td>
    </c:if>
              <td align="left" colspan="2"><input type="button" name="Cancel"
                   value="Cancel" onClick="goHomePage();" /></td>
         </tr>
    </table>
    </form>
    </div>
    <hr class="noscreen"/>
    <div class="content-padding"></div>
    <script language="JavaScript">
         var cal1 = new calendar1(document.bookActivityController.elements['dateFrom']);
         cal1.year_scroll = true;
         cal1.time_comp = false;
    var cal2 = new calendar1(document.bookActivityController.elements['dateTo']);
         cal2.year_scroll = true;
         cal2.time_comp = false;
    </script></div>
    <!-- /content -->
    package com.uk.nhs.training.controller;
    import java.beans.PropertyEditorSupport;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.swing.text.html.HTMLDocument;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.util.StringUtils;
    import org.springframework.validation.BindException;
    import org.springframework.validation.Errors;
    import org.springframework.validation.ValidationUtils;
    import org.springframework.web.bind.ServletRequestDataBinder;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.AbstractWizardFormController;
    import org.springframework.web.servlet.view.RedirectView;
    import com.uk.nhs.training.contractUtility.ContractHtmlReader;
    import com.uk.nhs.training.data.Activity;
    import com.uk.nhs.training.data.ActivityMatrix;
    import com.uk.nhs.training.data.BookActivityEvent;
    import com.uk.nhs.training.data.Booking;
    import com.uk.nhs.training.data.BookingDetails;
    import com.uk.nhs.training.data.Client;
    import com.uk.nhs.training.data.Course;
    import com.uk.nhs.training.data.Trainer;
    import com.uk.nhs.training.data.Venue;
    import com.uk.nhs.training.data.ActivityTimeConstants;
    import com.uk.nhs.training.service.ActivityMatrixService;
    import com.uk.nhs.training.service.ActivityService;
    import com.uk.nhs.training.service.BookingDetailsService;
    import com.uk.nhs.training.service.BookingService;
    import com.uk.nhs.training.service.ClientService;
    import com.uk.nhs.training.service.CourseService;
    import com.uk.nhs.training.service.TrainersService;
    import com.uk.nhs.training.service.VenueService;
    public class BookActivityController extends AbstractWizardFormController {
         protected final Log logger = LogFactory.getLog(getClass());
         private BookingService bookingFacade;
         private BookingDetailsService bookingDetailsFacade;
         private CourseService courseFacade;
         private VenueService venueFacade;
         private ClientService clientFacade;
         private ActivityMatrixService activityMatrixFacade;
         private ActivityService activityFacade;
         private TrainersService trainersFacade;
         private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
         public BookActivityController() {
              setCommandClass(BookActivityEvent.class);
         setCommandName("bookactivityevent");
         setBindOnNewForm(true);
         protected Object formBackingObject(HttpServletRequest request)
                   throws Exception {
              BookActivityEvent bookActivityEvent = new BookActivityEvent();
              ActivityMatrix activityMatrix = new ActivityMatrix();
              activityMatrix.setActivity(new Activity());
              activityMatrix.setTrainer(new Trainer());
              List<Booking> bookingList = new ArrayList<Booking>();
              bookActivityEvent.setUserSuppliedActivity(activityMatrix);
              bookActivityEvent.setConflictBookings(bookingList);
              return bookActivityEvent;
         public Map referenceData(HttpServletRequest request, Object command, Errors errors, int Page)
              List trainers = trainersFacade.loadTrainers();
         Map trainersActivitiesMap = new HashMap();
              trainersActivitiesMap.put("trainers", trainers);          
              return trainersActivitiesMap;
         protected ModelAndView processFinish(HttpServletRequest request,
                   HttpServletResponse response, Object command, BindException errors) {
              try {
                   ActivityMatrix activity = (ActivityMatrix) command;
                   activityMatrixFacade.saveActivityMatrix(activity);
                   logger.info("Activity is successfully saved for the trainer");
              } catch (Exception e) {
                   e.getClass();
                   e.printStackTrace();
              return new ModelAndView("bookSuccess");
         @Override
         protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
              dateFormat.setLenient(true);
              binder.registerCustomEditor(java.sql.Date.class, "dateFrom", new SqlDateEditor(true));
              binder.registerCustomEditor(java.sql.Date.class, "dateTo", new SqlDateEditor(false));
              binder.registerCustomEditor(java.sql.Date.class, null, new SqlDateEditor(true));
         protected ModelAndView handleInvalidSubmit(HttpServletRequest request,
                   HttpServletResponse response) throws Exception {
              return new ModelAndView("bookInvalidSubmit");
         @Override
         protected ModelAndView processCancel(HttpServletRequest request,
                   HttpServletResponse response, Object command, BindException errors)
                   throws Exception {
              return new ModelAndView(new RedirectView("welcome.htm"));
         @Override
         protected void onBindAndValidate(HttpServletRequest request,
                   Object command, BindException errors, int page) throws Exception {
              BookActivityEvent bookActivityEvent = (BookActivityEvent) command;
              System.out.println(" PAGE : " + page);
              try {
                   switch (page) {
                   case 0:
                        if (request.getParameter("_target1") != null) {
                             ActivityMatrix userActivityMatrix = bookActivityEvent.getUserSuppliedActivity();
                             buildActivityMatrix(request, bookActivityEvent);     
                             validateActivityMatrix(bookActivityEvent, errors);
                             if (errors.getErrorCount() == 0)
                                  Trainer trainer = (Trainer) trainersFacade.loadTrainersById(userActivityMatrix.getTrainer().getTrainerId());
                                  bookActivityEvent.getUserSuppliedActivity().setTrainer(trainer);
                                  Activity activity= (Activity) activityFacade.loadActivitiesById(userActivityMatrix.getActivity().getActivityId());
                                  bookActivityEvent.getUserSuppliedActivity().setActivity(activity);
                                  boolean activityExists = checkForExistingActivities(userActivityMatrix, errors);
                                  if(!activityExists)
                                  boolean bookingsExist =      checkForBookedCourses(request, bookActivityEvent, errors);
                                  if(bookingsExist)
                                       // inject an error code so that it can be used in GUI
                                       errors.rejectValue("dateFrom","invalid dates","Trainer has Bookings in conflict with the Supplied Activity Dates");
                                  else
                                       errors.rejectValue("dateFrom","Activity Dates supplied already exist");
                        break;
                   case 1:
                        if (request.getParameter("_target2") != null)
                             * Get the user supplied activitymatrix and try to get all the bookings which are in conflict for the trainer
                        List<Booking> conflictBookingsList = (List<Booking>)request.getSession().getAttribute("conflictBookingsList");
                        break;
                   default:
              } catch (Exception e) {
                   System.err.println("Exception :" + e.getMessage());
              super.onBindAndValidate(request, command, errors, page);
         * @param request
         * @param userActivity
         * @param bookActivityEvent TODO
         private ActivityMatrix buildActivityMatrix(HttpServletRequest request, BookActivityEvent bookActivityEvent) {
              ActivityMatrix userActivity = bookActivityEvent.getUserSuppliedActivity();
              userActivity.getTrainer().setTrainerId((String)(request.getParameter("trainerId")));
              userActivity.getActivity().setActivityId((String)(request.getParameter("activitySelect")));          
              String activityTime = (String)request.getParameter("activityTimeSelect");
              String activitySubType = (String)request.getParameter("activityTimeSubType");
              if("fullday".equals(activityTime))
                   userActivity.getActivity().setTime(ActivityTimeConstants.FULLDAY.toString());
              else if("moredays".equals(activityTime))
                   userActivity.getActivity().setTime(ActivityTimeConstants.MOREDAYS.toString());
              else if("halfday".equals(activityTime)&& "am".equals(activitySubType))
                   userActivity.getActivity().setTime(ActivityTimeConstants.AM.toString());               
              else if("halfday".equals(activityTime)&& "pm".equals(activitySubType))
                   userActivity.getActivity().setTime(ActivityTimeConstants.PM.toString());
              if(!("moredays".equals(activityTime)))
                   userActivity.setDateTo(bookActivityEvent.getDateFrom());
              userActivity.setDateFrom(bookActivityEvent.getDateFrom());
              bookActivityEvent.setUserSuppliedActivity(userActivity);
              return userActivity;
         * Create an empty Booking details for client and course...
         * @param booking
         private void setInitialBookingDetails(Booking booking, BindException errors) {
              if (booking.getBookingType().equals("Client-Based")) {
                   if (booking.getClient() == null
                             || booking.getClient().getClientId() == null) {
                        booking.setClient(new Client());
              } else if (booking.getBookingType().equals("Staff")) {
                   booking.setClient(null);
              if (booking.getBookingDetails() == null) {
                   List<BookingDetails> bkDetailsList = new ArrayList<BookingDetails>();
                   BookingDetails bkDetails = new BookingDetails();
                   bkDetails.setCourse(new Course());
                   bkDetailsList.add(bkDetails);
                   booking.setBookingDetails(bkDetailsList);
              } else {
                   List bkDetList = booking.getBookingDetails();
                   if (bkDetList.size() < 1
                             || (bkDetList.size() > 0 && !((bkDetList.get(0)) instanceof BookingDetails))) {
                        BookingDetails bkDetails = new BookingDetails();
                        bkDetails.setCourse(new Course());
                        bkDetList.add(0, bkDetails);
                        booking.setBookingDetails(bkDetList);
                   } else if (((BookingDetails) bkDetList.get(0)).getCourse() == null
                             || ((BookingDetails) bkDetList.get(0)).getCourse()
                                       .getCourseId() == null) {
                        ((BookingDetails) bkDetList.get(0)).setCourse(new Course());
         @Override
         protected void validatePage(Object command, Errors errors, int page,
                   boolean finish) {
              BookActivityEvent activityEvent = (BookActivityEvent) command;
              if (finish) {
              super.validatePage(command, errors, page);
         * Validate client
         * @param booking
         * @param err
         private boolean checkForExistingActivities(ActivityMatrix userSuppliedActivity, Errors err)
              boolean exist = false;          
              List<ActivityMatrix> trainerActivityMatrixList =      activityMatrixFacade.getActivityMatrixBetweenDateRange(userSuppliedActivity.getTrainer().getTrainerId(),
                        userSuppliedActivity.getDateFrom(), userSuppliedActivity.getDateTo());
              if(ActivityTimeConstants.MOREDAYS.equals(userSuppliedActivity.getActivity().getTime()))
                   //checkForDates(trainerActivityMatrixList,);
              else if(ActivityTimeConstants.FULLDAY.equals(userSuppliedActivity.getActivity().getTime()))
                   // checkForDates(trainerActivityMatrixList,);
              else if(ActivityTimeConstants.AM.equals(userSuppliedActivity.getActivity().getTime()) ||
                        ActivityTimeConstants.PM.equals(userSuppliedActivity.getActivity().getTime()))
                   // checkForDates(trainerActivityMatrixList,);
         return exist;          
              * Check for existing bookings for a trainer and sets them on event object
              * @param request request.
              * @param event event.
              * @param err err.
              * @return true- bookings exist else false.
    private boolean checkForBookedCourses(HttpServletRequest request, BookActivityEvent event, Errors err)
         List<Booking> conflictBookingsList =      bookingFacade.loadBookingsByTrainerIdDateRange(event.getUserSuppliedActivity().getTrainer().getTrainerId(),
                   event.getUserSuppliedActivity().getDateFrom(),
                   event.getUserSuppliedActivity().getDateTo());
    request.getSession().setAttribute("conflictBookingsList",conflictBookingsList);     
                   if(conflictBookingsList!=null && conflictBookingsList.size()!=0)
                   event.setConflictBookings(conflictBookingsList);
                   return true;
                   else
                        return false;
         * Validate client
         * @param booking
         * @param err
         private void validateActivityMatrix(final BookActivityEvent activity, Errors err) {
    //          ValidationUtils.rejectIfEmptyOrWhitespace(err, "trainer.trainerId",
    //                    "required.trainer.trainerId", "Valid trainer needs to be selected.");
    ////          ValidationUtils.rejectIfEmptyOrWhitespace(err, "activity.activityId",
    ////                    "required.activity.activityId", "Valid activity needs to be selected.");
    //          if (err.getErrorCount() < 1)
    //                    if (activity.getDateFrom() == null) {
    //                         err.rejectValue("dateFrom", "required.dateFrom",
    //                                   "Valid Activity Start Date is required");
    //                    try
    //                         if (activity.getDateFrom() != null && activity.getDateTo() != null
    //                                   && (activity.getDateTo().before(activity.getDateFrom())))
    //                              err.rejectValue("dateTo", "required.dateTo",
    //                                        "Activity End Date Should be after start date.");
    //                    } catch (Exception ex) {
    //                         err.rejectValue("dateFrom",
    //                                   "dateFrom",
    //                                   "Improper dates, please provide valid dates.");
         * Validate Trainer
         * @param booking
         * @param e
         private void validateTrainer(final Booking booking, Errors e) {
              ValidationUtils.rejectIfEmptyOrWhitespace(e,
                        "bookingDetails[0].startDate",
                        "required.bookingDetails[0].startDate",
                        "Valid Booking Details startDate required.");
              ValidationUtils.rejectIfEmptyOrWhitespace(e,
                        "bookingDetails[0].trainer.trainerId",
                        "required.bookingDetails[0].trainer.trainerId",
                        "Valid Booking Details Trainer required.");
              if (e.getErrorCount() < 1)
                   for (BookingDetails bd : booking.getBookingDetails()) {
                        if (bd.getStartDate() == null) {
                             e.rejectValue("startDate", "required.bbb0",
                                       "Valid Booking details Start Date is required");
                        try {
                             if (bd.getStartDate() != null && bd.getEndDate() != null
                                       && (bd.getEndDate().before(bd.getStartDate())))
                                  e.rejectValue("endDate", "required.bbb0",
                                            "End Date Should be after starting date.");
                        } catch (Exception ex) {
                             e.rejectValue("bookingDetails[0].startDate",
                                       "before.bookingDetails[0].startDate",
                                       "Improper dates, please provide valid dates.");
                        if (bd.getTrainer() != null) {
                             e.rejectValue("trianerId", "required.trianerId",
                                       "Valid Trainer details required.");
         public BookingService getBookingFacade() {
              return bookingFacade;
         public void setBookingFacade(BookingService bookingFacade) {
              this.bookingFacade = bookingFacade;
         public CourseService getCourseFacade() {
              return courseFacade;
         public void setCourseFacade(CourseService courseFacade) {
              this.courseFacade = courseFacade;
         public VenueService getVenueFacade() {
              return venueFacade;
         public void setVenueFacade(VenueService venueFacade) {
              this.venueFacade = venueFacade;
         public ClientService getClientFacade() {
              return clientFacade;
         public void setClientFacade(ClientService clientFacade) {
              this.clientFacade = clientFacade;
         public TrainersService getTrainersFacade() {
              return trainersFacade;
         public void setTrainersFacade(TrainersService trainersFacade) {
              this.trainersFacade = trainersFacade;
         * getter method for activityFacade.
         * @return Returns the activityFacade.
         public ActivityService getActivityFacade() {
              return activityFacade;
         * setter method for activityFacade.
         * @param activityFacade The activityFacade to set.
         public void setActivityFacade(ActivityService activityFacade) {
              this.activityFacade = activityFacade;
         * getter method for activityMatrixFacade.
         * @return Returns the activityMatrixFacade.
         public ActivityMatrixService getActivityMatrixFacade() {
              return activityMatrixFacade;
         * setter method for activityMatrixFacade.
         * @param activityMatrixFacade The activityMatrixFacade to set.
         public void setActivityMatrixFacade(ActivityMatrixService activityMatrixFacade) {
              this.activityMatrixFacade = activityMatrixFacade;
         * getter method for bookingDetailsFacade.
         * @return Returns the bookingDetailsFacade.
         public BookingDetailsService getBookingDetailsFacade() {
              return bookingDetailsFacade;
         * setter method for bookingDetailsFacade.
         * @param bookingDetailsFacade The bookingDetailsFacade to set.
         public void setBookingDetailsFacade(BookingDetailsService bookingDetailsFacade) {
              this.bookingDetailsFacade = bookingDetailsFacade;
         class SqlDateEditor extends PropertyEditorSupport {
              private boolean isRequired = false;
              SqlDateEditor(boolean isRequired) {
                   this.isRequired = isRequired;
              public void setAsText(String text) throws IllegalArgumentException {
                   java.util.Date d = null;
                   if (!this.isRequired && !StringUtils.hasText(text)) {
                        setValue(null);
                   else
                        try {
                             d = dateFormat.parse(text);
                             setValue(new java.sql.Date(d.getTime()));
                        } catch (ParseException ex) {
                             throw new IllegalArgumentException("Could not parse date: " + ex.getMessage());
              public String getAsText() {
                   Date value = (java.sql.Date)getValue();
                   if (value != null) {
                        java.util.Date d = new java.util.Date(value.getTime());
                        return dateFormat.fo

    This topic is hopeless. Too much unnecessary code. Unformatted code. No question. No requirements. No step-by-step explanation how to reproduce problem. No expectations. No unexpectations/errors.
    Please read this how to get better help.

Maybe you are looking for

  • How to create an iview for ABAP Webdynpro Application in Portal?

    HI, I am Webdynpro Java webdynpro developer. I want to create an IVIEW for an ABAP Webdynpro application in the enterprise portal.

  • Apple Student Program for Colombia?

    Hi there, I've being searching the whole site, trying to find a number or an email to send this inquiry to but I couldn't so Had no other choise but to post this on the Discussions hoping for someone in the high roll to see this post. I've being a wa

  • Capitals to lower case

    I f I type a sentence with uppercase clicked on and then decide I do not want it in upper case but in lower case, so I go <Format> <Capitalization> <no Caps> nothing happens. I can't seem to be able to change to lower case except by re-typing the who

  • Advanced Data Grid - Multi-Select

    Good Day, I am using an Advanced Data Grid to display data to the user.  The user needs to be able to select multiple rows, and not necessarily in order.  This is all fine, however, they don't want to have to hold the CTRL or SHIFT keys when selectin

  • How do you convert a you tube audio into a ringback tone?

    How do I convert a you tube video audio into a ringback tone...?