?
Solved

use java 1.5 instead of java 1.4 for generics

Posted on 2012-09-11
8
Medium Priority
?
660 Views
Last Modified: 2012-09-17

I have a hashmap which has username and password information.
Map mapDetail = new HashMap();
mapDetail.put("username",username);
mapDetail.put("password",password);
HashMap is embedded in a arraylist like below
List missingList = new ArrayList();
missingList.add(mapDetail);
 


I am reading the username and password information to send it to one other method as follows.



private static void checkDatabase(Vector dataHolder) {
            String username="";
            String password="";
            PreparedStatement pstmt = null;      
            List<HashMap<String,String>> missingList = new ArrayList<HashMap<String,String>>();
            System.out.println("dataHolder.size()--->"+dataHolder.size());

            for (int i=1;i<dataHolder.size(); i++){
                  Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
                  int usernameIndex = new Integer(genericImporterProp.getString("username.index")).intValue();
                  HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(usernameIndex);
                  myCell.setCellType(myCell.CELL_TYPE_STRING);
                  String stringCellValue = myCell.toString();
                  username = stringCellValue;

                  int passwordIndex = new Integer(genericImporterProp.getString("password.index")).intValue();
                  myCell = (HSSFCell)cellStoreVector.elementAt(passwordIndex);
                  myCell.setCellType(myCell.CELL_TYPE_STRING);
                  stringCellValue = myCell.toString();
                  //stringCellValue=stringCellValue.t
                  password=stringCellValue;
                   // double aDouble = Double.parseDouble(stringCellValue);


                  try{
                        Class.forName("com.mysql.jdbc.Driver").newInstance();
                        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");
                        Statement stmt = con.createStatement();


                        String usernameColumn = genProp.getString("usernameColumn");
                        String passwordColumn = genProp.getString("passwordColumn");
                        ResultSet rs1 = stmt.executeQuery("select * from login where "  + usernameColumn + "='"+username+"' and " + passwordColumn + "='"+password+"'");


                        boolean isExist = false;
                        if (rs1!=null) {

                              while (rs1.next()){
                                    isExist=true;
                                    String rec1 = rs1.getString(1);
                                    String rec2 = rs1.getString(2);
                                    System.out.println("rec1 is--"+rec1+"---rec2 is---"+rec2);
                              }
                        }

                        if (!isExist) {
                              HashMap<String,String> mapDetail =new HashMap<String,String>();
                              mapDetail.put("username",username);
                              mapDetail.put("password",password);




                              for(HashMap<String,String> newMapDetail : missingList) {
                                    String myUseridToPass = newMapDetail.get("username");
                                    String myPasswordToPass = newMapDetail.get("password");
                                    System.out.println("myUseridToPass-->"+myUseridToPass);
                                    System.out.println("myPasswordToPass-->"+myPasswordToPass);
                                    
                              }


                              missingList.add(mapDetail);

                        }


                        //pstmt.close();
                        con.close();
                  }
                  catch(Exception e){

                        System.out.println("e-->"+e);
                  }
            }

            System.out.println("Missing List : "+missingList);

            generateCsvFile("c://MissingList.csv", missingList);
            sendErrorEmail("c://MissingList.csv");

      }


Challenge now I have is server is running on java 1.4 not java 1.5.
I need to modify my code to remove java 1.5 Generics and use java 1.4. How Can achieve it


>>>
List<HashMap<String,String>> missingList = new ArrayList<HashMap<String,String>>();


>>>
for(HashMap<String,String> newMapDetail : missingList) {
                                    String myUseridToPass = newMapDetail.get("username");
                                    String myPasswordToPass = newMapDetail.get("password");
                                    System.out.println("myUseridToPass-->"+myUseridToPass);
                                    System.out.println("myPasswordToPass-->"+myPasswordToPass);
                                    
                              }
Any ideas, suggestions, sample code, links, source code highly appreciated. Thanks in advance
0
Comment
Question by:gudii9
  • 3
  • 3
  • 2
8 Comments
 
LVL 36

Expert Comment

by:mccarl
ID: 38389954
Wow, that is some horribly inefficient code that you have there. You are passing in a vector that basically, at a high level, contains a number of username/password combinations and you want to find out which of that list are MISSING from the database, yeah?

However, for each username/password in the list, you are making an entirely new connection to the DB??? Move the connection setup so that it happens before the loop, as a start to making this more efficient.

What I probably would do (depending on how many rows there are in the 'login' table) is read all the db username/passwords in, store them in a temporary list/vector and then do the compare all in memory.


Now back to the original question, you can use the ArrayList without specifying the generic type, and it is compatible with java 1.4. It just means that you need to cast the objects within the list when you refer to them. And as for the HashMap that you are using, just get rid of it. You are using an object-oriented language, so make use of it. Create a class to hold your username and password strings, and then objects of that class can live in your missingList (the ArrayList). You should only use the Map when you aren't sure what you are going to store into it until runtime. However, since you know that it will always and only be a username and a password, than that is what you use objects to represent.
0
 
LVL 7

Author Comment

by:gudii9
ID: 38392042
>>>It just means that you need to cast the objects within the list when you refer to them.

>>You are using an object-oriented language, so make use of it. Create a class to hold your username and password strings, and then objects of that class can live in your missingList (the ArrayList).

can you please provide some sample code to do above
0
 
LVL 28

Expert Comment

by:dpearson
ID: 38393833
To make it not use generics change this:
   List<HashMap<String,String>> missingList = new ArrayList<HashMap<String,String>>();
into
   List missingList = new ArrayList();

Then change this:

for(HashMap<String,String> newMapDetail : missingList) {
                                    String myUseridToPass = newMapDetail.get("username");
                                    String myPasswordToPass = newMapDetail.get("password");
                                    System.out.println("myUseridToPass-->"+myUseridToPass);
                                    System.out.println("myPasswordToPass-->"+myPasswordToPass);
                                   
                              }

into something like:

Iterator iter = missingList.iterator() ;
while (iter.hasNext()) {
   // Note how you have to cast here with HashMap because the List
   // no longer has a type associated with it
   HashMap newMapDetail = (HashMap)iter.next() ;

   // Again need to cast when getting objects out of the map since
   // not using generics
   String myUseridToPass = (String)newMapDetail.get("username");
   String myPasswordToPass = (String)newMapDetail.get("password");
   ...
}

I think that's about right.  It's been several years since I wrote any Java 1.4 code but I think that should get you going in the right direction,

Doug
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 36

Expert Comment

by:mccarl
ID: 38393848
As for making this more object-oriented, create a class to store your username/password in.
public class UserDetail {
  private String username;
  private String password;

  public UserDetail(String username, String password) {
    this.username = username;
    this.password = password;
  }

  public String getUsername() {
    return username;
  }

  public String getPassword() {
    return password;
  }
}

Open in new window

And then, instead of the code that creates new HashMaps and 'puts' the username/password in them and then adds the map to 'missingList', do the following...
missingList.add(new UserDetail(username, password));

Open in new window

(Note: the above easily accomplished 3 things in a neat compact way, you are creating the object to store the details, initialising it with the username and password variables, and adding the object to 'missingList', all in one clear and understandable line)

And then a loop that reads 'missingList' and prints the details, (including Doug's code to remove generics) becomes this...
Iterator iter = missingList.iterator();
while (iter.hasNext()) {
   UserDetail userDetail = (UserDetail) iter.next();

   String myUseridToPass = userDetail.getUsername();
   String myPasswordToPass = userDetail.getPassword();
   System.out.println("myUseridToPass-->"+myUseridToPass);
   System.out.println("myPasswordToPass-->"+myPasswordToPass);
}

Open in new window

(Note: you still need to use the cast for the List, but since we have eliminated the Map altogether, retrieving the username/password from the UserDetail object is easy)
0
 
LVL 7

Author Comment

by:gudii9
ID: 38395276

i commented following


//      List<HashMap<String,String>> missingList = new ArrayList<HashMap<String,String>>();



and added new code as below              
 List missingList = new ArrayList();




i commented following as well ( both in checkDatabase(dataHolder); method which handles xls input files, and checkDatabases(rows)  which handles text files



      /*      for(HashMap<String,String> newMapDetail : missingList) {
                                    String myUseridToPass = newMapDetail.get("username");
                                    String myPasswordToPass = newMapDetail.get("password");
                                    System.out.println("myUseridToPass-->"+myUseridToPass);
                                    System.out.println("myPasswordToPass-->"+myPasswordToPass);
                                    
                              }*/




and added new code as below both methods checkDatabase(dataHolder); method which handles xls input files, and checkDatabases(rows)  which handles text files

Iterator iter = missingList.iterator();
                              while (iter.hasNext()) {
                                 UserDetail userDetail = (UserDetail) iter.next();

                                 //   String myUseridToPass = (String)newMapDetail.get("username");
                                // String myPasswordToPass = (String)newMapDetail.get("password");
                                
                                
                                
                                 String myUseridToPass = userDetail.getUsername();
                                 String myPasswordToPass = userDetail.getPassword();
                                 System.out.println("myUseridToPass-->"+myUseridToPass);
                                 System.out.println("myPasswordToPass-->"+myPasswordToPass);
                              }
                              //missingList.add(mapDetail);
                              missingList.add(new UserDetail(username, password));




I am getting following error inside main method at that particular method call

public static void main( String [] args ) {

String fileTypeNameColumn = genProp.getString("fileTypeName");
            String fileName=fileTypeNameColumn;
            if (fileTypeNameColumn.endsWith(".xls")){
                  System.out.println("Excel file");
                  Vector dataHolder=read(fileName);
                  checkDatabase(dataHolder);
            }
            else{
                  try {
                        String strContent = Repository.retrieveData("C:\\MySql.txt");
                        String [] rows = strContent.split(genProp.getString("row.seperator"));                        
                        checkDatabases(rows);//getting error here as i am passing text file not xls for this run
                  } catch (Exception ex) {

                        ex.printStackTrace();
                  }
            }


      }


java.lang.ClassCastException: com.aaa.UserDetail cannot be cast to java.util.Map

 Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 38395449
>>public class UserDetail {
  private String username;
  private String password;

  public UserDetail(String username, String password) {
    this.username = username;
    this.password = password;
  }

  public String getUsername() {
    return username;
  }

  public String getPassword() {
    return password;
  }
}


there are no setter methods. Do I need to write setter methods to set or put values. Please advise.

How do I initialize UserDetail.

Why it expecting me to cast UserDetail to map. Please advise
0
 
LVL 28

Assisted Solution

by:dpearson
dpearson earned 1000 total points
ID: 38397039
There's no need to have setting methods on UserDetail.  It's designed to be "set" through the constructor:

UserDetail oldDetail = new UserDetail("my-name",'mypassword") ;

so to change it you do something like:
UserDetail newDetail = new UserDetail(oldDetail.getUsername(), "my-new-password") ;

As for your exception, you should be getting a stack trace telling you exactly which line is causing this.  I'd guess it's here:
missingList.add(new UserDetail(username, password));

since you original said missingList is a list of HashMaps, not a list of UserDetail objects.

Doug
0
 
LVL 36

Accepted Solution

by:
mccarl earned 1000 total points
ID: 38397291
I believe Doug has answered your question about the UserDetail class and setter methods not being required. One extra thing that you could look up is "immutable vs mutable objects" and that will give you more info on why the UserDetail class is the way it is. Basically though, it you don't NEED setter methods, don't put them in. In this case you are only ever setting the username/password once, so your use case is a good fit for an immutable object. Also, if your needs ever do change, it is easy to add the setter methods at that point.


As for the error about casting to Map, I would guess that it is due to code in the generateCsvFile() method. You have a line that calls that method in your original question...

 generateCsvFile("c://MissingList.csv", missingList);

and not that you posted the code that implements that method, but since missingList WAS a List of Maps, I'm sure that you will have code in there that still expects a List of Maps. You should change the code in that method to handle the list similarly to what I posted above (that 3rd code section, the one that iterates the list).
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

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

When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
CTAs encourage people to do something specific to show interest in your company, product or service. Keep reading to learn why CTAs should always be thought of as extremely important, albeit small, sections of websites.
This video teaches viewers about errors in exception handling.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month15 days, 16 hours left to enroll

850 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