[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 535
  • Last Modified:

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import harvard.itis.sql.easy.EasyConnection;

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,(String) 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.securityDataSourceName, Constants.sqlErrorJsp);
                          postData.setValue("HUID", roleCookies.getHuid());
            }catch(Exception e){
            /** start with setting other values **/
                   try{/** getting cat_id value **/
                        HashMap hm = conn.getConvertNulls("Select cat_id from CATEGORY where CATEGORY_NAME = '" + (String)hlPostform.getValue("cat_id") +"'");
                  }catch(Exception e){
                        try{/** getting subcat_id value **/
                              HashMap hm1 = conn.getConvertNulls("Select subcat_id from SUB_CATEGORY where SUBCATEGORY_NAME = '" + (String)hlPostform.getValue("subcat_id") +"'");
                        }catch(Exception e){
                  /** now inserting into database **/
                              /** setting the post expiration date and date of creation and modification**/
                              Calendar cal = Calendar.getInstance();
                            Date today = new Date();
                            cal.add(Calendar.DATE, Integer.parseInt(hlPostform.getValueConvertNulls("duration")));
                            Date durationDaysLater = cal.getTime();
                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh24:mm:ss") ;
                              String dateStr = sdf.format( durationDaysLater ) ;
                              postData.setValue("DURATION", dateStr);
                              SimpleDateFormat todayDate = new SimpleDateFormat("MM/dd/yyyy hh24:mm:ss") ;
                              String dateCreated_modified = todayDate.format(new Date());
                              postData.setValue("DATE_CREATED", dateCreated_modified);
                              /** VALUE SET **/
                        /** checking and adding price right **/
                        /** 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){
                              System.out.println("Connection Closed");
                        System.out.println("REACHED HERE");
                  return mapping.findForward("success");

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();
            valueList.append(sequenceName + ".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;
                  fieldList.append(", " + fieldName);                        
                  valueList.append(", ?");

            // Build the SQL statement.
            String sql = "insert into " + tableName
                  + "(" + fieldList.toString() + ") values (" + valueList.toString() +")";
                        // 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();
                  // 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);

                  // Run a select to get the primary key of the record we just inserted.
                  String sql2 = "select " + sequenceName      + ".CurrVal from dual";
                        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.

            }catch (SQLException e){
                  displayException(e, "execInsert()", sql);
            return key;


private void bindVariable(String sql, DatabaseMetaData dmd, PreparedStatement stmt,
                        String tableName, String fieldName, Object fieldValue, int sequence) {
                  // 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());
                        fieldType = rs.getInt(5);
                  } 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.
                        // 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.LONGVARBINARY:
                        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(sequence, new java.io.StringReader(fieldStringValue),
                        // 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:
                              stmt.setObject(sequence, "");
                              stmt.setObject(sequence, strToTimestamp(fieldStringValue));
                        // For all other DB field types, we let the Oracle JDBC driver handle the conversion
                        // from the java.lang.String object.
                              stmt.setString(sequence, fieldStringValue);
            }catch(SQLException e){
                  displayException(e, null, sql);

private java.sql.Timestamp strToTimestamp(String str){
            // If we got the string SYSDATE, use the current date.            
                  return new java.sql.Timestamp(System.currentTimeMillis());
            // If we appear to have just a date, not a full datestamp, add time
            // to our string.
                  if(str.indexOf(":") == -1){
                        str += " 00:00:00";
            java.sql.Timestamp ts = new java.sql.Timestamp(0);
                  DateFormat df = new SimpleDateFormat(EasyConfig.SIMPLE_DATE_FORMAT);
                        java.util.Date d = df.parse(str);
                        }catch(ParseException pe){
                        displayException(pe, "strToTimestamp()");
            return ts;

Inserting string values coming from form and going into hash table of bean

Title - title
Location - location
12.34 - price
for sale >> cat_id=3
free >> subcat_id=11
7 -duration date new calculated
description - description
huid =12345
keyword- null
datecreated and datemodified= java date

Table structure
"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,
"PRICE" NUMBER(10,2) not null,
"ALERTED" NUMBER(22) default 0,

getting error

        at harvard.itis.sql.easy.EasyConnection.execInsert(EasyConnection.java:493)
        at app.HLPostAction.execute(HLPostAction.java:82)
        at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
        at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
        at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
        at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
        at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:971)
        at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:402)
        at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:305)
        at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:6350)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:317)
        at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:118)
        at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3635)
        at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2585)
        at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
        at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
Connection Closed


1 Solution
What does HLPostFormBean.getValues() return? It should return a Map or some subclass of it. If it returns a superclass or interface, it needs to be cast to a Map

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now