Solved

How to delete particular values from a HashMap

Posted on 2009-07-13
27
329 Views
Last Modified: 2013-11-11
Hi Experts,

               I have the following method, which runs an update query on the DB. the method has two parameters: HashMap hm, String Section.

               both of these parameters are fetched from a jsp page using:
         
Now the problem I am facing is, the is a save button at the bottom of this page(Snapshot attached), On submitting the save button, the update query in the code shown runs and it updates the Backend table and refreshs the page with new data.
             It works fine for the first time(When i open the page for the first time), but during its second iteration, it fails and SQL error i get is :
error occurred during batching: ORA-00904: "SECTIONS": invalid identifier

           because somehow, the parameters in URL gets passed to this query(String) and it fails. How do I restrict my hashmap to contain only integers or how do i pass only the integer values of the hashmap o the method that runs the SQL.


           
      @RequestMapping(method=RequestMethod.POST)
       public String saveAdminDetails(HttpServletRequest request ,ModelMap model, @ModelAttribute("editAdminForm") AdminChart AdminChart) {
            
            String sect = request.getParameter("section");
                        
//            log.info("EditControl>>POST>>>selected_sect>>>=" + sect);
            
            HashMap<String, String> map = new HashMap<String, String>();
            Enumeration e = request.getParameterNames();
            while (e.hasMoreElements()) {
                  String name = (String) e.nextElement();
                  String value = request.getParameter(name);
//                  log.info(">>>>editChart>>>>>" + name + "==>" + value);
                  map.put(name, value);
            }
            
            AdminChartSummaryData acsd = new AdminChartSummaryData();
            acsd.updateChart(map, sect);
            
            String chartUpdates = AdminChart.getNotes();
//            log.info(">>>>>edit_notes>>>>>>" + chartUpdates);
//            log.info(">>>>>edit_notes_chartId=>>>>>>" + AdminChart.getChartId());
            //adminChartSummaryData.updateChartNotes(AdminChart, chartUpdates);
            
            model.put("currentpage", "admin");
      
            return "redirect:/admin.html";
      }
      


public void updateArrayOfChartsPosition(HashMap hm ,String section) {

//		System.out.println("chartPostion mtd called>>>>>>>section=" + section);
 

		String updateQry = null;

		String table = " MYWORLD_CHART_DETAILS ";
 

		try {

			dbc = new DbConnection();

			con = dbc.getConnection(url, user, password);
 

			stmt = dbc.getStatement(con);

			

			if (section.equals("Summary")) {

				table = " MYWORLD_CHART_DETAILS ";

			} else if (section.equals("Transaction")) {

				table = " MYWORLD_CHART_DETAILS_TRX ";

			}

			

			Set myKeys = hm.keySet();

			Iterator itr = myKeys.iterator();
 

			 

			

			while (itr.hasNext()) {

				String ky = (String) (itr.next());

				 System.out.println(">>>>>>>" + ky + ">>>" + hm.get(ky));

					

				 if (!ky.equalsIgnoreCase("section")) {

					 										 

					 updateQry = "update " + table + " set CHART_POSITION='"

						+ hm.get(ky) + "' where ID=" + ky;				 

					 stmt.addBatch(updateQry);

				 }

			}

			int[] res = stmt.executeBatch();

			
 

		} catch (SQLException sqle) {

			sqle.printStackTrace();

		} catch (Exception e) {

			e.printStackTrace();

		} finally {

			try {

				dbc.closeResources(stmt, con);

			} catch (Exception e) {

				e.printStackTrace();

			}

		}

	}

Open in new window

AdminConsole.PNG
0
Comment
Question by:aman0711
  • 13
  • 11
  • 2
  • +1
27 Comments
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
I'm not sure what you're doing with the Map, but the parameters are already in one:

http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletRequest.html#getParameterMap()
0
 
LVL 10

Author Comment

by:aman0711
Comment Utility
Hi Charles,

                     I am fetchign everything from the page, and storing it in a Map... because the query that runs on the Table contains an id filed (id is in the backend table)
0
 
LVL 3

Assisted Solution

by:SordSord
SordSord earned 30 total points
Comment Utility
To restrict your Map to just integer values, put the "map.put(name, value);" inside a try/catch block and see if you can parseInt the value. If it fails, you don't have an integer.
String name = (String) e.nextElement();

String value = request.getParameter(name);

try {

  Integer.parseInt(value); // will throw an exception for non-integers

  map.put(name, value);

} catch (NumberFormatException e) {

}

Open in new window

0
 
LVL 10

Author Comment

by:aman0711
Comment Utility
Hi SordSord,

                   Going to try your solution
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>because the query that runs on the Table contains an id filed (id is in the backend table)

Why don't you just do req.getParameter("id") ?
0
 
LVL 10

Author Comment

by:aman0711
Comment Utility
Hi sordsord,
 
                   I actually cant see any error on the console maybe coz too much of stuff prints there.

But here is what I got. the first time when I hit save, This is what my HashMap looks like:
I have also posted the HashMap values, when i hit save for the second time:
FIRST TIME:
>>>>>>>19>>>2
>>>>>>>17>>>3
>>>>>>>18>>>89
>>>>>>>36>>>4
>>>>>>>15>>>92
>>>>>>>33>>>91
>>>>>>>16>>>1
>>>>>>>34>>>43
>>>>>>>13>>>93
>>>>>>>14>>>10
>>>>>>>118>>>115
>>>>>>>119>>>117
>>>>>>>12>>>94
>>>>>>>20>>>7
>>>>>>>103>>>102
>>>>>>>23>>>6
>>>>>>>24>>>9
>>>>>>>28>>>11
>>>>>>>29>>>38
>>>>>>>2>>>88
>>>>>>>1>>>551
>>>>>>>10>>>87
>>>>>>>7>>>991
>>>>>>>6>>>5
>>>>>>>32>>>41
>>>>>>>5>>>77
>>>>>>>31>>>40
>>>>>>>4>>>99
>>>>>>>9>>>8
>>>>>>>8>>>550

SECOND TIME:
>>>>>>>19>>>2
>>>>>>>17>>>3
>>>>>>>18>>>89
>>>>>>>36>>>4
>>>>>>>15>>>92
>>>>>>>33>>>91
>>>>>>>16>>>1
>>>>>>>34>>>43
>>>>>>>13>>>93
>>>>>>>14>>>10
>>>>>>>118>>>115
>>>>>>>119>>>117
>>>>>>>12>>>94
>>>>>>>20>>>7
>>>>>>>sections>>>Summary
>>>>>>>103>>>102
>>>>>>>23>>>6
>>>>>>>24>>>9
>>>>>>>currentpage>>>admin
>>>>>>>section>>>Summary
>>>>>>>28>>>11
>>>>>>>29>>>12
>>>>>>>2>>>88
>>>>>>>1>>>551
>>>>>>>10>>>87
>>>>>>>7>>>991
>>>>>>>6>>>5
>>>>>>>5>>>77
>>>>>>>32>>>41
>>>>>>>4>>>99
>>>>>>>31>>>40
>>>>>>>9>>>8
>>>>>>>8>>>550
java.sql.BatchUpdateException: error occurred during batching: ORA-00904: "SECTIONS": invalid identifier
0
 
LVL 10

Author Comment

by:aman0711
Comment Utility
@ Charles:

                  This is the table you are seeing in the snap shot.. This contains everything.

<form:form commandName="adminForm" onsubmit="return validateTable();">

<input type="hidden" value="${adminLeftForm.section}"/>
 

<display:table name="adminDetails" id="row" class="table-style">

    <display:column property="chartGroup" title="Report Group"/>

    <display:column property="chartSubgroup" title="Report Subgroup"/>

    <display:column property="chartName" title="Chart Name"/>

    <display:column property="chartType" title="Chart Type"/>

    <display:column property="liabilityCode" title="Customer Type"/>

    <display:column property="timeline" title="Timeline"/>    

    <display:column><a href="adminEdit.html?id=${row.chartId}&section=${adminLeftForm.section}">Edit</a></display:column>

    <display:column><a href="adminDelete.html?id=${row.chartId}&section=${adminLeftForm.section}" onclick="javascript:return confirm('Are you sure you want to delete the Chart? Please click Yes to continue or else click Cancel')">Delete</a></display:column>

    <display:column title="Chart Position"><input name="${row.chartId}" type="text" size="2" value="${row.chartPosition}""></display:column>

 </display:table>

 

 <table>

 <tr>

 			<td>  <input type="submit" value="Cancel" onclick="window.close()" align="middle" /></td>

              <td> <input type="reset" value="Refresh to Original" align="middle" /> </td> 

             <td><input type="submit" value="Save"  onsubmit="return validateTable();"></td>

</tr>  

 </table>

 

   </form:form>

Open in new window

0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 70 total points
Comment Utility
Try
for(Map.Entry e : req.getParameterMap().entrySet()) {

	String val = e.getKey().toString();

	String key = e.getValue().toString();

	if (val.matches("\\d+") && key.matches("\\d")) {

		// Do the insert

	}

}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Sorry

if (val.matches("\\d+") && key.matches("\\d+")) {
0
 
LVL 10

Author Comment

by:aman0711
Comment Utility
hi Charles.. these two things are not in one Java class.. the request.getParameter is in the Controller and the update method is in the backend class
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
OK, then just copy the parameter map:

Map m = new HashMap(request.getParameterMap());
0
 
LVL 10

Author Comment

by:aman0711
Comment Utility

>> Map m = new HashMap(request.getParameterMap());

Sorry didnt get you :( i controller or backend class :(

Below is the POST method of controller

@RequestMapping(method=RequestMethod.POST)

	 public String saveAdminDetails(HttpServletRequest request ,ModelMap model, @ModelAttribute("editAdminForm") AdminChart AdminChart) {

		

		String sect = request.getParameter("section");

				

//		log.info("EditControl>>POST>>>selected_sect>>>=" + sect);

		

		HashMap<String, String> map = new HashMap<String, String>();

		Enumeration e = request.getParameterNames();

		while (e.hasMoreElements()) {

			String name = (String) e.nextElement();

			String value = request.getParameter(name);

//			log.info(">>>>editChart>>>>>" + name + "==>" + value);

			

			try {

				  Integer.parseInt(value); 

			map.put(name, value);

			} catch (NumberFormatException e1) {

				

			}

		}

		

		AdminChartSummaryData acsd = new AdminChartSummaryData();

		acsd.updateChart(map, sect);

		acsd.updateArrayOfChartsPosition(map, sect);

		

		String chartUpdates = AdminChart.getNotes();

//		log.info(">>>>>edit_notes>>>>>>" + chartUpdates);

//		log.info(">>>>>edit_notes_chartId=>>>>>>" + AdminChart.getChartId());

		//adminChartSummaryData.updateChartNotes(AdminChart, chartUpdates);

		

		model.put("currentpage", "admin");

	

		return "redirect:/admin.html";

	}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
All this code:

>>

   Enumeration e = request.getParameterNames();
                while (e.hasMoreElements()) {
                        String name = (String) e.nextElement();
                        String value = request.getParameter(name);
//                      log.info(">>>>editChart>>>>>" + name + "==>" + value);
                       
                        try {
                                  Integer.parseInt(value);
                        map.put(name, value);
                        } catch (NumberFormatException e1) {
                               
                        }
                }
>>
can be replaced by the code i posted
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 10

Author Comment

by:aman0711
Comment Utility
Cool.. Gonna try right now :)
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>// Do the insert

(would mean insert into the Map)
0
 
LVL 10

Author Comment

by:aman0711
Comment Utility
Charles, getting an error on one of the line.


map.PNG
0
 
LVL 10

Author Comment

by:aman0711
Comment Utility
Yes I did the insert :(
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Looks like you have

map.Entry

instead of

Map.Entry
0
 
LVL 10

Author Comment

by:aman0711
Comment Utility
No I had Map.Entry but that was throwing an error, so i moved it to map.Entry

map.PNG
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>map.put(name, value)

should be

map.put(key, val)
0
 
LVL 10

Author Comment

by:aman0711
Comment Utility
Still throwing an error cannot convert an object to map entry
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Yes, sorry - you're going to have to use the Enumeration you had
0
 
LVL 10

Author Comment

by:aman0711
Comment Utility
U mean the whole code? :(
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
No - see below
        for(Enumeration e = req.getParameterNames();e.hasMoreElements();) {

            String key = e.nextElement().toString();

            String val = req.getParameter(key);

            if (val.matches("\\d+") && key.matches("\\d")) {

                // Do the insert

            }   

        }   

Open in new window

0
 
LVL 92

Accepted Solution

by:
objects earned 400 total points
Comment Utility
The code you already has is fine, just prefix the paramaters

in your jsp:

    <input name="_id${row.chartId}" type="text" size="2" value="${row.chartPosition}"">

in your controller


               if (name.startsWith("_id"))   map.put(name.substring(3), value);


should be all you need, no need to go overcompilicating your code :)
0
 
LVL 10

Author Comment

by:aman0711
Comment Utility
Objects you are great. just 2 lines fixed everything :)
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
(-:
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to implement Singleton Design Pattern in Java.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now