1 30 31 34 package com.nightlabs.ipanema.security; 35 36 import java.io.UnsupportedEncodingException ; 37 import java.security.MessageDigest ; 38 import java.security.NoSuchAlgorithmException ; 39 import java.util.ArrayList ; 40 import java.util.Collection ; 41 import java.util.Iterator ; 42 import java.util.List ; 43 44 import javax.jdo.PersistenceManager; 45 import javax.jdo.Query; 46 47 import sun.misc.BASE64Encoder; 48 49 52 public class UserAssistant 53 { 54 public static String encryptPassword(String password) 55 throws SecurityException 56 { 57 MessageDigest md = null; 58 try { 59 md = MessageDigest.getInstance("SHA"); 60 md.update(password.getBytes("UTF-8")); 61 } catch(NoSuchAlgorithmException e) { 62 throw new SecurityException (e); 63 } catch(UnsupportedEncodingException e) { 64 throw new SecurityException (e); 65 } 66 byte raw[] = md.digest(); 67 return (new BASE64Encoder()).encode(raw); 68 } 69 70 public static UserSearchResult searchUsers ( 71 PersistenceManager pm, 72 String userType, 73 String searchStr, boolean exact, int itemsPerPage, int pageIndex, int userIncludeMask) 74 throws SecurityException 75 { 76 try { 77 if ("".equals(searchStr)) 78 searchStr = null; 79 80 if (itemsPerPage <= 0) { 81 itemsPerPage = Integer.MAX_VALUE; 82 pageIndex = 0; 83 } 84 85 if (pageIndex < 0) 86 pageIndex = 0; 87 88 Query query = pm.newQuery(pm.getExtent(User.class, true)); 89 query.declareImports("import java.lang.String"); 90 query.declareParameters("String userType, String searchStr"); 91 StringBuffer filter = new StringBuffer (); 92 if (userType != null) 93 filter.append("this.userType == userType"); 94 95 if (userType != null && searchStr != null) 96 filter.append(" && "); 97 98 if (searchStr != null) { 99 searchStr = searchStr.toLowerCase(); 100 if (exact) 101 filter.append("this.userID.toLowerCase() == searchStr"); 102 else 103 filter.append("this.userID.toLowerCase().indexOf(searchStr) >= 0"); 104 } 105 query.setFilter(filter.toString()); 106 query.setOrdering("this.organisationID ascending, this.userID ascending"); 107 Collection c = (Collection )query.execute(userType, searchStr); 108 int itemsFound = c.size(); 109 Iterator it = c.iterator(); 110 List items = new ArrayList (); 111 int idx = 0; 112 int firstIdx = 0; int lastIdx = Integer.MAX_VALUE; 113 if (pageIndex >= 0) 114 firstIdx = itemsPerPage * pageIndex; 115 lastIdx = firstIdx + itemsPerPage - 1; 116 117 while (it.hasNext()) { 118 User user = (User)it.next(); 119 if (idx >= firstIdx) 120 items.add(user); 121 122 ++idx; 123 if (idx > lastIdx) 124 break; 125 } return new UserSearchResult(itemsFound, itemsPerPage, pageIndex, items); 127 } catch (Exception x) { 128 throw new SecurityException (x); 129 } 130 } 131 } 132 | Popular Tags |