su_harvie
asked on
Class cast exception struts
Here is my code:
Action Class
package app;
//import java.util.Iterator;
//import java.util.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Calendar;
import java.text.*;
import javax.servlet.http.HttpSer vletReques t;
import javax.servlet.http.HttpSer vletRespon se;
import org.apache.struts.action.A ctionForm;
import org.apache.struts.action.A ctionForwa rd;
import org.apache.struts.action.A ctionMappi ng;
import harvard.itis.sql.easy.Easy Connection ;
import app.HLPostFormBean;
public class HLPostAction extends AbstractAction {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
HLPostFormBean hlPostform = (HLPostFormBean) form;
/** making connection with database
*/
EasyConnection conn = new EasyConnection(request, response,
Constants.dataSourceName, Constants.sqlErrorJsp);
HLPostFormBean postData = new HLPostFormBean();
Set s = hlPostform.getKeys();
for(Iterator i = s.iterator(); i.hasNext(); ){
String key = (String) i.next();
postData.setValue(key,(Str ing) hlPostform.getValue(key));
}
/** getting huid from session for harvieslist use.
* At this point we need only Huid.
*/
try{ ApplicationCookies roleCookies = new ApplicationCookies(request , response,
Constants.securityDataSour ceName, Constants.sqlErrorJsp);
postData.setValue("HUID", roleCookies.getHuid());
}catch(Exception e){
e.printStackTrace();
}
/** start with setting other values **/
try{/** getting cat_id value **/
HashMap hm = conn.getConvertNulls("Sele ct cat_id from CATEGORY where CATEGORY_NAME = '" + (String)hlPostform.getValu e("cat_id" ) +"'");
postData.setValues(hm);
}catch(Exception e){
e.printStackTrace();
}
try{/** getting subcat_id value **/
HashMap hm1 = conn.getConvertNulls("Sele ct subcat_id from SUB_CATEGORY where SUBCATEGORY_NAME = '" + (String)hlPostform.getValu e("subcat_ id") +"'");
postData.setValues(hm1);
}catch(Exception e){
e.printStackTrace();
}
/** now inserting into database **/
try{
/** setting the post expiration date and date of creation and modification**/
Calendar cal = Calendar.getInstance();
Date today = new Date();
cal.setTime(today);
cal.add(Calendar.DATE, Integer.parseInt(hlPostfor m.getValue ConvertNul ls("durati on")));
Date durationDaysLater = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy yy hh24:mm:ss") ;
String dateStr = sdf.format( durationDaysLater ) ;
postData.setValue("DURATIO N", dateStr);
SimpleDateFormat todayDate = new SimpleDateFormat("MM/dd/yy yy hh24:mm:ss") ;
String dateCreated_modified = todayDate.format(new Date());
postData.setValue("DATE_CR EATED", dateCreated_modified);
postData.setValue("DATE_MO DIFIED",da teCreated_ modified);
/** VALUE SET **/
/** checking and adding price right **/
postData.setValue("PRICE", Float.valu eOf(hlPost form.getVa lueConvert Nulls("pri ce")));
/** INSERTING RECORD INTO TABLE **/
long id = conn.execInsert("HLPOST", "POST_ID", "POSTSEQUENCE", postData.getValues());
System.out.println("Id is insert done =" + id);
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("Connec tion Closed");
conn.close();
}
System.out.println("REACHE D HERE");
return mapping.findForward("succe ss");
//}
}
}
Easy connection class code:
public long execInsert(String tableName, String keyFieldName, String sequenceName, Map fields) {
long key = 0L;
tableName = tableName.toUpperCase();
StringBuffer fieldList = new StringBuffer();
StringBuffer valueList = new StringBuffer();
fieldList.append(keyFieldN ame);
valueList.append(sequenceN ame + ".NextVal");
ArrayList fieldsInMap = new ArrayList();
// Cycle through field names building list of field names, and list of '?' characters
// for each field/value provided.
Set keys = fields.keySet();
for(Iterator i=keys.iterator(); i.hasNext();){
String fieldName = (String) i.next();
if(fields.get(fieldName) == null) continue;
fieldsInMap.add(fieldName) ;
fieldList.append(", " + fieldName);
valueList.append(", ?");
}
// Build the SQL statement.
String sql = "insert into " + tableName
+ "(" + fieldList.toString() + ") values (" + valueList.toString() +")";
try{
// Save current autocommit setting, and turn autocommit off, because
// after we run the insert statement, we're going to run a select
// statement to get the value of the primary key assigned to the
// new record.
boolean autoCommitWasOn = conn.getAutoCommit();
conn.setAutoCommit(false);
// Cycle through field names a second time, this time setting data for each
// '?' placeholder. Execute the insert statement.
PreparedStatement stmt = conn.prepareStatement(sql) ;
DatabaseMetaData dmd = conn.getMetaData();
for(int x=1; x<=fieldsInMap.size(); x++){
String fieldName = (String) fieldsInMap.get(x-1);
bindVariable(sql, dmd, stmt,tableName, fieldName,
filter((String) fields.get(fieldName)), x);
}
stmt.executeUpdate();
// Run a select to get the primary key of the record we just inserted.
String sql2 = "select " + sequenceName + ".CurrVal from dual";
try{
Statement stmt2 = conn.createStatement();
ResultSet rs = stmt2.executeQuery(sql2);
if (rs != null && rs.next()){
key = rs.getLong(1);
}
}catch (SQLException e){
displayException(e, "execInsert()", sql2);
}
// If auto-commit was originally on, then commit our transaction
// and turn auto-commit back on.
if(autoCommitWasOn){
conn.commit();
conn.setAutoCommit(true);
}
}catch (SQLException e){
displayException(e, "execInsert()", sql);
}
return key;
}
and
private void bindVariable(String sql, DatabaseMetaData dmd, PreparedStatement stmt,
String tableName, String fieldName, Object fieldValue, int sequence) {
try{
// Ensure the provided field value is a java.lang.String, or null. Method accepts
// an Object so we can do error checking here, but what we really need is
// a String.
if(fieldValue != null && ! (fieldValue instanceof java.lang.String)){
throw new SQLException("bindVariable (): Field '" + fieldName
+ "' value must be a java.lang.String.");
}
String fieldStringValue = (String) fieldValue;
// Use the DB meta data to determine the field type.
int fieldType = 0;
ResultSet rs = dmd.getColumns(null, "%", tableName.toUpperCase(), fieldName.toUpperCase());
if(rs.next()){
fieldType = rs.getInt(5);
System.out.println(fieldTy pe);
} else {
throw new SQLException("bindVariable (): No such field '" + fieldName + "' in table '"
+ tableName + "'.");
}
// Push the data into the prepared statement using the method appropriate to
// the data type.
switch(fieldType){
// Unsupported data types. Hopefully we can reduce this list as we further
// develop this class library.
case java.sql.Types.ARRAY:
case java.sql.Types.CLOB:
case java.sql.Types.OTHER:
case java.sql.Types.BLOB:
case java.sql.Types.LONGVARBINA RY:
case java.sql.Types.VARBINARY:
throw new SQLException("bindVariable (): Unsupported data type: " + fieldType + ".");
// Special case: because setString() is limited to 4000 characters under Oracle,
// we handle LONGVARCHAR specially.
case java.sql.Types.LONGVARCHAR :
stmt.setCharacterStream(se quence, new java.io.StringReader(field StringValu e),
fieldStringValue.length()) ;
break;
// Special case: dates get converted from our standard string representation of
// a date.
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
if(fieldStringValue.equals ("")){
stmt.setObject(sequence, "");
}
else{
stmt.setObject(sequence, strToTimestamp(fieldString Value));
}
break;
// For all other DB field types, we let the Oracle JDBC driver handle the conversion
// from the java.lang.String object.
default:
stmt.setString(sequence, fieldStringValue);
break;
}
}catch(SQLException e){
displayException(e, null, sql);
}
}
private java.sql.Timestamp strToTimestamp(String str){
/*str="SYSDATE";
// If we got the string SYSDATE, use the current date.
if(str.equalsIgnoreCase("S YSDATE")){
return new java.sql.Timestamp(System. currentTim eMillis()) ;
}*/
// If we appear to have just a date, not a full datestamp, add time
// to our string.
if(!str.equals("")){
if(str.indexOf(":") == -1){
str += " 00:00:00";
}
}
java.sql.Timestamp ts = new java.sql.Timestamp(0);
if(!str.equals("")){
DateFormat df = new SimpleDateFormat(EasyConfi g.SIMPLE_D ATE_FORMAT );
try{
java.util.Date d = df.parse(str);
ts.setTime(d.getTime());
}catch(ParseException pe){
displayException(pe, "strToTimestamp()");
}
}
return ts;
}
Inserting string values coming from form and going into hash table of bean
Postid-sequesce
Title - title
Location - location
12.34 - price
for sale >> cat_id=3
free >> subcat_id=11
7 -duration date new calculated
description - description
image-id=null
huid =12345
keyword- null
alternateemail-
itemname-null
termsaccepted-true
datecreated and datemodified= java date
Table structure
"POST_ID" NUMBER(22) PRIMARY KEY not null,
"CAT_ID" NUMBER(22) not null,
"SUBCAT_ID" NUMBER(22) not null,
"IMAGE_ID" NUMBER(22) not null,
"HUID" VARCHAR2 not null,
"TITLE" VARCHAR2 not null,
"KEYWORDS" VARCHAR2,
"PRICE" NUMBER(10,2) not null,
"LOCATION" VARCHAR2,
"ALTERNATEMAIL" VARCHAR2,
"ITEMNAME" VARCHAR2,
"ITEMDESCRIPTION" VARCHAR2 not null,
"TERMS_ACCEPTED" VARCHAR2,
"DATE_CREATED" DATE default 'SYSDATE',
"DATE_MODIFIED" DATE default 'SYSDATE',
"DURATION" DATE,
"ALERTED" NUMBER(22) default 0,
"EXTRA1" VARCHAR2,
"EXTRA2" VARCHAR2)
getting error
java.lang.ClassCastExcepti on
at harvard.itis.sql.easy.Easy Connection .execInser t(EasyConn ection.jav a:493)
at app.HLPostAction.execute(H LPostActio n.java:82)
at org.apache.struts.action.R equestProc essor.proc essActionP erform(Req uestProces sor.java:4 84)
at org.apache.struts.action.R equestProc essor.proc ess(Reques tProcessor .java:274)
at org.apache.struts.action.A ctionServl et.process (ActionSer vlet.java: 1482)
at org.apache.struts.action.A ctionServl et.doPost( ActionServ let.java:5 25)
at javax.servlet.http.HttpSer vlet.servi ce(HttpSer vlet.java: 760)
at javax.servlet.http.HttpSer vlet.servi ce(HttpSer vlet.java: 853)
at weblogic.servlet.internal. ServletStu bImpl$Serv letInvocat ionAction. run(Servle tStubImpl. java:971)
at weblogic.servlet.internal. ServletStu bImpl.invo keServlet( ServletStu bImpl.java :402)
at weblogic.servlet.internal. ServletStu bImpl.invo keServlet( ServletStu bImpl.java :305)
at weblogic.servlet.internal. WebAppServ letContext $ServletIn vocationAc tion.run(W ebAppServl etContext. java:6350)
at weblogic.security.acl.inte rnal.Authe nticatedSu bject.doAs (Authentic atedSubjec t.java:317 )
at weblogic.security.service. SecurityMa nager.runA s(Security Manager.ja va:118)
at weblogic.servlet.internal. WebAppServ letContext .invokeSer vlet(WebAp pServletCo ntext.java :3635)
at weblogic.servlet.internal. ServletReq uestImpl.e xecute(Ser vletReques tImpl.java :2585)
at weblogic.kernel.ExecuteThr ead.execut e(ExecuteT hread.java :197)
at weblogic.kernel.ExecuteThr ead.run(Ex ecuteThrea d.java:170 )
Connection Closed
REACHED HERE
PleASE HELP
Action Class
package app;
//import java.util.Iterator;
//import java.util.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Calendar;
import java.text.*;
import javax.servlet.http.HttpSer
import javax.servlet.http.HttpSer
import org.apache.struts.action.A
import org.apache.struts.action.A
import org.apache.struts.action.A
import harvard.itis.sql.easy.Easy
import app.HLPostFormBean;
public class HLPostAction extends AbstractAction {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
HLPostFormBean hlPostform = (HLPostFormBean) form;
/** making connection with database
*/
EasyConnection conn = new EasyConnection(request, response,
Constants.dataSourceName, Constants.sqlErrorJsp);
HLPostFormBean postData = new HLPostFormBean();
Set s = hlPostform.getKeys();
for(Iterator i = s.iterator(); i.hasNext(); ){
String key = (String) i.next();
postData.setValue(key,(Str
}
/** getting huid from session for harvieslist use.
* At this point we need only Huid.
*/
try{ ApplicationCookies roleCookies = new ApplicationCookies(request
Constants.securityDataSour
postData.setValue("HUID", roleCookies.getHuid());
}catch(Exception e){
e.printStackTrace();
}
/** start with setting other values **/
try{/** getting cat_id value **/
HashMap hm = conn.getConvertNulls("Sele
postData.setValues(hm);
}catch(Exception e){
e.printStackTrace();
}
try{/** getting subcat_id value **/
HashMap hm1 = conn.getConvertNulls("Sele
postData.setValues(hm1);
}catch(Exception e){
e.printStackTrace();
}
/** now inserting into database **/
try{
/** setting the post expiration date and date of creation and modification**/
Calendar cal = Calendar.getInstance();
Date today = new Date();
cal.setTime(today);
cal.add(Calendar.DATE, Integer.parseInt(hlPostfor
Date durationDaysLater = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy
String dateStr = sdf.format( durationDaysLater ) ;
postData.setValue("DURATIO
SimpleDateFormat todayDate = new SimpleDateFormat("MM/dd/yy
String dateCreated_modified = todayDate.format(new Date());
postData.setValue("DATE_CR
postData.setValue("DATE_MO
/** VALUE SET **/
/** checking and adding price right **/
postData.setValue("PRICE",
/** INSERTING RECORD INTO TABLE **/
long id = conn.execInsert("HLPOST", "POST_ID", "POSTSEQUENCE", postData.getValues());
System.out.println("Id is insert done =" + id);
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("Connec
conn.close();
}
System.out.println("REACHE
return mapping.findForward("succe
//}
}
}
Easy connection class code:
public long execInsert(String tableName, String keyFieldName, String sequenceName, Map fields) {
long key = 0L;
tableName = tableName.toUpperCase();
StringBuffer fieldList = new StringBuffer();
StringBuffer valueList = new StringBuffer();
fieldList.append(keyFieldN
valueList.append(sequenceN
ArrayList fieldsInMap = new ArrayList();
// Cycle through field names building list of field names, and list of '?' characters
// for each field/value provided.
Set keys = fields.keySet();
for(Iterator i=keys.iterator(); i.hasNext();){
String fieldName = (String) i.next();
if(fields.get(fieldName) == null) continue;
fieldsInMap.add(fieldName)
fieldList.append(", " + fieldName);
valueList.append(", ?");
}
// Build the SQL statement.
String sql = "insert into " + tableName
+ "(" + fieldList.toString() + ") values (" + valueList.toString() +")";
try{
// Save current autocommit setting, and turn autocommit off, because
// after we run the insert statement, we're going to run a select
// statement to get the value of the primary key assigned to the
// new record.
boolean autoCommitWasOn = conn.getAutoCommit();
conn.setAutoCommit(false);
// Cycle through field names a second time, this time setting data for each
// '?' placeholder. Execute the insert statement.
PreparedStatement stmt = conn.prepareStatement(sql)
DatabaseMetaData dmd = conn.getMetaData();
for(int x=1; x<=fieldsInMap.size(); x++){
String fieldName = (String) fieldsInMap.get(x-1);
bindVariable(sql, dmd, stmt,tableName, fieldName,
filter((String) fields.get(fieldName)), x);
}
stmt.executeUpdate();
// Run a select to get the primary key of the record we just inserted.
String sql2 = "select " + sequenceName + ".CurrVal from dual";
try{
Statement stmt2 = conn.createStatement();
ResultSet rs = stmt2.executeQuery(sql2);
if (rs != null && rs.next()){
key = rs.getLong(1);
}
}catch (SQLException e){
displayException(e, "execInsert()", sql2);
}
// If auto-commit was originally on, then commit our transaction
// and turn auto-commit back on.
if(autoCommitWasOn){
conn.commit();
conn.setAutoCommit(true);
}
}catch (SQLException e){
displayException(e, "execInsert()", sql);
}
return key;
}
and
private void bindVariable(String sql, DatabaseMetaData dmd, PreparedStatement stmt,
String tableName, String fieldName, Object fieldValue, int sequence) {
try{
// Ensure the provided field value is a java.lang.String, or null. Method accepts
// an Object so we can do error checking here, but what we really need is
// a String.
if(fieldValue != null && ! (fieldValue instanceof java.lang.String)){
throw new SQLException("bindVariable
+ "' value must be a java.lang.String.");
}
String fieldStringValue = (String) fieldValue;
// Use the DB meta data to determine the field type.
int fieldType = 0;
ResultSet rs = dmd.getColumns(null, "%", tableName.toUpperCase(), fieldName.toUpperCase());
if(rs.next()){
fieldType = rs.getInt(5);
System.out.println(fieldTy
} else {
throw new SQLException("bindVariable
+ tableName + "'.");
}
// Push the data into the prepared statement using the method appropriate to
// the data type.
switch(fieldType){
// Unsupported data types. Hopefully we can reduce this list as we further
// develop this class library.
case java.sql.Types.ARRAY:
case java.sql.Types.CLOB:
case java.sql.Types.OTHER:
case java.sql.Types.BLOB:
case java.sql.Types.LONGVARBINA
case java.sql.Types.VARBINARY:
throw new SQLException("bindVariable
// Special case: because setString() is limited to 4000 characters under Oracle,
// we handle LONGVARCHAR specially.
case java.sql.Types.LONGVARCHAR
stmt.setCharacterStream(se
fieldStringValue.length())
break;
// Special case: dates get converted from our standard string representation of
// a date.
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
if(fieldStringValue.equals
stmt.setObject(sequence, "");
}
else{
stmt.setObject(sequence, strToTimestamp(fieldString
}
break;
// For all other DB field types, we let the Oracle JDBC driver handle the conversion
// from the java.lang.String object.
default:
stmt.setString(sequence, fieldStringValue);
break;
}
}catch(SQLException e){
displayException(e, null, sql);
}
}
private java.sql.Timestamp strToTimestamp(String str){
/*str="SYSDATE";
// If we got the string SYSDATE, use the current date.
if(str.equalsIgnoreCase("S
return new java.sql.Timestamp(System.
}*/
// If we appear to have just a date, not a full datestamp, add time
// to our string.
if(!str.equals("")){
if(str.indexOf(":") == -1){
str += " 00:00:00";
}
}
java.sql.Timestamp ts = new java.sql.Timestamp(0);
if(!str.equals("")){
DateFormat df = new SimpleDateFormat(EasyConfi
try{
java.util.Date d = df.parse(str);
ts.setTime(d.getTime());
}catch(ParseException pe){
displayException(pe, "strToTimestamp()");
}
}
return ts;
}
Inserting string values coming from form and going into hash table of bean
Postid-sequesce
Title - title
Location - location
12.34 - price
for sale >> cat_id=3
free >> subcat_id=11
7 -duration date new calculated
description - description
image-id=null
huid =12345
keyword- null
alternateemail-
itemname-null
termsaccepted-true
datecreated and datemodified= java date
Table structure
"POST_ID" NUMBER(22) PRIMARY KEY not null,
"CAT_ID" NUMBER(22) not null,
"SUBCAT_ID" NUMBER(22) not null,
"IMAGE_ID" NUMBER(22) not null,
"HUID" VARCHAR2 not null,
"TITLE" VARCHAR2 not null,
"KEYWORDS" VARCHAR2,
"PRICE" NUMBER(10,2) not null,
"LOCATION" VARCHAR2,
"ALTERNATEMAIL" VARCHAR2,
"ITEMNAME" VARCHAR2,
"ITEMDESCRIPTION" VARCHAR2 not null,
"TERMS_ACCEPTED" VARCHAR2,
"DATE_CREATED" DATE default 'SYSDATE',
"DATE_MODIFIED" DATE default 'SYSDATE',
"DURATION" DATE,
"ALERTED" NUMBER(22) default 0,
"EXTRA1" VARCHAR2,
"EXTRA2" VARCHAR2)
getting error
java.lang.ClassCastExcepti
at harvard.itis.sql.easy.Easy
at app.HLPostAction.execute(H
at org.apache.struts.action.R
at org.apache.struts.action.R
at org.apache.struts.action.A
at org.apache.struts.action.A
at javax.servlet.http.HttpSer
at javax.servlet.http.HttpSer
at weblogic.servlet.internal.
at weblogic.servlet.internal.
at weblogic.servlet.internal.
at weblogic.servlet.internal.
at weblogic.security.acl.inte
at weblogic.security.service.
at weblogic.servlet.internal.
at weblogic.servlet.internal.
at weblogic.kernel.ExecuteThr
at weblogic.kernel.ExecuteThr
Connection Closed
REACHED HERE
PleASE HELP
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.