?
Solved

How to delete particular values from a HashMap

Posted on 2009-07-13
27
Medium Priority
?
339 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 13
  • 11
  • 2
  • +1
27 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 24843736
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
ID: 24843792
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 120 total points
ID: 24843815
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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 10

Author Comment

by:aman0711
ID: 24843841
Hi SordSord,

                   Going to try your solution
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24843902
>>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
ID: 24843929
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
ID: 24843938
@ 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 280 total points
ID: 24844072
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
ID: 24844077
Sorry

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

Author Comment

by:aman0711
ID: 24844122
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
ID: 24844158
OK, then just copy the parameter map:

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

Author Comment

by:aman0711
ID: 24844187

>> 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
ID: 24844259
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
 
LVL 10

Author Comment

by:aman0711
ID: 24844270
Cool.. Gonna try right now :)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24844329
>>// Do the insert

(would mean insert into the Map)
0
 
LVL 10

Author Comment

by:aman0711
ID: 24844344
Charles, getting an error on one of the line.


map.PNG
0
 
LVL 10

Author Comment

by:aman0711
ID: 24844347
Yes I did the insert :(
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24844357
Looks like you have

map.Entry

instead of

Map.Entry
0
 
LVL 10

Author Comment

by:aman0711
ID: 24844374
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
ID: 24844429
>>map.put(name, value)

should be

map.put(key, val)
0
 
LVL 10

Author Comment

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

Expert Comment

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

Author Comment

by:aman0711
ID: 24844548
U mean the whole code? :(
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24844664
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 1600 total points
ID: 24844707
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
ID: 24851726
Objects you are great. just 2 lines fixed everything :)
0
 
LVL 92

Expert Comment

by:objects
ID: 24854897
(-:
0

Featured Post

RHCE - Red Hat OpenStack Prep Course

This course will provide in-depth training so that students who currently hold the EX200 & EX210 certifications can sit for the EX310 exam. Students will learn how to deploy & manage a full Red Hat environment with Ceph block storage, & integrate Ceph into other OpenStack service

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Suggested Courses
Course of the Month12 days, 21 hours left to enroll

777 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