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

x
  • 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){
                  e.printStackTrace();
            }
            /** 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") +"'");
                        postData.setValues(hm);
                        
                  }catch(Exception e){
                        e.printStackTrace();
                  }
                        try{/** getting subcat_id value **/
                              HashMap hm1 = conn.getConvertNulls("Select subcat_id from SUB_CATEGORY where SUBCATEGORY_NAME = '" + (String)hlPostform.getValue("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(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);
                              postData.setValue("DATE_MODIFIED",dateCreated_modified);
                              /** VALUE SET **/
                        /** checking and adding price right **/
                              postData.setValue("PRICE",Float.valueOf(hlPostform.getValueConvertNulls("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("Connection Closed");
                              conn.close();
                        }
                        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();
            fieldList.append(keyFieldName);      
            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;
                  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(fieldType);
                  } 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.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),
                        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(fieldStringValue));
                        }
                              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("SYSDATE")){
                  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.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(EasyConfig.SIMPLE_DATE_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.ClassCastException
        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
REACHED HERE


PleASE HELP



0
su_harvie
Asked:
su_harvie
1 Solution
 
mhuntsCommented:
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
0

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